@cursor/sdk 1.4.0 → 1.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bundled/index.js +565 -532
- package/dist/bundled/sqlite.js +1 -1
- package/dist/cjs/144.js +206 -0
- package/dist/cjs/730.js +1 -1
- package/dist/cjs/index.js +1 -1
- package/dist/cjs/local-executor.d.ts.map +1 -1
- package/dist/cjs/mcp-allowlist-notice.d.ts +30 -0
- package/dist/cjs/mcp-allowlist-notice.d.ts.map +1 -0
- package/dist/esm/144.js +206 -0
- package/dist/esm/730.js +1 -1
- package/dist/esm/index.js +1 -1
- package/dist/esm/local-executor.d.ts.map +1 -1
- package/dist/esm/mcp-allowlist-notice.d.ts +30 -0
- package/dist/esm/mcp-allowlist-notice.d.ts.map +1 -0
- package/package.json +6 -6
- package/dist/cjs/993.js +0 -211
- package/dist/esm/993.js +0 -211
package/dist/esm/993.js
DELETED
|
@@ -1,211 +0,0 @@
|
|
|
1
|
-
import{createRequire as e}from"node:module";const t=e(import.meta.url);export const __webpack_esm_id__=993;export const __webpack_esm_ids__=[993];export const __webpack_esm_modules__={"./src/agent/local-executor.ts"(e,t,r){r.d(t,{createLocalExecutor:()=>cB});var n=r("node:buffer"),o=r("node:os"),s=r("node:path"),i=r("../proto/dist/generated/agent/v1/agent_pb.js");const a={textDelta:(e,t)=>new i.Uq({messageStartedAtMs:t,message:{case:"textDelta",value:new i.PtE({text:e})}}),toolCallStarted:(e,t,r)=>new i.Uq({messageStartedAtMs:t.startedAtMs,message:{case:"toolCallStarted",value:new i.xuG({callId:e,toolCall:t,modelCallId:r})}}),toolCallCompleted:(e,t,r)=>new i.Uq({messageStartedAtMs:t.startedAtMs,message:{case:"toolCallCompleted",value:new i.LLS({callId:e,toolCall:t,modelCallId:r})}}),toolCallDelta:(e,t,r,n)=>new i.Uq({messageStartedAtMs:n,message:{case:"toolCallDelta",value:new i.I0n({callId:e,toolCallDelta:t,modelCallId:r})}}),thinkingDelta:(e,t,r)=>new i.Uq({messageStartedAtMs:r,message:{case:"thinkingDelta",value:new i.cHB({text:e,thinkingStyle:t})}}),thinkingCompleted:(e,t,r)=>new i.Uq({messageStartedAtMs:t,message:{case:"thinkingCompleted",value:new i.tr3({thinkingDurationMs:e,...!0===r?{narration:!0}:{}})}}),thinkingNote:e=>new i.Uq({message:{case:"thinkingNote",value:new i.Y$k({text:e})}}),taskChild:(e,t,r)=>"thinkingNote"===t.message.case?t:a.toolCallDelta(e,new i.V1v({delta:{case:"taskToolCallDelta",value:new i.aon({interactionUpdate:t})}}),r),userMessageAppended:e=>new i.Uq({messageStartedAtMs:e.startedAtMs,message:{case:"userMessageAppended",value:new i.v$T({userMessage:e})}}),partialToolCall:(e,t,r)=>new i.Uq({messageStartedAtMs:t.startedAtMs,message:{case:"partialToolCall",value:new i.fxF({callId:e,toolCall:t,modelCallId:r})}}),tokenDelta:e=>new i.Uq({message:{case:"tokenDelta",value:new i.Fyz({tokens:e})}}),summary:e=>new i.Uq({message:{case:"summary",value:new i.ECk({summary:e})}}),summaryStarted:()=>new i.Uq({message:{case:"summaryStarted",value:new i.lWT}}),heartbeat:()=>new i.Uq({message:{case:"heartbeat",value:new i.ih1}}),summaryCompleted:(e,t,r)=>new i.Uq({message:{case:"summaryCompleted",value:new i.ZM9({hookMessage:e,failed:t,fallback:r})}}),shellOutputDelta:e=>new i.Uq({message:{case:"shellOutputDelta",value:new i.Nn_({event:e})}}),modelCallCompleted:(e,t)=>new i.Uq({message:{case:"modelCallCompleted",value:new i.c2D({modelCallId:e,inputTokens:BigInt(t.inputTokens),outputTokens:BigInt(t.outputTokens),cacheReadTokens:BigInt(t.cacheReadTokens),cacheWriteTokens:BigInt(t.cacheWriteTokens),...void 0!==t.reasoningTokens?{reasoningTokens:BigInt(t.reasoningTokens)}:{}})}}),turnEnded(e,t){const r=e?.catalogCostCents;return new i.Uq({message:{case:"turnEnded",value:new i.lJj({...e?{inputTokens:BigInt(e.inputTokens),outputTokens:BigInt(e.outputTokens),cacheReadTokens:BigInt(e.cacheReadTokens),cacheWriteTokens:BigInt(e.cacheWriteTokens),reasoningTokens:BigInt(e.reasoningTokens??0)}:{},...void 0!==t?{endedAtMs:t}:{},...void 0!==r&&Number.isFinite(r)?{estimatedCost:new i.QVp({rawCostCents:r,chargedCents:r,source:i.nnk.CATALOG})}:{}})}})},stepStarted:e=>new i.Uq({message:{case:"stepStarted",value:new i.dwJ({stepId:BigInt(e)})}}),toolRequestsListed:e=>new i.Uq({message:{case:"toolRequestsListed",value:new i.BU$({callCount:Math.max(0,e)})}}),voiceCallUtterance:e=>new i.Uq({message:{case:"voiceCallUtterance",value:e}}),stepCompleted:(e,t)=>new i.Uq({message:{case:"stepCompleted",value:new i.Lrv({stepId:BigInt(e),stepDurationMs:BigInt(t)})}}),activeBranchChange:(e,t)=>new i.Uq({message:{case:"activeBranchChange",value:new i.PSN({path:e,branchName:t})}}),feedbackRequest:(e,t,r,n=[],o={})=>new i.Uq({message:{case:"feedbackRequest",value:new i.apn({requestId:e,canonicalModelName:t,categories:[...r],categoryGroups:[...n],title:o.title,negativeTitle:o.negativeTitle,commentPlaceholder:o.commentPlaceholder})}})};class c{constructor(e=0){this.nextId=e}next(){return this.nextId++}peekNext(){return this.nextId}observe(e){Number.isSafeInteger(e)&&e>=this.nextId&&(this.nextId=e+1)}}var l=r("../context/dist/logger.js"),u=r("../metrics/dist/index.js"),d=r("../proto/dist/generated/agent/v1/exec_pb.js"),h=r("../utils/dist/writable-iterable.js");const p=/https?:\/\/\S+/gi,f=/[)"'<>,.;:\]}]$/;function m(e){const{url:t,wrappers:r}=function(e){let t=e.length;for(;t>0&&f.test(e.slice(t-1,t));)t-=1;return{url:e.slice(0,t),wrappers:e.slice(t)}}(e),n=t.search(/[?#]/),o=-1===n?t:t.slice(0,n),s=o.indexOf("//")+2,i=o.slice(s).search(/[/?#]/),a=-1===i?o.length:s+i,c=o.lastIndexOf("@",a-1);return c<s?o+r:o.slice(0,s)+o.slice(c+1)+r}const g=/ \[git: ([^\]]*)\]/;function w(e,t,r){if("object"!=typeof t||null===t)return e;if(g.test(e))return e;const n=t,o=[];if("string"==typeof n.gitErrorCode&&n.gitErrorCode.length>0&&o.push(`gitErrorCode=${n.gitErrorCode}`),"number"==typeof n.exitCode&&Number.isFinite(n.exitCode)&&o.push(`exitCode=${n.exitCode}`),0===o.length)return e;let s=`${e} [git: ${o.join(" ")}]`;var i,a;return!0===r?.includeStderr&&"string"==typeof n.stderr&&n.stderr.length>0&&(s+=`\n--- git stderr ---\n${a=n.stderr,i=a.replace(p,m),i.length<=2048?i:`${i.slice(0,2048)}… [truncated to 2048 chars]`}`),s}var y=r("../context/dist/core.js");const v=(0,y.cF)(Symbol("machineProfile"),void 0),b=(0,l.h)("SimpleControlledExecManager"),S=(0,u.v5)("agent_exec.controlled.exec.duration_ms",{description:"Duration of controlled exec operations in milliseconds",labelNames:["exec_case"]}),k=(0,u.v5)("agent_exec.controlled.exec.machine_duration_ms",{description:"Duration of grep, shell and hook execs by coarse machine profile",labelNames:["exec_case","cpu_cores","ram_gb","defender_rt"]}),_=new Set(["grepArgs","shellStreamArgs","executeHookArgs"]),C=(0,u.Pu)("agent_exec.controlled.exec.success",{description:"Count of successful controlled exec operations",labelNames:["exec_case"]}),E=(0,u.Pu)("agent_exec.controlled.exec.error",{description:"Count of failed controlled exec operations",labelNames:["exec_case"]}),x={computerUseArgs:"Computer use is not enabled for this environment, so the Computer tool and the computerUse subagent cannot run here. Do not retry computer actions; verify with non-GUI methods (automated tests, shell commands) instead. (No computer-use handler is registered on this exec daemon.)",recordScreenArgs:"Screen recording is not enabled for this environment, so recordings cannot be captured here. Do not retry; skip the recording and present other evidence instead. (No record-screen handler is registered on this exec daemon.)"};class P extends Error{constructor(e){super(e),this.name="ControlledExecDisposedError"}}function I(e){return e instanceof P?"EXEC_BACKEND_UNAVAILABLE":e instanceof Error&&"AgentExecStreamStartTimeoutError"===e.name?"AGENT_EXEC_STREAM_START_TIMEOUT":void 0}class R{constructor(e,t,r){this.exec=e,this.deserializeArgs=t,this.serializeResult=r}handle(e,t){const r=this.deserializeArgs(t);if(void 0===r)return;const{id:n,args:o}=r;return async function*(r){const s=performance.now(),i=[],a=await r.exec.execute(e,o,{execId:t.execId,hookContextCollector:i,deliverAgentStoreConflictNotices:!0===t.acceptHookAdditionalContexts,recordAgentView:!0===t.recordAgentView,refuseUnreadChanges:!0===t.refuseUnreadChanges}),c=r.serializeResult(n,a);c.localExecutionTimeMs=Math.round(Math.max(0,performance.now()-s)),i.length>0&&(c.hookAdditionalContexts=i),yield c}(this)}}class T{constructor(e,t,r){this.exec=e,this.deserializeArgs=t,this.serializeStream=r}handle(e,t){const r=this.deserializeArgs(t);if(void 0===r)return;const{id:n,args:o}=r;return async function*(r){const s=performance.now(),i=[],a=r.exec.execute(e,o,{execId:t.execId,hookContextCollector:i,deliverAgentStoreConflictNotices:!0===t.acceptHookAdditionalContexts});try{for await(const e of a){const t=r.serializeStream(n,e);t.localExecutionTimeMs=Math.round(Math.max(0,performance.now()-s)),yield t}}finally{const e=i.filter((e=>"agentStoreConflict"===e.hookEventName));e.length>0&&(yield new d.yT({id:n,hookAdditionalContexts:e}))}}(this)}}class A{constructor(e){this.handlers=[],this.runningExecs=new Map;const t=e?.includeGitStderrInThrows??!1;this.includeGitStderrInThrows="function"==typeof t?t:()=>t,this.observeResults=e?.observeResults}startResultObserver(e,t,r){if(void 0!==this.observeResults)try{return this.observeResults(e,t,r)}catch{return}}register(e){this.handlers.push(e)}handleControlMessage(e){if("abort"===e.message.case){const t=e.message.value.id,r=this.runningExecs.get(t);r&&r()}}handle(e,t){const[r,n]=e.withCancel();this.runningExecs.set(t.id,n);const o=t.message.case??"unknown";for(const e of this.handlers){const s=e.handle(r,t);if(void 0===s)continue;const i=s,a=(0,h.Jt)();let c;const l=()=>{c=setTimeout((()=>{a.write(new d.$Y({message:{case:"heartbeat",value:new d.VA({id:t.id})}})).then(l).catch((()=>{}))}),3e3)};l();const u=performance.now(),p=this.startResultObserver(r,o,t);return(async()=>{try{for await(const e of i){if(void 0!==p&&e instanceof d.yT)try{p.message(e)}catch{}await a.write(e)}await a.write(new d.$Y({message:{case:"streamClose",value:new d.D9({id:t.id})}})),C.increment(r,1,{exec_case:o})}catch(e){if(e instanceof h.W2)return;E.increment(r,1,{exec_case:o}),await a.write(new d.$Y({message:{case:"throw",value:new d.Fu({id:t.id,error:e instanceof Error?w(e.message,e,{includeStderr:this.includeGitStderrInThrows()}):"Unknown error",stackTrace:e instanceof Error?e.stack:void 0,errorCode:I(e)})}}))}finally{if(void 0!==p)try{p.done()}catch{}const e=performance.now()-u;if(S.histogram(r,e,{exec_case:o}),_.has(o)){const t=r.get(v)?.();void 0!==t&&k.histogram(r,e,{exec_case:o,...t})}clearTimeout(c),a.close(),this.runningExecs.delete(t.id),n()}})(),a}this.runningExecs.delete(t.id),n();const s=t.message.case,i=(void 0===s?void 0:x[s])??`No handler found for server message of type ${s}`;return b.error(e,i,{messageCase:s}),E.increment(e,1,{exec_case:o}),async function*(){yield new d.$Y({message:{case:"throw",value:new d.Fu({id:t.id,error:i})}}),yield new d.$Y({message:{case:"streamClose",value:new d.D9({id:t.id})}})}()}static fromResources(e,t){const r=new A(t);for(const[t,n]of e.entries())t.registerControlledImplementation(n,r);return r}}var $=r("../context/dist/otel.js");async function M(e){const t=e[Symbol.asyncIterator](),r=await t.next();if(r.done)return;const n={async*[Symbol.asyncIterator](){for(;;){const e=await t.next();if(e.done)return;yield e.value}}};return{firstItem:r.value,rest:n}}const D=(0,y.cF)(Symbol("agentExec.remoteExecResultObserverFactory"),void 0),O={message(){},[Symbol.dispose](){}};function F(e){const t=e.get(D);if(void 0===t)return O;let r;try{r=t(e)}catch{return O}return void 0===r?O:{message(e){try{r?.message(e)}catch{r=void 0}},[Symbol.dispose](){const e=r;r=void 0;try{e?.end()}catch{}}}}var N=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},L=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const j=(0,l.h)("ExecutorResource"),U=(0,u.Pu)("agent_exec.hook_additional_context.delivered",{description:"Hook additional_context carriers drained into the caller collector",labelNames:["hook_event_name"]});class B{constructor(e,t,r){this.execManager=e,this.serializeArgs=t,this.deserializeResult=r}async execute(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=N(n,(0,$.VI)(e.withName("ExecutorResource.execute")),!1),s=o.ctx;void 0!==r?.execId&&o.span.setAttribute("exec.id",r.execId);const i=(0,$.mJ)(s),a=i?new d.Kg(i):void 0,c=this.execManager.createExecInstance(s,(e=>{const n=this.serializeArgs(e,t);return new d.Ye({id:n.id,message:n.message,execId:r?.execId,machineId:r?.machineId,spanContext:a,acceptHookAdditionalContexts:void 0!==r?.hookContextCollector,recordAgentView:r?.recordAgentView,refuseUnreadChanges:r?.refuseUnreadChanges})})),l=await M(c);if(void 0===l)throw new Error("No exec result");let{firstItem:u,rest:h}=l;const p=N(n,F(s),!1),f=e=>{if(p.message(e),void 0!==r?.hookContextCollector&&e.hookAdditionalContexts.length>0){r.hookContextCollector.push(...e.hookAdditionalContexts);for(const t of e.hookAdditionalContexts)U.increment(s,1,{hook_event_name:t.hookEventName})}};f(u);let m=this.deserializeResult(u);for(;void 0===m;){const e=await M(h);if(void 0===e)throw new Error("No result value");u=e.firstItem,h=e.rest,f(u),m=this.deserializeResult(u)}return(async()=>{try{for await(const e of h)f(e)}catch(e){j.info(s,"Ignoring exec stream shutdown during detached drain",{error:e})}})().catch((()=>{})),m}catch(e){n.error=e,n.hasError=!0}finally{L(n)}}}class W{constructor(e,t,r){this.execManager=e,this.serializeArgs=t,this.deserializeStream=r}async*execute(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=N(n,(0,$.VI)(e.withName("StreamExecutorResource.execute")),!1).ctx,s=(0,$.mJ)(o),i=s?new d.Kg(s):void 0,a=this.execManager.createExecInstance(o,(e=>{const n=this.serializeArgs(e,t);return new d.Ye({id:n.id,message:n.message,execId:r?.execId,machineId:r?.machineId,spanContext:i,acceptHookAdditionalContexts:void 0!==r?.hookContextCollector||!0===r?.deliverAgentStoreConflictNotices})})),c=N(n,F(o),!1);for await(const e of a){c.message(e),void 0!==r?.hookContextCollector&&e.hookAdditionalContexts.length>0&&r.hookContextCollector.push(...e.hookAdditionalContexts);const t=this.deserializeStream(e);void 0!==t&&(yield t)}}catch(e){n.error=e,n.hasError=!0}finally{L(n)}}}function H(e){return Symbol.for(`@anysphere/agent-exec/resource/${e}`)}function q(e,t,r){return{name:e,symbol:H(e),remoteImplementation:t,registerControlledImplementation:r}}class z{constructor(e,t){this.resource=e,this.value=t}}function G(e,t){return[e,t]}function V(e,t){return t}class K{constructor(){this.resources=new Map}register(e,t){this.resources.set(e.symbol,new z(e,t))}get(e){return V(0,this.resources.get(e.symbol)?.value)}entries(){return Array.from(this.resources.values()).map((e=>[e.resource,e.value]))}}class J{constructor(e,t){this.remoteAccessor=e,this.localResources=new Map;for(const[e,r]of t)this.localResources.set(e.symbol,{resource:e,implementation:r})}get(e){const t=this.localResources.get(e.symbol);return t?V(0,t.implementation):this.remoteAccessor.get(e)}*entries(){for(const{resource:e,implementation:t}of this.localResources.values())yield[e,t];for(const e of this.remoteAccessor.entries())this.localResources.has(e[0].symbol)||(yield e)}}function Z(e){return function(t,r){return new d.Ye({id:t,message:{case:e,value:r}})}}function X(e){return t=>{if(t.message.case===e)return t.message.value}}function Q(e){return function(t,r){const n={case:e,value:r};return new d.yT({id:t,message:n})}}function Y(e){return function(t){if(t.message.case===e)return{id:t.id,args:t.message.value}}}const ee=q("shell-stream-executor",(e=>new W(e,Z("shellStreamArgs"),X("shellStream"))),((e,t)=>{t.register(new T(e,Y("shellStreamArgs"),Q("shellStream")))}));var te=r("../proto/dist/generated/agent/v1/kv_pb.js"),re=r("../agent-kv/dist/blob-store.js"),ne=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const oe=(0,l.h)("ControlledKvManager");function se(e,t,r){return e?(0,$.F)({traceId:e.traceId,spanId:e.spanId,traceFlags:e.traceFlags??1},t,r):r}function ie(e,t,r,n,o){o<=r||(0,$.xd)(e.withName(`${t}.slow`),{startTime:n,attributes:{durationMs:o,slowThresholdMs:r}},n+o)}const ae=(0,u.v5)("agent_kv.controlled.get_blob.duration_ms",{description:"Duration of ControlledKvManager getBlob operations in milliseconds"}),ce=(0,u.v5)("agent_kv.controlled.set_blob.duration_ms",{description:"Duration of ControlledKvManager setBlob operations in milliseconds"});class le{constructor(e,t,r,n={}){this.serverStream=e,this.clientStream=t,this.blobStore=r,this.options=n}async run(e){const t={stack:[],error:void 0,hasError:!1};try{const r=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(t,(0,$.VI)(e.withName("ControlledKvManager.run")),!1).ctx,n=new Set,o=e=>{n.add(e),e.finally((()=>{n.delete(e)}))};try{for await(const e of this.serverStream){const t=performance.now(),n=Date.now();switch(e.message.case){case"getBlobArgs":{const s=e.message.value.blobId;o((async()=>{const o=se(e.spanContext,"ControlledKvManager.getBlob",r);try{await(this.options.beforeGetBlob?.(o,s));const t=await this.blobStore.getBlob(o,s);await this.clientStream.write(new te.gm({id:e.id,message:{case:"getBlobResult",value:{blobData:t?(0,re.Fo)(t):void 0}}}))}catch(t){oe.error(o,"Error handling getBlob",t);const r=t instanceof Error?t.message:String(t);try{await this.clientStream.write(new te.gm({id:e.id,message:{case:"getBlobResult",value:{blobData:void 0,error:{message:r}}}}))}catch(e){oe.error(o,"Error writing failed getBlobResult",e)}}finally{const e=performance.now()-t;ae.histogram(o,e),ie(o,"ControlledKvManager.getBlob",50,n,e)}})());break}case"setBlobArgs":{const s=e.message.value.blobId,i=e.message.value.blobData;o((async()=>{const o=se(e.spanContext,"ControlledKvManager.setBlob",r);try{await this.blobStore.setBlob(o,s,i),await this.clientStream.write(new te.gm({id:e.id,message:{case:"setBlobResult",value:{error:void 0}}}))}catch(t){const r=t instanceof Error?t.message:String(t);try{await this.clientStream.write(new te.gm({id:e.id,message:{case:"setBlobResult",value:{error:{message:r}}}}))}catch(e){oe.error(o,"Error writing setBlobResult",e)}}finally{const e=performance.now()-t;ce.histogram(o,e),ie(o,"ControlledKvManager.setBlob",100,n,e)}})());break}}}}finally{await Promise.allSettled(n)}}catch(e){t.error=e,t.hasError=!0}finally{ne(t)}}}function ue(e){return e instanceof Error?{abortReasonType:"error",abortReasonName:e.name,abortReasonMessage:e.message}:"string"==typeof e?{abortReasonType:"string",abortReasonMessage:e}:void 0===e?{abortReasonType:"undefined"}:{abortReasonType:typeof e}}var de=r("../proto/dist/generated/agent/v1/agent_service_pb.js"),he=r("../proto/dist/generated/agent/v1/shell_exec_pb.js");Error;const pe={stateRestoreMs:"client_prep_state_restore_ms",rootPromptRestoreMs:"client_prep_root_prompt_restore_ms",requestContextMs:"client_prep_request_context_ms",systemPromptMs:"client_prep_system_prompt_ms",preTurnSnapshotMs:"client_prep_pre_turn_snapshot_ms",preTurnSnapshotWaitMs:"client_prep_pre_turn_snapshot_wait_ms",preTurnSnapshotBlobWritesMs:"client_prep_pre_turn_snapshot_blob_writes_ms",preTurnSnapshotSerializeMs:"client_prep_pre_turn_snapshot_serialize_ms",firstStepToFirstInvocationMs:"client_prep_first_step_to_first_invocation_ms",promptMessageCount:"client_prep_prompt_message_count",turnCount:"client_prep_turn_count"},fe=Object.keys(pe).filter((e=>e in pe));function me(e){const t={};for(const r of fe){const n=e[r];void 0!==n&&(t[r]=n)}return t}new WeakMap;var ge=r("../utils/dist/fresh-uuid.js"),we=r("@bufbuild/protobuf"),ye=r("@connectrpc/connect"),ve=r("../../node_modules/.pnpm/@connectrpc+connect@1.6.1_patch_hash=c9c7616ccfc0246b19c6537f56676d8501713cb6c94b440d13_c9bdc997d82622067cc922804d7b4f50/node_modules/@connectrpc/connect/dist/esm/protocol/async-iterable.js"),be=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class Se{constructor(e,t,r){this.checkpointStream=e,this.checkpointHandler=t,this.ctx=r}async run(){const e={stack:[],error:void 0,hasError:!1};try{const t=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(e,(0,$.VI)(this.ctx.withName("CheckpointController.run")),!1).ctx,r=[];for await(const e of this.checkpointStream){let n;try{n=this.checkpointHandler.handleCheckpoint(t,e.checkpoint,e.metadata)}catch(t){throw e.onSettled?.(),t}r.push(n),void 0!==e.onSettled&&n.then(e.onSettled,e.onSettled)}await Promise.all(r)}catch(t){e.error=t,e.hasError=!0}finally{be(e)}}}const ke=(0,l.h)("@anysphere/agent-client:checkpoint-store-waits");class _e{constructor(e={}){this.options=e,this.inFlight=new Map}noteRouted(e){const t=Ee(e.pendingToolCalls);if(0===t.size)return Ce;let r;const n=new Promise((e=>{r=e}));for(const e of t){let t=this.inFlight.get(e);void 0===t&&(t=new Set,this.inFlight.set(e,t)),t.add(n)}return()=>{for(const e of t){const t=this.inFlight.get(e);t?.delete(n),0===t?.size&&this.inFlight.delete(e)}r()}}storedBefore(e,t){const r=this.inFlight.get(t);if(void 0!==r){try{this.options.onExecHeld?.(t)}catch(t){ke.warn(e,"onExecHeldForCheckpointStore callback failed",{error:String(t)})}return Promise.all(r).then(Ce)}}}function Ce(){}function Ee(e){const t=new Set;for(const r of e){let e;try{e=JSON.parse(r)}catch{continue}const n=Pe(e)?e.content:void 0;if(!Array.isArray(n))continue;const o=n;for(const e of o)Pe(e)&&"tool-call"===e.type&&"string"==typeof e.toolCallId&&t.add(e.toolCallId)}return t}function xe(e){if("executeHookArgs"===e.message.case)return function(e){const t=e.request?.request;switch(t?.case){case"preToolUse":case"postToolUse":case"postToolUseFailure":return""===t.value.toolUseId?void 0:t.value.toolUseId;case"subagentStart":return""===t.value.toolCallId?void 0:t.value.toolCallId;default:return}}(e.message.value);const t=e.message.value;return Pe(t)&&"string"==typeof t.toolCallId&&""!==t.toolCallId?t.toolCallId:void 0}function Pe(e){return"object"==typeof e&&null!==e}const Ie=(0,l.h)("@anysphere/agent-client:exec-checkpoint-gate"),Re=new Set(["shellArgs","shellStreamArgs","backgroundShellSpawnArgs","forceBackgroundShellArgs","miniSweAgentBashArgs","writeArgs","deleteArgs","mcpArgs","readMcpResourceExecArgs","computerUseArgs","recordScreenArgs","subagentArgs","forceBackgroundSubagentArgs","executeHookArgs"]),Te=new Set(["userMessageAction","resumeAction","backgroundTaskCompletionAction","goalContinuationAction","subscriptionNotificationAction","executePlanAction","asyncAskQuestionCompletionAction"]);function Ae(e){const t=e.message.case;return void 0!==t&&Re.has(t)?xe(e):void 0}const $e=e=>e.replace(/[\r\n]/g,"");function Me(e){return{...void 0!==e.parentRequestId?{"x-parent-request-id":$e(e.parentRequestId)}:{},...void 0!==e.rootParentRequestId?{"x-root-parent-request-id":$e(e.rootParentRequestId)}:{},...void 0!==e.parentAgentToolCallId?{"x-parent-agent-tool-call-id":$e(e.parentAgentToolCallId)}:{},...!0===e.directMetaParentChildSubagent?{"x-direct-meta-parent-child-subagent":"true"}:{}}}const De="x-inference-authentication-jwt";function Oe(){const e=globalThis.process?.env,t=e?.INFERENCE_PROXY_JWT?.trim();return void 0===t||""===t||t.startsWith("$")?{}:{[De]:t}}class Fe extends Error{constructor(e,t){super(`This conversation's data is missing and can't be restored. Start a new chat to continue.${function(e){if(0===e.length)return"";const t=e.slice(0,3).map((e=>e.slice(0,12)));return` (${1===e.length?`missing blob ${t[0]}`:`${e.length} missing blobs: ${t.join(", ")}${e.length>t.length?", …":""}`})`}(e)}`,void 0!==t?.cause?{cause:t.cause}:void 0),this.isUsageError=!0,this.isBlobNotFound=!0,this.name="BlobNotFoundError",this.blobIdHexes=[...e]}}function Ne(e){return e instanceof Error&&(e instanceof Fe||"isBlobNotFound"in e&&!0===e.isBlobNotFound||"BlobNotFoundError"===e.name)}var Le=r("../proto/dist/generated/aiserver/v1/utils_pb.js"),je=r("zod/v4");const Ue="relayedAttemptFailure",Be=je.object({transport:je.boolean(),stallAborted:je.boolean(),errorName:je.string(),connectCode:je.number().optional(),connectCodeName:je.string().optional(),connectCause:je.object({code:je.union([je.string(),je.number()]).optional(),name:je.string().optional()}).optional(),transportFailureKind:je.string().optional(),loop:je.string().optional(),transportMode:je.string().optional()});function We(e){const t=e?.details?.additionalInfo[Ue];if(void 0!==t)try{const e=Be.safeParse(JSON.parse(t));return e.success?e.data:void 0}catch{return}}class He extends Error{constructor(e,t={}){super(e),Object.setPrototypeOf(this,new.target.prototype),this.cause=t.cause,this.requestId=t.requestId,this.displayInfo=t.displayInfo,this.isTransport=t.isTransport}get name(){return this.kind}}class qe extends He{get kind(){return"RetriableError"}}class ze extends He{constructor(e,t,r={}){super(e,r),this.action=t}get kind(){return"ActionRequiredError"}}class Ge extends He{get kind(){return"NonRetriableError"}}class Ve extends Ge{constructor(e){const t=`This turn's step limit (${e}) needs an in-process agent loop; the network client cannot send it.`;super(t,{displayInfo:{title:"Step limit not supported",detail:t,isRetryable:!1}}),this.maxSteps=e}}class Ke extends He{get kind(){return"CancelledError"}}const Je=new Set([Le.yM.NOT_LOGGED_IN,Le.yM.AGENT_REQUIRES_LOGIN,Le.yM.AUTH_TOKEN_NOT_FOUND,Le.yM.AUTH_TOKEN_EXPIRED,Le.yM.INVALID_AUTH_ID,Le.yM.UNAUTHORIZED,Le.yM.GITHUB_NO_USER_CREDENTIALS,Le.yM.GITHUB_USER_NO_ACCESS]),Ze=new Set([Le.yM.FREE_USER_USAGE_LIMIT,Le.yM.FREE_USER_RATE_LIMIT_EXCEEDED,Le.yM.PRO_USER_ONLY,Le.yM.PRO_USER_USAGE_LIMIT,Le.yM.PRO_USER_RATE_LIMIT_EXCEEDED,Le.yM.RATE_LIMITED,Le.yM.RATE_LIMITED_CHANGEABLE,Le.yM.GENERIC_RATE_LIMIT_EXCEEDED]),Xe=new Set([Le.yM.USAGE_PRICING_REQUIRED,Le.yM.USAGE_PRICING_REQUIRED_CHANGEABLE]),Qe=new Set([Le.yM.BAD_API_KEY,Le.yM.BAD_USER_API_KEY,Le.yM.OUTDATED_CLIENT]),Ye=new Set([Le.yM.USER_ABORTED_REQUEST,Le.yM.DEBOUNCED]),et=new Set([Le.yM.CUSTOM_MESSAGE]),tt=new Map([[ye.Code.PermissionDenied,"Permission Denied"]]),rt=["NGHTTP2","ECONNRESET","ECONNREFUSED","ETIMEDOUT","EPIPE","socket hang up","Premature close","UND_ERR_SOCKET","ERR_STREAM","protocol error","http/2 stream","ERR_HTTP2_SESSION_ERROR","Session closed with error code","connection aborted","PING timed out","HTTP/2 session not established","HTTP/2 peer not answering","refused to tunnel to","HTTP CONNECT through proxy","Could not connect to proxy"],nt=new Set(["ENOTFOUND","EAI_AGAIN","EAI_FAIL","ENODATA","ESERVFAIL","EHOSTUNREACH","ENETDOWN","ENETUNREACH","ECONNABORTED"]),ot=new RegExp(`\\b(${[...nt].join("|")})\\b`),st=["IMAGE_TOO_LARGE","MAX_TOKENS","CONVERSATION_TOO_LONG","CONTENT_POLICY","DEPRECATED","MAX_MODE_REQUIRED","MODEL_NO_LONGER_SUPPORTED","UNSUPPORTED_REGION","OUTDATED_CLIENT"],it="x-cursor-inference-request-error-type",at="AgentWebSocketDeliveryAmbiguousError";function ct(e,t={}){const{requestId:r}=t;if(e instanceof He)return e;if(lt(e))return function(e,t){const r=dt(e),n=r.code,o=ht(e),s=void 0===o?void 0:function(e){if(void 0===e.details?.additionalInfo[Ue])return e;const t=e.clone();return void 0!==t.details&&(delete t.details.additionalInfo[Ue],t.details.equals(new Le.ej)&&(t.details=void 0)),t}(o),i={title:s?.details?.title,detail:s?.details?.detail,isRetryable:s?.details?.isRetryable,connectCode:n,errorCode:s?.error,inferenceRequestErrorType:pt(r,it)??pt(e,it),errorDetails:s},a={cause:e,requestId:t,displayInfo:i,...!0===We(o)?.transport?{isTransport:!0}:{}};if(n===ye.Code.Canceled||n===ye.Code.Aborted)return bt(e)?new qe(e.message,a):new Ke(e.message,a);if(void 0!==s?.error){const t=s.error;if(Ye.has(t))return new Ke(wt(e,s),a);const r=s.details?.analyticsMetadata?.actionRequired;if(void 0!==r&&""!==r)return new ze(wt(e,s),r,a);if(void 0!==At(s))return new qe(wt(e,s),a);if(Je.has(t))return new ze(wt(e,s),"login",a);if(Ze.has(t))return new ze(wt(e,s),"upgrade",a);if(Xe.has(t))return new ze(wt(e,s),"payment",a);if(Qe.has(t))return new ze(wt(e,s),"config",a);if(et.has(t)&&!0!==s.details?.isRetryable)return new Ge(wt(e,s),a);if(!1===s.details?.isRetryable)return new Ge(wt(e,s),a)}if(n===ye.Code.Unauthenticated)return new ze(e.message,"login",{...a,displayInfo:ut(i,"Sign in required",r)});const c=gt(r);if(It.test(c))return new ze(e.message,"proxy_sign_in",{...a,displayInfo:{...i,title:"Proxy sign-in required",detail:`${c}. Please check your sign-in for this proxy and try again.`,isRetryable:!0}});if(Rt.test(c))return new ze(e.message,"proxy_blocked",{...a,displayInfo:{...i,title:"Connection blocked by proxy",detail:`${c}. Your proxy doesn't allow this connection. Please ask your network administrator to allow it and try again.`,isRetryable:!0}});const l=tt.get(n);return void 0===l||!0===s?.details?.isRetryable||bt(e)?new qe(e.message,a):new Ge(wt(e,s),{...a,displayInfo:ut(i,l,r)})}(e,r);const n=function(e){let t=e;for(let e=0;e<10;e++){if(null==t)return;if(Ne(t))return t;if("object"!=typeof t||!("cause"in t))return;t=t.cause}}(e);if(void 0!==n)return new Ge(n.message,{cause:e instanceof Error?e:void 0,requestId:r,displayInfo:{title:"Conversation data missing",detail:n.message,isRetryable:!1}});const o=function(e){const t=new Set;let r=e;for(;r instanceof Error&&!t.has(r);){if(r.name===yt)return r;t.add(r),r=r.cause}}(e);if(void 0!==o)return new Ge(o.message,{cause:e instanceof Error?e:void 0,requestId:r,displayInfo:{title:"Context summarization failed",detail:o.message,isRetryable:!1}});if(function(e){const t=new Set;let r=e;for(;r instanceof Error&&!t.has(r);){const e="code"in r?r.code:void 0,n="errcode"in r?r.errcode:void 0;if("ENOSPC"===e||"ERR_SQLITE_ERROR"===e&&"number"==typeof n&&13==(255&n))return!0;t.add(r),r=r.cause}return!1}(e))return new Ge(vt,{cause:e instanceof Error?e:void 0,requestId:r,displayInfo:{title:"Out of disk space",detail:vt,isRetryable:!1}});if(e instanceof Error){if("AbortError"===e.name)return new Ke(e.message,{cause:e,requestId:r});if(e.name===at)return new qe(e.message,{cause:e,requestId:r,isTransport:!0});if(bt(e))return new qe(e.message,{cause:e,requestId:r})}const s=e instanceof Error?e.message:String(e);return new qe(s,{cause:e instanceof Error?e:void 0,requestId:r})}function lt(e){return null!==e&&"object"==typeof e&&"code"in e&&"name"in e&&("ConnectError"===e.name||"rawMessage"in e&&"string"==typeof e.rawMessage&&"details"in e&&Array.isArray(e.details)&&"findDetails"in e&&"function"==typeof e.findDetails)}function ut(e,t,r){return{...e,title:e.title||t,detail:e.detail||gt(r),isRetryable:e.isRetryable??!1}}function dt(e){let t=e;for(let e=0;e<10&&t.code===ye.Code.Unknown;e++){const e=t.cause;if(!lt(e))break;t=e}return t}function ht(e){let t=e;for(let e=0;e<10&<(t);e++){try{const e=t.findDetails?.(Le.vj);if(void 0!==e&&e.length>0)return e[0]}catch{}t=t.cause}}function pt(e,t){const r=e.metadata;if(null===r||"object"!=typeof r||!("get"in r)||"function"!=typeof r.get)return;const n=r.get(t);return"string"==typeof n?n:void 0}function ft(e){let t=e;for(let e=0;e<10&&"object"==typeof t&&null!==t;e++){if(lt(t))return t;t="cause"in t?t.cause:void 0}}function mt(e){const t=ft(e);return void 0===t?void 0:dt(t)}function gt(e){const t=e.rawMessage;return"string"==typeof t?t:e.message.replace(/^\[[a-z_]+\] /,"")}function wt(e,t){if(t?.details){const{title:r,detail:n}=t.details;return r&&n?`${r} ${n}`:r||n||e.message}return e.message}const yt="SummaryPlaceholderRejectedError",vt="Out of disk space. Free some space and try again.";function bt(e){const t=new Set;let r=e;for(;r instanceof Error&&!t.has(r);){t.add(r);const e=`${r.name}: ${r.message}`;if(rt.some((t=>e.includes(t)))||ot.test(e))return!0;const n=r.code;if("string"==typeof n&&(rt.some((e=>n.includes(e)))||nt.has(n)))return!0;r=r.cause}return!1}function St(e){return rt.some((t=>e.includes(t)))||ot.test(e)}function kt(e){return e instanceof He&&e.cause instanceof Error?bt(e.cause):e instanceof Error?bt(e):"string"==typeof e&&St(e)}function _t(e){return void 0!==e&&e>0}function Ct(e){return e+1}function Et(e){return Object.defineProperty(e,"code",{value:"connection_stalled",enumerable:!0,configurable:!0}),e}function xt(e){const{cause:t,requestId:r,transportErrorRetries:n,connectCode:o}=e;return _t(n)?Et(new qe("Connection stalled repeatedly",{cause:t,requestId:r,displayInfo:{title:"Connection stalled",detail:`The connection stalled ${Ct(n)} times. Please check your network connection and try again.`,isRetryable:!0,connectCode:o}})):Et(new qe("Connection stalled",{cause:t,requestId:r,displayInfo:{title:"Connection stalled",detail:"The connection stalled. Please try again.",isRetryable:!0,connectCode:o}}))}const Pt=/^(?:Proxy \S+ refused to tunnel to |HTTP CONNECT through proxy \S+ failed: |Could not connect to proxy \S+: )/,It=/^Proxy \S+ refused to tunnel to \S+: 407\b/,Rt=/^Proxy \S+ refused to tunnel to \S+: 403\b/;function Tt(e){let t=e.cause;for(let e=0;e<10&&void 0!==t;e++){if(t instanceof Error&&"AbortError"===t.name)return!0;if(lt(t)&&(t.code===ye.Code.Canceled||t.code===ye.Code.Aborted))return!0;t=null!==t&&"object"==typeof t&&"cause"in t?t.cause:void 0}return!1}function At(e){const t=e?.details?.additionalInfo;if(e?.error!==Le.yM.RATE_LIMITED||"run_inference_novel_tokens"!==t?.kind||void 0===t.retryAfterMs)return;const r=Number(t.retryAfterMs);return Number.isFinite(r)&&r>=0?r:void 0}var $t=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},Mt=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Dt=(0,l.h)("@anysphere/agent-client:exec-controller");class Ot extends Error{constructor(e){super(e),this.name="LostConnection"}}class Ft{constructor(e,t,r,n){this.serverStream=e,this.clientStream=t,this.controlledExecManager=r,this.checkpointStoreWaits=n}async run(e){const t={stack:[],error:void 0,hasError:!1};try{$t(t,(0,$.VI)(e.withName("ClientExecController.run")),!1);const r=[],n=t=>{if((0,we.isMessage)(t,d.Nv))this.controlledExecManager.handleControlMessage(t);else{const n=this.execute(e,t);n.catch((()=>{})),r.push(n)}};let o,s,i=!1;try{try{for await(const t of this.serverStream){const r=(0,we.isMessage)(t,d.Nv)?void 0:xe(t),a=void 0===r?void 0:this.checkpointStoreWaits?.storedBefore(e,r);if(void 0===o&&void 0===a){n(t);continue}const c=(o??Promise.resolve()).then((async()=>{await a,(0,we.isMessage)(t,d.Nv)||!i&&!e.canceled?n(t):Dt.info(e,"Dropped an exec queued behind a checkpoint's store",{toolCallId:r})})).catch((e=>{s??={error:e}}));o=c,c.then((()=>{o===c&&(o=void 0)}))}}finally{i=!0}if(await o,void 0!==s)throw s.error;await Promise.all(r)}catch(e){if(e instanceof ye.ConnectError&&"protocol error: missing EndStreamResponse"===e.rawMessage)throw new Ot(e.message);if(e instanceof ye.ConnectError&&e.code===ye.Code.Aborted){const t=e.cause;if(t instanceof Error&&"code"in t&&"string"==typeof t.code&&t.code.includes("ERR_STREAM_WRITE_AFTER_END"))throw new Ot(e.message)}else{if(e instanceof h.W2)throw new Ot(e.message);if(e instanceof ye.ConnectError&&e.code===ye.Code.Internal){const t=e.cause;if(t instanceof Error&&t.message.includes("NGHTTP2_PROTOCOL_ERROR"))throw new Ot(e.message)}}throw e}}catch(e){t.error=e,t.hasError=!0}finally{Mt(t)}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{let n,o;if(t.spanContext){const r=t.spanContext;n=(0,$.V5)({traceId:r.traceId,spanId:r.spanId,traceFlags:r.traceFlags??1},"exec.handle",e),o=(0,$.fU)(n)}else n=e;$t(r,o?new $.r2(n,o):void 0,!1);const s=this.controlledExecManager.handle(n,t);for await(const e of s)await this.clientStream.write(e)}catch(e){r.error=e,r.hasError=!0}finally{Mt(r)}}}const Nt=(0,l.h)("@anysphere/agent-client:stall-detector"),Lt=e=>"number"==typeof e&&Number.isFinite(e)?e:void 0,jt={nal:"[NAL client stall detector]",local_loop:"[local-loop client stall detector]",module:"[module client stall detector]"},Ut=new Set(["http2","http1_sse","http1_poll","websocket"]);function Bt(e){return void 0===e?"unknown":Ut.has(e)?e:"other"}const Wt=(0,u.Pu)("agent_client.stream.stall.count",{description:"Number of bidirectional stream stalls detected",labelNames:["activity_type","message_type","loop","transport_mode"]}),Ht=(0,u.v5)("agent_client.stream.stall.duration_ms",{description:"Duration of stream stalls in milliseconds",labelNames:["activity_type","loop","transport_mode"]}),qt=(0,u.Pu)("agent_client.stream.did_stall",{description:"Number of streams that experienced at least one stall",labelNames:["loop","transport_mode"]}),zt=(0,u.Pu)("agent_client.stream.total",{description:"Total number of streams monitored",labelNames:["loop","transport_mode"]});class Gt{constructor(){this.handlers=new Map}track(e,t){return this.handlers.set(e,{name:e,state:"started",startedAt:Date.now()}),t.then((t=>{const r=this.handlers.get(e);return r&&(r.state="completed",r.endedAt=Date.now()),t})).catch((t=>{const r=this.handlers.get(e);throw r&&(r.state="errored",r.endedAt=Date.now(),r.error=t instanceof Error?t.message:String(t)),t}))}getHandlerStates(){const e=Date.now(),t={};for(const[r,n]of this.handlers)t[r]={state:n.state,durationMs:(n.endedAt??e)-n.startedAt,error:n.error};return t}}class Vt{constructor(e,t,r){this.lastActivityTime=performance.now(),this.lastMeaningfulActivityTime=performance.now(),this.hasLogged=!1,this.hasLoggedAdvisory=!1,this.hasLoggedHeartbeatOnly=!1,this.hasEverStalled=!1,this.paused=!1,this.disposed=!1,this.activityHistory=[],this.ctx=e,"number"==typeof t?(this.thresholdMs=t,this.advisoryThresholdMs=void 0,this.heartbeatOnlyThresholdMs=3*t,this.onStall=r,this.onStallCallback=void 0,this.handlerTracker=void 0,this.loop="nal",this.readTransportMode=void 0):(this.thresholdMs=t.thresholdMs,this.advisoryThresholdMs=t.advisoryThresholdMs,this.heartbeatOnlyThresholdMs=t.heartbeatOnlyThresholdMs??3*t.thresholdMs,this.onStall=t.onStall,this.onStallCallback=t.onStallCallback,this.handlerTracker=t.handlerTracker,this.loop=t.loop??"nal",this.readTransportMode=t.transportMode),this.logPrefix=jt[this.loop],this.startTimer(),this.startAdvisoryTimer(),this.startHeartbeatOnlyTimer(),this.onCtxSignalAbort=()=>{this.trackActivity("ctx.signal","abort"),this.abortedAt=performance.now(),this.emitLifecycleLog(`${this.logPrefix} Stream aborted while stall detector active`,"aborted")},e.signal.addEventListener("abort",this.onCtxSignalAbort)}metricLabels(){return{loop:this.loop,transport_mode:Bt(this.readTransportMode?.())}}trackActivity(e,t){const r={type:e,messageType:t};this.lastActivity=r,"inbound_message"===e?this.lastInboundMessage=r:"outbound_write"===e&&(this.lastOutboundMessage=r);const n=this.activityHistory.at(-1);n?.type===e&&n.messageType===t?n.repeat=(n.repeat??1)+1:(this.activityHistory.push(r),this.activityHistory.length>10&&this.activityHistory.shift())}reset(e="inbound_message",t,r=!0){if(this.trackActivity(e,t),"inbound_message"===e){const e=this.hasLogged,t=this.hasLoggedAdvisory,n=this.hasLoggedHeartbeatOnly;e&&(this.hasLogged=!1,this.emitLogAndMetric()),n&&r&&(this.hasLoggedHeartbeatOnly=!1),t&&(this.hasLoggedAdvisory=!1),this.lastActivityTime=performance.now(),r&&(this.lastMeaningfulActivityTime=performance.now()),void 0===this.timer&&this.startTimer(),void 0===this.advisoryTimer&&this.startAdvisoryTimer(),r&&void 0===this.heartbeatOnlyTimer&&this.startHeartbeatOnlyTimer()}}onStreamEnded(){this.trackActivity("stream","ended"),this.streamEndedAt=performance.now()}onClientSentHeartbeat(){this.lastClientSentHeartbeatAt=performance.now()}onServerSentHeartbeat(){this.lastServerSentHeartbeatAt=performance.now()}setPaused(e){if(!this.disposed&&e!==this.paused&&(this.paused=e,!e)){const e=performance.now();this.lastActivityTime=e,this.lastMeaningfulActivityTime=e,void 0===this.timer&&this.startTimer(),void 0===this.advisoryTimer&&this.startAdvisoryTimer(),void 0===this.heartbeatOnlyTimer&&this.startHeartbeatOnlyTimer()}}restartedAfterLoopGap(e,t){const r=performance.now(),n=r-e;return!(n<5e3||t>=e||(this.reportLoopGap(n,r-t),this.lastActivityTime=r,this.lastMeaningfulActivityTime=r,0))}reportLoopGap(e,t){try{Nt.info(this.ctx,`${this.logPrefix} Stall check ran late - the process was not running, its windows restart`,this.buildLogMetadata({late_ms:e,window_ms:t,stall_type:"loop_gap"}))}catch(e){console.error("Error in stall detection:",e)}}startTimer(){if(this.disposed||this.thresholdMs<=0||void 0!==this.timer)return;let e=0;const t=t=>{e=performance.now()+t,this.timer=setTimeout(r,t)},r=()=>{if(this.paused||this.restartedAfterLoopGap(e,this.lastActivityTime))return void t(this.thresholdMs);const r=this.thresholdMs-(performance.now()-this.lastActivityTime);if(r<=0)return this.timer=void 0,void this.onStallDetected("no_activity");t(r)};t(this.thresholdMs)}startAdvisoryTimer(){if(this.disposed||void 0===this.advisoryThresholdMs||this.advisoryThresholdMs<=0||void 0!==this.advisoryTimer)return;const e=this.advisoryThresholdMs;let t=0;const r=e=>{t=performance.now()+e,this.advisoryTimer=setTimeout(n,e)},n=()=>{if(this.paused||this.restartedAfterLoopGap(t,this.lastActivityTime))return void r(e);const n=e-(performance.now()-this.lastActivityTime);if(n<=0)return this.advisoryTimer=void 0,void this.onAdvisoryDetected();r(n)};r(e)}startHeartbeatOnlyTimer(){if(this.disposed||this.thresholdMs<=0||this.heartbeatOnlyThresholdMs<=0||void 0!==this.heartbeatOnlyTimer)return;let e=0;const t=t=>{e=performance.now()+t,this.heartbeatOnlyTimer=setTimeout(r,t)},r=()=>{if(this.paused||this.restartedAfterLoopGap(e,this.lastMeaningfulActivityTime))return void t(this.heartbeatOnlyThresholdMs);const r=this.heartbeatOnlyThresholdMs-(performance.now()-this.lastMeaningfulActivityTime);if(r<=0)return this.heartbeatOnlyTimer=void 0,void this.onStallDetected("heartbeat_only");t(r)};t(this.heartbeatOnlyThresholdMs)}buildLogMetadata(e){const t=this.ctx.get(En),r={...e};t?.modelDetails?.displayName&&(r.model_name=t.modelDetails.displayName);const n=performance.now();void 0!==this.abortedAt&&(r.aborted_ago_ms=n-this.abortedAt),void 0!==this.disposedAt&&(r.disposed_ago_ms=n-this.disposedAt),void 0!==this.lastClientSentHeartbeatAt&&(r.last_client_sent_heartbeat_ago_ms=n-this.lastClientSentHeartbeatAt),void 0!==this.lastServerSentHeartbeatAt&&(r.last_server_sent_heartbeat_ago_ms=n-this.lastServerSentHeartbeatAt),void 0!==this.streamEndedAt&&(r.stream_ended_ago_ms=n-this.streamEndedAt),this.lastInboundMessage&&(r.last_inbound_message_type=this.lastInboundMessage.messageType),this.lastOutboundMessage&&(r.last_outbound_message_type=this.lastOutboundMessage.messageType);const o=[];let s;for(let e=this.activityHistory.length-1;e>=0;e--){const{type:t,messageType:r,repeat:n}=this.activityHistory[e];s!==t&&(s?o.push(`[${t}]`):o.push(`[${t}] (MOST RECENT)`),s=t),o.push(`${r}${n?` (x${n})`:""}`)}return r.activities=o.join("\n"),{reqId:t?.requestId,loop:this.loop,stall:r}}onAdvisoryDetected(){if(this.hasLogged||this.hasLoggedAdvisory)return;if(void 0===this.advisoryThresholdMs||this.advisoryThresholdMs<=0)return;const e=performance.now()-this.lastActivityTime;e<this.advisoryThresholdMs||(this.hasLoggedAdvisory=!0,this.reportAdvisory(e,this.advisoryThresholdMs))}reportAdvisory(e,t){try{const r=this.buildLogMetadata({duration_ms:e,threshold_ms:t,stall_type:"advisory_no_activity"});Nt.warn(this.ctx,`${this.logPrefix} Advisory stall detected - no activity for advisory threshold period`,r)}catch(e){console.error("Error logging advisory stall:",e)}}onStallDetected(e){if("heartbeat_only"===e){const t=performance.now(),r=t-this.lastActivityTime,n=t-this.lastMeaningfulActivityTime;if(r<this.thresholdMs&&n>=this.heartbeatOnlyThresholdMs){if(this.hasLoggedHeartbeatOnly)return;this.hasLoggedHeartbeatOnly=!0,this.reportStall(e,n)}return}if(this.hasLogged)return;this.hasLogged=!0,this.hasLoggedAdvisory=!0;const t=performance.now()-this.lastActivityTime;this.reportStall(e,t)}reportStall(e,t){const r=this.lastActivity,n=this.lastInboundMessage,o=this.lastOutboundMessage,s=this.ctx.get(En);try{const i=this.buildLogMetadata({duration_ms:t,threshold_ms:"heartbeat_only"===e?this.heartbeatOnlyThresholdMs:this.thresholdMs,stall_type:e}),a="heartbeat_only"===e?`${this.logPrefix} Stream receiving heartbeats only - no meaningful data for threshold period`:`${this.logPrefix} Bidirectional stream stall detected - no activity for threshold period`;if(Nt.warn(this.ctx,a,i),Wt.increment(this.ctx,1,{activity_type:r?.type??"unknown",message_type:r?.messageType??"unknown",...this.metricLabels()}),this.hasEverStalled||(this.hasEverStalled=!0,qt.increment(this.ctx,1,this.metricLabels())),this.onStallCallback){const t=performance.now(),i={type:e,lastActivityAgoMs:t-this.lastActivityTime,lastMeaningfulActivityAgoMs:t-this.lastMeaningfulActivityTime,lastActivityType:r?.messageType,lastInboundMessageType:n?.messageType,lastOutboundMessageType:o?.messageType,requestId:s?.requestId,modelName:s?.modelDetails?.displayName,streamEnded:void 0!==this.streamEndedAt,aborted:void 0!==this.abortedAt,lastServerHeartbeatAgoMs:void 0!==this.lastServerSentHeartbeatAt?t-this.lastServerSentHeartbeatAt:void 0,lastClientHeartbeatAgoMs:void 0!==this.lastClientSentHeartbeatAt?t-this.lastClientSentHeartbeatAt:void 0,thresholdMs:"heartbeat_only"===e?this.heartbeatOnlyThresholdMs:this.thresholdMs,handlers:this.handlerTracker?.getHandlerStates(),loop:this.loop};try{this.onStallCallback(i)}catch(e){console.error("Error in stall callback:",e)}}}catch(e){console.error("Error in stall detection:",e)}try{this.onStall?.(function(e){const t=new DOMException(`the stall detector cut the stream: ${e}`,"AbortError");return Object.defineProperty(t,"cursorStallCut",{value:!0}),t}("heartbeat_only"===e?`heartbeats alone for ${this.heartbeatOnlyThresholdMs} ms`:`no activity for ${this.thresholdMs} ms`))}catch(e){console.error("Error in onStall callback:",e)}}emitLifecycleLog(e,t){const r=performance.now()-this.lastActivityTime;try{const n=this.buildLogMetadata({duration_ms:r,event_type:t});Nt.info(this.ctx,e,n)}catch(e){console.error("Error logging stream lifecycle:",e)}}emitLogAndMetric(){const e=performance.now()-this.lastActivityTime;this.emitLifecycleLog(`${this.logPrefix} Stream activity resumed after stall`,"recovered"),Ht.histogram(this.ctx,e,{activity_type:this.lastActivity?.type??"unknown",...this.metricLabels()})}[Symbol.dispose](){this.disposed||zt.increment(this.ctx,1,this.metricLabels()),this.disposed=!0,this.paused=!1,void 0!==this.timer&&(clearTimeout(this.timer),this.timer=void 0),void 0!==this.advisoryTimer&&(clearTimeout(this.advisoryTimer),this.advisoryTimer=void 0),void 0!==this.heartbeatOnlyTimer&&(clearTimeout(this.heartbeatOnlyTimer),this.heartbeatOnlyTimer=void 0),this.ctx.signal.removeEventListener("abort",this.onCtxSignalAbort),this.trackActivity("disposed","disposed"),this.disposedAt=performance.now(),this.emitLifecycleLog(`${this.logPrefix} Stream stall detector disposed`,"disposed")}}const Kt={now:()=>performance.now(),setTimeout(e,t){const r=setTimeout(e,t);return r.unref?.(),r},clearTimeout(e){clearTimeout(e)}},Jt=(0,u.v5)("agent_client.first_message.event_loop_max_lag_ms",{description:"Longest event-loop block between the network phase start and the first server message of a run's first attempt",labelNames:["loop","transport_mode","first_message_slow"]}),Zt=(0,u.v5)("agent_client.first_message.event_loop_total_lag_ms",{description:"Summed event-loop blocking between the network phase start and the first server message of a run's first attempt",labelNames:["loop","transport_mode","first_message_slow"]}),Xt=(0,u.v5)("agent_client.first_message.network_ms",{description:"Time from the network phase start to the first server message of a run's first attempt, on attempts that sampled event-loop lag",labelNames:["loop","transport_mode","first_message_slow"]});var Qt=r("../proto/dist/generated/agent/v1/ask_question_tool_pb.js"),Yt=r("../proto/dist/generated/agent/v1/create_plan_tool_pb.js"),er=r("../proto/dist/generated/agent/v1/pr_management_tool_pb.js"),tr=r("../proto/dist/generated/agent/v1/replace_env_tool_pb.js"),rr=r("../proto/dist/generated/agent/v1/setup_vm_environment_tool_pb.js"),nr=r("../proto/dist/generated/agent/v1/connect_scm_tool_pb.js"),or=r("../proto/dist/generated/agent/v1/generate_image_tool_pb.js"),sr=r("../proto/dist/generated/agent/v1/mcp_auth_tool_pb.js"),ir=r("../proto/dist/generated/agent/v1/switch_mode_tool_pb.js"),ar=r("../proto/dist/generated/agent/v1/web_fetch_tool_pb.js"),cr=r("../proto/dist/generated/agent/v1/web_search_tool_pb.js");class lr extends Error{constructor(e){super(`Deferred interaction response requested for query ${e.id} (${e.query.case??"unknown"})`),this.query=e,this.name="DeferredInteractionResponseError",Object.setPrototypeOf(this,new.target.prototype)}}const ur=e=>new i.Y5({id:e,result:{case:"webSearchRequestResponse",value:new cr.lI({result:{case:"approved",value:new cr.XJ}})}}),dr=(e,t)=>new i.Y5({id:e,result:{case:"webSearchRequestResponse",value:new cr.lI({result:{case:"rejected",value:new cr.yc({reason:t??""})}})}}),hr=e=>new i.Y5({id:e,result:{case:"webFetchRequestResponse",value:new ar.fS({result:{case:"approved",value:new ar.Hs}})}}),pr=(e,t)=>new i.Y5({id:e,result:{case:"webFetchRequestResponse",value:new ar.fS({result:{case:"rejected",value:new ar.m$({reason:t??""})}})}}),fr=(e,t)=>new i.Y5({id:e,result:{case:"askQuestionInteractionResponse",value:new i.zT({result:t})}}),mr=e=>new i.Y5({id:e,result:{case:"switchModeRequestResponse",value:new ir.w$({result:{case:"approved",value:new ir.q5}})}}),gr=(e,t)=>new i.Y5({id:e,result:{case:"switchModeRequestResponse",value:new ir.w$({result:{case:"rejected",value:new ir.rA({reason:t??""})}})}}),wr=(e,t)=>new i.Y5({id:e,result:{case:"createPlanRequestResponse",value:new Yt.gz({result:t})}}),yr=(e,t)=>new i.Y5({id:e,result:{case:"setupVmEnvironmentResult",value:t}}),vr=(e,t)=>new i.Y5({id:e,result:{case:"replaceEnvResult",value:t}}),br=(e,t)=>new i.Y5({id:e,result:{case:"prManagementResult",value:t}}),Sr=(e,t)=>new i.Y5({id:e,result:{case:"mcpAuthRequestResponse",value:new sr.h({result:{case:"rejected",value:new sr.OI({reason:t??"Authentication was rejected"})}})}}),kr=(e,t)=>new i.Y5({id:e,result:{case:"connectScmRequestResponse",value:new nr.qG({result:{case:"rejected",value:new nr.lB({reason:t??"Connecting GitHub was skipped"})}})}}),_r=(e,t)=>new i.Y5({id:e,result:{case:"generateImageRequestResponse",value:new or.vW({result:{case:"approved",value:new or.l3({description:t??""})}})}}),Cr=(e,t)=>new i.Y5({id:e,result:{case:"generateImageRequestResponse",value:new or.vW({result:{case:"rejected",value:new or.Uq({reason:t??""})}})}});class Er extends Error{constructor(e,t={}){super(e),this.name="InteractionListenerStreamClosedError",this.cause=t.cause,Object.setPrototypeOf(this,new.target.prototype)}}Er.telemetryName="InteractionListenerStreamClosedError";var xr=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Pr=(0,l.h)("ClientInteractionController"),Ir=new Set(["askQuestionInteractionQuery","switchModeRequestQuery","mcpAuthRequestQuery","connectScmRequestQuery"]);class Rr{constructor(e,t,r,n){this.interactionStream=e,this.interactionListener=t,this.queryResponseStream=r,this.stallSuspender=n,this.pendingHumanQueries=0}async run(e){const t={stack:[],error:void 0,hasError:!1};try{const r=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(t,(0,$.VI)(e.withName("ClientInteractionController.run")),!1);e=r.ctx;let n,o=Promise.resolve();for await(const t of this.interactionStream){const r=()=>"interactionQuery"===t.case?this.handleInteractionQuery(e,t.value):this.handleInteractionUpdate(e,t.value);o=o.then(r).catch((r=>{Pr.error(e,"Error handling interaction message",r,{messageCase:t.case}),n??=r}))}if(await o,void 0!==n)throw n}catch(e){t.error=e,t.hasError=!0}finally{xr(t)}}async handleInteractionUpdate(e,t){await this.interactionListener.sendUpdate(e,t)}handleInteractionQuery(e,t){const r=void 0!==t.query.case&&Ir.has(t.query.case);let n=!1;const o=()=>{r&&!n&&(n=!0,this.pendingHumanQueries--,0===this.pendingHumanQueries&&this.stallSuspender?.setPaused(!1))};r&&(this.pendingHumanQueries++,1===this.pendingHumanQueries&&this.stallSuspender?.setPaused(!0)),(async()=>this.interactionListener.query(e,t))().catch((r=>{const n=function(e,t){switch(e.query.case){case"webSearchRequestQuery":return dr(e.id,t);case"webFetchRequestQuery":return pr(e.id,t);case"askQuestionInteractionQuery":return fr(e.id,new Qt.tz({result:{case:"rejected",value:new Qt.ox({reason:t})}}));case"switchModeRequestQuery":return gr(e.id,t);case"createPlanRequestQuery":return wr(e.id,new Yt.bK({result:{case:"error",value:new Yt.iY({error:t})}}));case"setupVmEnvironmentArgs":return yr(e.id,new rr.r$({result:{case:"success",value:new rr.JH({})}}));case"replaceEnvArgs":return vr(e.id,new tr.dV({result:{case:"failure",value:new tr.uq({errorMessage:t,setupLogs:""})}}));case"prManagementRequestQuery":return br(e.id,new er.HL({result:{case:"error",value:new er.K$({error:t})}}));case"mcpAuthRequestQuery":return Sr(e.id,t);case"connectScmRequestQuery":return kr(e.id,t);case"generateImageRequestQuery":return Cr(e.id,t);case void 0:return;default:return e.query}}(t,"The client could not show this request to the user");if(!(n instanceof i.Y5))throw r;return Pr.error(e,"Error handling interaction query; answering with a fail-closed response",{queryCase:t.query.case,error:r}),n})).then((e=>(o(),this.queryResponseStream.write(e)))).catch((t=>{Pr.error(e,"Error handling interaction query",t)})).finally(o)}}async function Tr(e,t){let r;try{r=await e(t.signal)}catch(e){if(t.isCanceled())throw new Ke("User aborted request");throw new Ge("Failed to mint LLM Gateway credential",{cause:e instanceof Error?e:void 0,requestId:t.requestId})}if(void 0===r)throw new Ge("LLM Gateway credential minter returned no credential",{requestId:t.requestId});if(""===r.bearerToken.trim())throw new Ge("LLM Gateway credential minter returned an empty bearer token",{requestId:t.requestId});return new i.Ibo({bearerToken:r.bearerToken})}const Ar=q("request-context-executor",(e=>new B(e,Z("requestContextArgs"),X("requestContextResult"))),((e,t)=>{t.register(new R(e,Y("requestContextArgs"),Q("requestContextResult")))}));var $r=r("../agent-kv/dist/serde.js"),Mr=r("../proto/dist/generated/agent/v1/request_context_exec_pb.js"),Dr=r("../utils/dist/promise-extras.js");const Or=15728640,Fr=(0,u.Pu)("agent_client.request_context_blob.prepared",{description:"Prepared RequestContext blob references"}),Nr=(0,u.v5)("agent_client.request_context_blob.bytes",{description:"Serialized RequestContext bytes staged by the client"}),Lr=(0,u.v5)("agent_client.request_context_blob.preparation_ms",{description:"Time to hydrate, serialize, and hash RequestContext"});function jr(e){switch(e.action.case){case"userMessageAction":case"subscriptionNotificationAction":case"resumeAction":case"executePlanAction":return e.action.value;default:return}}class Ur{constructor(e,t=62914560){this.parent=e,this.maxTransientBytes=t,this.transientBlobs=new Map,this.persistedBlobIds=new Set,this.transientBytes=0}seed(e,t){return this.seedAll([{blobId:e,blobData:t}])}seedAll(e){const t=new Map;for(const{blobId:r,blobData:n}of e)t.set((0,$r.nj)(r),n.byteLength);let r=this.transientBytes;for(const[e,n]of t)r-=this.transientBlobs.get(e)?.byteLength??0,r+=n;if(r>this.maxTransientBytes)return!1;for(const{blobId:t,blobData:r}of e)this.transientBlobs.set((0,$r.nj)(t),r);return this.transientBytes=r,!0}has(e){return this.transientBlobs.has((0,$r.nj)(e))}hasAll(e){return e.every((e=>this.has(e)))}async getBlob(e,t){const r=(0,$r.nj)(t),n=this.transientBlobs.get(r);return void 0===n?await this.parent.getBlob(e,t):n}async persistForRemoteRead(e,t){const r=(0,$r.nj)(t),n=this.transientBlobs.get(r);void 0===n||this.persistedBlobIds.has(r)||(await(0,Dr.O$)((()=>this.parent.setBlob(e,t,n)),2),this.persistedBlobIds.add(r))}async setBlob(e,t,r){await this.parent.setBlob(e,t,r)}async setBlobLocallyOnly(e,t,r){await this.parent.setBlobLocallyOnly(e,t,r)}async flush(e){await this.parent.flush(e)}}async function Br({ctx:e,action:t,resources:r,blobStore:n,mode:o,maxBlobBytes:s,maxInlineDynamicBytes:i=1048576,notesSessionId:a}){const c=performance.now(),l=jr(t);if(void 0===l)return{kind:"not_applicable"};if("legacy"===o)return t.requestContextParts=void 0,{kind:"legacy"};if(void 0!==t.requestContextParts){const e=void 0===(u=t.requestContextParts)?[]:[u.rulesBlobId,u.skillsBlobId,u.subagentsBlobId,u.mcpsBlobId],r=void 0!==l.requestContext,s=e.length>0&&n.hasAll(e);if(r||s){const e=t.requestContextParts;return"ref_only"===o&&r&&s&&void 0!==e?.dynamicContext&&(l.requestContext=void 0),{kind:"already_prepared"}}}var u;t.requestContextParts=void 0;const d=void 0===l.requestContext,h=l.requestContext??await async function({ctx:e,resources:t,notesSessionId:r}){const n=t.get(Ar),o=await n.execute(e,new Mr._K({notesSessionId:r})),s="success"===o.result.case?o.result.value.requestContext:void 0;if(void 0===s)throw new Error(`Failed to compute request context: ${o.result.case}`);return s}({ctx:e,resources:r,notesSessionId:a}),p=Math.min(Math.max(0,s),Or),f=await async function({requestContext:e,mode:t,maxBlobBytes:r,maxInlineDynamicBytes:n}){const o=function(e){const t=e.clone();return t.rules=[],t.nonFileRules=[],t.cloudRule=void 0,t.agentSkills=[],t.skillOptions=void 0,t.customSubagents=[],t.tools=[],t.mcpInstructions=[],t.mcpFileSystemOptions=void 0,t.mcpMetaToolOptions=void 0,{dynamicContext:t,rules:new Mr.T3({rules:e.rules.map((e=>e.clone())),nonFileRules:e.nonFileRules.map((e=>e.clone())),cloudRule:e.cloudRule}),skills:new Mr.CB({agentSkills:e.agentSkills.map((e=>e.clone())),skillOptions:e.skillOptions?.clone()}),subagents:new Mr.yb({customSubagents:e.customSubagents.map((e=>e.clone()))}),mcps:new Mr.vB({tools:e.tools.map((e=>e.clone())),mcpInstructions:e.mcpInstructions.map((e=>e.clone())),mcpFileSystemOptions:e.mcpFileSystemOptions?.clone(),mcpMetaToolOptions:e.mcpMetaToolOptions?.clone()})}}(e),s="ref_only"===t?o.dynamicContext.toBinary().byteLength:void 0;if(void 0!==s&&s>n)return;const i=o.rules.toBinary(),a=o.skills.toBinary(),c=o.subagents.toBinary(),l=o.mcps.toBinary(),u=i.byteLength+a.byteLength+c.byteLength+l.byteLength;if(u>r)return;const[d,h,p,f]=await Promise.all([(0,re.Bk)(i),(0,re.Bk)(a),(0,re.Bk)(c),(0,re.Bk)(l)]),m=[{blobId:d,blobData:i},{blobId:h,blobData:a},{blobId:p,blobData:c},{blobId:f,blobData:l}],g=new Mr.sG({rulesBlobId:d,rulesByteLength:i.byteLength,skillsBlobId:h,skillsByteLength:a.byteLength,subagentsBlobId:p,subagentsByteLength:c.byteLength,mcpsBlobId:f,mcpsByteLength:l.byteLength,dynamicContext:"ref_only"===t?o.dynamicContext:void 0});if("dual"===t)return{kind:"dual",inlineContext:e,byteLength:u,parts:g};if(void 0===s)throw new Error("ref_only request context did not measure dynamic bytes");return{kind:"ref_only",stagedBlobs:m,byteLength:u,parts:g,dynamicByteLength:s}}({requestContext:h,mode:o,maxBlobBytes:p,maxInlineDynamicBytes:Math.min(Math.max(0,i),p)});if(void 0===f)return l.requestContext=h,t.requestContextParts=void 0,Fr.increment(e,1,{mode:o,outcome:"oversized"}),{kind:"oversized"};if("ref_only"===f.kind&&!n.seedAll(f.stagedBlobs))return l.requestContext=h,t.requestContextParts=void 0,Fr.increment(e,1,{mode:o,outcome:"transient_budget_exceeded"}),{kind:"transient_budget_exceeded"};l.requestContext="dual"===f.kind?f.inlineContext:void 0,t.requestContextParts=f.parts;const m=f.byteLength;return Fr.increment(e,1,{mode:o,outcome:d?"hydrated":"inline"}),Nr.histogram(e,m,{mode:o}),Lr.histogram(e,performance.now()-c,{mode:o}),{kind:"prepared",byteLength:m,hydrated:d,rulesByteLength:f.parts.rulesByteLength,skillsByteLength:f.parts.skillsByteLength,subagentsByteLength:f.parts.subagentsByteLength,mcpsByteLength:f.parts.mcpsByteLength,dynamicByteLength:"ref_only"===f.kind?f.dynamicByteLength:void 0}}function Wr(e){return Object.keys(e.fileContents).length>0}function Hr(e,t){return Object.assign(new(e.getType()),e,t)}function qr(e){return Hr(e,{fileContents:{}})}function zr(e){for(const[t]of e.entries())if(t.symbol===Ar.symbol)return e.get(Ar)}var Gr=r("../proto/dist/generated/agent/v1/cursor_rules_pb.js");const Vr=102400;function Kr(e){return"AGENTS.md"===e||"CLAUDE.md"===e||"CLAUDE.local.md"===e}function Jr({content:e,filename:t}){return Buffer.byteLength(e,"utf8")>Vr?function({content:e,filename:t}){const r=Buffer.from(e,"utf8");let n=Vr;for(;128==(192&r.readUInt8(n));)n--;const o=`[truncated: ${t} is ${Math.round(r.length/1024)} KB; only the first 100 KB is included]`;return`${r.subarray(0,n).toString("utf8")}\n\n${o}`}({content:e,filename:t}):e}function Zr(e){const t=e.trim();return"true"===t||"false"!==t&&(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t)}function Xr(e){const t=e.trimStart();if(!t.startsWith("---"))return null;const r=t.split("---").filter(Boolean);if(r.length<2)return null;const n=r[0].trim(),o=r.slice(1).join("---").trim(),s={};let i=null,a=null;for(const e of n.split("\n")){const t=e.replace(/\r$/,""),r=t.match(/^\s+-\s+(.*)$/);if(r&&a){let e=r[1].trim();(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1));const t=s[a];Array.isArray(t)&&t.push(e);continue}const n=t.startsWith(" ")||t.startsWith("\t");if(i&&n){const e=t.trim(),r=e.indexOf(":");if(-1===r)continue;const n=e.slice(0,r).trim(),o=e.slice(r+1).trim(),c=Zr(o),l=`${i}.${n}`;""===o?(s[l]=[],a=l):"metadata.environments"===l||"metadata.disabledEnvironments"===l||"metadata.scopedTo"===l?(s[l]=String(c).split(",").map((e=>e.trim())).filter(Boolean),a=null):(s[l]=c,a=null);continue}i=null,a=null;const o=t.indexOf(":");if(-1===o)continue;const c=t.slice(0,o).trim(),l=t.slice(o+1).trim();if(""===l&&"metadata"===c){i=c;continue}if("globs"===c&&""===l){s.globs=[],a="globs";continue}const u=Zr(l);s[c]="metadata.environments"!==c&&"metadata.disabledEnvironments"!==c&&"metadata.scopedTo"!==c?u:String(u).split(",").map((e=>e.trim())).filter(Boolean)}return{frontmatter:s,rawFrontmatter:`---\n${n}\n---`,body:o}}function Qr(e){const t=e.replace(/\\/g,"/").replace(/^[A-Za-z]:/,(e=>e.toLowerCase())),r=[];for(const e of t.split("/"))""!==e&&"."!==e&&(".."!==e?r.push(e):r.pop());return`${t.startsWith("/")?"/":""}${r.join("/")}`}function Yr(e,t){return"/"===t?e.length>1:e.startsWith(`${t}/`)}const en=[[".cursor","skills"],[".cursor","skills-cursor"],[".claude","skills"],[".claude","plugins"],[".codex","skills"],[".grok","skills"],[".agents","skills"],[".cursor","plugins"]];class tn{constructor(){this.allowed=!1}observeHeaders(e){this.allowed="1"===e.get("x-cursor-lazy-rule-bodies")}isAllowed(){return this.allowed}}function rn(e){if("success"!==e.result.case)return e;const t=e.result.value,r=t.requestContext;if(void 0===r)return e;const n=function(e){const t=e.env?.workspacePaths??[];let r=!1;const n=e.rules.map((e=>{if(!function(e,t){if(!0===e.bodyOmitted||0===e.content.length||void 0!==e.parseError||e.source!==Gr.gv.UNSPECIFIED||void 0!==e.plugin||void 0!==e.marketplace||void 0!==e.pluginId||void 0!==e.marketplaceId)return!1;if(0===e.scopedTo.length&&0===e.frontmatter.length&&e.content.trimStart().startsWith("---"))return!1;const r=Qr(e.fullPath),n=r.startsWith("/"),o=r.split("/").filter((e=>e.length>0)),s=o.at(-1);if(void 0===s||function(e){return"SKILL.md"===e.at(-1)||e.some(((t,r)=>en.some((([n,o])=>t===n&&e[r+1]===o))))}(o))return!1;const i=t.map(Qr);if(!i.some((e=>Yr(r,e))))return!1;const a=function(e,t){let r=e.length-1;for(let t=e.length-2;t>=0;t--)if(".cursor"===e[t]&&"rules"===e[t+1]){r=t;break}return`${t?"/":""}${e.slice(0,r).join("/")}`}(o,n),c=a!==`${n?"/":""}${o.slice(0,-1).join("/")}`,l=e.type?.type.case;return"fileGlobbed"===l?s.endsWith(".mdc")&&c:"global"===l&&!!(Kr(s)||s.endsWith(".mdc")&&c)&&!i.includes(a)&&i.some((e=>Yr(a,e)))}(e,t))return e;r=!0;const n=Object.assign(new(e.getType()),e);return n.content=e.content.split("\n").find((e=>e.trim().length>0))??"",n.bodyOmitted=!0,n}));return r?Object.assign(new(e.getType()),e,{rules:n}):e}(r);return n===r?e:new Mr._G({result:{case:"success",value:Object.assign(new(t.getType()),t,{requestContext:n})}})}function nn(e){return void 0!==e&&Number.isFinite(e)&&Number.isInteger(e)}function on(e,t){const{rulesByteLength:r,skillsByteLength:n}=e,{subagentsByteLength:o,mcpsByteLength:s}=e;if(!(nn(r)&&nn(n)&&nn(o)&&nn(s)))return;const i=t?.dynamicByteLength;return{bytes:r+n+o+s+(i??0),bytesSource:"blob_parts",rulesBytes:r,skillsBytes:n,mcpBytes:s,subagentsBytes:o,...nn(i)?{dynamicBytes:i}:{}}}const sn=["alpn_failure","poll_seqno_gap","append_fatal","http_464","http_404_unimplemented","socket_reset","stream_closed_early","idle_deadline","stall","other"],an=/\bHTTP (\d{3})\b/;function cn(e){const t=e.message;return"string"==typeof t?t:""}function ln(e){return e instanceof Error&&("AbortError"===e.name||e.name===at)}const un={serverCap:3,transportCap:10},dn={alpn_failure:"server",poll_seqno_gap:"server",append_fatal:"by_signature",http_464:"server",http_404_unimplemented:"server",socket_reset:"transport",stream_closed_early:"server",idle_deadline:"server",stall:"transport",other:"server"};function hn(e){return{action:"retry",countAsServerError:!0,countAsTransportError:!1,transportFailureKind:e}}function pn(e,t,r){const n=r.attemptRequestId,o=!0===t.endless,s=r.retriesEnabled||o,i=(e,n)=>!o&&(e>=n||void 0!==t.sharedCap&&r.serverErrorRetries+r.transportErrorRetries>=t.sharedCap);let a=e instanceof He?e:ct(e,{requestId:n});const c=a instanceof Ke&&("owner"===r.abortOrigin||function(e){const t=e.displayInfo?.errorCode;return void 0!==t&&Ye.has(t)}(a)),l="stall_detector"===r.abortOrigin&&!c&&(a instanceof Ke||a instanceof qe),u="owner"===r.abortOrigin&&a instanceof qe&&Tt(a),d=function(e,t,r){return t.stalled?"stall":t.userStop?"other":function(e,t={}){const r=function(e){const t=[],r=new Set;let n=e;for(;"object"==typeof n&&null!==n&&!r.has(n);)r.add(n),t.push(n),n="cause"in n?n.cause:void 0;return t}(e);if(r.some((e=>"cursorBidiAppendFatal"in e)))return"append_fatal";const n=r.map(cn),o=e=>n.some((t=>t.includes(e))),s=function(e){return mt(e)?.code}(e),i=void 0===t.transportMode;if(i&&s===ye.Code.Unavailable&&o("ALPN protocol failed to negotiate"))return"alpn_failure";if((i||"http1_poll"===t.transportMode)&&s===ye.Code.Unavailable&&o("Unexpected seqno"))return"poll_seqno_gap";const a=n.map((e=>an.exec(e)?.[1])).find((e=>void 0!==e));return i&&s===ye.Code.Unknown&&"464"===a?"http_464":i&&s===ye.Code.Unimplemented&&"404"===a?"http_404_unimplemented":s===ye.Code.DeadlineExceeded&&function(e){const t=ft(e);return void 0===t?void 0:ht(t)?.error}(e)===Le.yM.TIMEOUT?"idle_deadline":i&&s===ye.Code.Unknown&&o("unsupported content type null")?"stream_closed_early":kt(e)||function(e){return e instanceof Error&&"isTransport"in e&&!0===e.isTransport}(e)||r.some(ln)?"socket_reset":"other"}(e,r)}(e,{stalled:l,userStop:c||u},{transportMode:r.attemptTransportMode}),h=(e,t={})=>({action:"throw",error:e,...t,transportFailureKind:d}),p=(e,n,{immediateFirstRetry:o})=>s?i(r.transportErrorRetries,t.transportCap)?h(e(),{countAsTransportError:!0}):function(e,t){return{action:"retry",countAsServerError:!1,countAsTransportError:!0,transportFailureKind:e,...t?{noBackoff:!0}:{}}}(d,o&&0===r.transportErrorRetries):h(n(),{countAsTransportError:!0}),f=()=>({cause:a.cause,requestId:n,transportErrorRetries:r.transportErrorRetries,connectCode:a.displayInfo?.connectCode});if(l){if(s&&void 0!==r.stallRetryElapsedMs&&r.stallRetryElapsedMs>=18e4)return h(xt(f()),{countAsTransportError:!0});const e=p((()=>xt(f())),(()=>xt({...f(),transportErrorRetries:void 0})),{immediateFirstRetry:!1});return"retry"===e.action?{...e,stall:!0}:e}if(a instanceof Ke&&!c&&Tt(a)&&(a=new qe(a.message,{cause:a.cause,requestId:n,displayInfo:a.displayInfo,isTransport:!0})),u)return h(new Ke(a.message,{cause:a.cause,requestId:n,displayInfo:a.displayInfo}));if(!0===t.retryAllInference&&(a instanceof ze||a instanceof Ge)&&function(e){const t=e.displayInfo?.inferenceRequestErrorType;return void 0!==t&&!st.some((e=>e===t))}(a))return i(r.serverErrorRetries,t.serverCap)?h(a):hn(d);if(a instanceof Ke||a instanceof ze||a instanceof Ge)return h(a);const m=function(e){return At(e.displayInfo?.errorDetails)}(a);if(a instanceof qe&&void 0!==m){const e=(r.rateLimitRetryElapsedMs??0)+m;return!s||!o&&e>3e5?h(a):{action:"retry",countAsServerError:!1,countAsTransportError:!1,transportFailureKind:d,retryAfterMs:m,rateLimit:!0}}if(a instanceof qe&&(!0===a.isTransport||function(e,t){const r=dn[e];return"by_signature"===r?kt(t):"transport"===r}(d,a)||"owner"!==r.abortOrigin&&Tt(a))){const e=function(e){const t=e.displayInfo,r=t?.title,n=t?.detail;return r&&n?{...t,title:r,detail:n}:void 0}(a);return p((()=>function(e){const{cause:t,requestId:r,transportErrorRetries:n,connectCode:o,ownCopy:s}=e;if(void 0!==s)return new qe(_t(n)?"Connection failed repeatedly":"Connection failed",{cause:t,requestId:r,displayInfo:{...s,isRetryable:!0,connectCode:o??s.connectCode}});const i=function(e){const t=new Set;let r=e;for(;r instanceof Error&&!t.has(r);){t.add(r);const e=lt(r)?gt(r):r.message;if(Pt.test(e))return e;r=r.cause}}(t),a=void 0===i?"Please check your network connection and try again.":"Please check your proxy settings and try again.";return _t(n)?new qe("Connection failed repeatedly",{cause:t,requestId:r,displayInfo:{title:"Connection failed",detail:`${void 0===i?"":`${i}. `}The connection failed ${Ct(n)} times. ${a}`,isRetryable:!0,connectCode:o}}):new qe("Connection failed",{cause:t,requestId:r,displayInfo:{title:"Connection failed",detail:`${i??"The connection was interrupted"}. ${a}`,isRetryable:!0,connectCode:o}})}({...f(),...void 0===e?{}:{ownCopy:e}})),(()=>a),{immediateFirstRetry:!0})}return s?i(r.serverErrorRetries,t.serverCap)?h(function(e){const{classified:t,requestId:r,serverErrorRetries:n}=e,o=t.displayInfo;return new qe(t.message,{cause:t.cause,requestId:r,displayInfo:{...o,title:o?.title||"Server error",detail:o?.detail||`The server failed ${Ct(n)} times. Please try again, or contact support if the issue persists.`,isRetryable:!0}})}({classified:a,requestId:n,serverErrorRetries:r.serverErrorRetries})):hn(d):h(a)}var fn=r("../proto/dist/generated/agent/v1/mcp_pb.js");const mn=(0,y.cF)(Symbol("agentTransportTimingRecorder"),void 0),gn=(0,l.h)("@anysphere/agent-client:turn-runner"),wn=1e3,yn=6e4;async function vn(e,t,r){await new Promise(((n,o)=>{if(t?.aborted)return void o(new Ke("Cancelled during backoff"));const s=new AbortController,i=setTimeout(a,e);function a(){clearTimeout(i),t?.removeEventListener("abort",c),s.abort(),n()}function c(){clearTimeout(i),s.abort(),o(new Ke("Cancelled during backoff"))}t?.addEventListener("abort",c,{once:!0});try{r?.(s.signal)?.then(a,(()=>{}))}catch{}}))}function bn(e,t){return e.length===t.length&&e.every(((e,r)=>{const n=t[r];return void 0!==n&&e.byteLength===n.byteLength&&e.every(((e,t)=>e===n[t]))}))}function Sn(e){const{connectCode:t,connectCodeName:r,...n}=e;return void 0===r?n:{...n,connectCode:r}}async function kn(e){const{ctx:t,checkpointHandler:r,runOptions:n,requestId:o,hooks:s,cancellation:a}=e,c=e.originalRequestId??o;let l=wn;const u=async(r,o,s,i,a)=>{if(s||(l=wn),void 0!==e.backoff)return void await e.backoff(r,o,i.retryAfterMs);if(!0===i.rateLimit&&void 0!==i.retryAfterMs){const n=i.retryAfterMs+1e3*Math.random();return e.logging&&gn.info(t,`[${e.logging.tag}] Waiting out a rate limit`,{attempt:r,retryAfterMs:i.retryAfterMs,selectedDelayMs:n}),void await vn(n,o)}const c=s?function(e,t){const r=Math.min(3e5,3*e);return t??wn+(r-wn)*Math.random()}(l,n.fixedRetryDelayMs):function(e,t,r){const n=t?100:wn,o=r??Math.min(n*2**e,yn);return o+(void 0===r?.2*o*Math.random():0)}(r,n.isRunningInTest,n.fixedRetryDelayMs),u=function(e,t){if(void 0===t||t<=e)return e;const r=Math.min(t,yn),n=Math.min(r+.2*r*Math.random(),yn);return Math.max(e,n)}(c,i.retryAfterMs);u!==c&&e.logging&&gn.info(t,`[${e.logging.tag}] Waiting for Retry-After`,{attempt:r,retryAfterMs:i.retryAfterMs,computedDelayMs:c,selectedDelayMs:u,endlessRetries:s}),s&&(l=c,e.logging&&gn.info(t,`[${e.logging.tag}] Endless retry delay selected`,{selectedDelayMs:u,attempt:r,retryCategory:i.countAsServerError?"server":"transport",endlessRetries:s}));const{retryWake:d}=n;await vn(u,o,void 0===d?void 0:e=>d({error:a,delayMs:u,waitEnded:e}))};let d,h,p,f,m,g=e.state,w=e.action,y=0,v=o,b=0,S=0,k=!1,_=0;const C=()=>{k&&(n.onConnectionStateChange?.({state:"connected"}),k=!1)},E=e=>()=>{e===y&&(m=!0,C())},x=e=>({handleCheckpoint:async(t,n,o)=>{e===y&&(m=!0),await r.handleCheckpoint(t,n,o),e===y&&(d=n,h=o?.resumeEligibility??"eligible",C())},getLatestCheckpoint:()=>r.getLatestCheckpoint()});for(;;){if(t.canceled)throw a.toCancelledError(void 0,v);if(d=void 0,h=void 0,m=!1,s.beginAttempt?.({attempt:y,originalRequestId:c}),y>0?(v=(0,ge.C)(),await(n.onRetryStarting?.(y,{actionCase:w.action.case,conversationState:g,isResume:"resumeAction"===w.action.case,attemptRequestId:v})),e.logging&&gn.info(t,`[${e.logging.tag}] Retrying attempt ${y}`,{attempt:y,actionCase:w.action.case,requestId:v,originalRequestId:c}),"resumeAction"===w.action.case&&(await(n.onRetryResuming?.({checkpointState:g,nextAttempt:y,reason:"resume_action"})),e.logging&&gn.info(t,`[${e.logging.tag}] Resuming from checkpoint`,{nextAttempt:y,reason:"resume_action"}))):(e.logging&&gn.info(t,`[${e.logging.tag}] Initial request`,{attempt:y,actionCase:w.action.case,requestId:v}),!0===e.notifyInitialResume&&"resumeAction"===w.action.case&&(await(n.onRetryResuming?.({checkpointState:g,nextAttempt:y,reason:"resume_action"})),e.logging&&gn.info(t,`[${e.logging.tag}] Resuming from checkpoint`,{nextAttempt:y,reason:"resume_action"}))),t.canceled)throw a.toCancelledError(void 0,v);try{return await s.runAttempt({state:g,action:w,checkpointHandler:x(y),attempt:y,attemptRequestId:v,notifyConnected:C,notifyApplicationProgress:E(y)}),C(),void(e.logging&&gn.info(t,`[${e.logging.tag}] Request successful`,{attempt:y,actionCase:w.action.case,requestId:v,originalRequestId:c}))}catch(r){if(!0===a.shortCircuit?.(r))throw a.toCancelledError(r,v);const o=!0===n.endlessRetries?.(),C=e.nowMs?.()??Date.now();m&&(p=void 0,f=void 0);const E=void 0===p?void 0:C-p,x=void 0===f?void 0:C-f;let R=s.classify(r,{attempt:y,attemptRequestId:v,originalRequestId:c,serverErrorRetries:b,transportErrorRetries:S,stallRetryElapsedMs:E,rateLimitRetryElapsedMs:x,endlessRetries:o});if("retry"===R.action){const n="resumeAction"===w.action.case||!0===e.noProgressGuardCountsReplays&&y>0;void 0!==d?_=0:n&&m&&(_++,_>=2&&(e.logging&&gn.warn(t,`[${e.logging.tag}] Resume attempts are streaming but not producing checkpoints; stopping automatic resume`,{noProgressResumeFailures:_,attempt:y,requestId:v,originalRequestId:c,errorName:r instanceof Error?r.name:typeof r}),R={action:"throw",error:new qe("Agent turn stopped after repeated resume attempts made no progress",{cause:r instanceof Error?r:void 0,requestId:v,displayInfo:{title:"Agent stopped retrying",detail:"The connection was interrupted repeatedly without saving progress, so the agent stopped to avoid repeating the same work. Retry to continue from the last saved state.",isRetryable:!0}}),transportFailureKind:R.transportFailureKind}))}const T={...void 0===R.transportFailureKind?{}:{transportFailureKind:R.transportFailureKind},...void 0===e.loop?{}:{loop:e.loop}},A=e.logging?.diagnostics?.(r);if(e.logging){const e="retry"===R.action?`RETRY (countAsServerError=${R.countAsServerError}, countAsTransportError=${R.countAsTransportError})`:`THROW ${R.error.kind}`;gn.warn(t,`[AGENT_ERROR_DIAGNOSTICS] requestId=${v} originalRequestId=${c} decision=${e}`,{decision:e,willRetry:"retry"===R.action,enableAgentRetries:n.enableAgentRetries??!1,endlessRetries:o,isRunningInTest:n.isRunningInTest??!1,serverErrorRetries:b,transportErrorRetries:S,attempt:y,requestId:v,originalRequestId:c,...T,...A})}if("throw"===R.action){if(0===y){const r={attempt:0,actionCase:w.action.case,error:R.error,requestId:v,originalRequestId:c,enableAgentRetries:!0===n.enableAgentRetries,endlessRetries:o,stallAborted:!1,abortSources:[]};try{await(n.onErrorNotRetried?.(s.buildNonRetriedErrorInfo?.(r)??r))}catch(r){e.logging&&gn.warn(t,`[${e.logging.tag}] onErrorNotRetried callback failed`,{error:String(r),requestId:v,originalRequestId:c})}}throw e.logging&&gn.warn(t,`[${e.logging.tag}] Error not retryable`,{...T,...A,attempt:y,actionCase:w.action.case,requestId:v,originalRequestId:c,errorName:R.error.name,...!0===e.logging.includeErrorObjects?{error:R.error}:{},serverErrorRetries:b,transportErrorRetries:S}),R.error}const $=y+1;if("ineligible_terminal_turn"===h)return void(e.logging&&gn.warn(t,`[${e.logging.tag}] Terminal checkpoint received before retryable error; completing without automatic resume`,{errorName:r instanceof Error?r.name:typeof r,errorMessage:r instanceof Error?r.message:String(r)}));!0!==R.immediate&&(n.onConnectionStateChange?.({state:"reconnecting",attempt:$,trigger:{...T,...s.reconnectTrigger?.(r,R,{originalRequestId:c,failedAttemptRequestId:v,nextAttempt:$})??{originatingRequestId:c,attemptRequestId:v}}}),k=!0),R.countAsServerError&&b++,R.countAsTransportError&&S++,!0===R.stall?p??=C:p=void 0,!0===R.rateLimit?f??=C:f=void 0,y=$,void 0!==d&&(I=d,bn((P=g).turns,I.turns)&&bn(P.rootPromptMessagesJson,I.rootPromptMessagesJson)||(l=wn),g=d,w=new i.QFf({action:{case:"resumeAction",value:new i.qKo}})),s.onRetryCommitted?.(),!0===R.immediate||!0===R.noBackoff&&void 0===R.retryAfterMs||await u(y,t.signal,o,R,r)}}var P,I}new Set(["textDelta","thinkingDelta","thinkingCompleted","partialToolCall","toolCallDelta","toolCallStarted","toolCallCompleted","tokenDelta"]);var _n=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},Cn=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const En=(0,y.cF)(Symbol("agentStreamMetadata"),void 0),xn=(0,l.h)("@anysphere/agent-client:abort"),Pn=(0,l.h)("@anysphere/agent-client:retry"),In=(0,l.h)("@anysphere/agent-client:request-context-blob");async function Rn({ctx:e,action:t,resources:r,blobStore:n,options:o,source:s,transportMode:i,notifyBytes:a}){!0===o.omitRequestContextFileContents&&function(e){const t=jr(e);if(void 0===t)return;const r=t.requestContext;void 0!==r&&Wr(r)&&(t.requestContext=qr(r));const n=e.requestContextParts,o=n?.dynamicContext;void 0!==n&&void 0!==o&&Wr(o)&&(e.requestContextParts=Hr(n,{dynamicContext:qr(o)}))}(t);try{const s=await Br({ctx:e,action:t,resources:r,blobStore:n,mode:i??o.requestContextBlobTransportMode??"legacy",maxBlobBytes:o.requestContextBlobMaxBytes??Or,maxInlineDynamicBytes:o.requestContextDynamicInlineMaxBytes??1048576,notesSessionId:o.conversationId});if(!0===a){const e=function({prepared:e,parts:t}){return"prepared"===e.kind?on(e,{dynamicByteLength:e.dynamicByteLength}):"already_prepared"===e.kind&&void 0!==t?on(t):void 0}({prepared:s,parts:t.requestContextParts});void 0!==e&&o.onRequestContextBytes?.(e)}}catch(r){t.requestContextParts=void 0,In.warn(e,"Failed to prepare request context blob; using legacy fallback",{actionCase:t.action.case,errorName:r instanceof Error?r.name:typeof r,source:s})}}const Tn=e=>{const t=[];switch(t.push(e.message.case),e.message.case){case"conversationAction":t.push(e.message.value.action.case);break;case"execClientMessage":case"execClientControlMessage":case"kvClientMessage":case"execServerMessage":case"execServerControlMessage":t.push(e.message.value.message.case);break;case"interactionResponse":t.push(e.message.value.result.case);break;case"interactionUpdate":switch(t.push(e.message.value.message.case),e.message.value.message.case){case"partialToolCall":case"toolCallCompleted":case"toolCallStarted":t.push(e.message.value.message.value.toolCall?.tool.case);break;case"toolCallDelta":t.push(e.message.value.message.value.toolCallDelta?.delta.case)}break;case"interactionQuery":t.push(e.message.value.query.case)}return t.filter((e=>void 0!==e)).join(":")};function An(e){if(e instanceof Error)return`${e.name}: ${e.message}`;if("string"==typeof e)return e;if("number"==typeof e||"boolean"==typeof e||"bigint"==typeof e)return String(e);if(null==e)return String(e);try{const t=JSON.stringify(e);return"string"==typeof t?t:"unserializable error"}catch{return"unserializable error"}}async function $n(e,t,r){for await(const n of t)switch(n.event.case){case"stdout":await r.sendUpdate(e,a.shellOutputDelta({case:"stdout",value:new he.o0({data:n.event.value.data})}));break;case"stderr":await r.sendUpdate(e,a.shellOutputDelta({case:"stderr",value:new he.Db({data:n.event.value.data})}));break;case"exit":await r.sendUpdate(e,a.shellOutputDelta({case:"exit",value:new he.vb({code:n.event.value.code,aborted:n.event.value.aborted})}))}}function Mn(e){return e instanceof Error?e.name:void 0}class Dn{constructor(e,t,r={}){this.client=e,this.endpointUrl=t,this.options=r,this.hasStartedStream=!1}async run(e,t,r,n,o,s,i,a,l,u,d){const h={stack:[],error:void 0,hasError:!1};try{if(void 0!==d.maxSteps)throw new Ve(d.maxSteps);const g=!0===d.omitRequestContextFileContents?function(e){const t=zr(e);return void 0===t?e:new J(e,[G(Ar,{execute:async(e,r,n)=>function(e){if("success"!==e.result.case)return e;const t=e.result.value,r=t.requestContext;return void 0!==r&&Wr(r)?new Mr._G({result:{case:"success",value:Hr(t,{requestContext:qr(r)})}}):e}(await t.execute(e,r,n))})])}(s):s,w=!0===d.lazyFileScopedRuleBodies?new tn:void 0,y=void 0===w?g:function(e,t){const r=zr(e);return void 0===r?e:new J(e,[G(Ar,{execute:async(e,n,o)=>{const s=await r.execute(e,n,o);return void 0!==o?.execId&&t.isAllowed()?rn(s):s}})])}(g,w),v=void 0===w?d:{...d,onHeader:e=>{w.observeHeaders(e),d.onHeader?.(e)}},b=new Ur(i),S=d.generationUUID??(0,ge.C)(),k=new c,_=(m=k,p=o,f=e=>{m.observe(e.id)},{sendUpdate:(e,t)=>p.sendUpdate(e,t),query:(e,t)=>(f(t),p.query(e,t)),enqueuePostTurnEndedWork:p.enqueuePostTurnEndedWork?.bind(p),flushPostTurnEndedWork:p.flushPostTurnEndedWork?.bind(p)}),C={sources:[],abortReasonName:void 0,abortReasonMessage:void 0},E=e=>{const t=function(e){const t=ft(e);return void 0===t?void 0:We(ht(t))}(e),r=C.sources.includes("stall_detector")||!0===t?.stallAborted,n=(o=C.sources).some((e=>"stall_detector"!==e))?"owner":o.includes("stall_detector")?"stall_detector":"none";var o;const s=function(e){const t={errorName:Mn(e)},r=mt(e);if(void 0===r)return t;const n=function(e){if(null!==e&&"object"==typeof e&&"cause"in e)return e.cause}(r),o=function(e){if(null===e||"object"!=typeof e||!("code"in e))return;const t=e.code;return"string"==typeof t||"number"==typeof t?t:void 0}(n),s=Mn(n);return{...t,underlyingConnectError:{code:r.code,codeName:ye.Code[r.code],cause:void 0!==o||void 0!==s?{code:o,name:s}:void 0}}}(e),i=s.underlyingConnectError;return{relayed:t,stallAborted:r,abortOrigin:"none"===n&&r?"stall_detector":n,reading:void 0===t?{errorName:s.errorName,connectCode:i?.code,connectCodeName:i?.codeName,connectCause:i?.cause,abortSources:[...C.sources],abortReasonName:C.abortReasonName,...void 0===i?{}:{underlyingConnectError:i}}:{errorName:t.errorName,connectCode:t.connectCode,connectCodeName:t.connectCodeName,connectCause:t.connectCause,...(a=t.loop,"nal"===a||"local_loop"===a||"module"===a?{loop:t.loop}:{}),...void 0===t.transportMode?{}:{transportMode:t.transportMode}}};var a};let x=0,P=0;const I={networkPhaseStartedAt:performance.now()};try{d.onNetworkPhaseStart?.()}catch(t){Pn.warn(e,"onNetworkPhaseStart callback failed",{error:String(t)})}const R=_n(h,(0,$.VI)(e.withName("networkPhase")),!1);e=R.ctx,await(0,$.MG)(R.span,(()=>kn({ctx:e,state:t,action:r,checkpointHandler:l,runOptions:d,requestId:S,loop:this.options.loop??"nal",notifyInitialResume:!0,logging:{...this.options.retryLogging??{tag:"nal_agent_retries",includeErrorObjects:!0},diagnostics:e=>{const{stallAborted:t,abortOrigin:r,reading:n}=E(e);return{stallAborted:t,abortOrigin:r,...Sn(n)}}},cancellation:{toCancelledError:()=>new Ke("Request cancelled")},hooks:{beginAttempt:()=>{C.sources=[],C.abortReasonName=void 0,C.abortReasonMessage=void 0,P=++x},runAttempt:async({state:t,action:r,checkpointHandler:o,attempt:s,attemptRequestId:i,notifyConnected:c,notifyApplicationProgress:l})=>{const d=function(e,t,r){return{sendUpdate:async(n,o)=>{if(t===r())return e.sendUpdate(n,o);"toolCallCompleted"===o.message?.case&&Pn.warn(n,"nal.await_stall.stale_completion_dropped",{attemptGen:t,currentGen:r()})},query:async(n,o)=>{if(t!==r())throw new Ke("Stale query from previous attempt");return e.query(n,o)},enqueuePostTurnEndedWork:e.enqueuePostTurnEndedWork?t=>e.enqueuePostTurnEndedWork(t):void 0,flushPostTurnEndedWork:e.flushPostTurnEndedWork?t=>e.flushPostTurnEndedWork(t):void 0}}(_,P,(()=>x));await this.runInternal(e,t,r,n,d,y,b,a,o,u,v,i,S,k,C,c,l,s,I)},classify:(e,t)=>{const{abortOrigin:r,relayed:n}=E(e),o=pn(e,function(e,t,r=un){const n=function(e){if(void 0!==e&&Number.isFinite(e))return Math.min(Math.max(Math.floor(e),1),100)-1}(e.maxRetries),o=void 0===n?r:{serverCap:n,transportCap:n};return{serverCap:o.serverCap,transportCap:!0===e.isRunningInTest?Math.min(o.transportCap,2):o.transportCap,...void 0===n?{}:{sharedCap:n},endless:t.endlessRetries,retryAllInference:!0===e.retryAllInferenceErrors}}(d,t),{...t,retriesEnabled:d.enableAgentRetries??!1,abortOrigin:r}),s=n?.transportFailureKind;return"string"==typeof(i=s)&&sn.includes(i)?{...o,transportFailureKind:s}:o;var i},buildNonRetriedErrorInfo:e=>({...e,enableAgentRetries:d.enableAgentRetries??!1,stallAborted:E(e.error).stallAborted,abortSources:[...C.sources],abortReasonName:C.abortReasonName,abortReasonMessage:C.abortReasonMessage}),reconnectTrigger:(e,t,r)=>{const{relayed:n,stallAborted:o,reading:s}=E(e),i=e instanceof He?e:ct(e,{requestId:r.failedAttemptRequestId});return{errorClass:n?.errorName??i.name,connectCode:s.connectCode,connectCodeName:s.connectCodeName,errorCode:i.displayInfo?.errorCode,countAsServerError:t.countAsServerError,countAsTransportError:t.countAsTransportError,stallAborted:o,originatingRequestId:r.originalRequestId,attemptRequestId:r.failedAttemptRequestId,...void 0===s.transportMode?{}:{transportMode:s.transportMode},endpointUrl:this.endpointUrl}},onRetryCommitted:()=>a.reopen()}})))}catch(e){h.error=e,h.hasError=!0}finally{Cn(h)}var p,f,m}async runInternal(e,t,r,n,o,s,a,c,l,u,p,f,m,g,w,y,v,b,S,k="agent.request.attempt"){const _={stack:[],error:void 0,hasError:!1};try{const x=e;e=this.options.prepareAttemptContext?.(e,{attempt:b,attemptRequestId:f,originalRequestId:m,runOptions:p})??e;const P=_n(_,(0,$.VI)(e.withName(k)),!1);P.span.setAttribute("agent.attempt",b),P.span.setAttribute("agent.request_id",f),P.span.setAttribute("agent.original_request_id",m),e=P.ctx,e=(0,$.Mf)(e,"agent.request_id",f),e=(e=(0,$.Mf)(e,"agent.original_request_id",m)).with(En,{requestId:f,rootParentRequestId:p.rootParentRequestId,modelDetails:n});const I=new Set(w.sources);let R=void 0!==w.abortReasonName||void 0!==w.abortReasonMessage;const T=(t,r)=>{if(I.has(t))return;I.add(t),w.sources=[...I];const n=(e=>{const t="string"==typeof e?.abortReasonName?e.abortReasonName:void 0,r="string"==typeof e?.abortReasonMessage?e.abortReasonMessage:void 0;if(void 0!==t||void 0!==r)return{abortReasonName:t,abortReasonMessage:r}})(r);R||void 0===n||(R=!0,w.abortReasonName=n.abortReasonName,w.abortReasonMessage=n.abortReasonMessage),xn.error(e,"Agent client stream abort",new Error(t),{abortSource:t,requestId:f,conversationId:p.conversationId,...r??{}})};if(e.signal.aborted){const t=e.signal.reason;T("ctx_signal_abort",ue(t))}else e.signal.addEventListener("abort",(()=>{const t=e.signal.reason;T("ctx_signal_abort",ue(t))}),{once:!0});const[M,D]=e.withCancel();if(c.signal?.aborted){const e=c.signal?.reason;T("conversation_action_abort",ue(e)),D()}else c.signal?.addEventListener("abort",(()=>{const e=c.signal?.reason;T("conversation_action_abort",ue(e)),D()}),{once:!0});if(e.canceled||M.canceled){const t={ctxCanceled:e.canceled,softCancel:M.canceled};throw T("pre_run_cancel",t),new Ke("User aborted request")}const O=(0,$.VI)(e.withName("createControlledExecManager")),F=A.fromResources(s);O[Symbol.dispose]();const[N,L]=e.withCancel(),j=new Gt,{failThresholdMs:U,advisoryThresholdMs:B}=function(e,t){const r=Lt(e?.failTimeoutMs)??3e4,n=r>0&&!0!==t?.isRunningInTest?Math.max(r,2e4):r,o=Lt(e?.advisoryTimeoutMs);return{failThresholdMs:n,advisoryThresholdMs:void 0!==o&&o>0&&(n<=0||o<n)?o:void 0}}(p.stallDetectorConfig,{isRunningInTest:p.isRunningInTest});let W;const H=_n(_,new Vt(N,{thresholdMs:U,advisoryThresholdMs:B,loop:this.options.loop,transportMode:()=>W,onStall:e=>{T("stall_detector",{thresholdMs:U,advisoryThresholdMs:B}),L(e)},onStallCallback:p.onStall,handlerTracker:j}),!1);let q,z,G;const V=(0,ve.Jt)(),K=new h.F8(V,(e=>(H.reset("outbound_write",Tn(e)),e))),J=_n(_,(0,$.VI)(e.withName("writeInitialRequest")),!1);let Z;const X=function(e){return new fn.Or({mcpTools:e.map((e=>({name:e.name,providerIdentifier:e.providerIdentifier,toolName:e.toolName,description:e.description,inputSchema:e.inputSchema?we.Value.fromJson(e.inputSchema):void 0,outputSchemaJson:void 0!==e.outputSchema?JSON.stringify(e.outputSchema):void 0})))})}(u),Q=p.requestContextBlobTransportMode??"legacy",Y=0===b&&"userMessageAction"===r.action.case&&0===t.turns.length,te="ref_only"===Q&&Y?"dual":Q,[,re]=await Promise.all([Rn({ctx:e,action:r,resources:s,blobStore:a,options:p,source:"run_request",transportMode:te,notifyBytes:0===b}),void 0===p.mintLlmGatewayCredential?Promise.resolve(void 0):Tr(p.mintLlmGatewayCredential,{signal:M.signal,isCanceled:()=>M.canceled,requestId:f})]),ne={action:r,headers:p.headers??{}},oe=this.options.decorateAttempt?.(ne,p)??ne,se=new i.Mpn({conversationState:t,action:oe.action,modelDetails:n,requestedModel:p.requestedModel,clientLlmGatewayCredential:re,mcpTools:X,conversationGroupId:p.conversationGroupId,conversationId:p.conversationId,agentSessionId:p.agentSessionId,mcpFileSystemOptions:p.mcpFileSystemOptions,customSystemPrompt:p.customSystemPrompt,systemPromptSpec:p.systemPromptSpec,harness:p.harness,computerUseCoordinateMode:p.computerUseCoordinateMode,subagentTypeName:p.subagentTypeName,excludeWorkspaceContext:p.excludeWorkspaceContext,devRawModelSlug:p.devRawModelSlug,selectedSubagentModels:p.selectedSubagentModels,subagentModelOverrides:p.subagentModelOverrides??[],selectedSubagentModelDetails:p.selectedSubagentModelsLegacy,clientSupportsInlineImages:p.clientSupportsInlineImages,clientSupportsPreviewCard:p.clientSupportsPreviewCard,startedAsNewProject:p.startedAsNewProject,firstProjectOnboarding:p.firstProjectOnboarding,clientSupportsSendToUser:p.clientSupportsSendToUser,clientSupportsRoutedModelUpdate:p.clientSupportsRoutedModelUpdate,emitModelCallUsage:p.emitModelCallUsage,canCreateCloudSubagents:p.canCreateCloudSubagents,suppressSubagentProgressUpdateTool:p.suppressSubagentProgressUpdateTool,transcriptParentConversationId:p.transcriptParentConversationId,runId:m,nextInteractionQueryId:g.peekNext(),voiceCallNotes:p.voiceCallNotes});if(Z=K.write(new de.KS({message:{case:"runRequest",value:se}})),M.canceled){const t={ctxCanceled:e.canceled,softCancel:M.canceled};throw T("post_write_cancel",t),J[Symbol.dispose](),new Ke("User aborted request")}const ie={...oe.headers,"x-request-id":f,"x-original-request-id":m,...Me(p),...Oe()};q=(0,$.VI)(e.withName("handshakeEstablishment")),q.span.setAttribute("handshake.firstStreamOnClient",!this.hasStartedStream),this.hasStartedStream=!0;const ae=function(e){return e?.get(mn)}(e)?.startTransportRun(),ce=void 0===ae?q.ctx:function(e,t){return e.with(mn,t)}(q.ctx,ae),pe=0===b&&void 0!==p.onTtftBreakdown?S?.networkPhaseStartedAt:void 0;let fe;const ge=void 0===ae&&void 0===pe?V:(C=V,E=()=>{fe=performance.now(),ae?.markFirstRequestSent(fe)},{[Symbol.asyncIterator](){const e=C[Symbol.asyncIterator]();let t=!1;const r={next:()=>(t||(t=!0,E()),e.next())};return void 0!==e.return&&(r.return=t=>e.return(t)),void 0!==e.throw&&(r.throw=t=>e.throw(t)),r}}),ye=this.client.run(ce,ge,{signal:N.signal,headers:ie,onHeader:e=>{W=e.get("x-cursor-agent-transport-mode")??void 0,p.onHeader?.(e)},onNetworkStarted:()=>{void 0===z&&(z=performance.now(),0===b&&(G=function(e=Kt,t=25){let r,n=0,o=0,s=e.now()+t;const i=e=>{e<=0||(o+=e,e>n&&(n=e))},a=()=>{const r=e.now();i(r-s),s=r+t,c=e.setTimeout(a,t)};let c=e.setTimeout(a,t);return{stop:()=>(void 0===r&&(e.clearTimeout(c),i(e.now()-s),r={maxLagMs:n,totalLagMs:o}),r)}}()))}}),be=performance.now();let ke;const Ce=t=>{q&&(q.span.setAttribute("handshake.firstMessageHeartbeat",t),void 0!==z&&q.span.setAttribute("handshake.preNetworkMs",z-be),q[Symbol.dispose](),q=void 0),y();const r=performance.now();ke=r,p.onFirstMessage?.(r-be),void 0!==z&&(p.onFirstMessageNetwork?.(r-z),void 0!==G&&(function(e,t){const r={loop:t.loop??"nal",transport_mode:Bt(t.transportMode),first_message_slow:t.firstMessageNetworkMs>=1e3?"true":"false"};Jt.histogram(e,t.reading.maxLagMs,r),Zt.histogram(e,t.reading.totalLagMs,r),Xt.histogram(e,t.firstMessageNetworkMs,r)}(e,{loop:this.options.loop,transportMode:W,firstMessageNetworkMs:r-z,reading:G.stop()}),G=void 0))},xe=()=>{v(),p.onFirstNonHeartbeatResponse?.(performance.now()-be,b)},Pe=p.onTtftBreakdown?e=>{const t=performance.now(),r=void 0===pe||void 0===fe||"server"!==e.clock?void 0:function(e){const t=Math.min(e.firstRequestTakenAt,e.firstMessageAt);return{requestBuildMs:Math.max(0,e.transportRunCalledAt-e.networkPhaseStartedAt),connectMs:Math.max(0,t-e.transportRunCalledAt),roundTripMs:Math.max(0,e.firstMessageAt-t),firstByteToOutputMs:Math.max(0,e.firstOutputAt-e.firstMessageAt),firstOutputReceivedAtEpochMs:e.firstOutputAtEpochMs}}({networkPhaseStartedAt:pe,transportRunCalledAt:be,firstRequestTakenAt:fe,firstMessageAt:ke??t,firstOutputAt:t,firstOutputAtEpochMs:Date.now()});p.onTtftBreakdown(void 0===r?e:{...e,transit:r},b)}:void 0,Re=!0===this.options.execCheckpointGate?function(e,t,r,n={}){return Te.has(r.action.action.case)?async function*(e,t,r,n){const o=[];let s=0;const i=()=>o.flatMap((e=>void 0===e.toolCallId?[]:[e.toolCallId])),a=e=>{const t=[];for(;o.length>0;){const n=o[0];if(!e&&void 0!==n.toolCallId&&!r.has(n.toolCallId))break;t.push(n.message),o.shift()}return t.length>0&&o.length>0&&(s=n.now()),t},c=()=>{const e=o.filter((e=>"execServerControlMessage"===e.message.message.case)),t=o.filter((e=>"execServerControlMessage"!==e.message.message.case));return o.splice(0,o.length,...t),e.map((e=>e.message))},l=t[Symbol.asyncIterator]();let u=!0;try{for(;;){let t;try{t=await l.next()}catch(e){throw u=!1,yield*c(),e}if(!0===t.done)return u=!1,void(yield*c());const d=t.value,h=d.message;if("execServerMessage"!==h.case&&"execServerControlMessage"!==h.case)if("conversationCheckpointUpdate"!==h.case){if(yield d,o.length>0&&n.now()-s>=n.holdMs){Ie.info(e,"No checkpoint named held tool calls on a stream still delivering: handed on as they came",{toolCallIds:i().join(", "),waitedMs:Math.round(n.now()-s)});for(const e of i())r.add(e);yield*a(!0)}}else{for(const e of Ee(h.value.pendingToolCalls))r.add(e);if(yield d,o.length>0){const t=Math.round(n.now()-s),r=a(!1);r.length>0&&Ie.debug(e,"Handed held execs on after their checkpoint",{count:r.length,waitedMs:t}),yield*r}}else{const t="execServerMessage"===h.case?Ae(h.value):void 0,i=void 0!==t&&!r.has(t);if(0===o.length&&!i){yield d;continue}if(0===o.length&&(s=n.now()),o.push({message:d,toolCallId:i?t:void 0}),i){Ie.debug(e,"Held a tool call's exec for the checkpoint that names it",{toolCallId:t});try{n.onHeld?.(t)}catch(t){Ie.warn(e,"onExecHeldForCheckpoint callback failed",{error:String(t)})}}}}}catch(e){if(u){u=!1;try{await(l.return?.())}catch{}}throw e}finally{o.length>0&&Ie.info(e,"The stream ended before a checkpoint named held tool calls: dropped, never run",{toolCallIds:i().join(", ")}),u&&await(l.return?.())}}(e,t,Ee(r.state.pendingToolCalls),{holdMs:n.holdMs??5e3,now:n.now??(()=>performance.now()),onHeld:n.onHeld}):t}(e,ye,{action:oe.action,state:t},void 0===this.options.onExecHeldForCheckpoint?{}:{onHeld:this.options.onExecHeldForCheckpoint}):ye,$e=!0===this.options.execAfterCheckpointStored||!0===this.options.execCheckpointGate?new _e(void 0===this.options.onExecHeldForCheckpointStore?{}:{onExecHeld:this.options.onExecHeldForCheckpointStore}):void 0,{interactionStream:De,execStream:Fe,checkpointStream:Ne,kvStream:Le,done:je}=function(e,t,r,n,o,s,i,a,c){const l=(0,ve.Jt)(),u=(0,ve.Jt)(),d=(0,ve.Jt)(),h=(0,ve.Jt)();let p=!1,f=!1;return{interactionStream:l,execStream:u,checkpointStream:d,kvStream:h,done:async function(){let m,g,w=!1,y=!1;try{for await(const o of t){if(void 0!==o.ttftBreakdown){const t=o.ttftBreakdown;try{a?.({serverFirstTokenMs:t.serverFirstTokenMs,preStreamSetupMs:t.preStreamSetupMs,waitForFirstEventMs:t.waitForFirstEventMs,providerTtftMs:t.providerTtftMs,slowPoolWaitMs:t.slowPoolWaitMs,...void 0===t.clientPrepMs?{}:{clientPrepMs:t.clientPrepMs},...void 0===t.clientPrepLegs?{}:{clientPrepLegs:me(t.clientPrepLegs)},...void 0===t.preHandlerMs?{}:{preHandlerMs:t.preHandlerMs},clock:t.clientClock?"client":"server"})}catch(t){Pn.warn(e,"onTtftBreakdown callback failed",{error:String(t)})}}const t="interactionUpdate"===o.message.case&&"heartbeat"===o.message.value.message.case;if(p||(p=!0,n(t)),t)r.onServerSentHeartbeat(),r.reset("inbound_message","heartbeat");else{if(!f){f=!0;try{i?.()}catch(t){Pn.warn(e,"onFirstNonHeartbeatMessage callback failed",{error:String(t)})}}r.reset("inbound_message",Tn(o))}if("interactionUpdate"===o.message.case&&"turnEnded"===o.message.value.message.case&&(w=!0),"interactionUpdate"!==o.message.case&&"interactionQuery"!==o.message.case||await l.write(o.message).catch((()=>{})),"execServerMessage"!==o.message.case&&"execServerControlMessage"!==o.message.case||await u.write(o.message.value),"conversationCheckpointUpdate"===o.message.case){const e=w?"ineligible_terminal_turn":"eligible";"ineligible_terminal_turn"===e&&(y=!0);const t=c?.noteRouted(o.message.value);try{await d.write({checkpoint:o.message.value,metadata:{resumeEligibility:e},...void 0===t?{}:{onSettled:t}})}catch(e){throw t?.(),e}}"kvServerMessage"===o.message.case&&await h.write(o.message.value)}r.onStreamEnded()}catch(e){m=e}finally{if(g=m,w&&y&&void 0!==m&&!o?.aborted&&!s?.aborted&&function(e){const t=e instanceof He?e:ct(e);return t instanceof qe&&function(e){return!0===e.isTransport||(e.cause instanceof Error?bt(e.cause):St(e.message))}(t)}(m)&&(Pn.debug(e,"Ignoring transport close after terminal agent stream",{caughtError:m instanceof Error?`${m.name}: ${m.message}`:String(m)}),r.onStreamEnded(),g=void 0),w||o?.aborted||s?.aborted){if(!w&&!o?.aborted){const t=`Stream ended without turnEnded, abort signals: signal.aborted=${o?.aborted}, parentSignal.aborted=${s?.aborted}; firstMessageFired=${p}`;Pn.warn(e,t)}}else{const t="Stream ended without turnEnded — connection likely dropped mid-stream";void 0===m?(Pn.warn(e,t),g=new qe(t,{isTransport:!0})):m instanceof Error&&"[aborted] aborted"===m.message?(Pn.warn(e,`${t}; retrying caught [aborted] aborted error`),g=new qe(t,{cause:m,isTransport:!0})):Pn.warn(e,`${t}; caught non-retriable stream error, rethrowing as-is`,{caughtError:An(m)})}l.close(),u.close(),d.close(),h.close()}if(void 0!==g)throw g}()}}(e,Re,H,Ce,M.signal,e.signal,xe,Pe,$e);let Ue;const Be={handleCheckpoint:async(e,t,r)=>{await l.handleCheckpoint(e,t,r),Ue=r?.resumeEligibility??"eligible"},getLatestCheckpoint:()=>l.getLatestCheckpoint()};J[Symbol.dispose]();const We=5e3;let ze;const Ve=()=>{ze=setTimeout((()=>{K.write(new de.KS({message:{case:"clientHeartbeat",value:new de.kA}})).then((()=>H.onClientSentHeartbeat()),(()=>{})),Ve()}),We)},Je=()=>{void 0!==ze&&(clearTimeout(ze),ze=void 0)};Ve();try{let t;if("shellCommandAction"===r.action.case&&r.action.value.execId){const n=r.action.value,i=new he.a({command:n.shellCommand?.command||"",parsingResult:new he.HO,skipApproval:!0}),a=s.get(ee).execute(e,i,{execId:n.execId}),c=new Rr(De,o,new h.F8(K,(e=>new de.KS({message:{case:"interactionResponse",value:e}}))),H);t={run:async e=>{await Promise.all([j.track("handleShellStream",$n(e,a,o)),j.track("interactionController",c.run(e))])}}}else{const e=new Rr(De,o,new h.F8(K,(e=>new de.KS({message:{case:"interactionResponse",value:e}}))),H);t={run:async t=>{await j.track("interactionController",e.run(t))}}}void 0!==Z&&await Promise.race([Z,je.catch((()=>{}))]);const i=new h.F8(K,(e=>{if((0,we.isMessage)(e,d.yT))return new de.KS({message:{case:"execClientMessage",value:e}});if((0,we.isMessage)(e,d.$Y))return new de.KS({message:{case:"execClientControlMessage",value:e}});throw new Error(`Unknown exec message (type: ${(0,we.isMessage)(e)?e.getType().typeName:typeof e})`)})),l=new Ft(Fe,i,F,$e),b=new le(Le,new h.F8(K,(e=>new de.KS({message:{case:"kvClientMessage",value:e}}))),a,{beforeGetBlob:async(e,t)=>a.persistForRemoteRead(e,t)}),S=new Se(Ne,Be,e);let k,_;const C={promise:new Promise(((e,t)=>{k=e,_=t})),resolve:k,reject:_};M.canceled?(C.resolve(),De.close()):M.signal.addEventListener("abort",(()=>{C.resolve(),De.close()}),{once:!0}),l.run(M).then(C.resolve).catch(C.reject);const E=Promise.allSettled([j.track("streamSplitter",je.finally((()=>{Je(),c.close(),i.close()}))),j.track("execHandler",C.promise),t.run(e),j.track("checkpointController",S.run()),j.track("kvHandler",b.run(e)),j.track("conversationActionManager",c.run(e,{write:async t=>{await Rn({ctx:e,action:t,resources:s,blobStore:a,options:p,source:"queued_action"}),await K.write(new de.KS({message:{case:"conversationAction",value:t}}))}}))]);let P,I;const R={promise:new Promise(((e,t)=>{P=e,I=t})),resolve:P,reject:I};E.then(R.resolve).catch(R.reject),e.canceled?R.reject(new Ke("User aborted request")):e.signal.addEventListener("abort",(()=>R.reject(new Ke("User aborted request"))),{once:!0});const T=()=>{e.signal.aborted?L():function(e){const t=e.lingerMs??6e3;return new Promise((r=>{let n=!1;const o=e=>{n||(n=!0,clearTimeout(s),r(e))},s=setTimeout((()=>o("linger_timed_out")),t);e.done.then((()=>o("stream_ended")),(()=>o("stream_ended")))}))}({done:je,lingerMs:p.softCancelLingerMs}).then((t=>{Pn.info(e,"Soft-cancel transport linger finished",{outcome:t,requestId:f}),L()}))};M.canceled?(T(),R.reject(new Ke("User aborted request"))):M.signal.addEventListener("abort",(()=>{T(),R.reject(new Ke("User aborted request"))}),{once:!0});const A=await R.promise,$=A[0],D=A[1],O=A[3],N=e=>e.reason instanceof Error?`${e.reason.name}: ${e.reason.message}`:String(e.reason);if("rejected"===O.status)throw new Ge("Checkpoint persistence failed",{cause:O.reason instanceof Error?O.reason:void 0,requestId:f,displayInfo:{title:"Checkpoint persistence failed",detail:N(O),isRetryable:!1}});const U="ineligible_terminal_turn"===Ue;if(U){const t={..."rejected"===$.status?{streamSplitter:N($)}:{},..."rejected"===D.status?{execHandler:N(D)}:{}};Object.keys(t).length>0&&Pn.debug(e,"Ignoring handler errors after terminal checkpoint",t)}if("rejected"===$.status&&!U)throw $.reason;if("rejected"===D.status&&!U)throw D.reason;M.canceled||await this.processUnprocessedMessages(x,c,Be,n,o,s,a,u,p,f,m,g,w,H,y,v)}finally{Je(),G?.stop(),G=void 0,q&&(q[Symbol.dispose](),q=void 0)}}catch(e){_.error=e,_.hasError=!0}finally{Cn(_)}var C,E}async processUnprocessedMessages(e,t,r,n,o,s,a,c,l,u,d,h,p,f,m,g){if(!t.hasUnprocessedMessages())return;const w=t.getUnprocessedUserMessages(),y=r.getLatestCheckpoint();if(!y||0===w.length)return;const v=w[0];t.markMessageAsProcessed(v),t.resetStream(),f[Symbol.dispose]();const b=r.getLatestCheckpoint();try{await this.runInternal(e,y,new i.QFf({action:{case:"userMessageAction",value:new i.Vtf({userMessage:v})}}),n,o,s,a,t,r,c,l,u,d,h,p,m,g,0,void 0,"agent.request.queuedMessage")}catch(e){throw b===r.getLatestCheckpoint()&&t.requeueMessage(v),e}}}const On="cursor-ide-browser",Fn="cursor-dev-control",Nn="custom-user-tools",Ln=new Set(["cursor-app-control","cursor-backend-control","cursor-browser-extension",On,Fn,Nn,"fsd","cursor-subscriptions","cursor-cloud","suggestions","Cursor Slack Tools","Cursor Automation Tools"]);function jn(e){return!Ln.has(e)}const Un=new Set([Fn,On]);function Bn(e){if(void 0!==e&&0!==Object.keys(e).length)try{return JSON.stringify(e)}catch{return}}function Wn(e){return{name:e.toolName,description:e.description,arguments:e.inputSchema,outputSchema:e.outputSchema,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId}}var Hn;function qn(e){return void 0===e||void 0===e.serverIdentifiers}function zn(e){switch(e.kind){case"ready":return void 0===e.toolListError?"connected":"error";case"requires_authentication":return"needsAuth";case"error":return"error";default:return"loading"}}(0,y.cF)(Symbol("mcpHostFilledArguments"),[]),function(e){e.Snapshots="cursor_mcp_lease_snapshot_store",e.Status="cursor_mcp_lease_server_status",e.Settings="cursor_mcp_lease_settings",e.Providers="cursor_mcp_lease_providers",e.Unknown="cursor_mcp_lease_unknown"}(Hn||(Hn={}));const Gn=q("mcp-executor",(e=>new B(e,Z("mcpArgs"),X("mcpResult"))),((e,t)=>{t.register(new R(e,Y("mcpArgs"),Q("mcpResult")))})),Vn=q("list-mcp-resources-executor",(e=>new B(e,Z("listMcpResourcesExecArgs"),X("listMcpResourcesExecResult"))),((e,t)=>{t.register(new R(e,Y("listMcpResourcesExecArgs"),Q("listMcpResourcesExecResult")))})),Kn=q("read-mcp-resource-executor",(e=>new B(e,Z("readMcpResourceExecArgs"),X("readMcpResourceExecResult"))),((e,t)=>{t.register(new R(e,Y("readMcpResourceExecArgs"),Q("readMcpResourceExecResult")))})),Jn=q("mcp-state-executor",(e=>new B(e,Z("mcpStateExecArgs"),X("mcpStateExecResult"))),((e,t)=>{t.register(new R(e,Y("mcpStateExecArgs"),Q("mcpStateExecResult")))}));var Zn=r("../proto/dist/generated/agent/v1/subagent_exec_pb.js");(0,y.cF)(Symbol("pendingSubagentReplay"),void 0);class Xn extends Error{constructor(e,t){super(e),this.name="SubagentHostError",this.agentId=t?.agentId,this.cause=t?.cause}}const Qn=q("subagent-executor",(e=>new B(e,Z("subagentArgs"),X("subagentResult"))),((e,t)=>{t.register(new R(e,Y("subagentArgs"),Q("subagentResult")))})),Yn=q("subagent-await-executor",(e=>new B(e,Z("subagentAwaitArgs"),X("subagentAwaitResult"))),((e,t)=>{t.register(new R(e,Y("subagentAwaitArgs"),Q("subagentAwaitResult")))})),eo=q("force-background-subagent-executor",(e=>new B(e,Z("forceBackgroundSubagentArgs"),X("forceBackgroundSubagentResult"))),((e,t)=>{t.register(new R(e,Y("forceBackgroundSubagentArgs"),Q("forceBackgroundSubagentResult")))}));var to=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/status.js"),ro=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/span_kind.js");const no=(0,ye.createContextKey)(void 0,{description:"anysphere.callerContext"});function oo(e){return null!==e&&"object"==typeof e&&Symbol.asyncIterator in e}function so(e){return e instanceof Error?e:new Error(String(e))}function io(e,t,r){return{[Symbol.asyncIterator](){const n=e[Symbol.asyncIterator]();let o=!1;const s=e=>{o||(o=!0,e?(t?.recordException(so(e)),t?.setStatus({code:to.s.ERROR,message:e instanceof Error?e.message:"Stream failed"})):t?.setStatus({code:to.s.OK}),t?.end(),r?.())};return{async next(){try{const e=await n.next();return e.done&&s(),e}catch(e){throw s(e),e}},return:async e=>(s(),n.return?n.return(e):{done:!0,value:void 0}),async throw(e){if(s(e),n.throw)return n.throw(e);throw e}}}}}function ao(...e){const t=new Headers;for(const r of e)r&&(r instanceof Headers?r:new Headers(r)).forEach(((e,r)=>{t.set(r,e)}));return t}function co(e,t){const{injectTraceHeaders:r=!0,extractHeaders:n}=t;return new Proxy(e,{get(e,o){const s=e[o];return"function"!=typeof s?s:(i,a,c={})=>{const l=(0,$.fR)(i.withName(`rpc.${String(o)}`),{kind:ro.v.CLIENT,attributes:{"rpc.method":String(o),"rpc.system":"connect"}}),u=(0,$.fU)(l);let d;try{let o;if(r&&(o=function(e){const t=new Headers;try{const r=(0,$.fU)(e),n=r?.spanContext?.();if(n?.traceId&&n.spanId){const e=n.traceFlags??0,r=`00-${n.traceId}-${n.spanId}-${e.toString(16).padStart(2,"0")}`;t.set("traceparent",r),t.set("backend-traceparent",r),n.traceState&&t.set("tracestate",n.traceState.serialize())}}catch{}return t}(l)),n){const e=n(l);e&&(o=ao(o,e))}const i=ao(c.headers,o),{signal:p,cleanup:f}=!0===t.enableAbortSignal?function(e,t){if(void 0===t||t===e)return{signal:e};const r=new AbortController,n=()=>{r.abort(e.reason)},o=()=>{r.abort(t.reason)};e.addEventListener("abort",n,{once:!0}),t.addEventListener("abort",o,{once:!0}),e.aborted?n():t.aborted&&o();return{signal:r.signal,cleanup:()=>{e.removeEventListener("abort",n),t.removeEventListener("abort",o)}}}(l.signal,c.signal):{signal:c.signal,cleanup:void 0};d=f;const m=(c.contextValues??(0,ye.createContextValues)()).set(no,l),g={...c,headers:i,signal:p,contextValues:m},w=s.call(e,a,g);return oo(w)?io(w,u,d):null!==(h=w)&&"object"==typeof h&&"then"in h&&"function"==typeof h.then?Promise.resolve(w).then((e=>oo(e)?io(e,u,d):(u?.setStatus({code:to.s.OK}),u?.end(),d?.(),e))).catch((e=>{throw u?.recordException(so(e)),u?.setStatus({code:to.s.ERROR,message:e instanceof Error?e.message:"RPC call failed"}),u?.end(),d?.(),e})):(u?.setStatus({code:to.s.OK}),u?.end(),d?.(),w)}catch(e){throw u?.recordException(so(e)),u?.setStatus({code:to.s.ERROR,message:e instanceof Error?e.message:"RPC call failed"}),u?.end(),d?.(),e}var h}}})}var lo=r("node:crypto?8af2"),uo=r("../utils/dist/workspace-paths.js");function ho(){return(0,s.join)(function(){const e=process.env.CURSOR_DATA_DIR;return e?.trim()?e:(0,s.join)((0,o.homedir)(),".cursor")}(),"projects")}function po(e){return(0,s.join)(ho(),(0,uo.r_)(e))}var fo=r("node:fs/promises"),mo=r("../../node_modules/.pnpm/lru-cache@11.2.5/node_modules/lru-cache/dist/esm/index.js"),go=r("node:fs");const wo="local";function yo(e,t){return`${e}:task_progress:${t}`}function vo(e){const t={};return"string"==typeof e.title&&e.title.trim().length>0&&(t.title=e.title),"string"==typeof e.cwd&&e.cwd.trim().length>0&&(t.cwd=e.cwd),"number"==typeof e.startTimeMs&&Number.isFinite(e.startTimeMs)&&e.startTimeMs>0&&(t.startTimeMs=String(Math.floor(e.startTimeMs))),Object.keys(t).length>0?t:void 0}function bo(e,t){e.hookApprovalRequirement=void 0!==t?new he.In(t):void 0}function So(e){return e.hookApprovalRequirement}function ko(e){return e?.kind===he.b.FORCE_PROMPT}function _o(e){return!(!e.skipApproval||e.smartModeClassifierAllowed&&ko(e.hookApprovalRequirement))}var Co=r("../proto/dist/generated/agent/v1/background_shell_exec_pb.js"),Eo=r("../shell-exec/dist/api/index.js"),xo=r("./src/agent/native/tree-sitter.webpack.cjs"),Po=r("./src/agent/native/tree-sitter-bash.webpack.cjs");const Io=function(e,t=console.warn){let r;return()=>{if(void 0!==r)return r;try{const t=e();t.setLanguage(Po),r=t}catch(e){if(!function(e){return"object"==typeof e&&null!==e&&"CURSOR_TREE_SITTER_STUBBED"===e.code}(e))throw e;r=null,t("shell-parser: tree-sitter natives are unavailable in this artifact; shell command analysis degrades to parsingFailed")}return r}}((()=>new xo)),Ro=new Set(["file_redirect","heredoc_redirect","herestring_redirect","heredoc","here_string","redirect","redirection"]),To=new Set(["<",">",">>",">|","<>","<&",">&","&>","&>>"]);function Ao(e,t){if(null===e)return{legacy:{simpleCommands:[],hasInputRedirect:!1,hasOutputRedirect:!1},structured:{parsingFailed:!0,executableCommands:[],hasRedirects:!1,hasCommandSubstitution:!1,redirects:[]}};const r=e.parse(t),n=new WeakSet;let o=!1,s=!0;const i={simpleCommands:[],hasInputRedirect:!1,hasOutputRedirect:!1},a={parsingFailed:!1,executableCommands:[],hasRedirects:!1,hasCommandSubstitution:!1,redirects:[]},c=e=>{o=!0,a.hasRedirects=!0,s=s&&e},l=e=>{if(e&&/^\d+$/.test(e.text))return Number.parseInt(e.text,10)},u=()=>({fdTargets:new Map([[0,"original-stdin"],[1,"original-stdout"],[2,"original-stderr"]])}),d=(e,t)=>{const r=(e=>{const t=e.children,r=t.findIndex((e=>To.has(e.type)));if(-1!==r)return{operator:t[r]?.type??"",target:t.slice(r+1).find((e=>"comment"!==e.type))}})(e);if(!r)return!1;const{operator:n,target:o}=r,s=((e,t)=>{if("&>"===t||"&>>"===t)return[1,2];const r=(e=>l(e.children.find((e=>"file_descriptor"===e.type))))(e);return void 0!==r?[r]:t.startsWith("<")?[0]:[1]})(e,n),i=(e=>{if(e){if("word"===e.type)return 0===e.namedChildren.length?e.text:void 0;if("number"===e.type)return e.text;if("raw_string"===e.type){if(e.text.length<2)return;return e.text.slice(1,-1)}if("string"===e.type){const t=e.namedChildren;if(0===t.length||t.some((e=>"string_content"!==e.type)))return;return t.map((e=>e.text)).join("")}}})(o),c={operator:n,destinationFds:s,targetNodeType:o?.type??""};if(void 0!==i&&(c.targetText=i),a.redirects.push(c),">&"===n){const e=l(o),r=void 0===e?void 0:t.fdTargets.get(e);if(!(e=>"original-stdout"===e||"original-stderr"===e||"dev-null"===e)(r)){for(const e of s)t.fdTargets.set(e,"unsafe");return!1}for(const e of s)t.fdTargets.set(e,r);return!0}if("<&"===n){const e=l(o),r=void 0===e?void 0:t.fdTargets.get(e);if("dev-null"!==r){for(const e of s)t.fdTargets.set(e,"unsafe");return!1}for(const e of s)t.fdTargets.set(e,r);return!0}if(!(e=>{if(!e)return!1;if("word"===e.type)return"/dev/null"===e.text;if("raw_string"===e.type)return"'/dev/null'"===e.text;if("string"===e.type){const t=e.namedChildren;return 1===t.length&&"string_content"===t[0]?.type&&"/dev/null"===t[0].text}return!1})(o)){for(const e of s)t.fdTargets.set(e,"unsafe");return!1}for(const e of s)t.fdTargets.set(e,"dev-null");return!0},h=(e,t)=>{if(!n.has(e)){if(n.add(e),(e=>{var t;t=e.text,/(^|\s)[0-9]*<<?<?/.test(t)&&(i.hasInputRedirect=!0),(/(^|\s)[0-9]*>>/.test(t)||/(^|\s)[0-9]*>(\||&)?/.test(t)||/(^|\s)&>/.test(t)||/(^|\s)[0-9]+>&[0-9]+/.test(t))&&(i.hasOutputRedirect=!0),"heredoc_redirect"!==e.type&&"herestring_redirect"!==e.type||(i.hasInputRedirect=!0)})(e),"heredoc_redirect"===e.type){const{redirect:t,isAllowlistSafe:r}=(e=>{const t=(e=>{const t=e.parent;if("redirected_statement"!==t?.type)return;const r=t.children.find((e=>"command"===e.type)),n=r?.childForFieldName("name");return n?.text})(e),r=void 0!==t&&!(e=>{let t=e.parent;for(;t;){if("command_substitution"===t.type&&"string"!==t.parent?.type)return!0;t=t.parent}return!1})(e),n={operator:r?"<<":"",destinationFds:r?[0]:[],targetNodeType:e.type};return r&&(n.targetText=t),{redirect:n,isAllowlistSafe:r}})(e);return a.redirects.push(t),void c(r)}if("file_redirect"!==e.type)return a.redirects.push({operator:"",destinationFds:[],targetNodeType:e.type}),void c(!1);c(d(e,t))}};return function e(t){const r=t.type;if((e=>{const t=u();for(const r of e.children)Ro.has(r.type)&&h(r,t)})(t),Ro.has(r)&&!n.has(t)&&h(t,u()),"command"===r){const e=t.childForFieldName("name");if(null===e)a.parsingFailed=!0;else{i.simpleCommands.push(e.text);let r=e.text;const n=[];for(const e of function(e){const t=[],r=e.walk();if(r.gotoFirstChild())do{"argument"===r.currentFieldName&&t.push(r.currentNode)}while(r.gotoNextSibling());return t}(t))n.push({type:e.type,value:e.text}),r+=` ${e.text}`;a.executableCommands.push({name:e.text,args:n,fullText:r})}}if("command_name"===r||"simple_command"===r)if("command_name"!==r||i.simpleCommands.includes(t.text)){if("simple_command"===r){const e=t.firstNamedChild;e&&"command_name"===e.type?i.simpleCommands.includes(e.text)||i.simpleCommands.push(e.text):i.simpleCommands.push(t.text)}}else i.simpleCommands.push(t.text);"command_substitution"!==r&&"process_substitution"!==r||(a.hasCommandSubstitution=!0);for(const r of t.children)e(r)}(r.rootNode),o&&(a.allRedirectsAreDevNull=s),{legacy:i,structured:a}}function $o(e){return Ao(Io(),e)}function Mo(e,t){return t>0&&t<e.length&&((r=e.charCodeAt(t-1))>=55296&&r<=56319)&&function(e){return e>=56320&&e<=57343}(e.charCodeAt(t));var r}function Do(e,t){return t>0?t>=e.length?e.length:Math.trunc(t):0}function Oo(e,t){const r=Do(e,t);return Mo(e,r)?r-1:r}function Fo(e,t){const r=Do(e,t);return Mo(e,r)?r+1:r}function No(e,t){return t>0?e.length<=t?e:e.slice(0,Oo(e,t)):""}function Lo(e,t){return t>0?e.length<=t?e:e.slice(Fo(e,e.length-Math.trunc(t))):""}let jo,Uo;function Bo(e,t){jo??=new TextEncoder,Uo??=new Uint8Array(65536);let r=0,n=0;for(;r<e.length&&n<t;){const o=Math.min(t-n,Uo.length),s=e.slice(r,r+o),i=jo.encodeInto(s,Uo.subarray(0,o));if(0===i.read)break;r+=i.read,n+=i.written}return{read:r,written:n}}var Wo=r("../../node_modules/.pnpm/re2js@1.2.2/node_modules/re2js/build/index.esm.js"),Ho=r("../utils/dist/path-utils.js");const qo="path is empty or only whitespace",zo=async e=>{const t=(0,Ho.o1)(e);try{return await(0,fo.realpath)(t)}catch{return t}},Go=1048576,Vo=52428800;var Ko=r("../proto/dist/generated/agent/v1/sandbox_pb.js");function Jo(e){if(!e)return;let t;return"allow"===e.default?t=Ko.h1.ALLOW:"deny"===e.default&&(t=Ko.h1.DENY),new Ko.RB({version:e.version,defaultAction:t,deny:e.deny??[],allow:e.allow??[],logging:e.logging?(r=e.logging,new Ko.Qq({decisionLogPath:r.decisionLogPath,logFormat:r.logFormat})):void 0});var r}function Zo(e){const t=function(e){if(!e)return;const t={};if(1===e.version&&(t.version=1),void 0!==e.defaultAction)switch(e.defaultAction){case Ko.h1.ALLOW:t.default="allow";break;case Ko.h1.DENY:t.default="deny"}return e.deny&&e.deny.length>0&&(t.deny=e.deny),e.allow&&e.allow.length>0&&(t.allow=e.allow),e.logging&&(t.logging=function(e){const t={};return e.decisionLogPath&&(t.decisionLogPath=e.decisionLogPath),"jsonl"===e.logFormat&&(t.logFormat="jsonl"),t}(e.logging)),t}(e.networkPolicy);return t||(e.networkAccess?(0,Eo.T6)():(0,Eo.Po)())}function Xo(e){switch(e){case"system":return Ko.Sz.SYSTEM;case"workspace":return Ko.Sz.WORKSPACE;default:return Ko.Sz.UNSPECIFIED}}function Qo(e){const t=function(e){switch(e){case Ko.Sz.SYSTEM:return"system";case Ko.Sz.WORKSPACE:return"workspace";case Ko.Sz.UNSPECIFIED:default:return}}(e.readBoundary),r=e.additionalReadPaths??[];return{readBoundary:t,additionalReadPaths:"workspace"===t&&r.length>0?r:void 0}}function Yo(e){if(!e)return{type:"insecure_none"};switch(e.type){case Ko.vc.INSECURE_NONE:case Ko.vc.UNSPECIFIED:return{type:"insecure_none",allowlistEscalated:e.allowlistEscalated,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies};case Ko.vc.WORKSPACE_READWRITE:return{type:"workspace_readwrite",networkPolicy:Zo(e),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadwritePaths:e.additionalReadwritePaths,additionalReadonlyPaths:e.additionalReadonlyPaths,disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicyStrict:e.networkPolicyStrict,...Qo(e)};case Ko.vc.WORKSPACE_READONLY:return{type:"workspace_readonly",networkPolicy:Zo(e),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadonlyPaths:e.additionalReadonlyPaths,disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicyStrict:e.networkPolicyStrict,...Qo(e)};default:return{type:"insecure_none"}}}function es(e){if(e)return"insecure_none"===e.type?new Ko.Mw({type:Ko.vc.INSECURE_NONE,allowlistEscalated:e.allowlistEscalated,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies}):"workspace_readwrite"===e.type?new Ko.Mw({type:Ko.vc.WORKSPACE_READWRITE,networkAccess:(0,Eo.$b)(e.networkPolicy),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadwritePaths:e.additionalReadwritePaths??[],additionalReadonlyPaths:e.additionalReadonlyPaths??[],disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicy:Jo(e.networkPolicy),networkPolicyStrict:e.networkPolicyStrict,readBoundary:Xo(e.readBoundary),additionalReadPaths:"workspace"===e.readBoundary?e.additionalReadPaths??[]:[]}):"workspace_readonly"===e.type?new Ko.Mw({type:Ko.vc.WORKSPACE_READONLY,networkAccess:(0,Eo.$b)(e.networkPolicy),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadonlyPaths:e.additionalReadonlyPaths??[],disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicy:Jo(e.networkPolicy),networkPolicyStrict:e.networkPolicyStrict,readBoundary:Xo(e.readBoundary),additionalReadPaths:"workspace"===e.readBoundary?e.additionalReadPaths??[]:[]}):new Ko.Mw({type:Ko.vc.INSECURE_NONE})}function ts(e){return" "===e||"\t"===e||"\n"===e||"\r"===e||" "===e||""===e||""===e||""===e||"\ufeff"===e}function rs(e){let t="",r=!1;for(const n of e)ts(n)?r=!0:(r&&t.length>0&&(t+=" "),r=!1,t+=n);return t}function ns(e){if(0===e.length)return!1;for(let t=0;t<e.length;t++)if("*"!==e[t])return!1;return!0}function os(e){const t=e.indexOf(":");if(t<=0)return;const r=e.slice(0,t).trim();for(let e=0;e<r.length;e++){const t=r[e];if(void 0!==t&&0===t.trim().length)return}return{executablePattern:r,argsPattern:e.slice(t+1).trim()}}function ss(e){const t=e.trim();return{trimmedPattern:t,regexSource:`^${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\\\*/g,".*")}$`}}function is(e,t){const{trimmedPattern:r,regexSource:n}=ss(e);try{return new RegExp(n).test(t)}catch{return r===t}}function as({command:e,parsingResult:t}){return[...new Set([e,...t.executableCommands.map((e=>e.fullText))])]}const cs={a:"",b:"\b",e:"",E:"",f:"\f",n:"\n",r:"\r",t:"\t",v:"\v","\\":"\\","'":"'",'"':'"',"?":"?"};function ls(e){let t="",r="plain",n=0;for(;n<e.length;){const o=e[n];if("plain"===r){"$"===o&&"'"===e[n+1]?(r="ansi",n+=2):"$"===o&&'"'===e[n+1]?(r="double",n+=2):"'"===o?(r="single",n++):'"'===o?(r="double",n++):"\\"===o&&n+1<e.length?("\n"!==e[n+1]&&(t+=e[n+1]),n+=2):(t+=o,n++);continue}if("single"===r){"'"===o?r="plain":t+=o,n++;continue}if("double"===r){if('"'===o){r="plain",n++;continue}if("\\"===o&&n+1<e.length){const r=e[n+1];if("$"===r||"`"===r||'"'===r||"\\"===r||"\n"===r){"\n"!==r&&(t+=r),n+=2;continue}}t+=o,n++;continue}if("'"===o){r="plain",n++;continue}if("\\"!==o||n+1>=e.length){t+=o,n++;continue}const s=e[n+1],i=cs[s];if(void 0!==i){t+=i,n+=2;continue}const a="x"===s?e.slice(n+2).match(/^[0-9a-fA-F]{1,2}/)?.[0]:"u"===s?e.slice(n+2).match(/^[0-9a-fA-F]{1,4}/)?.[0]:"U"===s?e.slice(n+2).match(/^[0-9a-fA-F]{1,8}/)?.[0]:e.slice(n+1).match(/^[0-7]{1,3}/)?.[0],c="u"===s||"U"===s,l="x"===s||c?16:8;if(void 0!==a){const e=Number.parseInt(a,l);if(!c||e<=1114111){t+=c?String.fromCodePoint(e):String.fromCharCode(e),n+=a.length+(16===l?2:1);continue}}t+=s,n+=2}return rs(t)}function us({rule:e,command:t}){const r=rs(e).trim();return 0!==r.length&&(null!==function(e){const t=rs(e).trim();if(0===t.length)return"Rule cannot be empty";if(t.length>512)return"Rule cannot exceed 512 characters";if(ns(t))return"Rule cannot match every command; be more specific than wildcards alone";if(t.startsWith(":"))return"Colon rules need an executable before `:` (e.g. `aws:*s3 rm*`)";const r=os(t);if(void 0!==r){const{executablePattern:e,argsPattern:t}=r;if(ns(e)&&(0===t.length||ns(t)))return"Rule cannot match every command; narrow the executable or argument pattern"}return null}(r)||[t.trim(),rs(t).trim(),ls(t).trim()].some((e=>function(e,t){const r=os(e);if(void 0!==r){const{executablePattern:e,argsPattern:n}=r,o=t.indexOf(" "),s=-1===o?t:t.slice(0,o),i=-1===o?"":t.slice(o+1).trim();if(is(e,s)&&is(n,i))return!0}return e.includes("*")?is(e,t):t===e||t.startsWith(`${e} `)}(r,e))))}function ds({matchForms:e,blockedCommands:t}){const r=t.map((e=>e.trim())).filter((e=>e.length>0));if(0===r.length)return;const n=e.map((e=>e.trim())).filter((e=>e.length>0)),o=n.length>0?n:[""];for(const e of r)if(o.some((t=>us({rule:e,command:t}))))return e}function hs(e){return`Denied: this command was blocked by administrator policy (denylist rule: ${e}) and was not executed. It cannot be approved from this conversation; only a user can run it manually outside the agent. You may continue working on the task.`}function ps({command:e,parsingResult:t,blockedCommands:r}){if(0===r.length)return;if(t.parsingFailed||0===t.executableCommands.length)return"Denied: this command could not be conclusively analyzed against your team's administrator command denylist, so it was blocked (fail-closed) and was not executed. It cannot be approved from this conversation; only a user can run it manually outside the agent. You may continue working on the task.";const n=ds({matchForms:as({command:e,parsingResult:t}),blockedCommands:r});return void 0===n?void 0:hs(n)}var fs=r("../utils/dist/test-resets.js");const ms="CURSOR_FORCED_SHELL_EGRESS_NETWORK_DEFAULT",gs="CURSOR_FORCED_SHELL_EGRESS_DEPENDENCY_DENY_DOMAINS",ws=/\$\(|`|<\(|>\(/,ys=/[;&|]/;let vs,bs,Ss,ks;function _s(){if(void 0===vs){const e=(process.env.CURSOR_FORCED_SHELL_EGRESS??"").trim().toLowerCase();vs=""!==e&&"0"!==e&&"false"!==e&&"off"!==e}return vs}function Cs(e){const t=(process.env[e]??"").trim();if(t)try{return new RegExp(t,"i"),t}catch(t){throw new Error(`[forced-egress] invalid regex in ${e}: ${String(t)}`)}}function Es(e){return(process.env[e]??"").split(",").map((e=>e.trim())).filter((e=>e.length>0))}function xs(e){const t=(process.env[e]??"").split(":").map((e=>e.trim())).filter((e=>e.length>0)),r=t.filter((e=>e.startsWith("/"))),n=t.length-r.length;return n>0&&console.error(`[forced-egress] ignoring ${n} non-absolute path(s) in ${e}.`),r}function Ps(){if(void 0===ks){const e=(process.env[ms]??"").trim().toLowerCase();let t="deny";"allow"===e||"deny"===e?t=e:""!==e&&console.error(`[forced-egress] ignoring invalid value in ${ms} (expected "allow" or "deny"); using "deny".`);const r=Es("CURSOR_FORCED_SHELL_EGRESS_DENY_DOMAINS"),n=(process.env[gs]??"").trim();let o=r;"none"===n.toLowerCase()?o=[]:""!==n&&(o=Es(gs)),ks={networkDefault:t,denyDomains:r,dependencyDenyDomains:o,allowDomains:Es("CURSOR_FORCED_SHELL_EGRESS_ALLOW_DOMAINS"),writablePaths:xs("CURSOR_FORCED_SHELL_EGRESS_WRITABLE_PATHS")}}return ks}function Is(e,t,r={}){const n=[Cs(e),Cs(t)].filter((e=>void 0!==e)).map((e=>`(?:${e})`));if(0===n.length)return null;const o=n.join("|"),s=r.anchorToExecutable?`^\\s*(?:[A-Za-z_][A-Za-z0-9_]*=[^\\s]*\\s+)*(?:${o})`:o;return new RegExp(s,"i")}function Rs(e,t){const r=function(){const e=Ps();return{type:"workspace_readwrite",...e.writablePaths.length>0?{additionalReadwritePaths:e.writablePaths}:{},networkPolicy:{version:1,default:e.networkDefault,allow:["127.0.0.0/8","::1/128","localhost",...e.allowDomains],...e.denyDomains.length>0?{deny:e.denyDomains}:{}},networkPolicyStrict:!0,skipStatsigDefaults:!0,enableSharedBuildCache:!0}}(),n=(void 0===bs&&(bs=Is("CURSOR_FORCED_SHELL_EGRESS_DEPENDENCY_REGEX","CURSOR_FORCED_SHELL_EGRESS_EXTRA_DEPENDENCY_REGEX",{anchorToExecutable:!0})),bs);if(null===n)return r;const o=t?.executableCommands??[];if(t?.parsingFailed||0===o.length)return r;if(ws.test(e))return r;const s=(void 0===Ss&&(Ss=Is("CURSOR_FORCED_SHELL_EGRESS_SOURCE_REGEX","CURSOR_FORCED_SHELL_EGRESS_EXTRA_SOURCE_REGEX")),Ss);for(const e of o){const t=e.fullText?.trim()||e.name?.trim()||"";if(!t||s?.test(t)||ys.test(t))return r}return o.every((e=>n.test(e.fullText?.trim()||e.name?.trim()||"")))?function(){const e=Ps();return{type:"workspace_readwrite",...e.writablePaths.length>0?{additionalReadwritePaths:e.writablePaths}:{},networkPolicy:{version:1,default:"allow",...e.dependencyDenyDomains.length>0?{deny:e.dependencyDenyDomains}:{}},skipStatsigDefaults:!0,enableSharedBuildCache:!0}}():r}(0,fs.J)((function(){vs=void 0,bs=void 0,Ss=void 0,ks=void 0}));var Ts=r("../utils/dist/lru-cache.js");const As=["Desktop","Documents","Downloads","Music","Movies","Pictures","Library",".Trash"],$s="/Volumes";function Ms(e){const t=e.replace(/\/{2,}/g,"/");return t.length>1&&t.endsWith("/")?t.slice(0,-1):t}function Ds(e,t){if("darwin"!==t.platform)return[];const r=Ms(e),n=r.toLowerCase(),o=Ms(t.homeDirectory),s="/"===r?1:r.split("/").length;return[...As.map((e=>`${o}/${e}`)),$s].filter((e=>{return(t=e.toLowerCase())!==(r=n)&&t.startsWith(r.endsWith("/")?r:`${r}/`);var t,r})).map((e=>{const t=e.split("/").slice(s).join("/");return`${"/"===r?"":r}/${t}`}))}var Os=r("../utils/dist/safe-spawn-cwd.js"),Fs=r("node:util");const Ns=8388608;var Ls=r("../../node_modules/.pnpm/iconv-lite@0.7.0/node_modules/iconv-lite/lib/index.js"),js=r("../../node_modules/.pnpm/jschardet@3.1.4/node_modules/jschardet/index.js");function Us(e){let t=1,r=0;for(;;){const n=e.indexOf("\n",r);if(-1===n)return t;t++,r=n+1}}const Bs="utf8",Ws="utf8bom",Hs="latin1",qs={"windows-1250":"cp1250","windows-1251":"cp1251","windows-1252":"cp1252","windows-1253":"cp1253","windows-1254":"cp1254","windows-1255":"cp1255","windows-1256":"cp1256","windows-1257":"cp1257","windows-1258":"cp1258","iso-8859-1":"iso88591","iso-8859-2":"iso88592","iso-8859-5":"iso88595","iso-8859-6":"iso88596","iso-8859-7":"iso88597","iso-8859-8":"iso88598","iso-8859-9":"iso88599","iso-8859-15":"iso885915","iso-8859-16":"iso885916",shift_jis:"shiftjis","euc-jp":"eucjp","euc-kr":"euckr","iso-2022-jp":"iso2022jp","iso-2022-kr":"iso2022kr",gb2312:"gb2312",gbk:"gbk",gb18030:"gb18030",big5:"big5","big5-hkscs":"big5hkscs","koi8-r":"koi8r","koi8-u":"koi8u",ibm855:"cp855",ibm866:"cp866",maccyrillic:"maccyrillic","x-mac-cyrillic":"maccyrillic","utf-16le":"utf16le","utf-16be":"utf16be","utf-32le":"utf32le","utf-32be":"utf32be",johab:"johab",cp949:"cp949",cp932:"cp932"};function zs(e){return qs[e]||e}function Gs(e){return e.startsWith("\ufeff")?e.slice(1):e}function Vs(e){const t=e.toLowerCase();return"latin-1"===t?Hs:"utf-8"===t?Bs:"utf-8-bom"===t||"utf-8 bom"===t?Ws:t}function Ks(e){const t=[],r=[];let n=0;for(let o=e.indexOf("\n");-1!==o;o=e.indexOf("\n",n)){const s=13===e.charCodeAt(o-1);t.push(e.slice(n,s?o-1:o)),r.push(s?"\r\n":"\n"),n=o+1}return t.push(e.slice(n)),r.push(""),{lines:t,ends:r}}const Js=new Fs.TextDecoder("utf-8",{fatal:!1}),Zs=new Fs.TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),Xs="�";function Qs(e){return Js.decode(e)}function Ys(e){let t=0,r=0,n=0,o=0;for(let s=0;s<e.length;s++){const i=e.charCodeAt(s);i<128?(r+=n,n=0,o=0):65533===i?(t++,r+=Math.max(0,n-2),n=0,o=2):o>0?o--:n++}return r+=n,r>t}function ei(e,t=1/0){let r=0,n=0;for(;r<t;){const t=e.indexOf(Xs,n);if(-1===t)break;r++,n=t+1}return r}function ti(e,t){const r=e[t];let n,o=128,s=191;if(r>=194&&r<=223)n=2;else if(r>=224&&r<=239)n=3,224===r&&(o=160),237===r&&(s=159);else{if(!(r>=240&&r<=244))return 1;n=4,240===r&&(o=144),244===r&&(s=143)}let i=1;for(;i<n&&t+i<e.length;){const r=e[t+i];if(r<(1===i?o:128)||r>(1===i?s:191))break;i++}return i===n?void 0:i}function ri(e){return e<128?1:e<2048?2:e<65536?3:4}var ni;!function(e){e.CRLF="CRLF",e.LF="LF"}(ni||(ni={}));const oi=[".mp4",".webm",".mov",".avi",".mkv",".wmv",".flv",".m4v"],si=new Set(oi),ii=new Fs.TextDecoder("utf-8",{fatal:!0}),ai=new Fs.TextDecoder("latin1"),ci=Buffer.from([239,187,191]),li={utf16le:Buffer.from([255,254]),utf16be:Buffer.from([254,255]),utf32le:Buffer.from([255,254,0,0]),utf32be:Buffer.from([0,0,254,255])},ui=8192,di="UTF-8",hi="windows-1252",pi=/[^\u0000-\u007f\ufffd]/u,fi=/(?:\p{Script=Cyrillic}\p{M}*){3,}/gu,mi=/(?:\p{Script=Greek}\p{M}*){3,}/gu,gi=/(?:\p{Script=Hebrew}\p{M}*){3,}/gu,wi=new Map([["windows-1251",fi],["ISO-8859-5",fi],["KOI8-R",fi],["x-mac-cyrillic",fi],["IBM866",fi],["IBM855",fi],["ISO-8859-7",mi],["windows-1253",mi],["windows-1255",gi],["ISO-8859-8",gi],["TIS-620",/(?:\p{Script=Thai}\p{M}*){3,}/gu]]),yi=/\p{Script=Latin}\p{M}*[\p{Script=Cyrillic}\p{Script=Greek}\p{Script=Hebrew}\p{Script=Thai}]|[\p{Script=Cyrillic}\p{Script=Greek}\p{Script=Hebrew}\p{Script=Thai}]\p{M}*\p{Script=Latin}/u,vi=/[\p{L}\p{M}]+/gu,bi=String.raw`[\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u00FF\u0152\u0153\u0160\u0161\u017D\u017E\u0178]`,Si=new RegExp(`[A-Za-z]${bi}{1,2}(?!${bi})|^${bi}{1,2}[A-Za-z]`,"u"),ki=new Map,_i=new Set([".png",".jpg",".jpeg",".gif",".webp",".ico",".bmp",".pdf",".zip",".tar",".gz",".exe",".dll",".so",".dylib",".bin",...oi]),Ci=/\.(png|jpg|jpeg|gif|webp|ico|bmp)$/i,Ei=new Set([".ps1",".psm1",".psd1"]),xi=/[^\u0000-\u007f]/u;function Pi(e){const t=e.toLowerCase(),r=t.lastIndexOf(".");return-1===r?"":t.substring(r)}function Ii(e){const t=Pi(e);return si.has(t)}function Ri(e){const t=Pi(e);return{encoding:"binary",lineEnding:ni.LF,isBinaryFile:!0,isImageFile:Ci.test(t),isVideoFile:si.has(t)}}async function Ti(e,t){return(await Ai(e,t)).text}async function Ai(e,t){const{stamp:r,buf:n}=await async function(e){const t=await(0,fo.open)(e,"r");try{return{stamp:await t.stat(),buf:await t.readFile()}}finally{await t.close()}}(e),o=Oi(n);if(o.isBinaryFile)throw new Error("Binary file cannot be decoded as text");const s=Hi(e,r);let i;i=t||s||o.encoding;const{text:a,encoding:c}=Gi(n,i),l=Gs(a),u=c===Bs&&Vi(n)?Ws:c;qi(e,r,u);const d=function(e,t){if(t===Ws)return Vi(e);const r=li[zs(Vs(t))];return void 0!==r&&e.subarray(0,r.length).equals(r)}(n,u);if(o.lineEnding===ni.CRLF){const e=l.match(/\r\n/g)?.length??0,t=(l.match(/\n/g)?.length??0)-e;return{text:l.replaceAll("\r\n","\n"),encoding:u,bom:d,lineEnding:e>t?"CRLF":"LF"}}return{text:l,encoding:u,bom:d,lineEnding:"LF"}}async function $i(e,t){if("binary"===t.encoding)return void Wi(e);let r;try{r=await(0,fo.stat)(e)}catch{return void Wi(e)}r.size===t.buffer.byteLength?qi(e,r,t.encoding):Wi(e)}async function Mi(e,t,r,o){let s,i;try{s=r?await async function(e,t){try{return await Di(e)}catch{}const r=Pi(e);if(_i.has(r))return Ri(e);try{return await async function(e){const t=new Map;let r=0;for await(const n of Ui(e)){if(r>=100)break;try{const e=await Di(n);if(!e.isBinaryFile){const r=`${e.encoding}:${e.lineEnding}`,n=t.get(r);if(n){if(n.count++,n.count>=3)return n.format}else t.set(r,{format:e,count:1})}r++}catch(e){}}let n;for(const e of t.values())(!n||e.count>n.count)&&(n=e);return n?n.format:Bi()}(t)}catch{return Bi()}}(e,r):await Di(e)}catch{const t=Pi(e);s=_i.has(t)?Ri(e):Bi()}const a=()=>i??=async function(e){try{const t=await(0,fo.stat)(e);if(!t.isFile()||t.size>Ns)return;return await(0,fo.readFile)(e)}catch{return}}(e),c=Hi(e,await async function(e){try{return await(0,fo.stat)(e)}catch{return}}(e));let l;if(!s.isBinaryFile){let r;o?r=Vs(o):c?r=Vs(c):(r=Vs(s.encoding),r!==Bs&&r!==Ws||(r=await async function(e,t){const r=await t();return void 0===r||(0,n.isUtf8)(r)?e:zi(r).encoding===Hs?Hs:e}(r,a))),r===Bs&&!o&&function(e,t){return"win32"===process.platform&&Ei.has(Pi(e))&&xi.test(t)&&!t.startsWith("#!")}(e,t)&&(await async function(e){try{return await(0,fo.stat)(e),!1}catch(e){return e instanceof Error&&"code"in e&&"ENOENT"===e.code}}(e)||await async function(e){const t=await e();return void 0!==t&&(0,n.isAscii)(t)}(a))&&(r=Ws);const i=r===Ws||r===Bs&&!o&&await Ki(e,ci),u=li[zs(r)];i?l=ci:u&&await Ki(e,u)&&(l=u),s={...s,encoding:i?Ws:r}}const u=Us(t),d=t.includes("\r\n")?void 0:await async function(e,t){if(t.isBinaryFile)return;const r=await e();if(void 0===r||!r.includes(13))return;const n=Gs(Gi(r,t.encoding).text);return function(e){let t=!1,r=!1;for(let n=e.indexOf("\n");-1!==n;n=e.indexOf("\n",n+1))if(13===e.charCodeAt(n-1)?t=!0:r=!0,t&&r)return!0;return!1}(n)?n:void 0}(a,s);if(void 0!==d?t=function({content:e,existing:t,defaultEnding:r}){const n=Ks(t),o=Ks(e),s=function({before:e,after:t}){const r=new Int32Array(t.length).fill(-1);let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];)r[n]=n,n++;let o=0;for(;o<e.length-n&&o<t.length-n&&e[e.length-1-o]===t[t.length-1-o];)r[t.length-1-o]=e.length-1-o,o++;const s=e.length-n-o,i=t.length-n-o;if(s>0&&i>0&&(s+1)*(i+1)<=4e6){const o=i+1,a=new Uint16Array((s+1)*o);for(let r=s-1;r>=0;r--)for(let s=i-1;s>=0;s--)a[r*o+s]=e[n+r]===t[n+s]?a[(r+1)*o+s+1]+1:Math.max(a[(r+1)*o+s],a[r*o+s+1]);for(let c=0,l=0;c<s&&l<i;)e[n+c]===t[n+l]?(r[n+l]=n+c,c++,l++):a[(c+1)*o+l]>=a[c*o+l+1]?c++:l++}let a=-1,c=-1;for(let n=0;n<=t.length;n++){const o=n===t.length?e.length:r[n];if(-1!==o){if(o-a==n-c)for(let e=1;e<n-c;e++)r[c+e]=a+e;a=o,c=n}}return r}({before:n.lines,after:o.lines});let i=r,a="";for(let e=0;e<o.lines.length;e++){const t=s[e];let r=o.ends[e];"\n"===r&&(r=-1!==t&&""!==n.ends[t]?n.ends[t]:i),""!==r&&(i=r),a+=o.lines[e]+r}return a}({content:t,existing:d,defaultEnding:s.lineEnding===ni.CRLF?"\r\n":"\n"}):s.lineEnding===ni.CRLF&&(t=t.replace(/(?<!\r)\n/g,"\r\n")),"binary"===s.encoding){const e=function(e){const t=e.trim().replace(/\s/g,"");if(t.length>50&&/^[A-Za-z0-9+/]*={0,2}$/.test(t))try{const e=Buffer.from(t,"base64");if(e.length>0){const r=Math.floor(.5*t.length);if(e.length>=r)return e}}catch{}return Buffer.from(e,"latin1")}(t);return{lines:u,buffer:e,format:s}}const h=l?Gs(t):t,p=s.encoding===Ws?Bs:s.encoding,f=p===Bs?await async function(e,t){if(!t.includes(Xs))return;const r=await e();return void 0===r?void 0:function(e,t){if(!e.includes(Xs)||(0,n.isUtf8)(t))return;const r=function(e){const t=[];let r=0;for(const n of Zs.decode(e)){const o=n.codePointAt(0)??0;if(65533!==o){r+=ri(o);continue}const s=ti(e,r);void 0===s?(t.push(void 0),r+=3):(t.push(e.subarray(r,r+s)),r+=s)}return r===e.length?t:void 0}(t),o=e.split(Xs);if(void 0===r||o.length-1!==r.length)return;const s=[];for(let e=0;e<o.length;e++)s.push(Buffer.from(o[e],"utf8")),e<r.length&&s.push(r[e]??Buffer.from(Xs,"utf8"));return Buffer.concat(s)}(t,r)}(a,h):void 0,m=f??Ls.encode(h,p,{defaultEncoding:Bs});return{lines:u,buffer:l?Buffer.concat([l,m]):m,format:s}}async function Di(e){const t=Oi((r=await ji(e)).length===ui?function(e){for(let t=e.length-1;t>=Math.max(0,e.length-3);t--){const r=e[t];if(r<128)return e;if(r>=192){const n=r>=240?4:r>=224?3:2;return e.length-t<n?e.subarray(0,t):e}}return e}(r):r);var r;return t.isBinaryFile?{...t,isVideoFile:Ii(e)}:{...t,isVideoFile:!1}}function Oi(e){if(0===e.length)return Bi();const t=function(e){if(e.length<4)return null;if(255===e[0]&&254===e[1]&&(0!==e[2]||0!==e[3]))return"UTF-16LE";if(254===e[0]&&255===e[1])return"UTF-16BE";let t=0,r=0;const n=Math.min(50,Math.floor(e.length/2));for(let o=0;o<2*n&&!(o+1>=e.length);o+=2){if(0===e[o+1]){const r=e[o];(r>=32&&r<=126||9===r||10===r||13===r)&&t++}if(0===e[o]){const t=e[o+1];(t>=32&&t<=126||9===t||10===t||13===t)&&r++}}return t>.8*n?"UTF-16LE":r>.8*n?"UTF-16BE":null}(e)??function(e){if(e.length<8)return null;if(0===e[0]&&0===e[1]&&254===e[2]&&255===e[3])return"UTF-32BE";if(255===e[0]&&254===e[1]&&0===e[2]&&0===e[3])return"UTF-32LE";let t=0,r=0;const n=Math.min(50,Math.floor(e.length/4));for(let o=0;o<4*n&&!(o+3>=e.length);o+=4){if(0===e[o]&&0===e[o+1]&&0===e[o+2]){const r=e[o+3];(r>=32&&r<=126||9===r||10===r||13===r)&&t++}if(0===e[o+1]&&0===e[o+2]&&0===e[o+3]){const t=e[o];(t>=32&&t<=126||9===t||10===t||13===t)&&r++}}return t>.8*n?"UTF-32BE":r>.8*n?"UTF-32LE":null}(e);if(t)return{encoding:t,lineEnding:Ni(Ls.decode(e.subarray(0,ui),zs(Vs(t)))),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1};if(!function(e){const t=Math.min(ui,e.length);if(0===t)return!0;for(let r=0;r<t;r++)if(0===e[r])return!1;let r=0;for(let n=0;n<t;n++){const t=e[n];t<32&&9!==t&&10!==t&&13!==t&&r++}return r/t*100<5}(e))return{encoding:"binary",lineEnding:ni.LF,isBinaryFile:!0,isImageFile:(r=e,!(r.length<4)&&(r.length>=8&&137===r[0]&&80===r[1]&&78===r[2]&&71===r[3]&&13===r[4]&&10===r[5]&&26===r[6]&&10===r[7]||255===r[0]&&216===r[1]&&255===r[2]||r.length>=12&&82===r[0]&&73===r[1]&&70===r[2]&&70===r[3]&&87===r[8]&&69===r[9]&&66===r[10]&&80===r[11]||r.length>=6&&71===r[0]&&73===r[1]&&70===r[2]&&56===r[3]&&(55===r[4]||57===r[4])&&97===r[5])),isVideoFile:!1};var r,o,s;if((0,n.isUtf8)(e)&&(!e.includes(27)||!(0,n.isAscii)(e)))return{encoding:di,lineEnding:Fi(e),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1};if(!(0,n.isUtf8)(e)&&(o=Qs(e),s=e.length,Ys(o)||1024*ei(o)<=s&&!pi.test(o)))return{encoding:di,lineEnding:Fi(e),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1};const i=js.detect(e);let a=i.confidence>.7?i.encoding:"utf-8";"ascii"===a&&(a="utf-8");const c=wi.get(a);return void 0!==c&&(a=function(e,t,r){const n=zs(Vs(t));if(!Ls.encodingExists(n))return t;const o=Ls.decode(e,n);return yi.test(o)&&function(e,t,r){const n=t.match(r)?.length??0;let o=0;for(const[t]of Ls.decode(e,hi).matchAll(vi))Si.test(t)&&o++;return o>n}(e,o,r)?hi:t}(e,a,c)),a!==hi||function(e,t){const r=zs(Vs(t));return!Ls.getDecoder(r).write(e).includes(Xs)}(e,a)||(a="utf-8"),{encoding:a??"utf-8",lineEnding:Fi(e),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1}}function Fi(e){let t=0,r=0;for(let n=0;n<e.length;n++)10===e[n]&&(n>0&&13===e[n-1]?t++:r++);return Li(t,r)}function Ni(e){const t=e.match(/\n/g)?.length??0,r=e.match(/\r\n/g)?.length??0;return Li(r,t-r)}function Li(e,t){return 0===e&&0===t?ni.LF:e/(e+t)*100>=5?ni.CRLF:ni.LF}async function ji(e){const t=await(0,fo.open)(e,"r");try{const e=Buffer.allocUnsafe(ui),{bytesRead:r}=await t.read(e,0,ui,0);return e.subarray(0,r)}finally{await t.close()}}async function*Ui(e){const t=new Set(["node_modules",".git",".svn",".hg","dist","build","out",".next",".cache","coverage","__pycache__",".venv","venv",".turbo"]);try{const r=await(0,fo.readdir)(e,{withFileTypes:!0});for(const n of r){if(n.name.startsWith(".")&&".gitignore"!==n.name)continue;const r=(0,s.join)(e,n.name);n.isDirectory()?t.has(n.name)||(yield*Ui(r)):n.isFile()&&(yield r)}}catch(e){return}}function Bi(){return{encoding:Bs,lineEnding:"win32"===process.platform?ni.CRLF:ni.LF,isBinaryFile:!1,isImageFile:!1,isVideoFile:!1}}function Wi(e){ki.delete(e)}function Hi(e,t){const r=ki.get(e);if(void 0!==r)return void 0!==t&&r.size===t.size&&r.mtimeMs===t.mtimeMs?r.encoding:void ki.delete(e)}function qi(e,t,r){if(ki.has(e)&&ki.delete(e),ki.set(e,{encoding:r,size:t.size,mtimeMs:t.mtimeMs}),ki.size<=100)return;const n=ki.keys().next().value;void 0!==n&&ki.delete(n)}function zi(e){try{return{text:ii.decode(e),encoding:Bs}}catch{const t=Qs(e);return Ys(t)?{text:t,encoding:Bs}:{text:ai.decode(e),encoding:Hs}}}function Gi(e,t){const r=Vs(t);if(r===Bs||r===Ws||"ascii"===r){const t=zi(e);return r===Ws&&t.encoding===Bs?{text:t.text,encoding:Ws}:t}if(r===Hs)return{text:ai.decode(e),encoding:Hs};try{const t=zs(r);if(Ls.encodingExists(t))return{text:Ls.decode(e,t),encoding:r}}catch{}return zi(e)}function Vi(e){return e.length>=ci.length&&e[0]===ci[0]&&e[1]===ci[1]&&e[2]===ci[2]}async function Ki(e,t){try{return(await ji(e)).subarray(0,t.length).equals(t)}catch{return!1}}var Ji=r("../../node_modules/.pnpm/ignore@7.0.5/node_modules/ignore/index.js");class Zi{constructor({ttlMs:e,now:t=Date.now}){this.entries=new Map,this.nextSweepAtMs=0,this.ttlMs="function"==typeof e?e:Zi.validated(e),this.now=t}static validated(e){if(!Number.isFinite(e)||e<=0)throw new Error(`TTL cache requires a positive ttlMs, got ${e}`);return()=>e}get(e){const t=this.entries.get(e);if(void 0!==t){if(!(t.expiresAtMs<=this.now()))return t.value;this.entries.delete(e)}}has(e){const t=this.entries.get(e);return!(void 0===t||t.expiresAtMs<=this.now()&&(this.entries.delete(e),1))}get size(){return this.entries.size}set(e,t){const r=this.now(),n=this.ttlMs();if(this.entries.set(e,{value:t,expiresAtMs:r+n}),!(r<this.nextSweepAtMs)){this.nextSweepAtMs=r+n;for(const[e,t]of this.entries)t.expiresAtMs<=r&&this.entries.delete(e)}}delete(e){return this.entries.delete(e)}clear(){this.entries.clear(),this.nextSweepAtMs=0}}var Xi=r("node:string_decoder");const Qi=new Map,Yi=new Map;let ea;function ta(e){return(0,lo.createHash)("sha256").update(e).digest("hex").slice(0,16)}async function ra(e){try{return await(0,fo.access)(e),!0}catch{return!1}}async function na(e){const t=await(0,fo.stat)(e),r=Qi.get(e);if(void 0!==r&&r.mtimeMs===t.mtimeMs&&r.size===t.size&&(r.ripgrepPath===e||await ra(r.ripgrepPath)))return r.ripgrepPath;const i=t.size>1048576?e:await async function(e,t){const r=function(e){const t=Buffer.isBuffer(e)?e:Buffer.from(e.buffer,e.byteOffset,e.byteLength),r=Oi(t);return r.isBinaryFile?Qs(t):Gs(Gi(t,r.encoding).text)}(t);return function(e,t){if(!(0,n.isUtf8)(e))return!1;const r=e.toString("utf8");return(r.startsWith("\ufeff")?r.slice(1):r)===t}(t,r)?e:async function(e,t){const r=await(ea??=(0,fo.mkdtemp)((0,s.join)((0,o.tmpdir)(),"cursorignore-utf8-")).then((e=>(process.once("exit",(()=>{try{(0,go.rmSync)(e,{recursive:!0,force:!0})}catch{}})),e))),ea),n=(0,s.join)(r,`cursorignore-${ta(e)}-${ta(t)}.txt`);if(await ra(n))return n;const i=`${n}.${process.pid}.${Date.now()}.tmp`;return await(0,fo.writeFile)(i,t,"utf8"),await(0,fo.rename)(i,n),n}(e,r)}(e,await(0,fo.readFile)(e));return Qi.set(e,{mtimeMs:t.mtimeMs,size:t.size,ripgrepPath:i}),i}function oa(e){return Promise.all(e.map((e=>async function(e){const t=Yi.get(e);if(void 0!==t)return t;const r=na(e).catch((()=>e)).finally((()=>{Yi.delete(e)}));return Yi.set(e,r),r}(e))))}(0,fs.J)((function(){Qi.clear(),Yi.clear()}));var sa=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function ia(e){if(e.aborted)return{aborted:Promise.resolve("aborted"),[Symbol.dispose](){}};let t=()=>{};const r=new Promise((e=>{t=()=>e("aborted")}));return e.addEventListener("abort",t,{once:!0}),{aborted:r,[Symbol.dispose](){e.removeEventListener("abort",t)}}}function aa(e,{root:t,searchPaths:r=[],includeGlobs:n=[],excludeGlobs:s=[],caseSensitive:i=!1,cursorIgnoreFiles:a=[],sandboxPolicy:c={type:"insecure_none"},noIgnoreVcs:l=!1,followSymlinks:u=!1,source:d="ripwalk"}){const h=["--files","--hidden","--no-require-git","--no-config","--color=never"],p=function(e=process.env){const t=e.CURSOR_RIPWALK_THREADS?.trim();if(void 0!==t&&""!==t){const e=Number(t);if(Number.isInteger(e)&&e>=0)return 0===e?void 0:e}return Math.min(2,(0,o.availableParallelism)())}();void 0!==p&&h.push("--threads",String(p)),u&&h.push("--follow"),l&&h.push("--no-ignore-vcs"),i&&h.push("--case-sensitive");for(const e of n)h.push("--iglob",e);for(const e of s)h.push("--iglob",`!${e}`);const f=r.length>0?["--",...r]:[];let m,g=!1;const w=new Promise((e=>{m=e}));return{lines:async function*(){const r={stack:[],error:void 0,hasError:!1};try{const n=[];for(const e of await oa(a))n.push("--cursor-ignore",e);const o=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(r,function(e,t,r,n){const o=(0,Eo.spawnInSandbox)((0,Eo.Ko)(),t,{cwd:r},n),s=[];o.stderr?.on("data",(e=>{s.push(e)}));const i=new Promise(((e,t)=>{o.on("error",t),o.on("close",(t=>e(t??0)))}));if(i.catch((()=>{})),!o.stdout)throw new Error("No stdout from ripgrep process");const a=ia(e.signal);return{stdout:o.stdout,processExit:i,stderr:()=>Buffer.concat(s).toString(),aborted:a.aborted,[Symbol.dispose](){a[Symbol.dispose](),o.kill()}}}(e,[...h,...n,...f],t,c),!1);let s=0;const i=async function*(e){const t=new Xi.StringDecoder("utf8");let r="";for await(const n of e){r+=t.write(n);const e=r.split("\n");r=e.pop()??"",e.length>0&&(yield e)}r+=t.end(),r&&(yield[r])}(o.stdout)[Symbol.asyncIterator]();e:for(;;){const t=await Promise.race([i.next(),o.aborted]);if("aborted"===t){g=!0,m(!0);break}if(t.done)break;for(const r of t.value){if(e.signal.aborted){g=!0,m(!0);break e}s++,yield r}}if(s>0);else if(!g){const e=await o.processExit;if(0!==e&&1!==e){const t=o.stderr();throw new Error(`Ripgrep failed (exit ${e}) with no results${t?`: ${t}`:""}`)}}g||m(!1)}catch(e){r.error=e,r.hasError=!0}finally{sa(r)}}(),didTimeout:w}}var ca=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});let la;function ua(e=process.env){if(void 0!==la)return la;const t=e.CURSOR_RIPWALK_CACHE_TTL_MS?.trim();if(void 0!==t&&""!==t){const e=Number(t);if(Number.isFinite(e)&&e>0)return e}return 2e4}function da({root:e,searchPaths:t=[],includeGlobs:r=[],excludeGlobs:n=[],caseSensitive:o=!1,cursorIgnoreFiles:s=[],sandboxPolicy:i={type:"insecure_none"},noIgnoreVcs:a=!1,followSymlinks:c=!1}){return JSON.stringify({root:e,searchPaths:t,includeGlobs:r,excludeGlobs:n,caseSensitive:o,cursorIgnoreFiles:s,sandboxPolicy:i,noIgnoreVcs:a,followSymlinks:c})}class ha{constructor(e=()=>ua()){this.cache=new Zi({ttlMs:e})}get size(){return this.cache.size}clear(){this.cache.clear()}delete(e){this.cache.delete(da(e))}walk(e,t){const r=da(t);let n,o=!1,s=!1;const i=new Promise((e=>{n=e})),a=e=>{s||(s=!0,n(e))};return{lines:async function*(){const n=this.cache.get(r);if(void 0!==n){const t={stack:[],error:void 0,hasError:!1};try{const s=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(t,ia(e.signal),!1),i=await Promise.race([n.linesPromise.then((e=>({type:"lines",lines:e})),(e=>({type:"error",error:e}))),s.aborted.then((()=>({type:"aborted"})))]);if("aborted"===i.type)return o=!0,void a(!0);if("lines"===i.type)return a(!1),void(yield*i.lines);this.cache.get(r)===n&&this.cache.delete(r)}catch(e){t.error=e,t.hasError=!0}finally{ca(t)}}let s,i;const c={linesPromise:new Promise(((e,t)=>{s=e,i=t}))};c.linesPromise.catch((()=>{})),this.cache.set(r,c);const l=[];let u,d=!1;try{const r=aa(e,t);for await(const e of r.lines)l.push(e),yield e;if(await r.didTimeout)return o=!0,u=new Error("Ripwalk aborted before cacheable result was available"),void a(!0);d=!0}catch(e){throw u=e,e}finally{d?s?.(l):(this.cache.get(r)===c&&this.cache.delete(r),i?.(u??new Error("Ripwalk terminated before cacheable result was available"))),o||a(!1)}}.bind(this)(),didTimeout:i}}}const pa=[{stage:"prod",gitHost:"origin.cursor.com",gitCdnHost:"gitcdn.origin.cursor.com",cloneKitS3Host:"git-forge-prod-bundles.s3.us-east-1.amazonaws.com",rawUserContentHost:"raw.cursorusercontent.com",apiHost:"api.origin.cursor.com",internalHost:"origin-prod.internal.cursor.com"},{stage:"staging",gitHost:"origin-staging.cursor.com",gitCdnHost:"gitcdn.origin-staging.cursor.com",cloneKitS3Host:"git-forge-staging-bundles.s3.us-east-1.amazonaws.com",rawUserContentHost:"raw.staging.cursorusercontent.com",apiHost:"api.origin-staging.cursor.com",internalHost:"origin-staging.internal.cursor.com"},{stage:"test",gitHost:"origin-test.cursor.com",gitCdnHost:"gitcdn.origin-test.cursor.com",cloneKitS3Host:"git-forge-test-bundles.s3.us-east-1.amazonaws.com",rawUserContentHost:"raw.test.cursorusercontent.com",apiHost:"api.origin-test.cursor.com",internalHost:"origin-test.internal.cursor.com"}];function fa(e){let t=e.length;for(;t>0&&47===e.charCodeAt(t-1);)t--;const r=e.slice(0,t).replace(/\.git$/i,"");return r&&"/"!==r?r.startsWith("/")?r:`/${r}`:""}function ma(e,t){const r=fa(t);return r?`${e}${r}`.toLowerCase():""}new Map(pa.map((e=>[e.gitHost,e.apiHost]))),new Map(pa.map((e=>[e.gitHost,e.gitCdnHost]))),new Map(pa.map((e=>[e.gitHost,e.cloneKitS3Host]))),new Map(pa.map((e=>[e.gitHost,e.rawUserContentHost]))),new Map(pa.map((e=>[e.apiHost,e.gitHost]))),new Map(pa.map((e=>[e.apiHost,e.internalHost])));const ga=new Map;function wa(e){const t=ga.get(e);if(void 0!==t)return t;const r=function(e){const t=e.trim();if(!t)return"";try{const e=function(e){if(/^[a-z][a-z0-9+.-]*:\/\//i.test(e))return e;const t=`https://${e}`;try{return new URL(t),t}catch{const r=e.match(/^([^@/\s]+@)?([^:/\s]+):(.+)$/);return r?`ssh://${r[1]??""}${r[2]}/${r[3]}`:t}}(t),r=new URL(e);return ma(r.hostname,r.pathname)}catch{const e=t.replace(/^(?:https?|ssh|git):\/\//i,""),r=e.indexOf("/"),n=-1===r?e:e.slice(0,r),o=-1===r?"":e.slice(r);return ma(n.includes("@")?n.slice(n.lastIndexOf("@")+1):n,o)}}(e);return ga.size>=16384&&ga.clear(),ga.set(e,r),r}function ya(e){return/^origin(-[a-z0-9]+)?\.cursor\.com$/i.test(e)}(function(e){const t=pa.find((t=>t.stage===e));if(void 0===t)throw new Error(`unknown Origin stage: ${e}`);return t})("prod").gitHost;const va=new Map;function ba(e){if(void 0===e)return;if(va.has(e))return va.get(e);const t=function(e){const t=e?function(e){let t=e.trim();if(""!==t){t.startsWith("git@")?t=`https://${t.slice(4).replace(":","/")}`:/^[a-z][a-z0-9+.-]*:\/\//i.test(t)&&!/^https?:\/\//i.test(t)?t=t.replace(/^[a-z][a-z0-9+.-]*:\/\//i,"https://"):/^https?:\/\//i.test(t)||(t=`https://${t}`);try{return new URL(t)}catch{return}}}(e):void 0;if(void 0===t||!ya(t.hostname))return;const r=fa(t.pathname).split("/").filter(Boolean),n=3===r.length&&"git"===r[0]?.toLowerCase(),o=2===r.length&&"git"!==r[0]?.toLowerCase();if(!n&&!o)return;const s=n?r[1]:r[0],i=n?r[2]:r[1];return s&&i?Object.freeze({hostname:t.hostname,owner:s,name:i}):void 0}(e);return va.size>=16384&&va.clear(),va.set(e,t),t}function Sa(e){return void 0!==function(e){const t=ba(e);return void 0===t?void 0:{owner:t.owner,name:t.name}}(e)}new Set(["github.com","www.github.com"]),new RegExp("^tmp-[0-9a-f]{16}$");const ka=new WeakMap;function _a(e,t,r){const n=performance.now();let o=ka.get(t);void 0===o&&(o=new Map,ka.set(t,o));const s=o.get(r);if(void 0!==s&&n-s.startedAt<5e3)return s.root;for(const[e,t]of o)n-t.startedAt>=5e3&&o.delete(e);const i=async function(e,t,r){try{return(await t.exec(e,r,["rev-parse","--show-toplevel"],{caller:"findGitRoot"})).stdout.trim()}catch{return null}}(e,t,r);return o.set(r,{startedAt:n,root:i}),i}async function Ca(e,t,r){try{return(await t.exec(e,r,["config","--get","remote.origin.url"],{caller:"getGitRemoteUrl"})).stdout.trim()}catch{return}}function Ea(e){const t=e.trim();if(""===t)return t;try{const e=new URL(t);return""===e.host?Pa(t)??e.toString():(e.username="",e.password="",e.toString())}catch{return function(e){const t=e.replace(/^[\u0000-\u0020]+|[\u0000-\u0020]+$/g,"").replace(/[\t\n\r]/g,""),r=t.indexOf(":"),n=t.slice(0,r);if(r<0||!/^[A-Za-z][A-Za-z0-9+.-]*$/.test(n))return;const o=t.slice(r+1),s=xa.has(n.toLowerCase());let i;if(s)i=o.replace(/^[/\\]+/,"");else{if(!o.startsWith("//"))return;i=o.slice(2)}const a=i.search(s?/[/?#\\]/:/[/?#]/),c=a<0?i.length:a,l=i.slice(0,c),u=l.lastIndexOf("@");return u<0?void 0:`${t.slice(0,t.length-i.length)}${l.slice(u+1)}${i.slice(c)}`}(t)??Pa(t)??t}}const xa=new Set(["ftp","file","http","https","ws","wss"]);function Pa(e){const t=e.indexOf("/"),r=t<0?e:e.slice(0,t),n=r.indexOf(":"),o=r.lastIndexOf("@",r.lastIndexOf(":"));if(!(n<0||o<0||r.indexOf("@")<n))return e.slice(o+1)}const Ia=["**/node_modules/**","**/.git/**","**/.turbo/**","**/.next/**","**/.cache/**","**/.pnpm/**","**/.yarn/**","**/dist/**","**/build/**","**/out/**","**/target/**","**/.vscode/**","**/.idea/**","**/venv/**","**/__pycache__/**","**/logs/**","**/tmp/**","**/temp/**"];function Ra(e,t){return Ds(e,t).map((t=>`/${s.posix.relative(e,t)}`))}var Ta=r("../../node_modules/.pnpm/picomatch@4.0.5/node_modules/picomatch/index.js");function Aa(e,t){return e.some((e=>{return"*"===e.url.trim()?(e.patterns??[]).some((e=>Da(e.pattern,t))):!((r=e.url).includes("://")||r.includes("github.com")||r.includes("gitlab.com")||r.includes("bitbucket.org")||r.includes("@"))&&Da(e.url,t);var r}))}function $a(e,t,r){return Ma(e.url,t)&&(e.patterns??[]).some((e=>Da(e.pattern,r)))}function Ma(e,t){return e.includes("*")?"*"===e.trim()||function(e,t){const r=e.trim();return!!Da(r,t)||!!r.startsWith("*/")&&Da(`**/${r.slice(2)}`,t)}(ja(e),ja(t)):ja(e)===ja(t)}function Da(e,t){const r=e.trim();return!("."!==t&&""!==t||"**"!==r&&"**/*"!==r)||function(e){const t=Na.get(e);if(void 0!==t)return t;let r;try{const t=Ta(e,{dot:!0});r=r=>{try{return t(r)}catch{return e===r}}}catch{r=t=>e===t}return La(Na,Oa,e,r)}(r)(t)}const Oa=2048,Fa=new Map,Na=new Map;function La(e,t,r,n){if(e.set(r,n),e.size>t){const t=e.keys().next().value;void 0!==t&&e.delete(t)}return n}function ja(e){const t=Fa.get(e);if(void 0!==t)return t;const r=(function(e){const t=ba(e);if(void 0!==t)return`${t.hostname}/git/${t.owner}/${t.name}`.toLowerCase()}(n=e)??wa(n))||function(e){let t=e.trim();t.startsWith("git@")&&(t=`https://${t.slice(4).replace(":","/")}`),/^[a-z][a-z0-9+.-]*:\/\//i.test(t)&&!/^https?:\/\//i.test(t)&&(t=t.replace(/^[a-z][a-z0-9+.-]*:\/\//i,"https://")),/^https?:\/\//i.test(t)||(t=`https://${t}`);try{const e=new URL(t),r=e.pathname.replace(/\/+$/,"").replace(/\.git$/i,"").replace(/\/+$/,"");return e.hostname+r}catch{return t=t.replace(/^https?:\/\//i,""),t=t.replace(/[?#].*$/,""),t=t.replace(/\/+$/,""),t=t.replace(/\.git$/i,""),t=t.replace(/\/+$/,""),t}}(e).toLowerCase();var n;return La(Fa,2048,e,r)}function Ua(e){if("object"==typeof e&&null!==e&&"code"in e){const t=e.code;if("string"==typeof t)return t}}function Ba(e){if(e instanceof Error)return e.message;if("object"==typeof e&&null!==e&&"message"in e){const t=e.message;if("string"==typeof t)return t}return""}(0,fs.J)((function(){Fa.clear(),Na.clear()}));const Wa=[".gitignore",".cursorignore"];async function Ha(e){if(!(0,s.isAbsolute)(e))return null;const t=await(0,Ho.DN)(e);return null===t?null:t}function qa(e,t){if(!e||0===e.length)return[...t];const r=new Set(e);for(const e of t)r.has(e)&&r.delete(e),r.add(e);return[...r]}class za{constructor(e,t,r,n={}){this.disposeRequested=!1,this.initIgnoreService=()=>Ka.init((0,y.q6)(),e,r??[process.cwd()],t),!0!==n.deferInit&&this.ensureStarted()}ensureStarted(){if(void 0===this.ignoreServicePromise){if(this.disposeRequested)return Promise.reject(new Error("LazyIgnoreService was disposed before its ignore-file scan started"));this.ignoreServicePromise=this.initIgnoreService()}return this.ignoreServicePromise}isIgnoredByAny(e){return this.ensureStarted().then((t=>t.isIgnoredByAny(e)))}isGitIgnored(e){return this.ensureStarted().then((t=>t.isGitIgnored(e)))}isCursorIgnored(e,t){return this.ensureStarted().then((r=>r.isCursorIgnored(e,t)))}isRepoBlocked(e){return this.ensureStarted().then((t=>t.isRepoBlocked(e)))}listCursorIgnoreFilesByRoot(e){return this.ensureStarted().then((t=>t.listCursorIgnoreFilesByRoot(e)))}getCursorIgnoreMapping(){return this.ensureStarted().then((e=>e.getCursorIgnoreMapping()))}getShellSandboxIgnoreMapping(e){return this.ensureStarted().then((t=>t.getShellSandboxIgnoreMapping(e)))}getGitIgnoreMapping(){return this.ensureStarted().then((e=>e.getGitIgnoreMapping()))}getRepoBlockExcludeGlobs(e){return this.ensureStarted().then((t=>t.getRepoBlockExcludeGlobs(e)))}handleCursorIgnoreCreated(e){return this.ensureStarted().then((t=>t.handleCursorIgnoreCreated(e)))}handleCursorIgnoreChanged(e){return this.ensureStarted().then((t=>t.handleCursorIgnoreChanged(e)))}handleCursorIgnoreDeleted(e){return this.ensureStarted().then((t=>t.handleCursorIgnoreDeleted(e)))}dispose(){this.disposeRequested||(this.disposeRequested=!0,this.ignoreServicePromise?.then((e=>{e.dispose()})).catch((()=>{})))}}const Ga=Math.min(8,Math.max(1,Math.floor(o.default.availableParallelism()/2)));class Va{constructor(e){this.maxLookups=e,this.instances=new Map,this.lookups=0}get(e,t){this.lookups>=this.maxLookups&&this.clear(),this.lookups++;let r=this.instances.get(e);return void 0===r&&(r=Ji().add(t),this.instances.set(e,r)),r}delete(e){this.instances.delete(e)}clear(){this.instances.clear(),this.lookups=0}}class Ka{constructor(e,t,r,n,o,s){this.gitExecutor=e,this.gitIgnoreMapping=t,this.cursorIgnoreMapping=r,this.teamSettingsService=n,this.rootDirectories=o,this.scanEnvironment=s,this.gitIgnoreCache=new Ts.q({max:2e3}),this.cursorIgnoreCache=new Ts.q({max:2e3}),this.gitRootCache=new Ts.q({max:1e4}),this.gitRemoteUrlCache=new Ts.q({max:200}),this.hasGitDirCache=new Ts.q({max:1e3}),this.gitParsedIgnoreCache=new Va(1e4),this.cursorParsedIgnoreCache=new Va(1e4),this.ignoreMappingsHaveEntries=!1,this.directoryWalkPlacementCache=new Ts.q({max:1e4}),this.extraRootCursorIgnoreCache=new Ts.q({max:32}),this.extraGitRepoMappingCache=new Ts.q({max:32}),this.unwalkedFolders=o.flatMap((e=>Ds(e,s)))}static getRipwalkCache(){return Ka.ripwalkCache??=new ha,Ka.ripwalkCache}hasNoWorkspaceFolders(){return!this.ignoreMappingsHaveEntries&&(this.ignoreMappingsHaveEntries=Object.keys(this.gitIgnoreMapping).length>0||Object.keys(this.cursorIgnoreMapping).length>0,!this.ignoreMappingsHaveEntries)}async resolveLookupRoot(e){return await(0,Ho.DN)(e)??(0,Ho.o1)(e)}static async init(e,t,r,n,s={platform:process.platform,homeDirectory:o.default.homedir()}){const i={...s,homeDirectory:await(0,Ho.DN)(s.homeDirectory)??s.homeDirectory},a=await(0,Dr.PH)(r,(async e=>{const t=await(0,Ho.DN)(e);return null===t?(console.warn(`[IgnoreService] Cannot resolve workspace root, using as-is: ${e}`),e):t})),c={},l={},u=(await(0,Dr.PH)(a,(async r=>{const n=await _a(e,t,r);return null!==n&&Ds(n,i).length>0?r:n}))).filter((e=>null!==e));return u.length>0&&await Promise.all([Ka.initializeIgnoreMapping(u,".gitignore",c,i),Ka.initializeIgnoreMapping(a,".cursorignore",l,i)]),new Ka(t,c,l,n,a,i)}static async preloadHierarchy(e,t,r,n){let o=(0,Ho.o1)(e);const i=(0,s.parse)(o).root;for(;o!==i;){if(n?.has(o)){const e=(0,s.dirname)(o);if(e===o)break;o=e;continue}void 0===r[o]&&await Ka.handleHierarchyIgnore(o,t,r),n?.add(o);const e=(0,s.dirname)(o);if(e===o)break;o=e}}static async handleHierarchyIgnore(e,t,r){const n=(0,s.join)(e,t);try{await(0,fo.access)(n,fo.default.constants.F_OK);const t=await Ti(n),o=Ka.parseIgnoreRules(t);r[e]=o}catch(o){"ENOENT"===Ua(o)||console.error(`Error reading ${t} file at ${n}:`,o),r[e]=[]}}static async initializeIgnoreMapping(e,t,r,n){try{const o=Ka.deduplicateRootDirectories(e),i=await Ka.promiseQueue.enqueueList(o,(e=>Ka.findFilesWithRipgrep(e,t,n))),a=Array.from(i.values()).flat();await Promise.all(a.map((async e=>{try{const t=await Ti(e),n=Ka.parseIgnoreRules(t),o=(0,s.dirname)(e);r[o]=n}catch(r){console.error(`Error processing ${t} file at ${e}:`,r)}})));const c=new Set;for(const e of o)await Ka.preloadHierarchy(e,t,r,c)}catch(e){console.error(`Error initializing ignore mapping for ${t}:`,e)}}static async findFilesWithRipgrep(e,t,r){const n=(0,y.q6)(),o=[],i={root:e,includeGlobs:Wa.map((e=>`**/${e}`)),excludeGlobs:[...Ia,...Ra(e,r)],source:"ignore_scan"},a=Ka.getRipwalkCache().walk(n,i);for await(const r of a.lines)(0,s.basename)(r)===t&&o.push((0,s.join)(e,r));return o}async handleManualLookupWhenNoWorkspaceDirs(e,t,r){const n={};let o=(0,s.dirname)(e);const i=(0,s.parse)(o).root;for(;;){let e=r?.get(o);if(void 0===e){try{e=Ka.parseIgnoreRules(await Ti((0,s.join)(o,t)))}catch{e=[]}r?.set(o,e)}if(e.length>0&&(n[o]=e),o===i)break;o=(0,s.dirname)(o)}return this.testIgnored(e,n,((e,t)=>Ji().add(t)))}async isIgnoredByAny(e){const[t,r,n]=await Promise.all([this.checkGitIgnored(e),this.checkCursorIgnored(e),this.checkRepoBlocked(e)]);return t||r||n}async isGitIgnored(e){return this.checkGitIgnored(e)}async isCursorIgnored(e,t){return this.checkCursorIgnored(e,t)}async checkGitIgnored(e){if(this.hasNoWorkspaceFolders())return this.handleManualLookupWhenNoWorkspaceDirs(e,".gitignore");const t=this.gitIgnoreCache.get(e);if(void 0!==t)return t;await this.populateHierarchyIfNeeded(e,".gitignore",this.gitIgnoreMapping);const r=this.checkIgnored(e,this.gitIgnoreMapping,this.gitParsedIgnoreCache);return this.gitIgnoreCache.set(e,r),r}async checkCursorIgnored(e,t){if(this.hasNoWorkspaceFolders())return this.handleManualLookupWhenNoWorkspaceDirs(e,".cursorignore",t);const r=this.cursorIgnoreCache.get(e);if(void 0!==r)return r;await this.populateHierarchyIfNeeded(e,".cursorignore",this.cursorIgnoreMapping);const n=this.checkIgnored(e,this.cursorIgnoreMapping,this.cursorParsedIgnoreCache);return this.cursorIgnoreCache.set(e,n),n}isInUnwalkedFolder(e){const t="darwin"===this.scanEnvironment.platform,r=t?e.toLowerCase():e;return this.unwalkedFolders.some((e=>(0,Ho.ZU)({basePath:t?e.toLowerCase():e,targetPath:r})))}directoryWalkPlacement(e){const t=this.directoryWalkPlacementCache.get(e);if(void 0!==t)return t;let r;return r=this.isInUnwalkedFolder(e)?"unwalked":this.rootDirectories.some((t=>(0,Ho.ZU)({basePath:t,targetPath:e})))?"walked":"outside",this.directoryWalkPlacementCache.set(e,r),r}async populateHierarchyIfNeeded(e,t,r){let n=(0,s.dirname)((0,Ho.o1)(e));const o=[],i=(0,s.parse)(n).root;for(;n!==i;){const e=this.directoryWalkPlacement(n),t="unwalked"===e;if("walked"===e){n=(0,s.dirname)(n);continue}if(void 0===r[n])o.push(n);else if(!t)break;const i=(0,s.dirname)(n);if(i===n)break;n=i}o.length>0&&(await Ka.promiseQueue.enqueueList(o,(e=>Ka.handleHierarchyIgnore(e,t,r))),".gitignore"===t?this.gitIgnoreCache.clear():this.cursorIgnoreCache.clear())}testIgnored(e,t,r){for(const[n,o]of Object.entries(t)){if(0===o.length)continue;if(!(0,Ho.ZU)({basePath:n,targetPath:e}))continue;const t=(0,s.relative)(n,e);if(""===t)continue;const i=r(n,o),a=(0,Ho.oL)(t),c=i.test(a);if(c.ignored&&!c.unignored)return!0;const l=i.test(`${a}/`);if(l.ignored&&!l.unignored)return!0}return!1}checkIgnored(e,t,r){return this.testIgnored(e,t,((e,t)=>r.get(e,t)))}async listCursorIgnoreFilesByRoot(e){const t=await this.resolveLookupRoot(e),r=[];for(const[e,n]of Object.entries(this.cursorIgnoreMapping)){if(0===n.length)continue;if(!(0,Ho.ZU)({basePath:t,targetPath:e}))continue;const o=(0,s.join)(e,".cursorignore");try{await(0,fo.access)(o),r.push(o)}catch{}}return r}async getCursorIgnoreMapping(){return{...this.cursorIgnoreMapping}}async getShellSandboxIgnoreMapping(e=[]){const t={...this.cursorIgnoreMapping},r=[];for(const t of e){if((0,Os.$f)(t))continue;const e=await(0,Ho.DN)(t);if(null===e||".git"===(0,s.basename)(e)||this.rootDirectories.some((t=>(0,Ho.ZU)({basePath:t,targetPath:e})))||r.includes(e))continue;const n=await fo.default.stat(e).catch((e=>{if(void 0===Ua(e))throw e}));n?.isDirectory()&&r.push(e)}const n=Date.now();for(const e of r){let r=this.extraRootCursorIgnoreCache.get(e);if(void 0===r||r.expiresAt<=n){const t={};await Ka.initializeIgnoreMapping([e],".cursorignore",t,this.scanEnvironment),r={mapping:t,expiresAt:n+ua()},this.extraRootCursorIgnoreCache.set(e,r)}for(const[e,n]of Object.entries(r.mapping))t[e]=qa(t[e],n)}for(const e of[...this.rootDirectories,...r]){const r=await this.getRepoBlockExcludeGlobs(e);0!==r.length&&(t[e]=qa(t[e],r))}return t}async getGitIgnoreMapping(){return{...this.gitIgnoreMapping}}static deduplicateRootDirectories(e){const t=[...e.map((e=>(0,Ho.o1)(e)))].sort(((e,t)=>e.length-t.length)),r=[];for(const e of t)r.some((t=>e.startsWith(`${t}/`)||e.startsWith(`${t}\\`)))||r.push(e);return r}static parseIgnoreRules(e){return e.split("\n").map((e=>e.replace(/\r$/,"").trimStart())).filter((e=>""!==e&&!e.startsWith("#")))}clearCaches(){this.gitIgnoreCache.clear(),this.cursorIgnoreCache.clear(),this.gitRootCache.clear(),this.gitRemoteUrlCache.clear(),this.hasGitDirCache.clear(),this.gitParsedIgnoreCache.clear(),this.cursorParsedIgnoreCache.clear(),this.extraRootCursorIgnoreCache.clear(),this.extraGitRepoMappingCache.clear()}dispose(){this.gitIgnoreCache=new Ts.q({max:1}),this.cursorIgnoreCache=new Ts.q({max:1}),this.gitRootCache=new Ts.q({max:1}),this.gitRemoteUrlCache=new Ts.q({max:1}),this.hasGitDirCache=new Ts.q({max:1}),this.directoryWalkPlacementCache=new Ts.q({max:1}),this.extraRootCursorIgnoreCache=new Ts.q({max:1}),this.extraGitRepoMappingCache=new Ts.q({max:1}),this.gitParsedIgnoreCache.clear(),this.cursorParsedIgnoreCache.clear(),this.gitRepoMappingPromise=void 0}async handleCursorIgnoreCreated(e){const t=(0,s.dirname)(e),r=await Ti(e),n=Ka.parseIgnoreRules(r);this.cursorIgnoreMapping[t]=n,this.cursorParsedIgnoreCache.delete(t),this.cursorIgnoreCache.clear(),this.extraRootCursorIgnoreCache.clear()}async handleCursorIgnoreChanged(e){const t=(0,s.dirname)(e),r=await Ti(e),n=Ka.parseIgnoreRules(r);this.cursorIgnoreMapping[t]=n,this.cursorParsedIgnoreCache.delete(t),this.cursorIgnoreCache.clear(),this.extraRootCursorIgnoreCache.clear()}handleCursorIgnoreDeleted(e){const t=(0,s.dirname)(e);this.cursorIgnoreMapping[t]=[],this.cursorParsedIgnoreCache.delete(t),this.cursorIgnoreCache.clear(),this.extraRootCursorIgnoreCache.clear()}async findGitRootsForFile(e){const t=(0,Ho.o1)(e),r=this.gitRootCache.get(t);if(void 0!==r)return r;const n=[],o=[],i=[];let a=t;const c=(0,s.parse)(a).root;for(;a!==c;){o.push(a),void 0===this.hasGitDirCache.get(a)&&i.push(a);const e=(0,s.dirname)(a);if(e===a)break;a=e}if(i.length>0){const e=i.map((e=>(0,fo.access)((0,s.join)(e,".git"),fo.default.constants.F_OK).then((()=>[e,!0])).catch((()=>[e,!1])))),t=await Promise.all(e);for(const[e,r]of t)this.hasGitDirCache.set(e,r)}for(const e of o)!0===this.hasGitDirCache.get(e)&&n.push(e);return this.gitRootCache.set(t,n),n}async isRepoBlocked(e){return this.checkRepoBlocked(e)}async checkRepoBlocked(e){const t=function(e){if(void 0===e)return;const t=e.repos??[],r=e.disableLocalExecAllowlistEnforcement?[]:e.allowedRepos??[];return 0===t.length&&0===r.length?void 0:{blocked:t,allowed:r}}(await(this.teamSettingsService?.getTeamRepos()));if(void 0===t)return!1;const r=await this.findGitRootsForFile(e);if(0===r.length)return 0!==t.allowed.length&&!(0,Ho.ZU)({basePath:await this.getCursorDataDir(),targetPath:e})&&function(e,t){return 0!==e.allowed.length&&!Aa(e.allowed,t)}(t,this.getWorkspaceRelativePath(e));const n=[];for(const t of r)n.push({url:await this.remoteUrlOf(t),relativePath:(0,s.relative)(t,e)||"."});return function(e,t){let r=0===e.allowed.length,n=!1;for(const{url:o,relativePath:s}of t)if(void 0!==o){if(e.blocked.some((e=>$a(e,o,s))))return!0;e.allowed.length>0&&!n&&(n=!0,r=e.allowed.some((e=>$a(e,o,s))))}else 0;return!r}(t,n)}async remoteUrlOf(e){if(this.gitRemoteUrlCache.has(e))return this.gitRemoteUrlCache.get(e);const t=await Ca((0,y.q6)(),this.gitExecutor,e);return void 0!==t&&this.gitRemoteUrlCache.set(e,t),t}getWorkspaceRelativePath(e){let t;for(const r of this.rootDirectories)(0,Ho.ZU)({basePath:r,targetPath:e})&&(void 0===t||r.length>t.length)&&(t=r);return void 0!==t?(0,Ho.oL)((0,s.relative)(t,e)):(0,Ho.oL)(e)}getCursorDataDir(){return this.cursorDataDirPromise??=(async()=>{const e=(0,s.join)(o.default.homedir(),".cursor");return await(0,Ho.DN)(e)??e})(),this.cursorDataDirPromise}async getRepoBlockExcludeGlobs(e){const t=await(this.teamSettingsService?.getTeamRepos());if(!t?.repos?.length)return[];const r=await this.resolveLookupRoot(e);let n;if(this.rootDirectories.some((e=>(0,Ho.ZU)({basePath:e,targetPath:r}))))n=await this.getGitRepoMapping();else{const e=this.extraGitRepoMappingCache.get(r);void 0!==e?n=e:(n=await this.initializeGitRepoMapping([r]),this.extraGitRepoMappingCache.set(r,n))}if(0===n.size)return[];const o=[];for(const[e,i]of n){if(void 0===i)continue;const n=this.normalizePathForComparison(e),a=this.normalizePathForComparison(r);let c=!1,l="";if(a.startsWith(n)?(c=!0,l=""):n.startsWith(a)&&(c=!0,l=(0,s.relative)(r,e)),!c)continue;const u=t.repos.filter((e=>Ma(e.url,i)));if(0!==u.length)for(const e of u)for(const t of e.patterns||[]){const e=t.pattern.trim();if(!e)continue;let r;r=l?(0,s.join)(l,e).replace(/\\/g,"/"):e,o.push(r),r.endsWith("/**")||o.push(`${r}/**`)}}return o}normalizePathForComparison(e){let t=e.replace(/\\/g,"/");return t.startsWith("/")&&t.length>2&&":"===t[2]&&(t=t.substring(1)),"win32"===process.platform&&(t=t.toLowerCase()),t}getGitRepoMapping(){return this.gitRepoMappingPromise||(this.gitRepoMappingPromise=this.initializeGitRepoMapping()),this.gitRepoMappingPromise}async initializeGitRepoMapping(e=this.rootDirectories){const t=new Map,r=[],n=["**/node_modules/**","**/.turbo/**","**/.next/**","**/.cache/**","**/.pnpm/**","**/.yarn/**","**/dist/**","**/build/**","**/out/**","**/target/**","**/.vscode/**","**/.idea/**","**/venv/**","**/__pycache__/**","**/logs/**","**/tmp/**","**/temp/**"],o=(0,y.q6)();for(const t of e){const e=(0,Ho.o1)(t);try{await(0,fo.access)((0,s.join)(e,".git"),fo.default.constants.F_OK),r.includes(e)||r.push(e)}catch{}let i=(0,s.dirname)(e);const a=(0,s.parse)(i).root;for(;i!==a&&""!==i;){try{await(0,fo.access)((0,s.join)(i,".git"),fo.default.constants.F_OK),r.includes(i)||r.push(i)}catch{}const e=(0,s.dirname)(i);if(e===i)break;i=e}try{const t={root:e,includeGlobs:["**/.git/config"],excludeGlobs:[...n,...Ra(e,this.scanEnvironment)],noIgnoreVcs:!0,source:"ignore_scan"},i=Ka.getRipwalkCache().walk(o,t);for await(const t of i.lines){const n=(0,s.join)(e,t),o=(0,s.dirname)(n),i=(0,s.dirname)(o);r.includes(i)||r.push(i)}}catch{}}return await Promise.all(r.map((async e=>{try{const r=await Ca(o,this.gitExecutor,e);t.set(e,r)}catch{t.set(e,void 0)}}))),t}}async function Ja(e,t){let r=e;if(_s()&&(r=Rs(t.command,t.parsingResult)),!r||"insecure_none"===r.type)return r;const n="workspace_readwrite"===r.type&&t.permissionsService.resolveLinkedWorktreeSandboxGrants?await t.permissionsService.resolveLinkedWorktreeSandboxGrants(r,{command:t.command,workingDirectory:t.workingDirectory}):void 0,o=function(e,t){if(!e)return t;const r={...e};for(const[e,n]of Object.entries(t))r[e]=qa(r[e],n);return r}(r.ignoreMapping,await async function(e,t){return e.getShellSandboxIgnoreMapping?e.getShellSandboxIgnoreMapping(t):e.getCursorIgnoreMapping()}(t.ignoreService,n?.roots));if("workspace_readwrite"===r.type&&void 0!==n){const e=(0,Eo.s9)(r.additionalReadwritePaths,[...n.roots,...n.commonDirs]);return{...r,additionalReadwritePaths:e.length>0?e:void 0,ignoreMapping:o}}return{...r,ignoreMapping:o}}Ka.promiseQueue=new Dr.TJ({max:Ga});var Za=r("../proto/dist/generated/agent/v1/mcp_exec_pb.js");const Xa="agent-tools",Qa=51380224;var Ya=r("../proto/dist/generated/agent/v1/utils_pb.js");const ec=new Fs.TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}),tc=new Map([["€",128],["‚",130],["ƒ",131],["„",132],["…",133],["†",134],["‡",135],["ˆ",136],["‰",137],["Š",138],["‹",139],["Œ",140],["Ž",142],["‘",145],["’",146],["“",147],["”",148],["•",149],["–",150],["—",151],["˜",152],["™",153],["š",154],["›",155],["œ",156],["ž",158],["Ÿ",159]]),rc=new Set([194,195,226,239]),nc=/\p{Lu}/u,oc=new Set([" ","","«","»","‹","›","‘","’","“","”","•","–","—","…","™"]),sc=new Set(["¿","¡"]),ic=new Map([[215,new Set(["¹","²","³","¼","½","¾","°","±","€","¢","£","¤","¥"])],[216,new Set(["¹","²","³","¼","½","¾","°","±","€","¢","£","¤","¥"])],[197,new Set(["¹","²","³"])],[205,sc],[209,sc],[211,sc],[218,sc],[220,sc]]),ac=new Set(["ƒ","Š","Œ","Ž","š","œ","ž","Ÿ"]),cc=/[\p{Cc}\p{Cn}\p{Cs}\p{Co}]/u;function lc(e){if(void 0===e)return;const t=e.charCodeAt(0);return t>=128&&t<=191?t:tc.get(e)}function uc(e,t){const r=e.charCodeAt(t),n=function(e){return e>=194&&e<=222?201===e?0:2:e>=224&&e<=239?3:240===e?4:0}(r);if(0===n||t+n>e.length)return;const o=new Uint8Array(n);o[0]=r;for(let r=1;r<n;r++){const n=lc(e[t+r]);if(void 0===n)return;o[r]=n}const s=e[t+1];if(rc.has(r)){if(195===r&&oc.has(s)&&t>0&&nc.test(e[t-1]))return}else{if(oc.has(s))return;if(!0===ic.get(r)?.has(s))return;if(3===n&&ac.has(s)&&oc.has(e[t+2]))return}let i;try{i=ec.decode(o)}catch{return}return cc.test(i)?void 0:{index:t,text:e.slice(t,t+n),repaired:i}}function dc(e,t=Number.POSITIVE_INFINITY){const r=[];let n=0;for(;n<e.length&&r.length<t;){const t=e.charCodeAt(n);if(t<194||t>240){n++;continue}const o=uc(e,n);void 0!==o?(r.push(o),n+=o.text.length):n++}return r}const hc=`[\\u00c2-\\u00f0][\\u0080-\\u00bf${[...tc.keys()].join("")}]`,pc=new RegExp(hc),fc=/\p{L}/u;function mc(e,t){const r=e.charCodeAt(t);let n;if(r>=194&&r<=223)n=2;else if(r>=224&&r<=239)n=3;else{if(!(r>=240&&r<=244))return 0;n=4}if(t+n>e.length)return 0;for(let r=1;r<n;r++){const n=e.charCodeAt(t+r);if(!(n>=128&&n<=191)&&(n<128||!tc.has(e[t+r])))return 0}return n}function gc(e,t){if(t.text.length>2)return!0;const r=t.text.charCodeAt(1);if(r>=128&&r<=159)return!0;if(0===t.index||!nc.test(e[t.index-1]))return!0;const n=t.index+t.text.length;return n<e.length&&fc.test(e[n])}const wc=["mojibake","replacement_chars"];function yc(e){return e<=1?"1":e<6?"2-5":"6+"}function vc(e){return e<=0?"0":yc(e)}function bc(e,t,r){if(void 0===e)return"new";if(t>0)return"damaged";const n=xc(r);return"utf8"!==n&&"utf8_bom"!==n?"other_encoding":"intact"}function Sc(e,t){return e<=t?"existing_only":"new_damage"}function kc(e,t){const r=new Set(t.map((e=>e.text))),n=e.filter((e=>!r.has(e.text))),o=n.length>0?n:e;if(function(e){let t="",r=-1;for(const n of e){if(n.index!==r){if(dc(t,1).length>0)return!0;t=""}t+=n.repaired,r=n.index+n.text.length}return dc(t,1).length>0}(o))return"double";if(1!==new Set(o.map((e=>e.text.length))).size)return"mixed";switch(o[0].text.length){case 2:return"two_byte";case 3:return"three_byte";default:return"four_byte"}}function _c(e){return{detector:e,outcome:"clean",afterCount:0,beforeCount:0}}function Cc(e,t,r){const n=dc(r,1e3);if(0===n.length)return _c("mojibake");const o=void 0===e?[]:dc(e,Math.max(n.length,6));return{detector:"mojibake",outcome:Sc(n.length,o.length),file:bc(e,o.length,t),afterCount:n.length,beforeCount:o.length,pattern:kc(n,o)}}function Ec(e,t,r){const n=ei(r);if(0===n)return _c("replacement_chars");const o=void 0===e?0:ei(e);return{detector:"replacement_chars",outcome:Sc(n,o),file:bc(e,o,t),afterCount:n,beforeCount:o}}function xc(e){if(void 0===e)return"none";const t=e.toLowerCase().replace(/[^a-z0-9]/g,"");return"utf8"===t||"ascii"===t?"utf8":"utf8bom"===t?"utf8_bom":t.startsWith("utf16")?"utf16":"latin1"===t||"iso88591"===t?"latin1":"windows1252"===t||"cp1252"===t?"windows_1252":"gbk"===t||"gb2312"===t||"gb18030"===t||"cp936"===t?"gbk":"shiftjis"===t||"sjis"===t||"cp932"===t||"windows31j"===t?"shift_jis":"euckr"===t||"cp949"===t?"euc_kr":"big5"===t||"big5hkscs"===t||"cp950"===t?"big5":"other"}const Pc=new Map([["md",["md","mdx","markdown"]],["txt",["txt","text","log","rst","adoc","asciidoc","tex"]],["js_ts",["js","jsx","mjs","cjs","ts","tsx","mts","cts"]],["web",["html","htm","xhtml","css","scss","sass","less","vue","svelte","astro"]],["py",["py","pyi","pyw","ipynb"]],["jvm",["java","kt","kts","scala","groovy","gradle"]],["dotnet",["cs","csx","vb","fs","fsx","razor","cshtml","xaml"]],["c_cpp",["c","h","cc","cpp","cxx","c++","hpp","hh","hxx","h++","m","mm"]],["other_code",["go","rs","rb","erb","php","swift","dart","lua","pl","pm","r","ex","exs","erl","hs","clj","cljs","zig","nim","jl","sol","elm","ml","mli","pas","bas"]],["shell",["sh","bash","zsh","fish","ps1","psm1","psd1","bat","cmd"]],["sql",["sql","psql","ddl","dml"]],["config",["json","jsonc","json5","yaml","yml","toml","ini","cfg","conf","env","properties","editorconfig"]],["xml",["xml","xsl","xslt","xsd","svg","csproj","vbproj","fsproj","props","targets","nuspec","plist","storyboard","xib"]],["i18n",["po","pot","strings","stringsdict","arb","xlf","xliff","ftl","resx"]],["csv",["csv","tsv"]]].flatMap((([e,t])=>t.map((t=>[t,e])))));function Ic(e){const t=(0,s.extname)(e).slice(1).toLowerCase();return""===t?"none":Pc.get(t)??"other"}const Rc=new Map([[1252,"1252"],[1250,"1250"],[1251,"1251"],[874,"874"],[932,"932"],[936,"936"],[949,"949"],[950,"950"],[65001,"65001"]]);function Tc(e){if("string"==typeof e)return e;const t=void 0===e.acp?void 0:Rc.get(e.acp);return void 0===t?"other":e.oemcp===e.acp?t:`${t}_split`}function Ac(e,t){if("clean"===e.outcome)return{detector:e.detector,outcome:"clean",file:"unclassified"};const r={outcome:e.outcome,file:e.file,ext:Ic(t.path),encoding:xc(t.encoding),code_page:Tc(t.pages),run_count:yc(e.afterCount),delta:(n=e.afterCount-e.beforeCount,n<0?"neg":vc(n)),before_count:vc(e.beforeCount)};var n;return"mojibake"===e.detector?{detector:"mojibake",pattern:e.pattern,...r}:{detector:"replacement_chars",...r}}class $c{constructor(){this.counts={stdout:0,stderr:0},this.produced={stdout:!1,stderr:!1}}note(e,t){if(0===t.length)return;this.produced[e]=!0;const r=this.counts[e];r>=6||(this.counts[e]=r+ei(t,6-r))}labels(e,t){const r=Tc(t),n=[];for(const t of["stdout","stderr"]){if(!this.produced[t])continue;const o=this.counts[t];n.push({detector:"replacement_chars",outcome:o>0?"damaged":"clean",run_count:vc(o),branch:e[t],stream:t,code_page:r})}return n}}const Mc=/[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/,Dc=Object.getOwnPropertyDescriptor(String.prototype,"isWellFormed")?.value;const Oc=["replacement","lone_surrogate","mojibake_high","mojibake_medium","utf16","c1","clean"],Fc=/\0[^\0]\0/,Nc=/[\u0080-\u009f]/,Lc=new RegExp(`[\\u0080-\\u009f]|${hc}`),jc="\\u0000",Uc=/\\u(?:[dD][89a-fA-F]|0000)/,Bc=/\\u[dD](?:([89abAB])|[c-fC-F])[0-9a-fA-F]{2}/g,Wc=/\\u[dD][c-fC-F][0-9a-fA-F]{2}/y;function Hc(e,t){let r=0;for(;r<t&&92===e.charCodeAt(t-1-r);)r++;return r%2==0}function qc(e,t){return 92!==e.charCodeAt(t)?1:117===e.charCodeAt(t+1)?6:2}function zc(e,t={}){const r=n.Buffer.byteLength(e,"utf8")===e.length;if(!r&&e.includes("�"))return"replacement";const o=!0===t.jsonEscaped&&Uc.test(e);if(!r&&function(e){return"function"!=typeof Dc?function(e){return Mc.test(e)}(e):!0!==Reflect.apply(Dc,e,[])}(e)||o&&function(e){Bc.lastIndex=0;for(let t=Bc.exec(e);null!==t;t=Bc.exec(e))if(Hc(e,t.index)){if(void 0===t[1])return!0;if(Wc.lastIndex=t.index+6,!Wc.test(e))return!0;Bc.lastIndex=t.index+12}return!1}(e))return"lone_surrogate";if(function(e,t){return!(!e.includes("\0")||!Fc.test(e))||t&&function(e){for(let t=e.indexOf(jc);-1!==t;t=e.indexOf(jc,t+6)){if(!Hc(e,t))continue;const r=t+6;if(!(r>=e.length||e.startsWith(jc,r))&&e.startsWith(jc,r+qc(e,r)))return!0}return!1}(e)}(e,o))return"utf16";if(r)return"clean";if(!Lc.test(e))return"clean";const s=function(e){if(!pc.test(e))return;let t=0,r=!1,n=!0,o=0;for(;o<e.length;){const s=e.charCodeAt(o);if(s<128){o++;continue}const i=!r&&s>=194&&s<=240?uc(e,o):void 0;if(void 0!==i){if(t++,r=gc(e,i),o+=i.text.length,!n||!r&&t>=256)return"medium";continue}const a=n?mc(e,o):0;if(0===a){if(n=!1,t>0)return"medium";o++}else o+=a}return 0!==t?r&&n?"high":"medium":void 0}(e);return void 0!==s?"high"===s?"mojibake_high":"mojibake_medium":Nc.test(e)?"c1":"clean"}const Gc=/^v?(\d{1,9})\.(\d{1,9})(?:\.\d{1,9})?(?:[-+][0-9A-Za-z.+-]*)?$/,Vc=["unknown","other","older","3.24","3.25","3.26","3.27","3.28","3.29","3.30","3.31","3.32","3.33","3.34","3.35","3.36","3.37","3.38","3.39","3.40","newer"].flatMap((e=>{const t=/^(\d+)\.(\d+)$/.exec(e);return null===t?[]:[{major:Number(t[1]),minor:Number(t[2]),bucket:e}]})),Kc=Vc[0].major,Jc=Vc[0].minor;function Zc(e){if(null==e)return"unknown";const t=e.trim();if(0===t.length||t.length>128)return"unknown";const r=Gc.exec(t);if(null===r)return"unknown";const n=Number(r[1]),o=Number(r[2]);if(n!==Kc)return"other";const s=Vc.find((e=>e.minor===o));return void 0!==s?s.bucket:o<Jc?"older":"newer"}const Xc=(0,l.h)("local-exec:encoding-slices");function Qc(e,t){if(void 0===e)return!1;try{const{enabled:r}=e;return"function"==typeof r?r(t):r}catch{return!1}}function Yc(e,t,r=!1){if("clean"===e)return"clean";switch(t){case"utf8_valid":return"lone_surrogate"===e?"new_damage_cut":"existing_only";case"utf8_invalid":return"lone_surrogate"===e?"new_damage_cut":"replacement"!==e?"existing_only":r?"unknown":"not_text";case"utf8_cut":return"lone_surrogate"===e?"new_damage_cut":"replacement"!==e?"existing_only":r?"unknown":"new_damage_cut";case"utf8_as_other":return"new_damage_decode";case"declared_other":return"replacement"!==e||r?"unknown":"new_damage_decode";case"other_encoding":case"unseen":return"unknown";default:return t}}function el(e){for(let t=1;t<=Math.min(3,e.length);t++){const r=e[e.length-t]??0;if(128!=(192&r))return(r>=240?4:r>=224?3:r>=192?2:1)>t?t:0}return 0}class tl{constructor(){this.seen=!1,this.invalid=!1,this.carry=new Uint8Array(0)}write(e){if(0===e.length)return;if(this.seen=!0,this.invalid)return;const t=this.carry.length>0?Buffer.concat([this.carry,e]):e,r=el(t);if(!(0,n.isUtf8)(t.subarray(0,t.length-r)))return this.invalid=!0,void(this.carry=new Uint8Array(0));this.carry=r>0?Uint8Array.from(t.subarray(t.length-r)):t.subarray(0,0)}evidence(){return this.seen?this.invalid?"utf8_invalid":this.carry.length>0?"utf8_cut":"utf8_valid":"unseen"}}const rl=new Map(Object.entries({zsh:"zsh",zsh_light:"zsh_light",bash:"bash",pwsh:"pwsh",powershell51:"powershell51",naive_pwsh:"naive_pwsh",naive_powershell51:"naive_powershell51",naive_bash:"naive_bash",naive_zsh:"naive_zsh",naive_other:"naive_other"})),nl=(0,u.Pu)("local_exec.encoding_slice",{description:"Results a local executor returned, and results about to be encoded for the wire, by the boundary they were counted at, the kind of encoding damage their text holds (one kind per result, clean included), whose the damage is as far as the bytes at that boundary say, which executor the result came from, the client's version bucket, for a shell result counted on Windows how the code page lookup stood, and for a shell result which shell ran the command",labelNames:["layer","kind","origin","source","version_bucket","code_page_lookup","shell_kind"]}),ol=Oc[0],sl=new Map(Oc.map(((e,t)=>[e,t])));function il(e){return sl.get(e)??Oc.length}class al{constructor(){this.worst="clean",this.remaining=262144}note(e){this.walk(e,0)}kind(){return this.worst}capped(){return this.remaining<=0}settled(){return this.remaining<=0||this.worst===ol}noteText(e){if(0===e.length)return;const t=e.length>this.remaining?No(e,this.remaining):e;this.remaining-=Math.max(t.length,1);const r=zc(t);il(r)<il(this.worst)&&(this.worst=r)}walk(e,t){if(this.settled())return;if("string"==typeof e)return void this.noteText(e);if("object"!=typeof e||null===e||t>=16)return;if(ArrayBuffer.isView(e)||e instanceof ArrayBuffer)return;if(Array.isArray(e)){for(const r of e)if(this.walk(r,t+1),this.settled())return;return}const r=Object.values(e);for(const e of r)if(this.walk(e,t+1),this.settled())return}}class cl{constructor(e=1024){this.capacity=e,this.counted=new Set}firstRead(e,t){if(""===e)return!0;const r=`${e}\n${t}`,n=this.counted.delete(r);if(this.counted.add(r),this.counted.size>this.capacity)for(const e of this.counted){this.counted.delete(e);break}return!n}}function ll(e,t,r,n){const o={layer:r.layer,kind:n,origin:Yc(n,r.evidence??"unseen",!0===r.partial),source:r.source??r.layer,version_bucket:Zc(e.clientVersion)};void 0!==r.codePageLookup&&(o.code_page_lookup=r.codePageLookup),void 0!==r.shellKind&&(o.shell_kind=r.shellKind),nl.increment(t,1,o)}function ul(e,t){Xc.warn(e,"encoding slice was not counted (result unaffected)",{error:t instanceof Error?t.name:"unknown"})}function dl(e,t,r,n){if(void 0!==e&&Qc(e,t))try{const o=new al;o.note(n),ll(e,t,r,o.kind())}catch(e){ul(t,e)}}function hl(e,t,r,n){if(void 0!==e&&Qc(e,t))try{ll(e,t,r,n)}catch(e){ul(t,e)}}class pl{constructor(){this.seen=!1,this.invalid=!1}note(e){this.seen=!0,this.invalid||(0,n.isUtf8)(e)||(this.invalid=!0)}evidence(){return this.seen?this.invalid?"utf8_invalid":"utf8_valid":"unseen"}}function fl(e,t,r,n){return void 0===t?e:{execute:async(o,s,i)=>{const a=await e.execute(o,s,i);if(Qc(t,o))try{n(a)&&dl(t,o,{layer:r},a)}catch(e){ul(o,e)}return a}}}new Map([["readArgs","exec_read"],["redactedReadArgs","exec_read"],["grepArgs","exec_grep"],["mcpArgs","exec_mcp"],["readMcpResourceExecArgs","exec_mcp"],["executeHookArgs","exec_hooks"],["fetchArgs","exec_web_fetch"],["shellArgs","exec_shell"],["shellStreamArgs","exec_shell"],["backgroundShellSpawnArgs","exec_shell"],["miniSweAgentBashArgs","exec_shell"],["writeArgs","exec_write"]]);class ml{constructor(){this.text={stdout:new al,stderr:new al},this.bytes={stdout:new tl,stderr:new tl},this.produced={stdout:!1,stderr:!1},this.dropped={stdout:!1,stderr:!1},this.shellKind="unknown"}noteBytes(e,t){this.bytes[e].write(t)}noteText(e,t){0!==t.length&&(this.produced[e]=!0,this.text[e].note(t))}noteDropped(e){this.dropped[e]=!0}noteShell(e){this.shellKind=function(e){return"string"!=typeof e?"unknown":rl.get(e)??"unknown"}(e)}record(e,t,r,n){for(const o of["stdout","stderr"])this.produced[o]&&hl(e,t,{layer:"exec_shell",evidence:this.evidence(o,r[o]),partial:this.dropped[o]||this.text[o].capped(),codePageLookup:n,shellKind:this.shellKind},this.text[o].kind())}evidence(e,t){if("utf8"!==t)return"other_encoding";const r=this.bytes[e].evidence();return"utf8_cut"===r?"utf8_invalid":r}}var gl=r("node:child_process"),wl=r("../utils/dist/workload-spawn.js");const yl=(0,l.h)("local-exec:shell-output-encoding"),vl=(0,Fs.promisify)(gl.execFile),bl=/^\s*OEMCP\s+REG_\w+\s+(\d+)\s*$/m,Sl=/^\s*ACP\s+REG_\w+\s+(\d+)\s*$/m;function kl(e,t){const r=t.exec(e);return null===r?void 0:Number(r[1])}const _l="㐀-䶿一-鿿豈-",Cl=" -〿㈀-㏿︰--",El="‐-※←-⇿─-◿★☆",xl="-ヿ",Pl=new Map([["cp932",{script:new RegExp(`[${_l}${Cl}${El}${xl}]`),doubleByte:!0}],["cp936",{script:new RegExp(`[${_l}${Cl}${El}${xl}-ㄯ]`),doubleByte:!0}],["cp949",{script:new RegExp(`[${_l}${Cl}${El}${xl}-가-]`),doubleByte:!0}],["cp950",{script:new RegExp(`[${_l}${Cl}${El}-ㄯ]`),doubleByte:!0}],["cp874",{script:new RegExp("[-]"),doubleByte:!1}]]);const Il=function(e){let t,r,n,o,s=!1,i=0;const a=()=>{i+=1;const e=i;n=async function(){const{stdout:e}=await(0,wl.D9)(vl,"\\\\.\\GLOBALROOT\\SystemRoot\\System32\\reg.exe",["query","HKLM\\SYSTEM\\CurrentControlSet\\Control\\Nls\\CodePage"],{encoding:"buffer",timeout:3e3,windowsHide:!0});return e}().then((e=>{const i=function(e){const t=Buffer.isBuffer(e)?function(e){return e.length>=2&&255===e[0]&&254===e[1]?e.subarray(2).toString("utf16le"):e.includes(0)?e.toString("utf16le"):e.toString("latin1")}(e):e,r={},n=kl(t,bl),o=kl(t,Sl);return void 0!==n&&(r.oemcp=n),void 0!==o&&(r.acp=o),r}(e);t=function(e){const{oemcp:t,acp:r}=e;if(void 0===t||void 0===r||t!==r)return;const n=function(e){if(65001===e)return;const t=`cp${e}`;return Ls.encodingExists(t)?t:void 0}(t);return void 0!==n&&Pl.has(n)?n:void 0}(i),r=i,s=!0,n=void 0,o=void 0===i.oemcp&&void 0===i.acp?"unparsed":"answered",yl.info((0,y.q6)(),"Resolved the fallback encoding for shell output",{encoding:t??"none",oemcp:i.oemcp??"none",acp:i.acp??"none"})}),(t=>{n=void 0,o=function(e){try{if("object"!=typeof e||null===e)return"spawn_error";const t="code"in e?e.code:void 0;return"killed"in e&&!0===e.killed&&"string"!=typeof t?"timeout":"number"==typeof t?"nonzero_exit":"spawn_error"}catch{return"spawn_error"}}(t),yl.warn((0,y.q6)(),"Could not read the Windows code pages; shell output stays UTF-8 only",{error:t instanceof Error?t.message:String(t),attempt:e})}))};return"win32"===e&&a(),{current:()=>("win32"===e&&!s&&void 0===n&&i<3&&a(),t),pages:()=>void 0!==r?r:"win32"!==e?"none":i>=3&&void 0===n?"failed":"pending",lastOutcome:()=>"win32"===e?o??"pending":void 0,settled:()=>n??Promise.resolve()}}(process.platform),Rl=Buffer.alloc(0),Tl=/[\u0080-\uffff]/;function Al(e){const t=Math.max(0,e.length-3);for(let r=e.length-1;r>=t;r--){const t=e[r];if(128==(192&t))continue;const n=t>=248?1:t>=240?4:t>=224?3:t>=192?2:1,o=e.length-r;return n>o?o:0}return 0}function $l(){const e=new Xi.StringDecoder("utf8");return{write:t=>e.write(t),end:()=>e.end()}}function Ml(e,t){return Ls.decode(t,e,{stripBOM:!1})}const Dl=/[\xe0-\xef][\x80-\xbf]\?/;const Ol=10,Fl=Buffer.alloc(0),Nl=new Set([7,8,9,10,11,12,13,27]);function Ll(e,t,r){for(let n=0;n+1<r;n+=2){const r="utf16le"===t?e[n]|e[n+1]<<8:e[n]<<8|e[n+1];if(r<32&&!Nl.has(r))return!1}return!0}function jl(e,t,r=0,n){if("utf8"===t){const t=e.indexOf(Ol);return-1===t?-1:t+1}const[o,s]="utf16le"===t?[Ol,0]:[0,Ol];if(r%2==1&&n===o&&e[0]===s)return 1;for(let t=e.indexOf(o);-1!==t;t=e.indexOf(o,t+1))if((r+t)%2==0&&e[t+1]===s)return t+2;return-1}function Ul(e){const t=new Xi.StringDecoder("utf16le");let r;return{write(n){const o=void 0===r?n:Buffer.concat([Buffer.of(r),n]),s=o.length-o.length%2;r=s<o.length?o[s]:void 0;const i=o.subarray(0,s);return t.write("utf16le"===e?i:Buffer.from(i).swap16())},end:()=>(r=void 0,t.end())}}const Bl={encoding:"utf8",skip:0};function Wl(e){const t=e();let r="utf8";const n={};let o=!1;const s=()=>"utf8"===r?t:n[r]??=Ul(r),i=e=>("utf8"!==r&&e.length>0&&(o=!0),e);let a,c=!0,l=Fl,u=!1,d=0;const h=(e,t)=>{const n=function(e){if(!(e.length<2))return 255===e[0]&&254===e[1]?"utf16le":254===e[0]&&255===e[1]?"utf16be":void 0}(e);if(void 0!==n)return{encoding:n,skip:2};if("utf8"===r){if(e.length<2)return t?Bl:void 0;const r=0===e[0]?"utf16be":0===e[1]?"utf16le":void 0;if(void 0===r)return Bl;const n=jl(e,r);if(-1!==n)return Ll(e,r,n)?{encoding:r,skip:0}:Bl;if(!t)return;const o=e.length-e.length%2;return function(e,t){const r="utf16le"===t?1:0;for(let t=0;t<e.length;t++)if(0===e[t]!=(t%2===r))return!1;return!0}(e,r)&&Ll(e,r,o)?{encoding:r,skip:0}:Bl}const o={encoding:r,skip:0},s=e.indexOf(0),i=e.indexOf(Ol);if(-1!==s&&(-1===i||s<i)){const n=s-s%2+2;return n>e.length?t?o:void 0:Ll(e,r,n)?o:Bl}if(-1===i)return t?Bl:void 0;if("utf16le"===r&&i%2==0){if(i+1>=e.length)return t?Bl:void 0;if(0===e[i+1])return o}return Bl},p=e=>{if(e===r)return"";const t=i(s().end());return r=e,t},f=e=>"utf8"===r&&0!==e&&e<128,m=(e,n)=>{let o="",m=e;for(;;){if(c){const e=Math.min(m.length,512-l.length);let r;if(r=l.length>0?Buffer.concat([l,m.subarray(0,e)]):e===m.length?m:m.subarray(0,e),0===r.length)return o;const s=h(r,n||r.length>=512);if(void 0===s)return 1===r.length&&f(r[0])&&(o+=t.write(r),u=!0),l=Buffer.from(r),o;let i=s.skip,g=!1;if(u&&(i="utf8"===s.encoding?1:2,g=r[0]===Ol,u=!1),0===l.length)i>0&&(m=m.subarray(i));else{const t=r.subarray(i);m=m.subarray(e),m=0===m.length?t:0===t.length?m:Buffer.concat([t,m]),l=Fl}if(c=g,d=0,a=void 0,o+=p(s.encoding),g)continue}if(0===m.length)return o;if("utf8"===r&&!m.includes(0)&&!m.includes(254)&&!m.includes(255)){const e=m.lastIndexOf(Ol),r=-1===e?-1:m.length-e-1;if(-1===r||r>=2)return o+t.write(m);if(c=!0,0===r)return e>0&&m[e-1]===Ol&&(l=Buffer.of(Ol),u=!0),o+t.write(m);const n=m[m.length-1];return l=Buffer.of(n),u=f(n),o+t.write(u?m:m.subarray(0,e+1))}const e=jl(m,r,d,a);if(-1===e)return d+=m.length,a=m[m.length-1],o+i(s().write(m));o+=i(s().write(m.subarray(0,e))),m=m.subarray(e),c=!0}};return{write:e=>0===e.length?s().write(e):m(e,!1),peek(){if(!c||0===l.length)return"";const t=h(l,!0);if(void 0===t)return"";const r=u?"utf8"===t.encoding?1:2:t.skip,n=l.subarray(r);return 0===n.length?"":"utf8"===t.encoding?e().write(n):Ul(t.encoding).write(n)},end(){const e=m(Fl,!0)+i(s().end());return c=!0,l=Fl,u=!1,d=0,a=void 0,e},branch:()=>!0===t.usedCodePage?.()?"code_page":o?"utf16":"utf8"}}var Hl=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},ql=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const zl=(0,l.h)("local-exec:shell-core"),Gl=(0,u.Pu)("local_exec.shell.encoding_check",{description:"Shell command output streams that produced text, per encoding detector (U+FFFD): whether the decoded text holds the pattern and how much, which decode path (UTF-8, Windows code page, UTF-16) produced it, which stream, and the machine's Windows code page",labelNames:["detector","outcome","run_count","branch","stream","code_page"]}),Vl="win32"===process.platform,Kl=["CURSOR_CONVERSATION_ID","CURSOR_REQUEST_ID","CURSOR_AGENT_STORE_FILES_DIR","CURSOR_AGENT_STORE_SHARED_PATHS"];function Jl(e){return`'${e.replace(/'/g,"'\\''")}'`}const Zl=["eval-cursorbench","cursorbench","sand-eval","eval-harness"];function Xl(e){return Zl.some((t=>e.includes(t)))?(0,lo.createHash)("sha256").update(e).digest("hex"):e}function Ql(e,t){return e[t]??process.env[t]}const Yl=/^[A-Za-z_][A-Za-z0-9_]*$/,eu=/CURSOR_SANDBOX/i;function tu(e){return Yl.test(e)&&!eu.test(e)}function ru(e){return"function"==typeof e?e():e}function nu(e,t){const r=void 0===e?[]:[...e];return r.includes(t)||r.push(t),r}function ou(e){let t=0,r=0;const n=e.length;for(;r<n;){const n=e.indexOf(10,r);if(-1===n)return t;t+=1,r=n+1}return t}class su extends Error{constructor(e){super(`working directory does not exist: ${e}; the command did not run`),this.name="WorkingDirectoryMissingError"}}class iu{constructor(e,t,r,n={}){this.executor=e,this.workspacePath=t,this.projectDir=r,this.options=n,this.conversationExecutors=new Map}executorFor(e){if(!e)return this.executor;let t=this.conversationExecutors.get(e);return void 0===t&&(t=this.executor.clone(this.workspacePath),this.conversationExecutors.set(e,t)),t}async*execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{Hl(r,(0,$.VI)(e.withName("ShellCoreExecutor.execute")),!1);const o=performance.now(),i=this.executorFor(t.conversationId),a=t.workingDirectory||await i.getCwd(),c=(0,Ho.o1)(a,this.workspacePath);if(!((0,Os.$f)(c)&&(0,Os.A)(c)||await async function(e){try{return(await(0,fo.stat)(e)).isDirectory()}catch(e){const t=Ua(e);if("ENOENT"===t||"ENOTDIR"===t)return!1;throw e}}(c))){if(c!==(0,Ho.o1)(await i.getCwd(),this.workspacePath))throw new su(c);return yield{type:"stderr",data:`The shell's working directory no longer exists: ${c}. The command did not run. Re-run it with working_directory set to an existing directory.\n`},void(yield{type:"exit",code:1,aborted:!1,localExecutionTimeMs:Math.round(performance.now()-o)})}let l,u,d=0,h=0,p=!1,f=!1,m=!1;t.fileOutputThresholdBytes&&this.projectDir&&(l={buffer:"",lineCount:0,size:0,threshold:Number(t.fileOutputThresholdBytes)});const g=t.signal,w={CURSOR_AGENT:"1"};t.conversationId&&(w.CURSOR_CONVERSATION_ID=(0,uo.sh)(t.conversationId)),t.requestId&&(w.CURSOR_REQUEST_ID=t.requestId),this.projectDir&&(w.AGENT_TRANSCRIPTS=s.default.join(this.projectDir,uo.O2));const y=this.options.extraEnvProvider?.(e,t);void 0!==y&&Object.assign(w,y);const v=t.requestScopedEnv??{};for(const[e,t]of Object.entries(v))void 0!==t&&tu(e)&&(w[e]=t);const b=w.CURSOR_REQUEST_ID;void 0!==b&&(w.CURSOR_REQUEST_ID=Xl(b)),function(e,t){const r=Kl,n=Object.keys(t).filter((e=>tu(e)&&!r.includes(e))),o=`builtin unset ${[...Kl,...n].join(" ")} 2>/dev/null || true`,s=[];for(const t of Kl){const r=Ql(e,t);void 0!==r&&s.push(`builtin export ${t}=${Jl(r)}`)}for(const e of n){const r=t[e];void 0!==r&&s.push(`builtin export ${e}=${Jl(r)}`)}const i=e.__CURSOR_SANDBOX_ENV_RESTORE?.trim(),a=process.env.__CURSOR_SANDBOX_ENV_RESTORE?.trim();e.__CURSOR_SANDBOX_ENV_RESTORE=[o,a,i,...s].filter((e=>void 0!==e&&""!==e)).join("; ")}(w,v),void 0!==w.__CURSOR_SANDBOX_ENV_RESTORE&&(w.__CURSOR_SANDBOX_ENV_RESTORE=function(e,t){let r=e;for(const e of t){if(null==e||0===e.length)continue;const t=Xl(e);t!==e&&(r=r.split(e).join(t))}return r}(w.__CURSOR_SANDBOX_ENV_RESTORE,[t.requestId,b,v.CURSOR_REQUEST_ID,process.env.CURSOR_REQUEST_ID]));const S=function(e,t){const r=Ql(t,"CURSOR_AGENT_STORE_FILES_DIR"),n=function(e){if(void 0===e)return[];try{const t=JSON.parse(e);if("object"!=typeof t||null===t)return[];const r=[];for(const e of Object.values(t))"object"==typeof e&&null!==e&&"path"in e&&"readOnly"in e&&"string"==typeof e.path&&"boolean"==typeof e.readOnly&&r.push({path:e.path,readOnly:e.readOnly});return r}catch{return[]}}(Ql(t,"CURSOR_AGENT_STORE_SHARED_PATHS"));if(void 0===r&&0===n.length)return e;const o=e?.perUser,s=e?.perRepo??e?.perUser??e?.teamAdmin;if("workspace_readwrite"!==s?.type&&"workspace_readonly"!==s?.type)return e;const i=o?.type===s.type?{...o}:{type:s.type};var a;void 0!==r&&(a=r,"workspace_readwrite"!==i.type?i.additionalReadonlyPaths=nu(i.additionalReadonlyPaths,a):i.additionalReadwritePaths=nu(i.additionalReadwritePaths,a));for(const e of n)e.readOnly||"workspace_readwrite"!==i.type?i.additionalReadonlyPaths=nu(i.additionalReadonlyPaths,e.path):i.additionalReadwritePaths=nu(i.additionalReadwritePaths,e.path);return{...e,perUser:i}}(t.sandboxPolicy,w),k=(0,Eo.CG)(S??Eo.BM);let _,C,E,x;S&&(yield{type:"start",sandboxed:"workspace_readonly"===k||"workspace_readwrite"===k}),t.askpassConfig&&!Vl&&(w.SUDO_ASKPASS=t.askpassConfig.helperPath,w.CURSOR_ASKPASS_SOCKET=t.askpassConfig.socketPath,w.CURSOR_ASKPASS_SECRET=t.askpassConfig.secret);const P=this.options.codePageLookup??Il,I=(this.options.outputFallbackEncoding??(()=>P.current()))(),R=()=>function(e){if(void 0===e)return $l();const t=Pl.get(e);return void 0!==t&&Ls.encodingExists(e)?function(e,t){const{script:r}=t,o=function(e){const{script:t}=e,r=new RegExp(`${t.source}{2}`);let n=!1,o=!1,s=!1;return{note(i,a){if(!s&&0!==i.length){if(!n){const e=Tl.exec(i);null!==e&&(n=!0,s=t.test(e[0]))}s||=o&&t.test(i[0])||r.test(i)||e.doubleByte&&void 0!==a&&Dl.test(a.toString("latin1")),o=t.test(i[i.length-1])}},isUtf8Text:()=>s,reset(){n=!1,o=!1,s=!1}}}(t);let s=Rl,i=0,a="utf8",c=!1;const l=()=>{a="utf8",o.reset(),i=0},u=(t,n)=>{const s=n?Al(t):0,l=t.subarray(0,t.length-s),u=l.toString("utf8");if("replacement"!==a){const t=l.subarray(i);if(i=0,o.note(t.toString("utf8"),t),o.isUtf8Text())a="replacement";else{const t=0===u.length?"":u[u.length-1],o=n&&r.test(t)?Buffer.byteLength(t):0,d=function(e,t,r){let n=Ml(e,t);if(!r)return{text:n,keep:0};const o=Math.min(3,t.length);let s=0;for(;s<o&&n.endsWith("�");)s+=1,n=Ml(e,t.subarray(0,t.length-s));return{text:n,keep:s}}(e,l.subarray(0,l.length-o),n);if("codePage"!==a&&(a=function(e,t){const r=Tl.exec(e);if(null!==r)return t.test(r[0])?"codePage":"replacement"}(d.text,r)??a),"replacement"!==a)return i=d.keep+o,"codePage"===a&&d.text.length>0&&(c=!0),{text:d.text,keep:i+s}}}return{text:u,keep:s}};return{write:e=>{const t=0===s.length?e:Buffer.concat([s,e]);if(s=Rl,"utf8"===a){const e=t.subarray(0,t.length-Al(t));if((0,n.isUtf8)(e)){e.length<t.length&&(s=Buffer.from(t.subarray(e.length)));const r=e.toString("utf8");return(e=>{const t=e.lastIndexOf("\n");-1===t?o.note(e):(l(),o.note(e.slice(t+1)))})(r),r}}let r="",i=0;for(;i<t.length;){const e=t.indexOf(10,i),c=-1===e?t.length:e+1,d=t.subarray(i,c);if("utf8"===a){const t=-1===e?Al(d):0,u=d.subarray(0,d.length-t);if((0,n.isUtf8)(u)){const n=u.toString("utf8");r+=n,t>0&&(s=Buffer.from(d.subarray(u.length))),-1===e?o.note(n):l(),i=c;continue}a="undecided"}const{text:h,keep:p}=u(d,-1===e);r+=h,p>0&&(s=Buffer.from(d.subarray(d.length-p))),-1!==e&&l(),i=c}return r},end:()=>{const e=s;s=Rl;const t=0===e.length?"":"utf8"===a?e.toString("utf8"):u(e,!1).text;return l(),t},usedCodePage:()=>c}}(e,t):$l()}(I),T={stdout:Wl(R),stderr:Wl(R)},A=new $c,M=Qc(this.options.encodingSlices,e)?new ml:void 0;let D=!1;const O=()=>{if(!D){D=!0;try{const t={stdout:T.stdout.branch(),stderr:T.stderr.branch()};for(const r of A.labels(t,P.pages()))Gl.increment(e,1,r);M?.record(this.options.encodingSlices,e,t,P.lastOutcome())}catch(t){zl.warn(e,"shell output encoding check failed (command result unaffected)",{error:t instanceof Error?t.message:String(t)})}}},F=e=>{void 0!==l&&0!==e.length&&(l.file?l.file.write(e):l.buffer+=e)},N=function*(){const e={stdout:p,stderr:f};for(const t of["stdout","stderr"]){const r=T[t].end();if(0===r.length)continue;const n=void 0!==l&&!0!==l.truncated;n&&F(r),!n&&e[t]||(A.note(t,r),M?.noteText(t,r)),e[t]||(yield{type:t,data:r})}O()};try{for await(const r of i.execute(e,t.command,{signal:g,workingDirectory:c,env:w,sandboxPolicy:S,sandboxWorkspaceRoot:this.workspacePath,pipeStdin:t.pipeStdin??!1,keepBackgroundJobs:this.options.keepBackgroundJobs??!1,bufferOutputEvents:this.options.shellOutputBackpressureOptions?.bufferOutputEvents,outputLimiterOptions:this.options.shellOutputBackpressureOptions?.outputLimiterOptions,powershellUtf8Console:ru(this.options.powershellUtf8Console),powershellUtf8ChildEnv:ru(this.options.powershellUtf8ChildEnv),powershellParseAfterUtf8Switch:ru(this.options.powershellParseAfterUtf8Switch),powershellWebRequestUtf8:ru(this.options.powershellWebRequestUtf8),powershellPerLineStateDump:ru(this.options.powershellPerLineStateDump)})){_=0,C="",E="",x="";let e=!1,t=!1;if("stdout"===r.type||"stderr"===r.type){const n=T[r.type],o="stdout"===r.type?p:f,i=void 0===l||!0===l.truncated;let a=!1;if(!o||!i){_=r.data.length;const c="stdout"===r.type?d:h,p=!o&&c+_<=Go,f=void 0!==l&&!0!==l.truncated&&l.size+_<=Qa;"stdout"===r.type?e=p:t=p;const m=!o&&!p,g=!i&&!f;if((m||g)&&(x=n.peek(),g&&F(x),m&&(E=x)),(p||f)&&(C=n.write(r.data),a=!0,A.note(r.type,C),M?.noteBytes(r.type,r.data),M?.noteText(r.type,C)),void 0!==l&&l.size+_>Qa)l.truncated=!0;else if(f&&void 0!==l)if(l.size+=_,l.lineCount+=ou(r.data),l.file)l.file.write(C);else if(l.buffer+=C,l.size>l.threshold){const e=s.default.join(this.projectDir,Xa);l.path=s.default.join(e,`${(0,lo.randomUUID)()}.txt`);try{await(0,fo.mkdir)(e,{recursive:!0}),l.file=(0,go.createWriteStream)(l.path),l.file.on("error",(e=>{u??=e})),l.file.write(l.buffer)}catch(e){u??=e instanceof Error?e:new Error(String(e)),l.truncated=!0}l.buffer=""}}a||(n.end(),A.note(r.type,x),M?.noteDropped(r.type),M?.noteText(r.type,x))}switch(r.type){case"stdout":e?(d+=_,C&&(yield{type:"stdout",data:C})):p||(E&&(yield{type:"stdout",data:E}),p=!0,yield{type:"stdout_trimmed"});break;case"suppressed_output":m||(m=!0,yield{type:"stdout",data:Eo.Ls});break;case"stderr":t?(h+=_,C&&(yield{type:"stderr",data:C})):f||(E&&(yield{type:"stderr",data:E}),f=!0,yield{type:"stderr_trimmed"});break;case"exit":{yield*N();const e=Math.max(0,Math.round(performance.now()-o));let t;if(l?.file){if(l.truncated){const e=`\n... (output truncated at ${l.size} bytes) ...\n`;l.file.write(e),l.size+=e.length,l.lineCount+=Us(e)-1}const e=await new Promise((e=>l.file.end(e)));u??=e??void 0,u?await(0,fo.rm)(l.path,{force:!0}):t=new Ya.pV({filePath:l.path,sizeBytes:BigInt(l.size),lineCount:BigInt(l.lineCount)})}u&&void 0!==l?.path&&(yield{type:"stderr",data:`\nThe full output could not be saved to ${l.path}: ${u.message}\n`}),yield{type:"exit",code:r.code,signal:r.signal,aborted:r.aborted,outputLocation:t,localExecutionTimeMs:e};break}case"stdin_ready":M?.noteShell(r.shell),yield{type:"stdin_ready",stdin:r.stdin,pid:r.pid};break;case"sandbox_denies":yield{type:"sandbox_denies",events:r.events}}}yield*N()}catch(t){if("ENOENT"===Ua(t)&&(0,Os.$f)(c))try{zl.warn(e,"shell failed with ENOENT in an agent store working directory",{...await(0,Os.KZ)(c)})}catch{}throw t}finally{O()}}catch(e){r.error=e,r.hasError=!0}finally{ql(r)}}async getCwd(e){return this.executorFor(e).getCwd()}getWorkspacePath(){if(!this.workspacePath)throw new Error("Workspace path is not configured");return this.workspacePath}}class au{constructor(e,t){this.innerExecutor=e,this.shellManager=t}async*execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{Hl(r,(0,$.VI)(e.withName("ManagedShellCoreExecutor.execute")),!1),zl.info(e,"Executing shell command",{command:t.command,workingDirectory:t.workingDirectory,toolCallId:t.toolCallId});let n=null;t.toolCallId&&(n=this.shellManager.getOrCreateShellEmitter(t.toolCallId));for await(const r of this.innerExecutor.execute(e,t)){if(n)switch(r.type){case"stdin_ready":n.emit({type:"stdin_ready",stdin:r.stdin,pid:r.pid});break;case"start":n.emit({type:"start",sandboxed:r.sandboxed});break;case"stdout":n.emit({type:"stdout",data:r.data});break;case"stderr":n.emit({type:"stderr",data:r.data});break;case"exit":n.emit({type:"exit",code:r.code??-1,aborted:r.aborted})}yield r}}catch(e){r.error=e,r.hasError=!0}finally{ql(r)}}async getCwd(e){return this.innerExecutor.getCwd(e)}getWorkspacePath(){return this.innerExecutor.getWorkspacePath()}}class cu{constructor(e,t){this.innerExecutor=e,this.askpassConfig=t}async*execute(e,t){const r={...t,askpassConfig:t.askpassConfig??this.askpassConfig};yield*this.innerExecutor.execute(e,r)}async getCwd(e){return this.innerExecutor.getCwd(e)}getWorkspacePath(){return this.innerExecutor.getWorkspacePath()}}async function lu(e,t){switch(e.type){case"needsApproval":return t.onNeedsApproval(e.approvalReason,e.approvalDetails);case"userRejected":return t.onUserRejected(e.reason);case"cursorIgnore":return t.onPermissionDenied("Blocked by cursor ignore");case"permissionsConfig":return t.onPermissionDenied("Blocked by permissions configuration",{isReadonly:e.isReadonly});case"cursorFiles":return t.onPermissionDenied("Blocked by cursor files protection");case"adminBlock":return t.onPermissionDenied("Blocked by admin repository block");case"adminCommandDenylist":return t.onPermissionDenied(hs(e.pattern));case"unsafeResolution":return t.onPermissionDenied(e.message);default:{const t=e;throw new Error(`Unhandled block reason type: ${JSON.stringify(t)}`)}}}function uu(e){switch(e.type){case"userRejected":return e.reason;case"unsafeResolution":return e.message;case"adminCommandDenylist":return hs(e.pattern);case"needsApproval":case"cursorIgnore":case"adminBlock":case"permissionsConfig":case"cursorFiles":return"Command is not allowed";default:{const t=e;return`Command is not allowed (${JSON.stringify(t)})`}}}function du(e,t,r){return"permissionsConfig"===r.type?{case:"permissionDenied",value:new he.jn({command:e,workingDirectory:t,error:"Command blocked by permissions configuration",isReadonly:r.isReadonly??!1})}:{case:"rejected",value:new he.pZ({command:e,workingDirectory:t,reason:uu(r)})}}var hu=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const pu=(0,l.h)("local-exec:background-shell");function fu(e,t,r){return new Co.Lt({result:du(e,t,r)})}class mu{constructor(e,t){this.id=e,this.abortController=t,this.disposed=!1,this.completed=!1,this.completionListeners=[]}abort(){this.abortController.abort()}dispose(){this.disposed||(this.disposed=!0,this.abortController.signal.aborted||this.abortController.abort())}get signal(){return this.abortController.signal}isDisposed(){return this.disposed}onComplete(e){this.completed&&this.completion?e(this.completion):this.completionListeners.push(e)}markCompleted(e){if(this.completed)return;this.completed=!0,this.completion=e;const t=[...this.completionListeners];this.completionListeners=[];for(const r of t)r(e)}}async function gu(e,t){let r;try{for(let n=await t.next();!n.done;n=await t.next())"stdin_ready"===n.value.type?(e.stdin=n.value.stdin,e.pid=n.value.pid):"exit"===n.value.type&&(r={code:n.value.code,signal:n.value.signal,aborted:n.value.aborted,outputPath:n.value.outputLocation?.filePath})}catch(e){}finally{e.markCompleted(r??{code:null,aborted:e.signal.aborted})}}function wu(e){e().catch((()=>{}))}class yu{constructor(e){if(this.args=e,this.carryover="",this.matchedOccurrences=0,this.emittedNotifications=0,this.finished=!1,this.monotonicStartMs=performance.now(),this.limit=e.config.notificationLimit??100,e.config.pattern.length>500)throw new Error("Output notification pattern exceeds 500 characters");this.regex=Wo.L3.compile(e.config.pattern,Wo.L3.MULTILINE)}observe(e){if(this.finished||this.matchedOccurrences>=this.limit||0===e.length)return;if(e.length>65536){for(const t of function(e){if(0===e.length)return[];const t=Math.max(1,Math.trunc(65536)||1),r=[];let n=0;for(;n<e.length;){let o=Oo(e,n+t);o<=n&&(o=Fo(e,n+t)),r.push(e.slice(n,o)),n=o}return r}(e)){if(this.matchedOccurrences>=this.limit)break;this.observe(t)}return}const t=this.carryover.length,r=`${this.carryover}${e}`,n=this.regex.matcher(r);for(;this.matchedOccurrences<this.limit&&n.find();){const e=n.group()??"";n.end()>t&&this.queueMatch(e)}this.carryover=Lo(r,1024)}finish(){this.finished||(this.finished=!0,this.flushPendingBatch("finish"),this.clearFlushTimer(),0===this.matchedOccurrences&&this.recordWatchOutcome("silent",{silent_ms:Su(this.monotonicStartMs)}))}queueMatch(e){if(this.matchedOccurrences>=this.limit)return;this.matchedOccurrences+=1;const t=this.matchedOccurrences,r=function(e,t){return e.length<=5e3?`${t}: ${e}`:`${t} is ${e.length} characters; omitted from notification detail.`}(e,1===t?"Matched text":"Latest match");return 1===t?(this.emitNotification({startOccurrence:t,endOccurrence:t,count:1,matchedTextDetail:r}),this.recordWatchOutcome("matched",{first_match_ms:Su(this.monotonicStartMs)}),void(t===this.limit&&this.emitLimitReachedNotification())):(this.pendingBatch?(this.pendingBatch.endOccurrence=t,this.pendingBatch.count+=1,this.pendingBatch.matchedTextDetail=r):this.pendingBatch={startOccurrence:t,endOccurrence:t,count:1,matchedTextDetail:r},t===this.limit?(this.flushPendingBatch("limit"),void this.emitLimitReachedNotification()):void this.scheduleFlush())}scheduleFlush(){if(void 0!==this.flushTimer)return;const e=this.getDebounceMs();this.flushTimer=setTimeout((()=>{this.flushPendingBatch("debounce")}),e)}getDebounceMs(){const e=this.args.debounceMs??function(e){const t=e.debounce;if(void 0!==t&&Number.isFinite(t))return Math.ceil(1e3*t)}(this.args.config)??5e3;return Math.max(e,5e3)}clearFlushTimer(){void 0!==this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=void 0)}flushPendingBatch(e){const t=this.pendingBatch;t&&(this.pendingBatch=void 0,this.clearFlushTimer(),this.emitNotification(t))}emitNotification(e){this.emittedNotifications+=1;const t=this.args.config.reason.trim()||`Shell output contains /${this.args.config.pattern}/`,r=this.args.config.pattern,n=void 0!==e.matchedTextDetail?` ${e.matchedTextDetail}.`:"",o=1===e.count?`Shell output has pattern /${r}/. This is occurrence number ${e.startOccurrence}.${n} The title message is being displayed to the user.`:`Shell output matched /${r}/ ${e.count} more times since the previous notification. The title message is being displayed to the user.${n}`,s=yo(String(this.args.shellId),this.emittedNotifications);var i;this.args.registry.enqueue({conversationId:this.args.conversationId,id:s,source:"shell",payload:{taskId:s,...void 0!==this.args.toolCallId?{toolCallId:this.args.toolCallId}:{},kind:"shell",status:"success",title:(i=t,i.length<=500?i:`${No(i,500)}...`),detail:o,outputPath:this.args.outputPath,reason:"task_progress"}})}emitLimitReachedNotification(){this.emittedNotifications+=1;const e=this.args.config.pattern,t=yo(String(this.args.shellId),this.emittedNotifications);this.args.registry.enqueue({conversationId:this.args.conversationId,id:t,source:"shell",payload:{taskId:t,...void 0!==this.args.toolCallId?{toolCallId:this.args.toolCallId}:{},kind:"shell",status:"success",title:`Notification limit reached (${this.limit})`,detail:`Shell output matched /${e}/ ${this.limit} times and has reached the notification limit. No further notifications will be sent for this pattern. To continue monitoring, read the output file directly at the output path.`,outputPath:this.args.outputPath,reason:"task_progress"}}),this.recordWatchOutcome("limit_reached")}recordWatchOutcome(e,t){void 0!==this.args.ctx&&pu.info(this.args.ctx,"agent.shell_output_notification_match",{event:"agent.shell_output_notification_match",outcome:e,shell_id:this.args.shellId,conversation_id:this.args.conversationId,tool_call_id:this.args.toolCallId,limit:this.limit,...t})}}class vu{constructor(e,t,r){this.innerFactory=e,this.projectDir=t,this.backgroundWorkRegistry=r}async spawn(e,t){const r=this.createObserver(e.ctx,e.shellId,e.conversationId,e.toolCallId,e.outputNotification);if(!r)return this.innerFactory.spawn(e,t);try{return await this.innerFactory.spawn(e,this.createObservingExecutor(t,r))}catch(e){throw r.finish(),e}}async adopt(e){const t=this.createObserver(e.ctx,e.shellId,void 0,e.toolCallId,e.outputNotification);if(!t)return this.innerFactory.adopt(e);e.initialOutput.length>0&&t.observe(e.initialOutput);try{return await this.innerFactory.adopt({...e,eventIterator:this.createObservingIterator(e.eventIterator,t)})}catch(e){throw t.finish(),e}}createObserver(e,t,r,n,o){if(!this.backgroundWorkRegistry||!o)return;if(0===o.pattern.trim().length)return;const i=s.join(this.projectDir,"terminals",`${t}.txt`);try{return new yu({shellId:t,outputPath:i,config:o,conversationId:r??wo,toolCallId:n,registry:this.backgroundWorkRegistry,ctx:e})}catch(r){return void(void 0!==e&&pu.warn(e,"Invalid shell output notification pattern",{shellId:t,error:r instanceof Error?r.message:String(r)}))}}createObservingExecutor(e,t){const r=e.execute.bind(e);return{...e,execute:async function*(e,n){try{for await(const o of r(e,n))"stdout"===o.type||"stderr"===o.type?t.observe(o.data):"exit"===o.type&&t.finish(),yield o}finally{t.finish()}}}}createObservingIterator(e,t){const r=e.return?.bind(e);return{next:async()=>{try{const r=await e.next();if(r.done)t.finish();else{const e=r.value;"stdout"===e.type||"stderr"===e.type?t.observe(e.data):"exit"===e.type&&t.finish()}return r}catch(e){throw t.finish(),e}},return:async e=>(t.finish(),r?r(e):{done:!0,value:void 0})}}}class bu{async spawn(e,t){const r=new AbortController,n=new mu(e.shellId,r),o=t.execute(e.ctx,{command:e.command,workingDirectory:e.workingDirectory,signal:r.signal,toolCallId:e.toolCallId,conversationId:e.conversationId,requestId:e.requestId,secretScopeId:e.secretScopeId,sandboxPolicy:e.sandboxPolicy,pipeStdin:e.enableWriteShellStdinTool,showElapsedTime:!0})[Symbol.asyncIterator]();try{for(let e=await o.next();!e.done;e=await o.next())if("stdin_ready"===e.value.type){n.stdin=e.value.stdin,n.pid=e.value.pid;break}}catch(e){if(e instanceof Eo.SandboxUnsupportedError||e instanceof su)throw e}return wu((()=>gu(n,o))),n}async adopt(e){const t=new mu(e.shellId,e.abortController);return t.stdin=e.stdin,t.pid=e.pid,wu((()=>gu(t,e.eventIterator))),t}}function Su(e){return Math.round(performance.now()-e)}function ku(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`}function _u(e){const t=String(e.runningForMs).padEnd(9," "),r=e.status.padEnd(9," ");let n="---\n";return void 0!==e.pid&&0!==e.pid&&(n+=`pid: ${e.pid}\n`),n+=`cwd: ${ku(e.cwd)}\n`,n+=`command: ${ku(e.command)}\n`,void 0!==e.title&&e.title.trim().length>0&&(n+=`title: ${ku(e.title)}\n`),n+=`status: ${r}\n`,n+=`started_at: ${e.startedAt}\n`,n+=`running_for_ms: ${t}\n`,n+="---\n",n}function Cu(e){return`\n[${e} truncated by cursor: the command wrote more than 1048576 characters to ${e}; only the first 1048576 were captured and the rest was dropped from this file]\n`}class Eu{constructor(e,t){this.innerFactory=e,this.projectDir=t}async spawn(e,t){const r=s.join(this.projectDir,"terminals");await(0,fo.mkdir)(r,{recursive:!0});const n=this.createLoggingExecutor(t,e,r);return this.innerFactory.spawn(e,n)}createLoggingExecutor(e,t,r){const o=e.execute.bind(e);return{...e,execute:async function*(e,i){let a,c,l,u=!1,d=!1,h=!1,p=!1;const f=Date.now(),m=new Date(f).toISOString(),g=performance.now();let w,y="running",v=!1,b=Promise.resolve();const S=async e=>{if(c)try{await c.write(e)}catch(e){}},k=t.shellId,_=s.join(r,`${k}.txt`),C=async()=>{if(!a)return;const e=Su(g),r=_u({pid:w,cwd:t.workingDirectory,command:t.command,title:t.description,status:y,startedAt:m,runningForMs:e});try{await a.write(r,0,"utf8")}catch(e){}},E=()=>(b=b.then(C).catch((()=>{})),b),x=()=>{void 0!==l&&(clearInterval(l),l=void 0)},P=async e=>{if(p)return;p=!0,w=e;const r=Su(g),n=_u({pid:e,cwd:t.workingDirectory,command:t.command,title:t.description,status:y,startedAt:m,runningForMs:r});await(0,fo.writeFile)(_,n,"utf8"),l=setInterval((()=>{E()}),5e3)},I=async()=>{a||(a=await go.promises.open(_,"r+")),c||(c=await go.promises.open(_,"a"))},R=async(e,t)=>{if(!v){if(v=!0,x(),p||await P(),await I(),void 0!==t){const e=Su(g),r=`\n---\n${t}\n`+(i.showElapsedTime?`elapsed_ms: ${e}\n`:"")+`ended_at: ${(new Date).toISOString()}\n---\n`;await S(r)}y=e,await E()}};try{for await(const r of o(e,i)){if("stdout"===r.type)p||(await P(),await I()),await S(r.data);else if("stderr"===r.type)p||(await P(),await I()),await S(r.data);else if("stdout_trimmed"!==r.type||d)if("stderr_trimmed"!==r.type||h)if("stdin_ready"!==r.type||u)"exit"===r.type&&await R(r.aborted?"aborted":0===r.code?"succeeded":"failed",`exit_code: ${r.code??"unknown"}`);else{u=!0,p||(await P(r.pid),await I());const e=r.stdin;if(e&&!0!==t.suppressStdinLogging){const t=e=>{if(null==e)return;const t="string"==typeof e?e:n.Buffer.isBuffer(e)||e instanceof Uint8Array?n.Buffer.from(e).toString():"";if(!t)return;const r=t.endsWith("\n")?t:`${t}\n`;S(`[stdin] ${r}`)},r=e.write.bind(e);if(e.write=(e,n,o)=>(t(e),r(e,n,o)),"function"==typeof e.end){const r=e.end.bind(e);e.end=(e,n,o)=>(void 0!==e&&t(e),r(e,n,o))}}}else h=!0,p||await P(),await I(),await S(Cu("stderr"));else d=!0,p||await P(),await I(),await S(Cu("stdout"));yield r}if(!v){const e=i.signal?.aborted??!1;await R(e?"aborted":"failed")}}catch(e){const t=i.signal?.aborted??!1,r=ku(e instanceof Error?e.message:"Unknown error");if(await R(t?"aborted":"failed",t?void 0:`error: ${r}`),!t)throw e}finally{if(x(),await b,a)try{await a.close()}catch{}if(c)try{await c.close()}catch{}}}}}async adopt(e){const t=s.join(this.projectDir,"terminals");await(0,fo.mkdir)(t,{recursive:!0});const r=s.join(t,`${e.shellId}.txt`),n=e.startTime,o=new Date(n).toISOString(),i=e.monotonicStartMs;let a="running";const c=Su(i),l=_u({pid:e.pid,cwd:e.workingDirectory,command:e.command,title:e.description,status:a,startedAt:o,runningForMs:c})+(e.initialOutput??"");await(0,fo.writeFile)(r,l,"utf8");const u=await go.promises.open(r,"r+");let d;try{d=await go.promises.open(r,"a")}catch(e){throw await u.close(),e}let h=!1,p=!1,f=!1,m=!1,g=Promise.resolve();const w=async()=>{const t=Su(i),r=_u({pid:e.pid,cwd:e.workingDirectory,command:e.command,title:e.description,status:a,startedAt:o,runningForMs:t});try{await u.write(r,0,"utf8")}catch{}},y=()=>(g=g.then(w).catch((()=>{})),g);let v=setInterval((()=>{y()}),5e3);const b=()=>{void 0!==v&&(clearInterval(v),v=void 0)},S=async()=>{if(!h){h=!0,b(),await g;try{await u.close()}catch{}try{await d.close()}catch{}}},k=async e=>{try{await d.write(e)}catch(e){}},_=async(t,r)=>{if(!p){if(p=!0,b(),void 0!==r){const t=Su(i),n=`\n---\n${r}\n`+(e.showElapsedTime?`elapsed_ms: ${t}\n`:"")+`ended_at: ${(new Date).toISOString()}\n---\n`;await k(n)}a=t,await y()}},C={next:async()=>{try{const t=await e.eventIterator.next();if(t.done){if(!p){const t=e.abortController.signal.aborted;await _(t?"aborted":"failed")}}else{const e=t.value;"stdout"===e.type||"stderr"===e.type?await k(e.data):"stdout_trimmed"!==e.type||f?"stderr_trimmed"!==e.type||m?"exit"===e.type&&(await _(e.aborted?"aborted":0===e.code?"succeeded":"failed",`exit_code: ${e.code??"unknown"}`),await S()):(m=!0,await k(Cu("stderr"))):(f=!0,await k(Cu("stdout")))}return t.done&&await S(),t}catch(t){const r=e.abortController.signal.aborted;throw await _(r?"aborted":"failed"),await S(),t}},return:async()=>{if(!p){const t=e.abortController.signal.aborted;await _(t?"aborted":"failed")}return await S(),e.eventIterator.return?e.eventIterator.return():{done:!0,value:void 0}}};return this.innerFactory.adopt({...e,eventIterator:C})}}class xu{constructor(e,t){this.factory=e,this.backgroundWorkRegistry=t,this.runningShells=new Map,this.nextShellId=1e3+Math.floor(999e3*Math.random())}registerShellWork(e,t){const r=String(e.id);this.backgroundWorkRegistry?.upsertWork({id:r,kind:"shell",state:"running",metadata:vo(t),abort:()=>{this.abort(e.id)}})}clearShellWork(e){this.backgroundWorkRegistry?.clearWork(String(e))}cleanupShell(e){this.runningShells.has(e)&&(this.runningShells.delete(e),this.clearShellWork(e))}enqueueShellCompletion(e,t,r,n,o,s){if(!this.backgroundWorkRegistry)return;const i=s.aborted?"aborted":0===s.code?"success":"error",a=function(e){if(!e.aborted)return void 0!==e.signal?`signal=${e.signal}`:null!==e.code&&0!==e.code?`exit_code=${e.code}`:void 0}(s),c=function(e){if(!e.aborted)return void 0!==e.signal?{kind:"signal",signal:e.signal}:null!==e.code?{kind:"exit",code:e.code}:void 0}(s),l=n.description?.trim()?n.description:void 0,u=String(e);this.backgroundWorkRegistry.enqueue({conversationId:r??wo,id:u,source:"shell",payload:{taskId:u,...void 0!==t?{toolCallId:t}:{},kind:"shell",status:i,title:n.description||n.command,...a?{detail:a}:{},...s.outputPath?{outputPath:s.outputPath}:{},reason:"task_finished",durationMs:Su(o),...c?{shellEnd:c}:{},...l?{description:l}:{}}})}async spawn(e,t){const r=await this.factory.spawn(e,t),n=Date.now(),o=performance.now();return this.runningShells.set(r.id,r),this.registerShellWork(r,{title:e.description||e.command,cwd:e.workingDirectory,startTimeMs:n}),r.signal.addEventListener("abort",(()=>{this.cleanupShell(r.id)})),r.onComplete?.((t=>{this.enqueueShellCompletion(r.id,e.toolCallId,e.conversationId,{command:e.command,description:e.description},o,t),this.cleanupShell(r.id)})),{shellId:r.id,pid:r.pid}}async adopt(e){const t=await this.factory.adopt(e);return this.runningShells.set(t.id,t),this.registerShellWork(t,{title:e.description||e.command,cwd:e.workingDirectory,startTimeMs:e.startTime}),t.signal.addEventListener("abort",(()=>{this.cleanupShell(t.id),e.onCleanup?.()})),t.onComplete?.((r=>{this.enqueueShellCompletion(t.id,e.toolCallId,void 0,{command:e.command,description:e.description},e.monotonicStartMs,r),this.cleanupShell(t.id),e.onCleanup?.()})),{shellId:t.id,pid:e.pid}}generateShellId(){for(let e=0;e<=998999;e++){this.nextShellId>999999&&(this.nextShellId=1e3);const e=this.nextShellId;if(this.nextShellId+=1,!this.runningShells.has(e))return e}throw new Error("No available background shell id in range")}abort(e){const t=this.runningShells.get(e);return!!t&&(t.abort(),this.runningShells.delete(e),this.clearShellWork(e),!0)}isRunning(e){return this.runningShells.has(e)}dispose(){for(const[e,t]of this.runningShells)t.dispose(),this.clearShellWork(e);this.runningShells.clear()}async writeStdin(e,t){const r=this.runningShells.get(e);if(!r)throw new Error("Shell not found");if(!r.stdin)throw new Error("Shell stdin not available");const n=t.indexOf(""),o=-1!==n?n:t.indexOf("\\u0004");if(-1!==o){const e=t.substring(0,o);e.length>0&&await new Promise(((t,n)=>{r.stdin.write(e,(e=>{e?n(e):t(void 0)}))})),r.stdin.end()}else await new Promise(((e,n)=>{r.stdin.write(t,(t=>{t?n(t):e(void 0)}))}))}}new WeakMap;class Pu{constructor(e,t){this.inner=e,this.ownerConversationId=t}enqueue(e){this.inner.enqueue({...e,conversationId:this.ownerConversationId})}enqueueCompletion(e){this.enqueue({conversationId:this.ownerConversationId,id:e.taskId,source:e.kind,payload:e})}pull(e){return this.inner.pull(e)}ack(e){return this.inner.ack(e)}nack(e,t){this.inner.nack(e,t)}suppress(e,t){this.inner.suppress(e,t)}upsertWork(e){this.inner.upsertWork(e)}clearWork(e){return this.inner.clearWork(e)}abortWork(e){return this.inner.abortWork(e)}hasRunningWork(e){return this.inner.hasRunningWork(e)}abortAllWork(e){return this.inner.abortAllWork(e)}listWork(e){return this.inner.listWork(e)}drainCompletions(){return this.inner.drainCompletions()}hasPendingCompletions(e){return this.inner.hasPendingCompletions(e)}markAwaitedCompletion(e){this.inner.suppress(this.ownerConversationId,e)}}class Iu{constructor(e,t,r,n,o,s,i,a){if(this.permissionsService=e,this.coreExecutor=t,this.ignoreService=r,void 0!==a)return this.backgroundShellManager=a,void(this.ownsBackgroundShellManager=!1);const c=s&&void 0!==i?new Pu(s,i):s,l=o??function(e){const t=new bu;return new Eu(t,e)}(n),u=new vu(l,n,c);this.backgroundShellManager=new xu(u,c),this.ownsBackgroundShellManager=!0}getManager(){return this.backgroundShellManager}dispose(){this.ownsBackgroundShellManager&&this.backgroundShellManager.dispose()}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,$.VI)(e.withName("LocalBackgroundShellExecutor.execute")),!1);const n=t.command,o=t.sandboxPolicy?Yo(t.sandboxPolicy):void 0,s=t.workingDirectory||await this.coreExecutor.getCwd(t.conversationId),i=(0,Ho.o1)(s),a=new he.HO($o(n).structured),c=ps({command:n,parsingResult:a,blockedCommands:t.adminCommandDenylist});if(void 0!==c)return new Co.Lt({result:{case:"rejected",value:new he.pZ({command:n,workingDirectory:i,reason:c})}});let l;if(pu.info(e,"Background shell: approval gate reached",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,hasSmartModeApproval:void 0!==t.smartModeApproval,hasSmartModeApprovalReason:void 0!==t.smartModeApproval?.reason,hasSmartModeApprovalRequestId:void 0!==t.smartModeApproval?.requestId,requestedPolicyType:o?.type??"undefined",parserCommandCount:a.executableCommands.length,classifierCommandCount:t.classifierResult?.commands.length??0,commandLength:n.length}),_o(t)){const r=await this.permissionsService.shouldEnforceShellInvariantBlocks(e,{workingDirectory:i,skipUnsafeWorkingDirectoryBlock:!0,command:n,parsingResult:a,toolCallId:t.toolCallId,resolveSkippedApprovalPolicy:!0},o);if("block"===r.kind)return pu.info(e,"Background shell: invariant blocked command",{toolCallId:t.toolCallId,blockReasonType:r.reason.type,skipApproval:t.skipApproval}),fu(n,i,r.reason);l=r.policy??o,pu.info(e,"Background shell: skipped local approval",{toolCallId:t.toolCallId,requestedPolicyType:o?.type??"undefined",effectivePolicyType:l?.type??"undefined"})}else{const r=await this.permissionsService.shouldBlockShellCommand(e,n,{workingDirectory:i,timeout:0,parsingResult:a,toolCallId:t.toolCallId,classifierResult:t.classifierResult,smartModeApprovalReason:t.smartModeApproval?.reason,smartModeApprovalRequestId:t.smartModeApproval?.requestId,hookApprovalRequirement:So(t)},o);if("block"===r.kind)return pu.info(e,"Background shell: approval gate blocked command",{toolCallId:t.toolCallId,blockReasonType:r.reason.type,hasSmartModeApproval:void 0!==t.smartModeApproval,skipApproval:t.skipApproval}),fu(n,i,r.reason);l=r.policy,pu.info(e,"Background shell: approval gate allowed command",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,effectivePolicyType:l.type})}l=await Ja(l,{command:n,workingDirectory:i,parsingResult:a,permissionsService:this.permissionsService,ignoreService:this.ignoreService});try{const r=this.backgroundShellManager.generateShellId(),o=l?{perRepo:l}:void 0,s={ctx:e,command:n,workingDirectory:i,toolCallId:t.toolCallId,conversationId:t.conversationId,requestId:t.requestId,secretScopeId:t.secretScopeId,sandboxPolicy:o,shellId:r,enableWriteShellStdinTool:t.enableWriteShellStdinTool,suppressStdinLogging:t.suppressStdinLogging,description:t.description,outputNotification:t.outputNotification},a=await this.backgroundShellManager.spawn(s,this.coreExecutor);return new Co.Lt({result:{case:"success",value:new Co.Po({shellId:r,command:n,workingDirectory:i,pid:a.pid})}})}catch(r){if(r instanceof Eo.SandboxUnsupportedError){const o=l?.type??"unknown";return pu.debug(e,"Background shell: sandbox policy unsupported on this host",{toolCallId:t.toolCallId,policyType:o,reason:r.reason}),new Co.Lt({result:{case:"sandboxUnsupported",value:new he.rI({command:n,workingDirectory:i,sandboxPolicyType:o,reason:r.reason??r.message,isReadonly:"workspace_readonly"===o})}})}return new Co.Lt({result:{case:"error",value:new Co.Of({command:n,workingDirectory:i,error:r instanceof Error?r.message:"Unknown error"})}})}}catch(e){r.error=e,r.hasError=!0}finally{hu(r)}}writeStdin(e,t){return this.backgroundShellManager.writeStdin(e,t)}}var Ru=r("node:async_hooks");r("../../node_modules/.pnpm/minimatch@10.2.5/node_modules/minimatch/dist/esm/index.js");function Tu(e){return e instanceof Error?e.message:String(e)}function Au(e){return"Failed to read skill file: "+Tu(e)}function $u(e){return"Invalid skill frontmatter: "+Tu(e)}function Mu(e,t){return e||t?void 0:"Description is required"}new Set(["EACCES","EPERM","ENOENT","ENOTDIR","EISDIR","ELOOP","ENAMETOOLONG"]);const Du=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function Ou(e){return e.toLocaleString("en-US")}var Fu=r("node:url");const Nu={beforeShellExecution:"beforeShellExecution",beforeMCPExecution:"beforeMCPExecution",afterShellExecution:"afterShellExecution",afterMCPExecution:"afterMCPExecution",beforeReadFile:"beforeReadFile",afterFileEdit:"afterFileEdit",beforeTabFileRead:"beforeTabFileRead",afterTabFileEdit:"afterTabFileEdit",stop:"stop",beforeSubmitPrompt:"beforeSubmitPrompt",afterAgentResponse:"afterAgentResponse",afterAgentThought:"afterAgentThought",sessionStart:"sessionStart",sessionEnd:"sessionEnd",preCompact:"preCompact",subagentStart:"subagentStart",subagentStop:"subagentStop",preToolUse:"preToolUse",postToolUse:"postToolUse",postToolUseFailure:"postToolUseFailure",workspaceOpen:"workspaceOpen"},Lu=e=>"string"==typeof e,ju=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),Uu=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),Bu=(e,t=[])=>({isValid:e,errors:t});function Wu(e,t,r){void 0===e||Lu(e)||r.push(`${t} must be a string if provided`)}const Hu=e=>{const t=[];if(!ju(e))return t.push("Hook script must be an object with either a 'command' property (command hook) or 'type: \"prompt\"' with a 'prompt' property (prompt hook)"),Bu(!1,t);const r=e.type;return"prompt"===r?((e,t)=>{Lu(e.prompt)?""===e.prompt.trim()&&t.push("Prompt hook 'prompt' property cannot be empty"):t.push("Prompt hook must have a 'prompt' property (string)"),void 0!==e.model&&(Lu(e.model)?""===e.model.trim()&&t.push("Prompt hook 'model' cannot be an empty string"):t.push("Prompt hook 'model' must be a string if provided"))})(e,t):"command"===r||void 0===r?((e,t)=>{Lu(e.command)||t.push("Hook script command must be a string")})(e,t):t.push(`Invalid hook type: "${r}". Must be "command", "prompt", or omitted (defaults to "command")`),((e,t)=>{if(void 0!==e.matcher)if(Lu(e.matcher)){if(""!==e.matcher&&"*"!==e.matcher)try{new RegExp(e.matcher)}catch(r){t.push(`Hook script matcher "${e.matcher}" is not a valid regex: ${r?.message??String(r)}`)}}else t.push("Hook script matcher must be a string if provided");if(void 0!==e.timeout&&("number"!=typeof e.timeout?t.push("Hook script timeout must be a number (seconds)"):e.timeout<=0?t.push("Hook script timeout must be a positive number"):e.timeout>3600&&console.warn(`[hooks] Hook timeout of ${e.timeout}s is very long (>1 hour)`)),void 0!==e.loop_limit){const r=e.loop_limit;null!==r&&("number"!=typeof r?t.push("Hook script loop_limit must be a positive integer or null"):Number.isInteger(r)?r<=0&&t.push("Hook script loop_limit must be a positive integer (use null for no limit)"):t.push("Hook script loop_limit must be an integer"))}void 0!==e.failClosed&&"boolean"!=typeof e.failClosed&&t.push("Hook script failClosed must be a boolean")})(e,t),Bu(0===t.length,t)},qu=(e,t)=>{const r=[];if(!Array.isArray(e))return r.push(`${t} must be an array of hook scripts`),Bu(!1,r);for(let n=0;n<e.length;n++){const o=Hu(e[n]);o.isValid||r.push(`${t}[${n}]: ${o.errors.join(", ")}`)}return Bu(0===r.length,r)},zu=e=>{const t=[];if(!ju(e))return t.push("Hooks config must be an object"),Bu(!1,t);if("number"!=typeof e.version?t.push("Config version must be a number"):(!Number.isInteger(e.version)||e.version<1)&&t.push("Config version must be a positive integer"),!ju(e.hooks))return t.push("Config hooks must be an object"),Bu(!1,t);void 0!==e.stop_hook_loop_limit&&console.warn("[hooks] DEPRECATION WARNING: 'stop_hook_loop_limit' is deprecated. Use 'loop_limit' on individual hook scripts instead. The configured value is being ignored.");const r=Object.values(Nu),n=e.hooks;for(const[e,o]of Object.entries(n))if(r.includes(e)){if(void 0!==o){const r=qu(o,e);r.isValid||t.push(...r.errors)}}else t.push(`Unknown hook type: ${e}. Valid types are: ${r.join(", ")}`);return Bu(0===t.length,t)},Gu={PreToolUse:Nu.preToolUse,PermissionRequest:null,PostToolUse:Nu.postToolUse,UserPromptSubmit:Nu.beforeSubmitPrompt,Stop:Nu.stop,SubagentStop:Nu.subagentStop,SessionStart:Nu.sessionStart,SessionEnd:Nu.sessionEnd,PreCompact:Nu.preCompact,Notification:null},Vu=Object.fromEntries(Object.entries(Gu).filter((e=>Ku(e[0])&&null!==e[1])).map((([e,t])=>[t,e])));function Ku(e){return Object.prototype.hasOwnProperty.call(Gu,e)}const Ju={Bash:"Shell",Read:"Read",Write:"Write",Edit:"Write",Glob:null,Grep:"Grep",WebFetch:"WebFetch",WebSearch:"WebSearch",Task:"Task"},Zu=["Glob"],Xu=["Notification","PermissionRequest"],Qu=/^[A-Za-z0-9_./:=+-]+$/,Yu=/^=|^-.*\./,ed=/\$\{(?:CLAUDE_PROJECT_DIR|CURSOR_PROJECT_DIR|CLAUDE_PLUGIN_ROOT|CURSOR_PLUGIN_ROOT)\}/g,td=/^[^\p{Cc}$`"]*$/u,rd=/\\(?:[$`"\\]|$)/;function nd(e){return`'${e.replace(/'/g,"'\\''")}'`}function od(e){if(Qu.test(e)&&!Yu.test(e))return e;const t=e.replace(ed,"");if((t!==e||e.includes("'"))&&td.test(t)&&!rd.test(e))return`"${e}"`;const r=[];let n=0;for(const t of e.matchAll(ed))t.index>n&&r.push(nd(e.slice(n,t.index))),r.push(`"${t[0]}"`),n=t.index+t[0].length;return(n<e.length||0===r.length)&&r.push(nd(e.slice(n))),r.join("")}const sd={warn:()=>{},info:()=>{}};function id(e,t,r=sd){const n={loop_limit:null,failClosed:!1};if(t&&"*"!==t&&(n.matcher=t),void 0!==e.timeout&&(n.timeout=e.timeout),"prompt"===e.type)return e.prompt?{type:"prompt",prompt:e.prompt,...n}:null;const o=function(e,t){const r=e.command;if(!r)return null;const n=e.args;return null==n?(void 0!==e.shell&&t.warn(`Hook "${r}" sets shell "${e.shell}", which Cursor does not support; the platform default shell will be used`),r):(o=n,Array.isArray(o)&&o.every((e=>"string"==typeof e))?function(e,t){return[e,...t].map(od).join(" ")}(r,n):(t.warn(`Hook "${r}" has invalid "args" (expected an array of strings), skipping`),null));var o}(e,r);return null===o?null:{type:"command",command:o,...n}}function ad(e,t,r=sd){const n=[];let o;if("PreToolUse"===t||"PostToolUse"===t){const t=function(e,t=sd){if(!e||"*"===e)return"*";const r=e.split("|"),n=[],o=[];for(const e of r){const t=e.trim();if(t.startsWith("mcp__")){const e=t.split("__");if(e.length>=3){const t=e.slice(2).join("__");n.push(`MCP:${t}`);continue}}const r=Ju[t];null!==r?void 0!==r?n.includes(r)||n.push(r):n.push(t):Zu.includes(t)&&o.push(`Tool "${t}" is not supported in Cursor and will be ignored`)}for(const e of o)t.warn(e);return 0===n.length?null:n.join("|")}(e.matcher,r);if(null===t)return r.warn(`All tools in matcher "${e.matcher}" are unsupported, skipping hooks`),[];o="*"===t?void 0:t}else"SessionStart"===t||"PreCompact"===t?(e.matcher&&"*"!==e.matcher&&""!==e.matcher&&("SessionStart"===t?["startup","resume","clear","compact"].includes(e.matcher):["manual","auto"].includes(e.matcher))&&r.warn(`${t} trigger matcher "${e.matcher}" is not supported in Cursor, hooks will fire for all triggers`),o=void 0):o=void 0;for(const t of e.hooks){const e=id(t,o,r);e&&n.push(e)}return n}function cd(e,t=sd){const r={};for(const[n,o]of Object.entries(e)){if(!Ku(n)){t.warn(`Unknown Claude Code event "${n}", skipping`);continue}if(Xu.includes(n)){t.warn(`Claude Code event "${n}" is not supported in Cursor and will be ignored`);continue}const e=Gu[n];if(!e){t.warn(`Unknown Claude Code event "${n}", skipping`);continue}const s=[];if(Array.isArray(o))for(const e of o){const r=ad(e,n,t);s.push(...r)}else void 0!==o&&t.warn(`Claude Code event "${n}" has invalid value (expected array), skipping`);if(s.length>0){const t=r[e]||[];r[e]=[...t,...s]}}return{version:1,hooks:r}}var ld=r("../../node_modules/.pnpm/gray-matter@4.0.3/node_modules/gray-matter/index.js");const ud=()=>({});function dd(e,t){return ld(e,{...t,engines:{...t?.engines,js:ud,javascript:ud}})}function hd(e,t,r){return ld.stringify({content:e,data:{}},t,r)}function pd(e){return e.replace(/\\/g,"/").replace(/\/+$/,"")||"/"}function fd(e,t){if(Object.hasOwn(e,t))return e[t]}function md(e,t,r,n){const o=e?.plugins;if(!o||"object"!=typeof o)return[];const s=t?.enabledPlugins??{},i={};r?.enabledPlugins&&Object.assign(i,r.enabledPlugins);const a=void 0!==n?pd(n):void 0,c=new Set,l=[];for(const[e,t]of Object.entries(o)){if(!Array.isArray(t)||0===t.length)continue;if(void 0!==a&&!1===fd(i,e))continue;let r;void 0!==a&&(r=t.find((t=>!("project"!==t.scope&&"local"!==t.scope||!t.projectPath)&&(pd(t.projectPath)===a&&!0===fd(i,e))))),r||!0!==fd(s,e)||(r=t.find((e=>"user"===e.scope))),r?.installPath&&!c.has(e)&&(l.push({pluginId:e,installPath:r.installPath}),c.add(e))}return l}var gd=r("../../node_modules/.pnpm/js-yaml@4.3.1/node_modules/js-yaml/dist/js-yaml.mjs");const wd=je.enum(["canvas"]),yd=je.array(wd).transform((e=>[...new Set(e)].sort())),vd=new Set(["https://agent-plugins.org/schemas/1.0.0/plugin.schema.json","https://agent-plugins.org/schemas/1.0.0/mcp.schema.json"]),bd=/^v?(\d+\.\d+(?:\.\d+)?)$/;function Sd(e){if("object"!=typeof(t=e)||null===t||Array.isArray(t))return;var t;const r=e.$schema;return"string"==typeof r&&r.length>0?r:void 0}function kd(e){let t;try{t=new URL(e).pathname.split("/")}catch{t=e.split("/")}for(const e of t){const t=bd.exec(e);if(null!==t)return t[1]}}function _d(e){return void 0===e?{kind:"absent"}:vd.has(e)?{kind:"supported",id:e,version:kd(e)??e}:{kind:"unsupported",id:e}}const Cd=10485760,Ed=/^[a-z0-9]([a-z0-9.-]*[a-z0-9])?$/,xd=[".cursor-plugin/plugin.json",".claude-plugin/plugin.json","plugin.json"],Pd=[".cursor-plugin",".claude-plugin"],Id=[".cursor-plugin/marketplace.json",".claude-plugin/marketplace.json"],Rd=je.object({source:je.literal("github"),repo:je.string().regex(/^[^/]+\/[^/]+$/,"Must be in owner/repo format"),ref:je.string().optional(),sha:je.string().length(40,"SHA must be 40 characters").regex(/^[a-f0-9]+$/,"SHA must be hexadecimal").optional()}),Td=je.object({source:je.literal("url"),url:je.string().url().endsWith(".git","URL must end with .git"),ref:je.string().optional(),sha:je.string().length(40,"SHA must be 40 characters").regex(/^[a-f0-9]+$/,"SHA must be hexadecimal").optional()}),Ad=je.object({source:je.literal("git-subdir"),url:je.string().url().endsWith(".git","URL must end with .git"),path:je.string().min(1),ref:je.string().optional(),sha:je.string().length(40,"SHA must be 40 characters").regex(/^[a-f0-9]+$/,"SHA must be hexadecimal").optional()}),$d=je.union([je.string(),Rd,Td,Ad]),Md=/^(\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?|never)$/,Dd='Must be a semver version (X.Y.Z) or "never"',Od=je.object({cursor:je.string().regex(Md,Dd).optional(),sand:je.string().regex(Md,Dd).optional(),sandMobile:je.string().regex(Md,Dd).optional()}),Fd=je.object({name:je.string().min(1,"Author name is required"),email:je.string().email().optional()}),Nd=je.enum(["string","number","integer","boolean","object","array","null"]),Ld=je.union([Nd,je.array(Nd).nonempty().superRefine(((e,t)=>{new Set(e).size!==e.length&&t.addIssue({code:je.ZodIssueCode.custom,message:"Schema type arrays must not contain duplicates"})}))]);function jd(e,t){if(void 0!==e.required)if(void 0===e.properties)for(const r of e.required)t.addIssue({code:je.ZodIssueCode.custom,message:`Required property "${r}" must be declared in properties`,path:["required"]});else for(const r of e.required)r in e.properties||t.addIssue({code:je.ZodIssueCode.custom,message:`Required property "${r}" must be declared in properties`,path:["required"]});void 0!==e.minLength&&void 0!==e.maxLength&&e.minLength>e.maxLength&&t.addIssue({code:je.ZodIssueCode.custom,message:"minLength must be less than or equal to maxLength",path:["minLength"]}),void 0!==e.minimum&&void 0!==e.maximum&&e.minimum>e.maximum&&t.addIssue({code:je.ZodIssueCode.custom,message:"minimum must be less than or equal to maximum",path:["minimum"]}),void 0!==e.exclusiveMinimum&&void 0!==e.exclusiveMaximum&&e.exclusiveMinimum>=e.exclusiveMaximum&&t.addIssue({code:je.ZodIssueCode.custom,message:"exclusiveMinimum must be less than exclusiveMaximum",path:["exclusiveMinimum"]}),void 0!==e.minItems&&void 0!==e.maxItems&&e.minItems>e.maxItems&&t.addIssue({code:je.ZodIssueCode.custom,message:"minItems must be less than or equal to maxItems",path:["minItems"]}),void 0!==e.minProperties&&void 0!==e.maxProperties&&e.minProperties>e.maxProperties&&t.addIssue({code:je.ZodIssueCode.custom,message:"minProperties must be less than or equal to maxProperties",path:["minProperties"]})}const Ud=je.lazy((()=>je.object({type:Ld.optional(),title:je.string().optional(),description:je.string().optional(),format:je.string().optional(),writeOnly:je.boolean().optional(),placeholder:je.string().optional(),default:je.unknown().optional(),enum:je.array(je.any()).nonempty().optional(),const:je.unknown().optional(),properties:je.record(je.string(),Ud).optional(),required:je.array(je.string()).optional(),additionalProperties:je.union([je.boolean(),Ud]).optional(),items:je.union([Ud,je.array(Ud)]).optional(),minLength:je.number().int().nonnegative().optional(),maxLength:je.number().int().nonnegative().optional(),minimum:je.number().optional(),maximum:je.number().optional(),exclusiveMinimum:je.number().optional(),exclusiveMaximum:je.number().optional(),multipleOf:je.number().positive().optional(),minItems:je.number().int().nonnegative().optional(),maxItems:je.number().int().nonnegative().optional(),uniqueItems:je.boolean().optional(),minProperties:je.number().int().nonnegative().optional(),maxProperties:je.number().int().nonnegative().optional()}).strict().superRefine(jd)));function Bd(e){const t=Ud.superRefine(((e,t)=>{qd(e)&&"object"===e.type||t.addIssue({code:je.ZodIssueCode.custom,message:'Plugin variable schemas must declare type "object"',path:["type"]})})).safeParse(e);return t.success?zd(t.data)?{success:!0,data:t.data}:{success:!1,error:new je.ZodError([{code:"custom",path:["type"],message:'Plugin variable schemas must declare type "object"'}])}:{success:!1,error:t.error}}const Wd=je.unknown().superRefine(((e,t)=>{const r=Bd(e);if(!r.success)for(const e of r.error.issues)t.addIssue({code:"custom",message:e.message,path:e.path})})).transform((e=>{if(!zd(e))throw new Error('Plugin variable schema must declare type "object"');return e})),Hd=(je.object({name:je.string().min(1).transform((e=>e.toLowerCase())).refine((e=>Ed.test(e)),"Name must be kebab-case (lowercase alphanumeric with hyphens and periods)"),displayName:je.string().optional(),source:$d,description:je.string().optional(),version:je.string().optional(),author:Fd.optional(),publisher:je.string().min(1).optional(),homepage:je.string().url().optional(),repository:je.string().url().optional(),license:je.string().optional(),keywords:je.array(je.string()).optional(),capabilities:yd.optional(),logo:je.string().optional(),category:je.string().optional(),tags:je.array(je.string()).optional(),minClientVersions:Od.optional(),strict:je.boolean().default(!0),commands:je.union([je.string(),je.array(je.string())]).optional(),agents:je.union([je.string(),je.array(je.string())]).optional(),skills:je.union([je.string(),je.array(je.string())]).optional(),rules:je.union([je.string(),je.array(je.string())]).optional(),hooks:je.union([je.string(),je.record(je.string(),je.unknown())]).optional(),variables:Wd.optional(),mcpServers:je.union([je.string(),je.record(je.string(),je.unknown()),je.array(je.union([je.string(),je.record(je.string(),je.unknown())]))]).optional()}),je.object({description:je.string().optional(),version:je.string().optional(),pluginRoot:je.string().optional()}),je.object({name:je.string().min(1).regex(Ed,"Name must be kebab-case (lowercase alphanumeric with hyphens and periods)"),displayName:je.string().optional(),description:je.string().optional(),version:je.string().optional(),author:Fd.optional(),publisher:je.string().min(1).optional(),homepage:je.string().url().optional(),repository:je.string().url().optional(),license:je.string().optional(),logo:je.string().optional(),keywords:je.array(je.string()).optional(),capabilities:yd.optional(),minClientVersions:Od.optional(),commands:je.union([je.string(),je.array(je.string())]).optional(),agents:je.union([je.string(),je.array(je.string())]).optional(),skills:je.union([je.string(),je.array(je.string())]).optional(),rules:je.union([je.string(),je.array(je.string())]).optional(),hooks:je.union([je.string(),je.record(je.string(),je.unknown())]).optional(),variables:Wd.optional(),mcpServers:je.union([je.string(),je.record(je.string(),je.unknown()),je.array(je.union([je.string(),je.record(je.string(),je.unknown())]))]).optional()}));function qd(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function zd(e){return qd(e)&&"object"===e.type}function Gd(e){return e.trim().toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")}function Vd(e,t){if(qd(e)&&"string"==typeof e.name){const t=Gd(e.name);if(t.length>0)return t}return function(e){const t=void 0!==e.repoName?Gd(e.repoName):"";return t.length>0?t:`cursor-marketplace-${e.fallbackId??(0,lo.randomUUID)()}`}(t)}function Kd(e){if(qd(e)&&qd(e.owner)){const t="string"==typeof e.owner.name&&e.owner.name.trim().length>0?e.owner.name:"Unknown",r="string"==typeof e.owner.email&&e.owner.email.trim().length>0?e.owner.email:void 0;return{name:t,...void 0!==r?{email:r}:{}}}return{name:"Unknown"}}function Jd(e){return"string"==typeof e?e:void 0}function Zd(e){if(!Array.isArray(e))return;const t=e.filter((e=>"string"==typeof e));return t.length>0?t:void 0}function Xd(e){return"string"==typeof e?e:Zd(e)}function Qd(e){if(!qd(e)||!qd(e.metadata))return;const t={description:Jd(e.metadata.description),version:Jd(e.metadata.version),pluginRoot:Jd(e.metadata.pluginRoot)};return void 0!==t.description||void 0!==t.version||void 0!==t.pluginRoot?t:void 0}function Yd(e){if(!qd(e))return;const t=Jd(e.name);if(void 0===t||0===t.length)return;const r=Jd(e.email);return{name:t,...void 0!==r?{email:r}:{}}}function eh(e){if("string"==typeof e||qd(e))return e;if(Array.isArray(e)){const t=e.filter((e=>"string"==typeof e||qd(e)));return t.length>0?t:void 0}}function th(e){if("string"==typeof e||qd(e))return e}function rh(e){if(void 0===e)return;const t=Bd(e);return t.success?t.data:void 0}function nh(e,t={}){if(e.length>Cd)return{success:!1,error:"Manifest exceeds maximum size of 10485760 bytes"};let r;try{r=JSON.parse(e)}catch(e){return{success:!1,error:`Invalid JSON: ${e instanceof Error?e.message:"Unknown error"}`}}if(!qd(r))return{success:!1,error:"Invalid marketplace manifest: expected a JSON object"};const n=[],o=[],i=new Set;return(Array.isArray(r.plugins)?r.plugins:[]).forEach(((e,t)=>{const r=function(e,t){if(!qd(e))return{skippedEntry:{index:t,error:`Plugin entry at index ${t} is not an object`}};const r="string"==typeof(n=e.source)?n:qd(n)?"github"===n.source&&"string"==typeof n.repo&&n.repo.length>0?{source:"github",repo:n.repo,ref:Jd(n.ref),sha:Jd(n.sha)}:("url"===n.source||void 0===n.source)&&"string"==typeof n.url&&n.url.length>0?{source:"url",url:n.url,ref:Jd(n.ref),sha:Jd(n.sha)}:"git-subdir"===n.source&&"string"==typeof n.url&&n.url.length>0&&"string"==typeof n.path&&n.path.length>0?{source:"git-subdir",url:n.url,path:n.path,ref:Jd(n.ref),sha:Jd(n.sha)}:"string"==typeof n.repo&&n.repo.length>0?{source:"github",repo:n.repo,ref:Jd(n.ref),sha:Jd(n.sha)}:void 0:void 0;var n;if(void 0===r){const r=Jd(e.name);return{skippedEntry:{index:t,...void 0!==r&&r.length>0?{name:r}:{},error:`Plugin entry at index ${t} has no usable source`}}}const o=("string"==typeof e.name?Gd(e.name):"")||function(e){if("string"==typeof e){const t=Gd((0,s.basename)(e));return t.length>0?t:void 0}if("github"===e.source){const t=Gd(e.repo.split("/").at(-1)??"");return t.length>0?t:void 0}if("git-subdir"===e.source){const t=Gd((0,s.basename)(e.path));return t.length>0?t:void 0}let t=e.url;try{t=new URL(e.url).pathname}catch{}for(;t.endsWith("/");)t=t.slice(0,-1);t.toLowerCase().endsWith(".git")&&(t=t.slice(0,-4));const r=Gd((0,s.basename)(t));return r.length>0?r:void 0}(r);if(void 0===o)return{skippedEntry:{index:t,error:`Plugin entry at index ${t} has no usable name`}};const i=yd.safeParse(e.capabilities);if(void 0!==e.capabilities&&!i.success)return{skippedEntry:{index:t,name:o,error:`Plugin entry at index ${t} has invalid capabilities: ${i.error.issues.map((e=>`${e.path.join(".")}: ${e.message}`)).join(", ")}`}};const a=i.success?i.data:void 0,c=function(e){const t=Od.safeParse(e);if(t.success&&(void 0!==t.data.cursor||void 0!==t.data.sand||void 0!==t.data.sandMobile))return t.data}(e.minClientVersions);return{entry:{name:o,displayName:Jd(e.displayName),source:r,description:Jd(e.description),version:Jd(e.version),author:Yd(e.author),publisher:Jd(e.publisher),homepage:Jd(e.homepage),repository:Jd(e.repository),license:Jd(e.license),keywords:Zd(e.keywords),logo:Jd(e.logo),category:Jd(e.category),tags:Zd(e.tags),strict:"boolean"!=typeof e.strict||e.strict,commands:Xd(e.commands),agents:Xd(e.agents),skills:Xd(e.skills),rules:Xd(e.rules),hooks:th(e.hooks),variables:rh(e.variables),mcpServers:eh(e.mcpServers),...void 0!==a&&{capabilities:a},...void 0!==c&&{minClientVersions:c}}}}(e,t);"skippedEntry"in r?o.push(r.skippedEntry):i.has(r.entry.name)?o.push({index:t,name:r.entry.name,error:`Duplicate plugin name "${r.entry.name}" at index ${t}`}):(i.add(r.entry.name),n.push(r.entry))})),{success:!0,data:{name:Vd(r,t),owner:Kd(r),description:Jd(r.description),plugins:n,metadata:Qd(r),skippedPluginEntries:o}}}function oh(e){if(e.length>Cd)return{success:!1,error:"Manifest exceeds maximum size of 10485760 bytes"};let t;try{t=JSON.parse(e)}catch(e){return{success:!1,error:`Invalid JSON: ${e instanceof Error?e.message:"Unknown error"}`}}const r=_d(Sd(t)),n=Hd.safeParse(t);return n.success?{success:!0,data:n.data,..."unsupported"===r.kind&&{unrecognizedSchemaId:r.id}}:{success:!1,error:`Invalid plugin manifest: ${n.error.issues.map((e=>`${e.path.join(".")}: ${e.message}`)).join(", ")}`,details:n.error}}function sh(e,t){if("string"!=typeof e)return null;let r=e;if(r.startsWith("./")&&(r=r.slice(2)),void 0!==t){let e=t;e.startsWith("./")&&(e=e.slice(2)),e.endsWith("/")&&(e=e.slice(0,-1)),r=`${e}/${r}`}return r||"."}function ih(e){return!e.includes("..")&&!(0,s.isAbsolute)(e)&&!e.includes("://")}var ah=r("../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/main.js");const ch=/\$\{(?:env:([A-Za-z_][A-Za-z0-9_]*)|([^:}]+)(?::-([^}]*))?)\}/g,lh=/\$%7B([^%/?#]+?)%7D/gi;function uh(e,t){return dh(e,"function"==typeof t?t:function(e){const t=new Map(Object.entries(e).map((([e,t])=>[e.toLowerCase(),t])));return r=>e[r]??t.get(r.toLowerCase())}(t))}function dh(e,t){if("string"==typeof e)return function(e,t){return e.replace(lh,"${$1}").replace(ch,((e,r,n,o)=>{if(void 0!==r)return t(r)??e;if(void 0===n)return e;const s=t(n);return void 0!==s?s:void 0!==o?o:e}))}(e,t);if(Array.isArray(e))return e.map((e=>dh(e,t)));if(function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}(e)){const r={};for(const[n,o]of Object.entries(e))r[n]=dh(o,t);return r}return e}function hh(e,t){return e.replace(/\$\{CLAUDE_PLUGIN_ROOT\}/g,(()=>t)).replace(/\$\{CURSOR_PLUGIN_ROOT\}/g,(()=>t))}const ph={log:()=>{},increment:()=>{},distribution:()=>{},captureException:()=>{}},fh=je.object({command:je.string().optional(),args:je.array(je.string()).optional(),env:je.record(je.string(),je.string()).optional(),url:je.string().optional(),headers:je.record(je.string(),je.string()).optional(),cwd:je.string().optional(),envFile:je.string().optional(),auth:je.object({CLIENT_ID:je.string(),CLIENT_SECRET:je.string().optional(),scopes:je.array(je.string()).optional()}).optional(),enabledTools:je.array(je.string()).optional(),placement:je.enum(["server","client"]).optional(),tls:je.object({caBundle:je.string().trim().min(1).max(131072)}).optional()}),mh=je.object({mcpServers:je.record(je.string(),fh).optional()}),gh=[".mcp.json","mcp.json"],wh=new Set(["author","owner","source","metadata"].map((e=>e.toLowerCase())));function yh(e,t){if(!function(e){return wh.has(e.toLowerCase())}(e))return!1;if(!function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}(t))return!1;const r=t;switch(e.toLowerCase()){case"author":case"owner":return"string"==typeof r.name;case"source":return"string"==typeof r.source||"string"==typeof r.repo||"string"==typeof r.path||"string"==typeof r.ref||"string"==typeof r.sha;case"metadata":return"string"==typeof r.description||"string"==typeof r.version||"string"==typeof r.pluginRoot;default:return!1}}function vh(e){return"object"==typeof e&&null!==e&&("command"in e||"url"in e)}function bh(e){const t=void 0!==e&&e.length>0?e.replace(/\/+$/,""):void 0;return gh.map((e=>void 0!==t?`${t}/${e}`:e))}function Sh(e,t,r){if(!e.mcpServers)return e;const n={};for(const[r,o]of Object.entries(e.mcpServers)){const e={...o};if("string"==typeof o.command&&(e.command=hh(o.command,t)),Array.isArray(o.args)&&(e.args=o.args.map((e=>"string"==typeof e?hh(e,t):e))),o.env&&"object"==typeof o.env){const r={};for(const[e,n]of Object.entries(o.env))r[e]="string"==typeof n?hh(n,t):n;e.env=r}"string"==typeof o.cwd&&(e.cwd=hh(o.cwd,t)),n[r]=e}return function(e,t){const r=t?.cloudAgentEnvLookup,n=t?.configuredVariables;if(void 0!==r)return uh(e,r);const o=new Map(Object.keys(n??{}).map((e=>[e.toLowerCase(),e])));return uh(e,(e=>{const t=process.env[e];if(void 0!==t)return t;const r=void 0!==n&&Object.hasOwn(n,e)?e:o.get(e.toLowerCase()),s=void 0!==r?n?.[r]:void 0;return null!=s?"string"==typeof s?s:"number"==typeof s||"boolean"==typeof s||"bigint"==typeof s?String(s):JSON.stringify(s):void 0}))}({...e,mcpServers:n},r)}function kh(e,t,r){try{const n=(0,ah.qg)(e),o=Sd(n);if(void 0!==o){const e=r?.log??ph;"unsupported"===_d(o).kind?e.log("debug",`mcp.json declares an unrecognized $schema, loading anyway: ${o}`):function(e,t){if(void 0===e||void 0===t)return!1;const r=kd(e),n=kd(t);return void 0!==r&&void 0!==n&&r!==n}(r?.pluginSchemaId,o)&&e.log("debug",`mcp.json $schema ${o} disagrees with plugin.json $schema ${r?.pluginSchemaId}, loading anyway`)}const s=mh.safeParse(n),i=!0===r?.skipExpansion;if(s.success&&s.data.mcpServers&&Object.keys(s.data.mcpServers).length>0)return i?s.data:Sh(s.data,t,r);const a={};for(const[e,t]of Object.entries(n))"mcpServers"!==e&&!yh(e,t)&&vh(t)&&(a[e]=t);if(Object.keys(a).length>0){const e=mh.safeParse({mcpServers:a});if(e.success)return i?e.data:Sh(e.data,t,r)}return null}catch{return null}}function _h(e,t,r){for(const[n,o]of Object.entries(t))e.mcpServers[n]=o,e.mcpServerSourcePaths[n]=r}async function Ch(e,t,r,n={}){const o=n.toSourcePath??(e=>e),s=n.installPathForExpansion??"",i=n.fallbackFileNames??gh,a=n.manifestPrecedence??"override",c={},l={};for(const t of i){const r=await e(t);if(null===r)continue;const i=kh(r,s,n.parserOptions);if(i?.mcpServers)for(const[e,r]of Object.entries(i.mcpServers))void 0===c[e]&&(c[e]=r,l[e]=o(t))}if(void 0!==t){const i=await async function(e,t,r={}){const n=r.toSourcePath??(e=>e),o=r.installPathForExpansion??"",s={mcpServers:{},mcpServerSourcePaths:{}},i=async e=>{const i=e.replace(/^\.\//,"");if(!ih(i))return;const a=await t(i);if(null===a)return;const c=kh(a,o,r.parserOptions);c?.mcpServers&&Object.keys(c.mcpServers).length>0&&_h(s,c.mcpServers,n(i))},a=e=>{const t=kh(JSON.stringify(e),o,r.parserOptions);t?.mcpServers&&Object.keys(t.mcpServers).length>0&&_h(s,t.mcpServers,r.manifestSourcePath??"manifest")};if("string"==typeof e)await i(e);else if(Array.isArray(e))for(const t of e)"string"==typeof t?await i(t):"object"==typeof t&&null!==t&&a(t);else"object"==typeof e&&null!==e&&a(e);return s}(t,e,{toSourcePath:o,manifestSourcePath:r,installPathForExpansion:s,parserOptions:n.parserOptions});for(const[e,t]of Object.entries(i.mcpServers))"fill"===a&&void 0!==c[e]||(c[e]=t,l[e]=i.mcpServerSourcePaths[e])}return 0===Object.keys(c).length?null:{mcpServers:c,...Object.keys(l).length>0&&{mcpServerSourcePaths:l}}}const Eh=new Set(["CREDENTIAL","CREDENTIALS","KEY","PASSPHRASE","PASSWORD","SECRET","TOKEN"]);function xh(e){return function(e){return e.replace(/([a-z\d])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/[^a-z\d]+/gi,"_").toUpperCase().split("_").filter((e=>e.length>0))}(e).some((e=>Eh.has(e)))}const Ph=/\$\{(?:env:([A-Z][A-Z0-9_]*)|([A-Z][A-Z0-9_]*)(?::-([^}]*))?)\}/g,Ih=new Set(["CURSOR_PLUGIN_ROOT","CLAUDE_PLUGIN_ROOT"]),Rh=new Set(["api","aws","db","dd","gcp","http","https","id","mcp","ssl","tls","uri","url"]);function Th(e){return e.split("_").filter((e=>e.length>0)).map((e=>{const t=e.toLowerCase();return Rh.has(t)?e.toUpperCase():e.charAt(0).toUpperCase()+t.slice(1)})).join(" ")}function Ah(e,t){if("string"!=typeof e){if(Array.isArray(e))for(const r of e)Ah(r,t);else if(null!==e&&"object"==typeof e)for(const r of Object.values(e))Ah(r,t)}else for(const[,r,n,o]of e.matchAll(Ph)){const e=r??n;if(void 0===e||Ih.has(e)||t.has(e))continue;const s=void 0===r?`\${${e}}`:`\${env:${e}}`;t.set(e,{reference:s,defaultValue:o})}}function $h(e){if(void 0===e?.mcpServers)return;const t=new Map;if(Ah(e.mcpServers,t),0===t.size)return;const r={};for(const e of[...t.keys()].sort()){const n=t.get(e);if(void 0===n)continue;const{reference:o,defaultValue:s}=n;r[e]={type:"string",title:Th(e),description:void 0===s||0===s.length?`Referenced as \`${o}\` in this plugin's MCP configuration.`:`Referenced as \`${o}\` in this plugin's MCP configuration. Defaults to \`${s}\` when left blank.`,...xh(e)?{writeOnly:!0}:{}}}return{type:"object",properties:r}}const Mh=[".md",".mdc",".markdown"],Dh=[...Mh,".txt"],Oh=/^---\s*\n([\s\S]*?)\n---/;function Fh(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Nh(e){return e.trim().toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9.-]/g,"")}function Lh(e){const t=e.match(Oh);if(!t)return{};try{const e=gd.Ay.load(t[1],{schema:gd.Ay.JSON_SCHEMA});if(!Fh(e))return{};const r=Fh(e.metadata)?e.metadata:void 0,n=jh(e.environments??r?.environments);return{disabledEnvironments:jh(e["disabled-environments"]??r?.disabledEnvironments),environments:n,name:"string"==typeof e.name?e.name:void 0,description:"string"==typeof e.description?e.description:void 0}}catch{const e=t[1],r=e.match(/^name:\s*(.+)$/m),n=e.match(/^description:\s*(.+)$/m);return r||n?{name:r?r[1].trim():void 0,description:n?n[1].trim():void 0}:{}}}function jh(e){if(Array.isArray(e)){const t=e.filter((e=>"string"==typeof e&&e.length>0));return 0===t.length?void 0:t}if("string"==typeof e){const t=e.split(",").map((e=>e.trim())).filter((e=>e.length>0));return 0===t.length?void 0:t}}function Uh(e){return Nh((0,s.basename)(e).replace(/\.(md|mdc|markdown|txt)$/i,""))}function Bh(e){const t=new Set,r=[];for(const n of e)t.has(n.name)||(t.add(n.name),r.push(n));return r}class Wh{constructor(e){this.fetcher=e}async discoverComponents(e={}){const t=e.basePath??"",r=t?`${t}/`:"",n=e.manifest;let o;try{o=await this.fetcher.listDirectory(t)}catch{o=[]}const s=new Set(o.filter((e=>"dir"===e.type)).map((e=>e.name.toLowerCase()))),i=gh.filter((e=>o.some((t=>"file"===t.type&&t.name===e)))),a=o.some((e=>"file"===e.type&&"SKILL.md"===e.name)),[c,l,u,d,h,p,f]=await Promise.all([a&&void 0===n?.skills?this.discoverRootSkill(r):Promise.resolve(null),void 0!==n?.skills?this.discoverFromManifestPaths(r,n.skills,!0,Mh):s.has("skills")?this.discoverSkills(`${r}skills`):Promise.resolve([]),void 0!==n?.agents?this.discoverFromManifestPaths(r,n.agents,!1,Mh):s.has("agents")?this.discoverMarkdownComponents(`${r}agents`,Mh):Promise.resolve([]),void 0!==n?.hooks?this.discoverHooksFromManifest(r,n.hooks):s.has("hooks")?this.discoverHooksFromJson(`${r}hooks/hooks.json`):Promise.resolve([]),void 0!==n?.commands?this.discoverFromManifestPaths(r,n.commands,!1,Dh):s.has("commands")?this.discoverMarkdownComponents(`${r}commands`,Dh):Promise.resolve([]),void 0!==n?.rules?this.discoverFromManifestPaths(r,n.rules,!1,Mh):s.has("rules")?this.discoverMarkdownComponents(`${r}rules`,Mh):Promise.resolve([]),this.discoverMcpServers(r,n?.mcpServers,i)]);return{skills:Bh(c?[c,...l]:l),agents:Bh(u),hooks:d,commands:Bh(h),rules:Bh(p),mcpServers:f.servers,mcpVariables:f.variables,mcpConfigs:f.configs}}async discoverHooksFromJson(e){try{if(!await this.fetcher.fileExists(e))return[];const{content:t}=await this.fetcher.fetchFile(e),r=JSON.parse(t);return Fh(r)&&Fh(r.hooks)?Object.keys(r.hooks).map((t=>({name:Nh(t),path:e,description:`Hook: ${t}`}))):[]}catch{return[]}}async discoverHooksFromManifest(e,t){if("string"==typeof t){if(!ih(t))return[];const r=`${e}${t.replace(/^\.\//,"")}`;return r.endsWith(".json")?this.discoverHooksFromJson(r):this.discoverHooksFromJson(`${r}/hooks.json`)}const r=t.hooks??t;return!r||"object"!=typeof r||Array.isArray(r)?[]:Object.keys(r).map((e=>({name:Nh(e),path:"manifest",description:`Hook: ${e}`})))}async discoverFromManifestPaths(e,t,r=!1,n=Mh){if("string"==typeof t){if(!ih(t))return[];const o=`${e}${t.replace(/^\.\//,"")}`.replace(/\/$/,"");return r?this.discoverSkills(o):this.discoverMarkdownComponents(o,n)}const o=[];for(const n of t)try{if(!ih(n))continue;const t=`${e}${n.replace(/^\.\//,"")}`;if(r){const e=t.endsWith("SKILL.md")?t:`${t.replace(/\/$/,"")}/SKILL.md`;if(!await this.fetcher.fileExists(e)){const e=t.replace(/\/$/,""),r=await this.discoverSkills(e);o.push(...r);continue}let r=Uh(t.endsWith("SKILL.md")?t.slice(0,-8).replace(/\/$/,""):t);const{content:n}=await this.fetcher.fetchFile(e),s=Lh(n);if(r=s.name??r,r){const t={disabledEnvironments:s.disabledEnvironments,environments:s.environments,name:Nh(r),path:e};void 0!==s.description&&(t.description=s.description),o.push(t)}}else{if(!await this.fetcher.fileExists(t))continue;let e=Uh(t);const{content:r}=await this.fetcher.fetchFile(t),n=Lh(r);e=n.name??e;const s=n.description;if(e){const r={name:Nh(e),path:t};void 0!==s&&(r.description=s),o.push(r)}}}catch{}return o}async discoverMarkdownComponents(e,t=Mh,r=new Set){let n;try{n=await this.fetcher.listDirectory(e,r)}catch{return[]}const o=n.filter((e=>"file"===e.type&&t.some((t=>e.name.endsWith(t))))),s=n.filter((e=>"dir"===e.type)),[i,a]=await Promise.all([Promise.all(o.map((async e=>{try{let t=Uh(e.name);const{content:r}=await this.fetcher.fetchFile(e.path),n=Lh(r);t=n.name?Nh(n.name):t;const o=n.description;if(!t)return null;const s={name:t,path:e.path};return void 0!==o&&(s.description=o),s}catch{return null}}))),Promise.all(s.map((e=>this.discoverMarkdownComponents(e.path,t,r))))]);return[...i.filter((e=>null!==e)),...a.flat()]}async discoverRootSkill(e){try{const t=`${e}SKILL.md`;let r=Nh((0,s.basename)(e.replace(/[\\/]+$/,"")));const{content:n}=await this.fetcher.fetchFile(t),o=Lh(n);if(r=o.name?Nh(o.name):r,!r)return null;const i={disabledEnvironments:o.disabledEnvironments,environments:o.environments,name:r,path:t};return void 0!==o.description&&(i.description=o.description),i}catch{return null}}async discoverSkills(e){let t;try{t=await this.fetcher.listDirectory(e)}catch{return[]}const r=t.filter((e=>"dir"===e.type));return(await Promise.all(r.map((async e=>{try{const t=`${e.path}/SKILL.md`;if(!await this.fetcher.fileExists(t))return null;const{content:r}=await this.fetcher.fetchFile(t),n=Lh(r),o=n.name?Nh(n.name):Nh(e.name);if(!o)return null;const s={disabledEnvironments:n.disabledEnvironments,environments:n.environments,name:o,path:t};return void 0!==n.description&&(s.description=n.description),s}catch{return null}})))).filter((e=>null!==e))}async discoverMcpServers(e,t,r){const n=new Map,o=async t=>{const r=n.get(t);if(void 0!==r)return r;const o=this.fetcher.fetchFile(`${e}${t}`).then((({content:e})=>e)).catch((()=>null));return n.set(t,o),o},s=async n=>Ch(o,t,void 0!==t?"manifest":void 0,{fallbackFileNames:r,manifestPrecedence:n,toSourcePath:t=>`${e}${t}`,parserOptions:{skipExpansion:!0}}),i=await s("fill");if(void 0===i?.mcpServers)return{servers:[],variables:void 0,configs:void 0};const a=void 0===t?i:await s("override"),c=a?.mcpServers??i.mcpServers,l={};for(const[e,t]of Object.entries(c))l[e]=t;return{servers:Object.keys(i.mcpServers).map((e=>({name:Nh(e),path:i.mcpServerSourcePaths?.[e]??"manifest"}))),variables:$h(a??i),configs:l}}}var Hh=r("node:stream"),qh=r("node:stream/promises"),zh=r("node:zlib");function Gh(e,t){const r=function(e){return e.split(/[/\\]/).filter((e=>e))}(e);for(let e=0;e<r.length-2;e++)if(".cursor"===r[e]&&"projects"===r[e+1]&&r[e+3]===t)return{workspaceId:r[e+2],remainingPath:r.slice(e+4)};return null}function Vh(e){return e.replace(/[^a-zA-Z0-9._-]/g,"_")}var Kh=r("../../node_modules/.pnpm/tar@7.5.21/node_modules/tar/dist/esm/index.min.js");const Jh=".cache-complete";function Zh(e){return Vh(e)}function Xh(e){const{parent:t,name:r}=e;return t.startsWith("\\\\")||/^[A-Za-z]:\\/.test(t)?s.win32.join(t,r):/^[A-Za-z]:\//.test(t)||t.startsWith("//")&&!t.startsWith("//?/")?`${t.replace(/\/+$/,"")}/${r}`:(0,s.join)(t,r)}function Qh(e,t){return function(e,t,r,n){const o=[t,r];return void 0!==n&&o.push(n),e.startsWith("\\\\")||/^[A-Za-z]:\\/.test(e)?s.win32.join(e,...o):/^[A-Za-z]:\//.test(e)||e.startsWith("//")&&!e.startsWith("//?/")?[e.replace(/\/+$/,""),...o].join("/"):(0,s.join)(e,...o)}(e,t.marketplaceSlug.replace(/[^a-zA-Z0-9_-]/g,"_"),t.pluginId.replace(/[^a-zA-Z0-9_-]/g,"_"),void 0!==t.version?Zh(t.version):void 0)}class Yh{constructor(e,t){const r=e??process.env.HOME??"";this.cacheRoot=t?.cacheRoot??(0,s.join)(r,".cursor","plugins/cache")}getCacheDir(e){return Qh(this.cacheRoot,e)}async isCached(e){const t=this.getCacheDir(e);try{const e=Xh({parent:t,name:Jh});return(await(0,fo.stat)(e)).isFile()}catch{return!1}}async extractToCache(e){const t=this.getCacheDir(e);await(0,fo.mkdir)(t,{recursive:!0});const r=Hh.Readable.from(e.tarball);return await(0,qh.pipeline)(r,(0,zh.createGunzip)(),(0,Kh.o6)({cwd:t,strip:1})),await this.markCacheComplete(e),t}async listCachedVersions(e){const t=Qh(this.cacheRoot,e);try{return(await(0,fo.readdir)(t,{withFileTypes:!0})).filter((e=>e.isDirectory())).map((e=>e.name))}catch{return[]}}async removeVersion(e){const t=this.getCacheDir(e);try{await(0,fo.rm)(t,{recursive:!0,force:!0})}catch{}}async removeAllVersions(e){const t=Qh(this.cacheRoot,e);await(0,fo.rm)(t,{recursive:!0,force:!0})}async pruneOldVersions(e){const t=await this.listCachedVersions({marketplaceSlug:e.marketplaceSlug,pluginId:e.pluginId}),r=new Set(e.keepVersions.map((e=>Zh(e))));for(const n of t)r.has(n)||await this.removeVersion({marketplaceSlug:e.marketplaceSlug,pluginId:e.pluginId,version:n})}async markCacheComplete(e){const t=this.getCacheDir(e);await(0,fo.writeFile)(Xh({parent:t,name:Jh}),"")}}class ep extends Error{constructor(e,t){super(`Invalid Claude Code plugin identifier "${t}": ${e}`),this.raw=t,this.name="CCPluginIdentifierError"}}function tp(e){const t=e.trim();if(!t)throw new ep("Empty identifier",e);const r=/^[a-zA-Z0-9_-]+$/,n=t.indexOf("@");if(n!==t.lastIndexOf("@"))throw new ep("Plugin identifier cannot contain multiple @ symbols",e);if(-1===n){if(!r.test(t))throw new ep("Plugin name must contain only alphanumeric characters, dashes, and underscores",e);if(t.length>100)throw new ep("Plugin name must be 100 characters or less",e);return{name:t,sourceType:"marketplace",marketplace:"claude-plugins-official",raw:e}}const o=t.slice(0,n).trim(),s=t.slice(n+1).trim();if(!o)throw new ep("Missing plugin name before @",e);if(!s)throw new ep("Missing source after @",e);if(!r.test(o))throw new ep("Plugin name must contain only alphanumeric characters, dashes, and underscores",e);if(o.length>100)throw new ep("Plugin name must be 100 characters or less",e);if(s.startsWith("github:")){const t=s.slice(7).trim();if(!t||!/^[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+$/.test(t))throw new ep("Invalid GitHub repo format, expected 'org/repo' (e.g., 'anthropics/claude-plugins')",e);return{name:o,sourceType:"github",githubRepo:t,raw:e}}if(s.startsWith("local:")){const t=s.slice(6).trim();if(!t)throw new ep("Missing path after 'local:'",e);return{name:o,sourceType:"local",localPath:t,raw:e}}if(s.startsWith("url:")){const t=s.slice(4).trim();if(!t)throw new ep("Missing Git URL after 'url:'",e);try{new URL(t)}catch{throw new ep("Invalid Git URL format",e)}return{name:o,sourceType:"url",gitUrl:t,raw:e}}const i=s.indexOf("#");let a,c;if(-1!==i?(a=s.slice(0,i).trim(),c=s.slice(i+1).trim()):a=s,!a)throw new ep("Missing marketplace name",e);if(!r.test(a))throw new ep("Marketplace name must contain only alphanumeric characters, dashes, and underscores",e);return{name:o,sourceType:"marketplace",marketplace:a,version:c,raw:e}}function rp(e){if("claude-plugin"===e.source)return e.sourceInfo.raw;if("user-local"===e.source)return`user-local:${e.sourceInfo.name}`;if("extension"===e.source){const t=e.sourceInfo;return`extension:${t.extensionId}:${t.localPath}`}const t=e.sourceInfo;return`${t.name}-${t.version}`}function np(e){return e.sourceInfo.name}function op(e){switch(e.source){case"claude-plugin":case"cursor-first-party":case"cursor-third-party":return e.sourceInfo.marketplace;default:return}}function sp(e){switch(e.source){case"cursor-first-party":case"cursor-third-party":return e.sourceInfo.pluginDbId;default:return}}function ip(e){switch(e.source){case"cursor-first-party":case"cursor-third-party":return e.sourceInfo.marketplaceDbId;default:return}}function ap(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function cp(e){return!!ap(e)&&(void 0===e.enabledPlugins||ap(e.enabledPlugins))}function lp(e){return JSON.parse(e)}function up(e){const t=e??process.env.HOME??"";return(0,s.join)(t,".claude")}async function dp(e){const t={enabledPlugins:{}};let r=!1;const n=(0,s.join)(e,".claude","settings.json");try{const e=lp(await(0,fo.readFile)(n,"utf-8"));cp(e)&&e.enabledPlugins&&(Object.assign(t.enabledPlugins,e.enabledPlugins),r=!0)}catch{}const o=(0,s.join)(e,".claude","settings.local.json");try{const e=lp(await(0,fo.readFile)(o,"utf-8"));cp(e)&&e.enabledPlugins&&(Object.assign(t.enabledPlugins,e.enabledPlugins),r=!0)}catch{}return r?t:null}function hp(e,t){const r=(0,s.resolve)(e),n=(0,s.resolve)(e,t),o=(0,s.relative)(r,n);if(o.startsWith("..")||(0,s.isAbsolute)(o))throw new Error(`Invalid subPath: path traversal not allowed (${JSON.stringify(t)})`);return n}async function pp(e){try{return(await(0,fo.lstat)(e)).isSymbolicLink()}catch{return!1}}async function fp(e){if(await pp(e))throw new Error(`Refusing to read symlink: ${e}`);return(0,fo.readFile)(e,"utf-8")}async function mp(e){if((await(0,fo.stat)(e)).size>10485760)throw new Error(`File ${e} exceeds maximum size of 10485760 bytes`)}function gp(e){const t=e instanceof Error?e.message:String(e);return/timed?\s*out/i.test(t)?"timeout":/clone|fetch|git/i.test(t)?"clone":/manifest|marketplace\.json/i.test(t)?"manifest":/parse|invalid|malformed/i.test(t)?"parse":/install|download|copy/i.test(t)?"install":"unknown"}async function wp({installPath:e,logo:t}){const r=t?.trim();if(r&&!(0,s.isAbsolute)(r)&&!r.includes("://"))try{const t=await(0,fo.realpath)(e),n=hp(t,r),o=await(0,fo.realpath)(n);if(hp(t,o),!(await(0,fo.stat)(o)).isFile())return;return await mp(o),(0,Fu.pathToFileURL)(o).href}catch{return}}function yp(e){const t={};return void 0!==e.version&&(t.version=e.version),void 0!==e.homepage&&(t.homepage=e.homepage),void 0!==e.repository&&(t.repository=e.repository),t}function vp(e){return void 0!==e.version||void 0!==e.homepage||void 0!==e.repository}function bp(e,t){return yp({version:e.version??t?.version,homepage:e.homepage??t?.homepage,repository:e.repository??t?.repository})}async function Sp(e,t,r){let n;for(const o of xd){const i=(0,s.join)(e,o);let a;try{if(await pp(i))continue;if(!(await(0,fo.stat)(i)).isFile())continue;await mp(i),a=await fp(i)}catch{continue}const c=oh(a);if(!c.success)continue;const l=c.data,u=l.commands,d=l.agents,h=l.skills,p=l.rules,f=l.hooks,m=l.mcpServers,g=void 0!==u||void 0!==d||void 0!==h||void 0!==p||void 0!==f||void 0!==m,w="string"==typeof l.displayName?l.displayName:void 0,y="string"==typeof l.description?l.description:void 0,v=l.author?.name,b=await wp({installPath:e,logo:l.logo}),S=yp(l),k=l.variables,_=l.capabilities,C=void 0!==w||void 0!==y||void 0!==v||void 0!==b||void 0!==k||void 0!==_;if(!g&&!C&&!vp(S))continue;if(!g&&!C){n=n?{...n,fields:bp(n.fields,S)}:{fields:S,path:i,relPath:o,unrecognizedSchemaId:c.unrecognizedSchemaId};continue}void 0!==c.unrecognizedSchemaId&&r.log("debug",`${t}: ${o} declares an unrecognized $schema, loading anyway: ${c.unrecognizedSchemaId}`);const E=bp(S,n?.fields);return{manifestFilePath:i,...g&&{manifestOptions:{commands:u,agents:d,skills:h,rules:p,hooks:f,mcpServers:m}},...(C||vp(E))&&{metadata:{displayName:w,description:y,authorName:v,logoUrl:b,...E,variables:k,capabilities:_}}}}if(void 0!==n)return void 0!==n.unrecognizedSchemaId&&r.log("debug",`${t}: ${n.relPath} declares an unrecognized $schema, loading anyway: ${n.unrecognizedSchemaId}`),{manifestFilePath:n.path,metadata:n.fields}}async function kp(e,t){const r=function(e,t){const r=new Map,n=(0,s.resolve)(e),o=(0,s.resolve)(t?.symlinkTargetRoot??n),i=(0,fo.realpath)(o).catch((()=>o));function a(e){const t=(0,s.resolve)(e);try{return hp(n,t)}catch{throw new Error(`Path escapes plugin directory: ${e}`)}}async function c(e){const t=a(e),r=await i,n=await(0,fo.realpath)(t);try{return hp(r,n)}catch{throw new Error(`Path escapes plugin directory via symlink: ${e}`)}}return{async listDirectory(t,r){const n=a(t?(0,s.join)(e,t):e);try{const e=await c(n);if(r?.has(e))return[];r?.add(e);const o=await(0,fo.readdir)(e,{withFileTypes:!0}),i=[];for(const e of o){const r=(0,s.join)(n,e.name);let o=e.isDirectory()?"dir":"file";if(e.isSymbolicLink())try{const e=await c(r);o=(await(0,fo.stat)(e)).isDirectory()?"dir":"file"}catch{continue}i.push({name:e.name,type:o,path:t?`${t}/${e.name}`:e.name})}return i}catch{return[]}},async fetchFile(t){const n=r.get(t);if(void 0!==n)return{content:n};const o=a((0,s.join)(e,t)),i=await c(o);await mp(i);const l=await(0,fo.readFile)(i,"utf-8");return r.set(t,l),{content:l}},async fileExists(t){try{const r=a((0,s.join)(e,t)),n=await c(r);return(await(0,fo.stat)(n)).isFile()}catch{return!1}}}}(e),n=new Wh(r),o=await n.discoverComponents({manifest:t}),[i,a,c,l]=await Promise.all([_p(r,o.skills,e),Ep(r,o.agents,e),xp(r,o.commands,e),Cp(r,o.rules,e)]);return{skills:i,agents:a,commands:c,rules:l}}async function _p(e,t,r){const n=[];for(const o of t)try{const{content:t}=await e.fetchFile(o.path),s=Ip({content:hh(t,r),relativePath:o.path});s&&n.push(s)}catch{}return n}async function Cp(e,t,r){const n=[];for(const o of t)try{const{content:t}=await e.fetchFile(o.path),s=Ip({content:hh(t,r),relativePath:o.path});s&&n.push({...s,name:o.name})}catch{}return n}async function Ep(e,t,r){const n=[];for(const o of t)try{const{content:t}=await e.fetchFile(o.path),s=Rp({content:hh(t,r),relativePath:o.path});s&&n.push(s)}catch{}return n}async function xp(e,t,r){const n=[];for(const o of t)try{const{content:t}=await e.fetchFile(o.path),s=Tp({content:hh(t,r),relativePath:o.path});s&&n.push(s)}catch{}return n}function Pp(e){if("string"==typeof e){const t=function(e){const t=[];let r=0,n=0;for(let o=0;o<e.length;o++){const s=e[o];if("{"===s)n++;else if("}"===s&&n>0)n--;else if(","===s&&0===n){const n=e.slice(r,o).trim();n&&t.push(n),r=o+1}}if(n>0){for(const n of e.slice(r).split(",")){const e=n.trim();e&&t.push(e)}return t}const o=e.slice(r).trim();return o&&t.push(o),t}(e);return t.length>0?t:void 0}if(Array.isArray(e)){const t=e.filter((e=>"string"==typeof e)).map((e=>e.trim())).filter(Boolean);return t.length>0?t:void 0}}function Ip({content:e,relativePath:t}){try{const r=dd(e),n=t.replace(/\\/g,"/"),o=n.split("/").filter((e=>e.length>0)),s=o.length>=2?o[o.length-2]:void 0,i=o[o.length-1]??n,a=s??i.replace(/\.md$/i,""),c="string"==typeof r.data.name?r.data.name.trim():void 0,l=jh(r.data.environments??r.data.metadata?.environments),u=jh(r.data["disabled-environments"]??r.data.metadata?.disabledEnvironments);return{path:t,name:c&&c.length>0?c:a,description:"string"==typeof r.data.description?r.data.description:void 0,globs:Pp(r.data.globs),alwaysApply:!0===r.data.alwaysApply,content:e,environments:l,disabledEnvironments:u}}catch{return null}}function Rp({content:e,relativePath:t}){try{const n=dd(e),o=n.content.trim();if(!o)return null;let i;"string"==typeof n.data.tools?i=n.data.tools.split(",").map((e=>e.trim())).filter(Boolean):Array.isArray(n.data.tools)&&(i=n.data.tools.map((e=>"string"==typeof e?e.trim():String(e))).filter(Boolean));const a=n.data.permissionMode??n.data.permissionmode,c=(0,s.basename)(t);return{path:t,name:"string"==typeof n.data.name?n.data.name:(0,s.basename)(c,(0,s.extname)(c)).replace(/[\s_]+/g,"-"),description:"string"==typeof n.data.description?n.data.description:void 0,tools:i,model:"string"==typeof n.data.model?n.data.model:"inherit",prompt:o,permissionMode:(r=a,"readonly"===(r??"").trim().toLowerCase()?"readonly":"default")}}catch{return null}var r}function Tp({content:e,relativePath:t}){try{const r=dd(e);let n;const o=r.data["argument-hint"];"string"==typeof o?n=o:Array.isArray(o)&&(n=`[${o.join(" ")}]`);const i=(0,s.basename)(t);return{path:t,name:"string"==typeof r.data.name?r.data.name:(0,s.basename)(i,(0,s.extname)(i)),description:"string"==typeof r.data.description?r.data.description:void 0,argumentHint:n,content:r.content.trim()}}catch{return null}}function Ap(e){if(void 0!==e)return{configuredVariables:e.configuredVariables}}async function $p(e,t,r){const n=r??Ap(t);return async function(e,t={}){const r=t.toSourcePath??(e=>e);let n,o,s;for(const t of xd){const i=await e(t);if(null===i)continue;let a;try{a=JSON.parse(i)}catch{continue}s=Sd(a);const c=oh(i);if(c.success){void 0!==c.data.mcpServers&&(n=c.data.mcpServers,o=r(t));break}}return Ch(e,n,o,void 0===s?t:{...t,parserOptions:{...t.parserOptions,pluginSchemaId:s}})}(function(e){return async t=>{if(!ih(t))return null;const r=(0,s.join)(e,t);try{return await pp(r)?null:(await(0,fo.stat)(r)).isFile()?(await mp(r),await fp(r)):null}catch{return null}}}(e),{fallbackFileNames:bh(),manifestPrecedence:"override",toSourcePath:t=>(0,s.join)(e,t),installPathForExpansion:e,parserOptions:n})}async function Mp(e,t,r){const n=await $p(e,void 0,{log:r});if(n)return n;for(const n of Id){const o=(0,s.join)(e,n);try{if(!(await(0,fo.stat)(o)).isFile())continue;const n=await(0,fo.readFile)(o,"utf-8"),i=JSON.parse(n);if(!Fp(i)||!Array.isArray(i.plugins))continue;const a=i.plugins.filter(Np),c=t.name,l=a.find((e=>e.name===c));if(!l?.mcpServers?.length)continue;for(const t of l.mcpServers){const n=t.replace(/^\.\//,"");if(!ih(n))continue;const o=(0,s.join)(e,n);try{await mp(o);const t=kh(await fp(o),e,{log:r});if(t?.mcpServers&&Object.keys(t.mcpServers).length>0){const e=Object.fromEntries(Object.keys(t.mcpServers).map((e=>[e,o])));return{...t,mcpServerSourcePaths:e}}}catch{}}return null}catch{}}return null}Error;const Dp=new Set(Object.values(Nu));function Op(e){return Dp.has(e)}function Fp(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Np(e){return!(!Fp(e)||"string"!=typeof e.name)&&(void 0===e.mcpServers||Array.isArray(e.mcpServers)&&e.mcpServers.every((e=>"string"==typeof e)))}function Lp(e,t){const r={};for(const[n,o]of Object.entries(e.hooks))Array.isArray(o)&&Op(n)&&(r[n]=o.map((e=>"command"in e&&"string"==typeof e.command?{...e,command:hh(e.command,t)}:"prompt"in e&&"string"==typeof e.prompt?{...e,prompt:hh(e.prompt,t)}:e)));return{...e,hooks:r}}async function jp(e,t,r,n,o){if("object"==typeof n){const s=Up(n,t,r);return s&&"config"in s?{config:Lp(s.config,e),...void 0!==o&&{sourcePath:o}}:s}let i,a,c;if("string"==typeof n){const t=n.replace(/^\.\//,"");if(!ih(t))return;i=t.endsWith(".json")?(0,s.join)(e,t):(0,s.join)(e,t,"hooks.json")}else i=(0,s.join)(e,"hooks","hooks.json");try{if(await pp(i))return;if(!(await(0,fo.stat)(i)).isFile())return}catch{return}try{await mp(i),a=await(0,fo.readFile)(i,"utf-8")}catch{return}try{c=JSON.parse(a)}catch{return{error:{source:"claude-plugin",message:`Plugin ${t} ${i}: invalid JSON`}}}const l=Up(c,t,r);return l&&"config"in l?{config:Lp(l.config,e),sourcePath:i}:l}function Up(e,t,r){const n=function(e){if(!Uu(e))return"unknown";const t=e,r="object"==typeof t.hooks&&null!==t.hooks?t.hooks:null;if(!r)return"unknown";for(const e of Object.values(r)){if(!Array.isArray(e)||0===e.length)continue;const t=e[0];if(Uu(t)){if("hooks"in t&&Array.isArray(t.hooks))return"claude-code";if("command"in t||"prompt"in t||"type"in t)return"cursor"}}return"unknown"}(e);if("cursor"===n){const r=zu(e);return r.isValid&&zu(e).isValid?{config:e}:{error:{source:"claude-plugin",message:`Plugin ${t} hooks: ${r.errors.join("; ")}`}}}if("claude-code"===n){if(!(Fp(o=e)&&Fp(o.hooks)&&Object.keys(o.hooks).length>0))return;const n=cd(e.hooks,{warn:e=>r.log("warn",`Plugin ${t} hooks: ${e}`),info:e=>r.log("info",`Plugin ${t} hooks: ${e}`)}),s=zu(n);return s.isValid?{config:n}:{error:{source:"claude-plugin",message:`Plugin ${t} hooks: ${s.errors.join("; ")}`}}}var o}async function Bp(e,t,r,n){const o=n?.log??ph,s=await Sp(e,t,o),i={...Ap(r)??(n?.configuredVariables?{configuredVariables:n.configuredVariables}:void 0),log:o},[a,c,l]=await Promise.all([kp(e,s?.manifestOptions),$p(e,r,i),jp(e,t,o,s?.manifestOptions?.hooks,s?.manifestFilePath)]);return{...a,...void 0!==s?.metadata?.displayName&&{displayName:s.metadata.displayName},...void 0!==s?.metadata?.description&&{description:s.metadata.description},...void 0!==s?.metadata?.authorName&&{authorName:s.metadata.authorName},...void 0!==s?.metadata?.logoUrl&&{logoUrl:s.metadata.logoUrl},...void 0!==s?.metadata?.version&&{version:s.metadata.version},...void 0!==s?.metadata?.homepage&&{homepage:s.metadata.homepage},...void 0!==s?.metadata?.repository&&{repository:s.metadata.repository},variablesSchema:s?.metadata?.variables,mcpConfig:c,capabilities:s?.metadata?.capabilities??[],hooks:l}}async function Wp(e,t,r){const n=r?.log??ph,o=await Sp(e,t.raw,n),[s,i,a]=await Promise.all([kp(e,o?.manifestOptions),Mp(e,t,n),jp(e,t.raw,n,o?.manifestOptions?.hooks,o?.manifestFilePath)]);return{identifier:{source:"claude-plugin",sourceInfo:t},installPath:e,...void 0!==o?.metadata?.displayName&&{displayName:o.metadata.displayName},...void 0!==o?.metadata?.description&&{description:o.metadata.description},...void 0!==o?.metadata?.authorName&&{authorName:o.metadata.authorName},...void 0!==o?.metadata?.logoUrl&&{logoUrl:o.metadata.logoUrl},...void 0!==o?.metadata?.version&&{version:o.metadata.version},...void 0!==o?.metadata?.homepage&&{homepage:o.metadata.homepage},...void 0!==o?.metadata?.repository&&{repository:o.metadata.repository},...s,mcpConfig:i??void 0,capabilities:o?.metadata?.capabilities??[],hooks:a}}async function Hp(e,t,r,n){const o=`${r.name}@${r.version}`,{displayName:s,description:i,authorName:a,logoUrl:c,version:l,homepage:u,repository:d,variablesSchema:h,skills:p,rules:f,agents:m,commands:g,mcpConfig:w,capabilities:y,hooks:v}=await Bp(e,o,r,{log:n?.log});return{identifier:{source:t,sourceInfo:r},installPath:e,...void 0!==s&&{displayName:s},...void 0!==i&&{description:i},...void 0!==a&&{authorName:a},...void 0!==c&&{logoUrl:c},...void 0!==l&&{version:l},...void 0!==u&&{homepage:u},...void 0!==d&&{repository:d},variablesSchema:h,skills:p,rules:f,agents:m,commands:g,mcpConfig:w??void 0,capabilities:y,hooks:v}}async function qp(e,t,r={}){const n=r.log??ph,o=performance.now(),i=await async function(e){const t=up(e),r=(0,s.join)(t,"plugins","installed_plugins.json");try{const e=lp(await(0,fo.readFile)(r,"utf-8"));return ap(n=e)&&ap(n.plugins)?e:null}catch{return null}var n}(r.userHomeDir);if(!i?.plugins)return n.log("info",`loadAllEnabledPlugins: no installed plugins metadata found (${(performance.now()-o).toFixed(1)}ms)`),[];const a=await async function(e){const t=up(e),r=(0,s.join)(t,"settings.json");try{const e=lp(await(0,fo.readFile)(r,"utf-8"));return cp(e)?e:null}catch{return null}}(r.userHomeDir),c=function(e){if(void 0===e)return[];const t="string"==typeof e?[e]:e,r=new Set,n=[];for(const e of t){if(!e)continue;const t=(0,s.resolve)(e);r.has(t)||(r.add(t),n.push(t))}return n}(e),l=function(e,t,r){if(0===r.length)return md(e,t,null,void 0);const n=new Set;for(const{settings:e}of r)for(const[t,r]of Object.entries(e?.enabledPlugins??{}))!1===r&&n.add(t);const o=new Set,s=[];for(const{workspacePath:i,settings:a}of r){const r=md(e,t,a,i);for(const e of r)o.has(e.pluginId)||n.has(e.pluginId)||(o.add(e.pluginId),s.push(e))}return s}(i,a,await(0,Dr.PH)(c,(async e=>({workspacePath:e,settings:await dp(e)})),{max:8})),u=[],d=r.onError;for(const{pluginId:e,installPath:t}of l)try{const r=performance.now(),o=tp(e),s=await Wp(t,o,{log:n});u.push(s),n.log("info",`loadClaudePlugin ${e} loaded in ${(performance.now()-r).toFixed(1)}ms`)}catch(t){const r=t instanceof Error?t:new Error(String(t));if(d)try{d(tp(e),r)}catch{d({name:e.split("@")[0]??e,sourceType:"marketplace",marketplace:"unknown",raw:e},r)}}return n.log("info",`loadAllEnabledPlugins completed in ${(performance.now()-o).toFixed(1)}ms (${l.length} resolved, ${u.length} loaded)`),u}async function zp(e){const t=e.log??ph,r=performance.now(),{client:n,userId:o,teamId:s,onCursorError:i,pruneOldVersions:a,pluginFilter:c,onPluginsListed:l}=e,u=[],d=e.cacheManager??new Yh(e.userHomeDir),h=performance.now();let p;try{p=await n.listEnabledPlugins(o,s)}catch(e){return t.captureException(e,{error_type:"list_enabled_plugins"}),t.increment("marketplace.source_unavailable",1),t.log("error",`marketplace listEnabledPlugins failed after ${(performance.now()-h).toFixed(1)}ms; treating source as unavailable: ${e instanceof Error?e.message:String(e)}`),{plugins:[],failures:[],sourceUnavailable:!0}}t.log("info",`marketplace listEnabledPlugins completed in ${(performance.now()-h).toFixed(1)}ms (${p.plugins.length} plugins)`),l&&await l(p.plugins);const f=[];if(p.listFailures){u.push(...p.listFailures);for(const e of p.listFailures)f.push({identifier:{source:e.marketplaceName&&"cursor-public"!==e.marketplaceName?"cursor-third-party":"cursor-first-party",sourceInfo:{name:e.pluginName,version:"",...void 0!==e.pluginDbId&&{pluginDbId:e.pluginDbId},marketplace:e.marketplaceName}},installPath:"",loadError:e.errorMessage,skills:[],rules:[],agents:[],commands:[],capabilities:[]})}const m=new Map;for(const e of p.plugins)if(!c||c(e))try{const r=e.marketplace?.name;if(!r){const t=new Error(`Plugin ${e.name} has no marketplace metadata — cannot determine cache path`);u.push({pluginName:e.name,pluginId:e.pluginId,marketplaceName:void 0,errorMessage:t.message,errorType:"manifest"}),i&&i(e,t);continue}const o=`${r}/${e.pluginId}`;let s,a=m.get(o);if(a||(a={slug:r,pluginId:e.pluginId,versions:[]},m.set(o,a)),a.versions.push(e.version),await d.isCached({marketplaceSlug:r,pluginId:e.pluginId,version:e.version}))s=d.getCacheDir({marketplaceSlug:r,pluginId:e.pluginId,version:e.version}),t.log("info",`loadFromMarketplaceSource: Found cached plugin: ${e.pluginId} at ${s}`,{marketplaceSlug:r,pluginId:e.pluginId,gitRef:e.version,marketplaceId:e.marketplace?.id});else{const o=d.getCacheDir({marketplaceSlug:r,pluginId:e.pluginId,version:e.version});t.log("info",`loadFromMarketplaceSource: Plugin missing from cache, installing: ${e.pluginId} at ${o}`,{marketplaceSlug:r,pluginId:e.pluginId,gitRef:e.version,marketplaceId:e.marketplace?.id}),await(0,fo.mkdir)(o,{recursive:!0});try{await n.installPlugin(e,o),await d.markCacheComplete({marketplaceSlug:r,pluginId:e.pluginId,version:e.version})}catch(e){try{await(0,fo.rm)(o,{recursive:!0,force:!0})}catch{}throw e}s=o}const c=e.marketplace?.name,l=void 0!==c&&"cursor-public"!==c&&c.length>0?"cursor-third-party":"cursor-first-party",h={name:e.name,version:e.version,pluginDbId:e.pluginDbId,configuredVariables:e.configuredVariables,marketplace:c,marketplaceDbId:e.marketplaceDbId,isTeamRequired:e.isTeamRequired},p=await Hp(s,l,h,{log:t});f.push(p);try{await d.pruneOldVersions({marketplaceSlug:r,pluginId:e.pluginId,keepVersions:[e.version]})}catch{}}catch(r){t.captureException(r,{error_type:"load_plugin_from_marketplace"});const n=r instanceof Error?r:new Error(String(r));u.push({pluginName:e.name,pluginId:e.pluginId,marketplaceName:e.marketplace?.name,errorMessage:n.message,errorType:gp(n)});const o=e.marketplace?.name,s=void 0!==o&&"cursor-public"!==o&&o.length>0;f.push({identifier:{source:s?"cursor-third-party":"cursor-first-party",sourceInfo:{name:e.name,version:e.version,pluginDbId:e.pluginDbId,marketplace:o,marketplaceDbId:e.marketplaceDbId,isTeamRequired:e.isTeamRequired}},installPath:"",loadError:n.message||"Plugin load failed",skills:[],rules:[],agents:[],commands:[],capabilities:[]}),i&&i(e,n)}if(a)for(const{slug:e,pluginId:t,versions:r}of m.values())try{await d.pruneOldVersions({marketplaceSlug:e,pluginId:t,keepVersions:r})}catch{}return t.log("info",`loadFromMarketplaceSource completed in ${(performance.now()-r).toFixed(1)}ms (${f.length} plugins loaded, ${u.length} failures)`),{plugins:f,failures:u,sourceUnavailable:!1}}function Gp(e){const{identifier:t}=e;switch(t.source){case"claude-plugin":return"marketplace"===t.sourceInfo.sourceType&&t.sourceInfo.marketplace?`${t.sourceInfo.marketplace}/${t.sourceInfo.name}`:void 0;case"cursor-first-party":case"cursor-third-party":return t.sourceInfo.marketplace?`${t.sourceInfo.marketplace}/${t.sourceInfo.name}`:void 0;default:return}}function Vp(e){return Gp(e)??`path:${e.installPath}`}function Kp(e,t={}){return{...e,model:t.stripModel?void 0:e.model,tools:t.stripTools?void 0:e.tools}}function Jp(e,t){const r=[];for(const o of e){const e=rp(o.identifier),i=`plugin:${e}`,a=np(o.identifier),c=op(o.identifier),l=sp(o.identifier),u=ip(o.identifier);for(const d of t(o)){const t=(0,s.join)(o.installPath,d.path),{type:h,globs:p,description:f}=(n=d).alwaysApply?{type:"global"}:n.globs&&n.globs.length>0?{type:"fileGlobbed",globs:n.globs}:n.description?{type:"agentFetched",description:n.description}:{type:"manuallyAttached"};r.push({fullPath:t,content:d.content,type:h,globs:p,description:f,pluginIdentifier:e,gitRemoteOrigin:i,plugin:a,marketplace:c,pluginId:l,marketplaceId:u,environments:d.environments,disabledEnvironments:d.disabledEnvironments})}}var n;return r}var Zp=r("../proto/dist/generated/agent/v1/agent_skills_pb.js");const Xp=(0,Fs.debuglog)("agent-skills-catalog-cache");function Qp(e){return(0,lo.createHash)("sha256").update(JSON.stringify({v:1,...e})).digest("hex")}async function Yp(e){try{return(await(0,fo.stat)(e)).mtimeMs}catch{return}}function ef(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}const tf=[".kits","cursor-pages"],rf={configDir:".cursor",subdir:"skills-cursor",thirdParty:!1,builtin:!0},nf=[{configDir:".cursor",subdir:"skills",thirdParty:!1,builtin:!1},{configDir:".claude",subdir:"skills",thirdParty:!0,builtin:!1},{configDir:".codex",subdir:"skills",thirdParty:!0,builtin:!1},{configDir:".grok",subdir:"skills",thirdParty:!0,builtin:!1},{configDir:".agents",subdir:"skills",thirdParty:!1,builtin:!1},rf],of=(new Set(nf.map((e=>e.configDir))),new Set(["imagegen","openai-docs","opneai-docs","plugin-creator","skill-creator","skill-installer"]));function sf(e){return e.replace(/\\/g,"/").split("/").filter(Boolean)}function af(e){const t=sf(e);if(function(e){const t=e.findIndex(((t,r)=>function(e,t){return nf.some((r=>r.configDir===e&&r.subdir===t))}(t,e[r+1])));return-1!==t&&e.slice(t+2).some((e=>e.startsWith(".")))}(t))return!0;const r=t.lastIndexOf(".codex");if(-1===r||"skills"!==t[r+1])return!1;const n=t.at(-1),o="SKILL.md"===n?t.at(-2):n;return void 0!==o&&of.has(o)}function cf(e){return{dirPath:(0,s.join)(e,rf.configDir,rf.subdir),scope:"builtin",source:"builtin"}}const lf="canvas";function uf(e,t){return{dirPath:(0,s.join)(cf(e).dirPath,...tf),scope:"builtin",source:"builtin"}}function df(e,t){const r=e.replace(/\\/g,"/"),n=t.replace(/\\/g,"/").replace(/\/+$/,"");if(r.startsWith(`${n}/`))return sf(r.slice(n.length+1))}function hf(e,t){const r=df(e,t);return void 0!==r&&!r.some((e=>e.startsWith(".")))}function pf(e){return nf.filter((t=>!t.builtin&&(e||!t.thirdParty)))}function ff(e,t){return pf(t).map((t=>({dirPath:(0,s.join)(e,t.configDir,t.subdir),scope:"project",source:"workspace"})))}function mf(e,t){return pf(t).map((t=>({dirPath:(0,s.join)(e,t.configDir,t.subdir),scope:"user",source:"user"})))}var gf=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function wf(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}const yf=nf.map((({configDir:e,subdir:t,thirdParty:r})=>({pattern:new RegExp(`[/\\\\]${wf(e)}[/\\\\]${wf(t)}[/\\\\]`,"i"),requiresThirdParty:r}))),vf=/[/\\]\.cursor[/\\]rules[/\\]/i,bf=[{pattern:/[/\\]\.cursor[/\\]agents[/\\]/i,requiresThirdParty:!1},{pattern:/[/\\]\.claude[/\\]agents[/\\]/i,requiresThirdParty:!0}],Sf=new Set(["AGENTS.md","CLAUDE.md","CLAUDE.local.md"]);function kf(e,t){const r=e.replace(/\\/g,"/"),n=(0,s.basename)(r);if(Sf.has(n))return"AGENTS.md"===n||t&&("CLAUDE.md"===n||"CLAUDE.local.md"===n)?"markdown":void 0;if(vf.test(r)&&n.endsWith(".mdc"))return"rules";if("SKILL.md"===n)for(const{pattern:e,requiresThirdParty:n}of yf)if(e.test(r)){if(n&&!t)continue;return"skills"}if(n.endsWith(".md"))for(const{pattern:e,requiresThirdParty:n}of bf)if(e.test(r)){if(n&&!t)continue;return"agents"}}class _f{constructor(e,t,r,n){this.root=e,this.gitExecutor=t,this.userHomeDirectory=r,this.getThirdPartyExtensibilityEnabled=n}static getRipwalkCache(){return _f.ripwalkCache??=new ha,_f.ripwalkCache}async discover(e){const t={stack:[],error:void 0,hasError:!1};try{const r=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(t,(0,$.VI)(e.withName("NestedExtensibilityService.discover")),!1),n={rules:[],skills:[],markdown:[],agents:[]},o=(0,s.resolve)(this.root),i=(0,s.resolve)(this.userHomeDirectory);if(o===i||Ds(o,{platform:process.platform,homeDirectory:i}).length>0)return r.span.setAttribute("nested_extensibility.rules",0),r.span.setAttribute("nested_extensibility.skills",0),r.span.setAttribute("nested_extensibility.markdown",0),r.span.setAttribute("nested_extensibility.agents",0),n;if(!await _a(e,this.gitExecutor,(0,s.resolve)(this.root)))return r.span.setAttribute("nested_extensibility.rules",0),r.span.setAttribute("nested_extensibility.skills",0),r.span.setAttribute("nested_extensibility.markdown",0),r.span.setAttribute("nested_extensibility.agents",0),n;const a=this.getThirdPartyExtensibilityEnabled(),c=this.buildIncludeGlobs(a),l={root:this.root,includeGlobs:c,excludeGlobs:Ia,followSymlinks:!0,source:"nested_extensibility"},u={rules:[],skills:[],markdown:[],agents:[]},d=_f.getRipwalkCache();try{const e=d.walk(r.ctx,l);try{for await(const t of e.lines){const e=kf(t,a);e&&u[e].push((0,s.resolve)(this.root,t))}}finally{d.delete(l)}}catch{}return r.span.setAttribute("nested_extensibility.rules",u.rules.length),r.span.setAttribute("nested_extensibility.skills",u.skills.length),r.span.setAttribute("nested_extensibility.markdown",u.markdown.length),r.span.setAttribute("nested_extensibility.agents",u.agents.length),u}catch(e){t.error=e,t.hasError=!0}finally{gf(t)}}buildIncludeGlobs(e){const t=["*/**/.cursor/**","*/**/.agents/**","*/**/AGENTS.md"];return e&&t.push("*/**/.claude/**","*/**/.codex/**","*/**/.grok/**","*/**/CLAUDE.md","*/**/CLAUDE.local.md"),t}}const Cf=new Set(["node_modules","__pycache__","dist","build"]);async function Ef({rootDir:e,includeFile:t,maxDepth:r=10,containmentRootDir:n}){const o=[],i=[{dir:e,depth:0}],a=new Set,c=void 0!==n?await(0,fo.realpath)(n):null,l=e=>{if(null===c)return!0;const t=(0,s.relative)(c,e);return""===t||!t.startsWith("..")&&!(0,s.isAbsolute)(t)};for(;i.length>0;){const e=i.pop();if(void 0===e)continue;const{dir:n,depth:c}=e;if(c>r)continue;try{const e=await(0,fo.realpath)(n);if(!l(e))continue;if(a.has(e))continue;a.add(e)}catch{continue}const d=await(0,fo.readdir)(n,{withFileTypes:!0,encoding:"utf8"}).catch((()=>null));if(null!==d)for(const e of d){const r=(0,s.join)(n,e.name);let a=e.isDirectory(),l=e.isFile();if(e.isSymbolicLink())try{const e=await(0,fo.stat)(r);a=e.isDirectory(),l=e.isFile()}catch{continue}if(a){if((u=e.name).startsWith(".")||Cf.has(u))continue;i.push({dir:r,depth:c+1})}else l&&t(e.name)&&o.push(r)}}var u;return o.sort(((e,t)=>e.localeCompare(t))),o}const xf={agentStoreSkillsDirs:[],userHomeDirectory:""};function Pf(e){const t=e.replace(/\\/g,"/");return t.endsWith("/")?t.slice(0,-1):t}function If(e,t){const r=Pf(t.userHomeDirectory),n=e.replace(/\\/g,"/");if(r.length>0)for(const e of t.agentStoreSkillsDirs){const t=Pf(e);if(t.length>0&&n.startsWith(`${t}/`))return{key:`${r}::skills/${n.slice(t.length+1)}`,inAgentStore:!0}}return{key:Rf(e),inAgentStore:!1}}function Rf(e){const t=e.replace(/\\/g,"/"),r=t.toLowerCase(),n=r.indexOf("/.cursor/"),o=r.indexOf("/.claude/"),s=r.indexOf("/.codex/"),i=r.indexOf("/.grok/"),a=r.indexOf("/.agents/");return-1!==n?`${t.slice(0,n)}::${t.slice(n+9)}`:-1!==o?`${t.slice(0,o)}::${t.slice(o+9)}`:-1!==s?`${t.slice(0,s)}::${t.slice(s+8)}`:-1!==i?`${t.slice(0,i)}::${t.slice(i+7)}`:-1!==a?`${t.slice(0,a)}::${t.slice(a+9)}`:e}function Tf(e,t){const r=new Map,n=[];for(const o of e){const{key:e,inAgentStore:s}=If(o.fullPath,t),i=r.get(e);void 0!==i?s&&!n[i].inAgentStore&&(n[i]={item:o,inAgentStore:s}):(r.set(e,n.length),n.push({item:o,inAgentStore:s}))}return n.map((e=>e.item))}var Af=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},$f=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Mf=(0,l.h)("local-exec:cursor-rules");function Df(e){return"/"===e||"\\"===e}function Of(e){return e.split(/[\\/]+/).filter((e=>e.length>0)).length}async function Ff(e){return await Ef({rootDir:e,includeFile:e=>"SKILL.md"===e})}async function Nf(e){let t;try{t=await Ti(e)}catch(t){return{skillFilePath:e,error:Au(t)}}try{return{skillFilePath:e,content:t,parsed:dd(t)}}catch(t){return{skillFilePath:e,error:$u(t)}}}async function Lf(e){const t=await zo(e);return{...await Nf(e),realSkillFilePath:t}}function jf(e){return Wf(e.data?.environments??e.data?.metadata?.environments)??[]}function Uf(e){return Wf(e.data?.["disabled-environments"]??e.data?.metadata?.disabledEnvironments)??[]}function Bf(e){return Wf(e.data?.metadata?.scopedTo??e.data?.["metadata.scopedTo"])??[]}function Wf(e){if(Array.isArray(e)){const t=e.filter((e=>"string"==typeof e&&e.length>0));return 0===t.length?void 0:t}if("string"==typeof e){const t=e.split(",").map((e=>e.trim())).filter((e=>e.length>0));return 0===t.length?void 0:t}}function Hf(e,t,r){const n=function(e){const t=e.data?.metadata?.surfaces;return Array.isArray(t)?t:"string"==typeof t?t.split(",").map((e=>e.trim())).filter(Boolean):[]}(e);return n.length>0&&!n.includes(t)&&!r.includes(e.data?.name)}function qf(e){return No(e,1536)}function zf(e){return!0===e.data?.alwaysApply}function Gf(e){return!0===e.data?.["disable-model-invocation"]}function Vf({skillFilePath:e,content:t,parsed:r}){const n=function(e){return function(e){const t=(e.matter??"").trim(),r=e.language?.toLowerCase();return t.length>0&&"js"!==r&&"javascript"!==r?`---\n${t}\n---`:hd("",e.data??{}).trim()}(e)}(r),o=function({fullPath:e,name:t,description:r,body:n}){const o=[],s=function(e){const t=e.replace(/\\/g,"/").split("/"),r=t[t.length-1]??"";return"SKILL.md"===r&&t.length>=2?t[t.length-2]??"":r}(e);s.length>64&&o.push(`Name is ${Ou(s.length)} characters; the limit is 64. Rename the skill's folder.`),Du.test(s)||o.push('Name should be lowercase letters and numbers joined by single hyphens, like "pdf-helper". Rename the skill\'s folder.'),void 0!==t&&t!==s&&o.push(`Frontmatter name ${JSON.stringify(t)} doesn't match the folder name ${JSON.stringify(s)}, which is the name the skill goes by. Make them the same.`);const i=r?.trim().length??0;i>1024&&o.push(`Description is ${Ou(i)} characters; the limit is ${Ou(1024)}.`);const a=Math.round(n.length/4);return a>5e3&&o.push(`Body is about ${Ou(a)} tokens; the recommended limit is ${Ou(5e3)}. Move details into reference files that SKILL.md links to.`),o}({fullPath:e,name:"string"==typeof r.data?.name?r.data.name:void 0,description:"string"==typeof r.data?.description?r.data.description:void 0,body:r.content});if(zf(r))return new Gr.DX({fullPath:e,content:t,frontmatter:n,type:new Gr.f5({type:{case:"global",value:new Gr.i9}}),environments:jf(r),disabledEnvironments:Uf(r),scopedTo:Bf(r),warnings:o});const s="string"==typeof r.data?.description?qf(r.data.description):void 0,i=Mu(s,Gf(r));return i?new Gr.DX({fullPath:e,parseError:i,frontmatter:n,scopedTo:Bf(r),type:new Gr.f5({type:{case:"agentFetched",value:new Gr.Xo}})}):new Gr.DX({fullPath:e,content:t,frontmatter:n,type:new Gr.f5({type:{case:"agentFetched",value:new Gr.Xo({description:s})}}),environments:jf(r),disabledEnvironments:Uf(r),scopedTo:Bf(r),warnings:o})}function Kf({skillFilePath:e,content:t,parsed:r}){const n="string"==typeof r.data?.description?qf(r.data.description):"",o=Pp(r.data?.paths??r.data?.globs),s=Gf(r);return new Zp.N({fullPath:e,content:t,description:n,globs:o??[],parseError:Mu(n,s),environments:jf(r),disabledEnvironments:Uf(r),scopedTo:Bf(r),disableModelInvocation:s})}function Jf({rules:e,agentSkills:t,skillFilePath:r,errorMessage:n}){e.push(function({skillFilePath:e,errorMessage:t}){return new Gr.DX({fullPath:e,parseError:t,type:new Gr.f5({type:{case:"agentFetched",value:new Gr.Xo}})})}({skillFilePath:r,errorMessage:n})),t.push(function({skillFilePath:e,errorMessage:t}){return new Zp.N({fullPath:e,parseError:t})}({skillFilePath:r,errorMessage:n}))}function Zf(e,t,r,n){if("error"in t)return e.realSkillFilePathsByFullPath.set(t.skillFilePath,t.realSkillFilePath),void Jf({rules:e.rules,agentSkills:e.agentSkills,skillFilePath:t.skillFilePath,errorMessage:t.error});Hf(t.parsed,r,n)||(e.realSkillFilePathsByFullPath.set(t.skillFilePath,t.realSkillFilePath),e.rules.push(Vf(t)),zf(t.parsed)||e.agentSkills.push(Kf(t)))}const Xf=(0,Fs.debuglog)("cursor-rules-service");function Qf(){return{rules:[],agentSkills:[],realSkillFilePathsByFullPath:new Map}}function Yf(e){return t=>(Xf("%s: %O",e,t),Qf())}function em(e,t){return Qp({kind:"agent-store",surface:e,roots:[...t].sort()})}function tm(e,t){const r=t.replace(/\\/g,"/").replace(/\/+$/,"");return""!==r&&e.replace(/\\/g,"/").startsWith(`${r}/`)}function rm(e){let t;if(!0===e.frontmatter.alwaysApply)t={case:"global",value:new Gr.i9};else{const r=Pp(e.frontmatter.globs);t=r&&r.length>0?{case:"fileGlobbed",value:new Gr.uT({globs:r})}:"string"==typeof e.frontmatter.description&&e.frontmatter.description.trim().length>0?{case:"agentFetched",value:new Gr.Xo({description:qf(e.frontmatter.description)})}:{case:"manuallyAttached",value:new Gr._u}}const r=e.frontmatter["metadata.environments"],n=Array.isArray(r)?r:[],o=e.frontmatter["metadata.disabledEnvironments"],s=Array.isArray(o)?o:[],i=e.frontmatter["metadata.scopedTo"],a=Array.isArray(i)?i:[];return new Gr.DX({fullPath:e.path,content:e.body,type:new Gr.f5({type:t}),environments:n,disabledEnvironments:s,scopedTo:a,frontmatter:e.rawFrontmatter??""})}class nm{constructor(e,t){this.cursorRulesServices=e,this.getAgentStoreSkillsContext=t,this.onChangeCallbacks=new Set}async getAllCursorRules(e){const t={stack:[],error:void 0,hasError:!1};try{const r=Af(t,(0,$.VI)(e.withName("MergedCursorRulesService.getAllCursorRules")),!1),n=this.cursorRulesServices.map((e=>e.getAllCursorRules(r.ctx).catch((e=>((0,Fs.debuglog)("Failed to load cursor rules from service:",e),[])))));return Tf((await Promise.all(n)).flat(),this.getAgentStoreSkillsContext())}catch(e){t.error=e,t.hasError=!0}finally{$f(t)}}reload(e){for(const t of this.cursorRulesServices)t.reload(e)}scheduleDidChangeRules(){void 0===this.changeTimer&&(this.changeTimer=setTimeout((()=>{this.changeTimer=void 0;for(const e of Array.from(this.onChangeCallbacks))e()}),nm.CHANGE_COALESCE_MS))}ensureChangeListenersRegistered(){void 0===this.disposeChangeListeners&&(this.disposeChangeListeners=this.cursorRulesServices.map((e=>e.onDidChangeRules((()=>this.scheduleDidChangeRules())))))}disposeChangeListenersIfUnused(){if(!(this.onChangeCallbacks.size>0||void 0===this.disposeChangeListeners)){for(const e of this.disposeChangeListeners)e();this.disposeChangeListeners=void 0,void 0!==this.changeTimer&&(clearTimeout(this.changeTimer),this.changeTimer=void 0)}}onDidChangeRules(e){return this.onChangeCallbacks.add(e),this.ensureChangeListenersRegistered(),()=>{this.onChangeCallbacks.delete(e),this.disposeChangeListenersIfUnused()}}dispose(){if(void 0!==this.changeTimer&&(clearTimeout(this.changeTimer),this.changeTimer=void 0),this.onChangeCallbacks.clear(),void 0!==this.disposeChangeListeners){for(const e of this.disposeChangeListeners)e();this.disposeChangeListeners=void 0}for(const e of this.cursorRulesServices)e.dispose&&e.dispose()}}nm.CHANGE_COALESCE_MS=1e3;class om{constructor(e,t,r,n,i,a,c,l){this.gitExecutor=t,this.rootDirectory=r,this.loadNestedRules=n,this.getThirdPartyExtensibilityEnabled=i,this.loadTraceId=void 0,this.onChangeCallbacks=new Set,this.nestedExtensibilityService=new _f(r,t,(0,o.homedir)(),i),this.ignoreService=c??new za(t,void 0,[this.rootDirectory]);const u=performance.now();if(this._rules=this.load(e,l).then((t=>{try{Mf.info(e,"LocalCursorRulesService load completed",{durationMs:Math.round(performance.now()-u),ruleCount:t.length})}catch{}return t})).catch((e=>((0,Fs.debuglog)("Failed to load cursor rules:",e),[]))),a){const e=[".cursor/rules/**/*.mdc","AGENTS.md","CLAUDE.md","CLAUDE.local.md",".cursorrules",".cursorignore"];this.unsubscribeWatcher=a.subscribe(this.rootDirectory,e,(e=>{const t={stack:[],error:void 0,hasError:!1};try{const r=(0,y.q6)(),n=Af(t,(0,$.VI)(r.withName("LocalCursorRulesService.fileWatcher.subscribe")),!1);if(".cursorignore"===(0,s.basename)(e))return om.getRipwalkCache().clear(),void this.reload(n.ctx);this.reloadAtPath(n.ctx,e)}catch(e){t.error=e,t.hasError=!0}finally{$f(t)}}))}}reload(e){this._rules=this.load(e).catch((e=>((0,Fs.debuglog)("Failed to load cursor rules:",e),[])));for(const e of this.onChangeCallbacks)e()}static getRipwalkCache(){return om.ripwalkCache??=new ha,om.ripwalkCache}reloadAtPath(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Af(r,(0,$.VI)(e.withName("LocalCursorRulesService.reloadAtPath")),!1);if(Kr((0,s.basename)(t)))return void this.reload(n.ctx);const o=this._rules;this._rules=(async()=>{const e=(await o).filter((e=>e.fullPath!==t));const r=(await this.readRulesAtPath(n.ctx,t)).map((e=>this.toCursorRule(e)));return[...e,...r]})().catch((e=>((0,Fs.debuglog)("Failed to load cursor rules at path:",e),[])));for(const e of this.onChangeCallbacks)e()}catch(e){r.error=e,r.hasError=!0}finally{$f(r)}}isRuleMarkdownFile(e){return Kr(e)}async readRulesAtPath(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Af(r,(0,$.VI)(e.withName("LocalCursorRulesService.readRulesAtPath")),!1),o=(0,s.basename)(t);if(".cursorrules"===o){const e=(0,s.resolve)(this.rootDirectory),t=await _a(n.ctx,this.gitExecutor,e)||e,r=await this.loadCursorRulesRule(n.ctx,t);return r?[r]:[]}if(o.endsWith(".mdc"))return await sm(t);if(this.isRuleMarkdownFile(o))try{return await this.loadRulesFromMarkdownFile(n.ctx,(0,s.dirname)(t),o)}catch{}return[]}catch(e){r.error=e,r.hasError=!0}finally{$f(r)}}onDidChangeRules(e){return this.onChangeCallbacks.add(e),()=>{this.onChangeCallbacks.delete(e)}}dispose(){this.unsubscribeWatcher&&(this.unsubscribeWatcher(),this.unsubscribeWatcher=void 0)}async load(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Af(r,(0,$.VI)(e.withName("LocalCursorRulesService.load")),!1);this.loadTraceId=n.span.spanContext().traceId;const o=(0,s.resolve)(this.rootDirectory),i=await _a(n.ctx,this.gitExecutor,o)||o,a=this.loadCursorRulesRule(n.ctx,i).then((e=>e?[e]:[])),c=this.loadRulesFromDirAndAncestors(n.ctx,o);let l,u;if(this.loadNestedRules){const e=t??this.nestedExtensibilityService.discover(n.ctx);l=e.then((e=>this.parseNestedRuleFiles(n.ctx,e.rules))),u=e.then((e=>this.parseNestedMarkdownFiles(n.ctx,e.markdown)))}else l=[],u=[];const d=(await Promise.all([a,c,l,u])).flat(),h=new Map;for(const e of d)h.set(e.path,e);const p=[...h.values()];return(await async function(e){const t=e.filter((e=>Kr((0,s.basename)(e.fullPath))));if(t.length<=1)return[...e];const r=await(0,Dr.PH)(t,(e=>async function(e){try{const t=await(0,fo.stat)(e,{bigint:!0});if(0n!==t.ino)return`ino:${String(t.dev)}:${String(t.ino)}`}catch{}return await zo(e)}(e.fullPath)),{max:16}),n=t.map(((e,t)=>({item:e,identity:r[t],dir:(0,s.dirname)(e.fullPath),content:e.content.trim()}))).sort(((e,t)=>{const r=Of(e.dir)-Of(t.dir);if(0!==r)return r;const n="AGENTS.md"===(0,s.basename)(e.item.fullPath);return n===("AGENTS.md"===(0,s.basename)(t.item.fullPath))?0:n?-1:1})),o=[];for(const e of n)o.some((t=>{return((r=t.dir)===(n=e.dir)||!!n.startsWith(r)&&(Df(r.at(-1))||Df(n[r.length])))&&(t.identity===e.identity||t.content===e.content);var r,n}))||o.push(e);const i=new Set(o.map((e=>e.item)));return e.filter((e=>!Kr((0,s.basename)(e.fullPath))||i.has(e)))}(p.map((e=>({fullPath:e.path,content:e.body,rule:e}))))).map((e=>this.toCursorRule(e.rule)))}catch(e){r.error=e,r.hasError=!0}finally{$f(r)}}async loadCursorRulesRule(e,t){const r={stack:[],error:void 0,hasError:!1};try{Af(r,(0,$.VI)(e.withName("LocalCursorRulesService.loadCursorrules")),!1);try{const e=(0,s.join)(t,".cursorrules");if((await(0,fo.stat)(e)).isFile())return{filename:".cursorrules",path:e,frontmatter:{alwaysApply:!0},body:await Ti(e)}}catch{}return null}catch(e){r.error=e,r.hasError=!0}finally{$f(r)}}async getAllCursorRules(e){const t={stack:[],error:void 0,hasError:!1};try{return Af(t,(0,$.VI)(e.withName("LocalCursorRulesService.getAllCursorRules")),!1).span.setAttribute("cacheTraceId",this.loadTraceId??"undefined"),await this._rules}catch(e){t.error=e,t.hasError=!0}finally{$f(t)}}toCursorRule(e){return rm({path:e.path,body:e.body,frontmatter:e.frontmatter,rawFrontmatter:e.rawFrontmatter})}async loadRulesFromDirAndAncestors(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Af(r,(0,$.VI)(e.withName("LocalCursorRulesService.loadRulesFromDirAndAncestors")),!1),o=[];let i=t;const a=this.getThirdPartyExtensibilityEnabled();for(;;){const e=(0,s.join)(i,".cursor","rules"),t=i;o.push((async()=>await this.dirIsDirectory(n.ctx,e)?this.loadRulesFromDirectory(n.ctx,t):[])());const r=[];a&&r.push("CLAUDE.md","CLAUDE.local.md"),r.push("AGENTS.md");for(const e of r)o.push(this.loadRulesFromMarkdownFile(n.ctx,i,e));const c=(0,s.dirname)(i);if(c===i)break;i=c}const c=(await Promise.all(o)).flat();return n.span.setAttribute("rules",c.length),c}catch(e){r.error=e,r.hasError=!0}finally{$f(r)}}async loadRulesFromMarkdownFile(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{Af(n,(0,$.VI)(e.withName("LocalCursorRulesService.loadRulesFromMarkdownFile")),!1).span.setAttribute("filename",r);try{const e=(0,s.join)(t,r);if(await this.isCursorIgnored(e))return[];if((await(0,fo.stat)(e)).isFile()){const t=Jr({content:await Ti(e),filename:r});return[{filename:(0,s.basename)(e,".md"),path:e,frontmatter:{alwaysApply:!0},body:t}]}}catch{}return[]}catch(e){n.error=e,n.hasError=!0}finally{$f(n)}}async isCursorIgnored(e){try{const t=await Ha((0,s.resolve)(this.rootDirectory,e));return null===t||await this.ignoreService.isCursorIgnored(t)}catch{return!1}}async parseNestedRuleFiles(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Af(r,(0,$.VI)(e.withName("LocalCursorRulesService.parseNestedRuleFiles")),!1),o=(await Promise.all(t.map((async e=>{try{const t=Xr(await Ti(e));if(t)return{filename:(0,s.basename)(e,".mdc"),path:e,frontmatter:t.frontmatter,rawFrontmatter:t.rawFrontmatter,body:t.body}}catch{}})))).filter((e=>void 0!==e));return n.span.setAttribute("ruleFiles",o.length),o}catch(e){r.error=e,r.hasError=!0}finally{$f(r)}}async parseNestedMarkdownFiles(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Af(r,(0,$.VI)(e.withName("LocalCursorRulesService.parseNestedMarkdownFiles")),!1),o=(await Promise.all(t.map((async e=>{try{const t=(0,s.basename)(e);if(!this.isRuleMarkdownFile(t))return[];const r=(0,s.dirname)(e);return await this.loadRulesFromMarkdownFile(n.ctx,r,t)}catch{}return[]})))).flat();return n.span.setAttribute("markdownFiles",o.length),o}catch(e){r.error=e,r.hasError=!0}finally{$f(r)}}async loadRulesFromDirectory(e,t){return await async function(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=Af(n,(0,$.VI)(e.withName("LocalCursorRulesService.loadRulesFromDirectory")),!1),i=[];try{(0,s.join)(t,".cursorignore");const e={root:(0,s.join)(t,".cursor","rules"),includeGlobs:["**/*.mdc"],followSymlinks:!0,source:"cursor_rules"},n=r.walk(o.ctx,e);for await(const t of n.lines){const r=(0,s.join)(e.root,t);i.push(...await sm(r))}}catch{}return o.span.setAttribute("rules",i.length),i}catch(e){n.error=e,n.hasError=!0}finally{$f(n)}}(e,t,om.getRipwalkCache())}async dirIsDirectory(e,t){const r={stack:[],error:void 0,hasError:!1};try{Af(r,(0,$.VI)(e.withName("LocalCursorRulesService.dirIsDirectory")),!1);try{return(await(0,fo.stat)(t)).isDirectory()}catch{return!1}}catch(e){r.error=e,r.hasError=!0}finally{$f(r)}}}async function sm(e){try{const t=Xr(await Ti(e));if(t)return[{filename:(0,s.basename)(e,".mdc"),path:e,frontmatter:t.frontmatter,rawFrontmatter:t.rawFrontmatter,body:t.body}]}catch{}return[]}class im{constructor(e,t,r,n,o,s,i=()=>!0,a=Promise.resolve(),c="ide",l,u=()=>[],d,h,p=()=>[],f){if(this.workspacePaths=t,this.userHomeDirectory=r,this.gitExecutor=n,this.getEnabledSkills=p,this.ignoreService=f,this.agentStoreLoadRequestedWhileInFlight=!1,this.agentStoreLoadGeneration=0,this.watchersByFolder=new Map,this.onChangeCallbacks=new Set,this.reloadRequestedDuringSeed=!1,this.surface=c,this.waitBeforeSkillLoad="function"==typeof a?a:()=>a,this.getAgentStoreSkillRoots=u,this.fileWatcher=s,this.getThirdPartyExtensibilityEnabled=i,this.catalogCache=d,this.builtinSkillRootDir=cf(r).dirPath,this.canvasKitSkillRootDir=void 0===h?void 0:uf(r).dirPath,this.workspaceCatalogKey=Qp({kind:"workspace",surface:c,loadNestedSkills:o,thirdPartyExtensibility:i(),workspacePaths:[...t].sort(),userHomeDirectory:r,...void 0===h?{}:{canvasKit:h}}),void 0!==l&&l.length!==t.length)throw new Error(`initialNestedExtensibilityResults length (${l.length}) must match workspacePaths length (${t.length})`);this.nestedExtensibilityEntries=o?t.map((e=>new _f(e,n,r,i))):[],this.foldersToWatch=this.computeFoldersToWatch();const m=performance.now();let g=!1,w=!1,y=!1;const v=this.loadAll(e,l).then((t=>{try{Mf.info(e,"AgentSkillsCursorRulesService load completed",{durationMs:Math.round(performance.now()-m),ruleCount:t.rules.length,skillCount:t.agentSkills.length,servedFromCache:g})}catch{}return t})).catch((e=>(w=!0,Yf("Failed to load Agent Skills")(e))));if(void 0===this.catalogCache)this._loaded=v;else{const t=this.readCatalog(this.workspaceCatalogKey).then((r=>(y=!0,this._loaded!==t?this._loaded:(w&&this.closeSeedWindow(e),void 0===r?v:(g=!0,r)))));this.seededLoaded=t,this._loaded=t,v.then((r=>{this._loaded===t?w?y&&this.closeSeedWindow(e):(this._loaded=v,g&&this.notifyChanged(),this.persistCatalog(this.workspaceCatalogKey,r),this.closeSeedWindow(e)):this.seededLoaded=void 0}))}this.refreshAgentStoreSkills(),this.setupWatchers(this.foldersToWatch)}closeSeedWindow(e){this.seededLoaded=void 0,this.reloadRequestedDuringSeed&&(this.reloadRequestedDuringSeed=!1,this.reload(e))}async readCatalog(e){if(void 0!==this.catalogCache)try{const t=await this.catalogCache.read(e);return void 0===t?void 0:await async function(e){if(!function(e){if(!ef(e))return!1;const t=e.fileMtimesMs;return 1===e.version&&Array.isArray(e.rules)&&Array.isArray(e.agentSkills)&&Array.isArray(e.realSkillFilePathsByFullPath)&&e.realSkillFilePathsByFullPath.every((e=>Array.isArray(e)&&2===e.length&&"string"==typeof e[0]&&"string"==typeof e[1]))&&ef(t)&&Object.values(t).every((e=>"number"==typeof e&&Number.isFinite(e)))}(e))return;const t=new Map;if(await Promise.all(e.realSkillFilePathsByFullPath.map((async([r,n])=>{const o=e.fileMtimesMs[n];void 0!==o&&await Yp(r)===o&&t.set(r,n)}))),0===t.size)return;const r=e=>void 0!==e&&t.has(e);try{return{rules:e.rules.map((e=>Gr.DX.fromJson(e,{ignoreUnknownFields:!0}))).filter((e=>r(e.fullPath))),agentSkills:e.agentSkills.map((e=>Zp.N.fromJson(e,{ignoreUnknownFields:!0}))).filter((e=>r(e.fullPath))),realSkillFilePathsByFullPath:t}}catch(e){return void Xp("snapshot failed to decode: %O",e)}}(t)}catch(e){return void Xf("Failed to read the skills catalog cache: %O",e)}}persistCatalog(e,t){const r=this.catalogCache;void 0!==r&&async function(e){const t=new Set(e.realSkillFilePathsByFullPath.values()),r={};return await Promise.all(Array.from(t,(async e=>{const t=await Yp(e);void 0!==t&&(r[e]=t)}))),{version:1,rules:e.rules.map((e=>e.toJson())),agentSkills:e.agentSkills.map((e=>e.toJson())),realSkillFilePathsByFullPath:Array.from(e.realSkillFilePathsByFullPath),fileMtimesMs:r}}(t).then((t=>r.write(e,t))).catch((e=>{Xf("Failed to persist the skills catalog cache: %O",e)}))}computeFoldersToWatch(){const e=this.getThirdPartyExtensibilityEnabled(),t=new Set;for(const r of this.workspacePaths){t.add((0,s.join)(r,".cursor","rules"));for(const n of ff(r,e))t.add(n.dirPath)}for(const r of mf(this.userHomeDirectory,e))t.add(r.dirPath);for(const e of this.getAgentStoreSkillRoots())t.add(e);return t.add(this.builtinSkillRootDir),void 0!==this.canvasKitSkillRootDir&&t.add(this.canvasKitSkillRootDir),Array.from(t)}isIgnoredSkillPath(e){if(void 0!==this.canvasKitSkillRootDir){if(hf(e,this.canvasKitSkillRootDir))return!1;if(function(e,t){const r=df(e,t);return void 0!==r&&2===r.length&&r[0]===lf&&"SKILL.md"===r[1]}(e,this.builtinSkillRootDir))return!0}return af(e)}setupWatchers(e){if(!this.fileWatcher)return;const t=["**"];for(const r of e){if(this.watchersByFolder.has(r))continue;const e=this.fileWatcher.subscribe(r,t,(e=>{const t={stack:[],error:void 0,hasError:!1};try{const r=(0,y.q6)(),n=Af(t,(0,$.VI)(r.withName("AgentSkillsCursorRulesService.fileWatcher.subscribe")),!1);this.reloadAtPath(n.ctx,e)}catch(e){t.error=e,t.hasError=!0}finally{$f(t)}}));this.watchersByFolder.set(r,e)}}removeWatchers(e){for(const t of e){const e=this.watchersByFolder.get(t);e&&(e(),this.watchersByFolder.delete(t))}}async getAllCursorRules(e){const[t]=await Promise.all([this._loaded,this.awaitAgentStoreSeed()]);return this.withAgentStoreSkills(t).rules}async awaitAgentStoreSeed(){void 0!==this.agentStoreSeedInFlight&&await(0,Dr.wj)(this.agentStoreSeedInFlight,250,"Agent Store skills cache read timed out").catch((()=>{}))}reload(e){this.syncWatchers(),this.seededLoaded=void 0,this.reloadRequestedDuringSeed=!1;const t=this.loadAll(e),r=t.catch(Yf("Failed to load Agent Skills"));this._loaded=r,t.then((e=>{this._loaded===r&&this.persistCatalog(this.workspaceCatalogKey,e)}),(()=>{})),this.refreshAgentStoreSkills(),this.notifyChanged()}reloadSkillRoots(){try{this.syncWatchers()}finally{this.refreshAgentStoreSkills()}}async agentStoreSkillsSettled(){for(let e=this.agentStoreWalk;void 0!==e;e=this.agentStoreWalk)await e}syncWatchers(){const e=this.computeFoldersToWatch(),t=new Set(this.foldersToWatch),r=new Set(e);this.removeWatchers(this.foldersToWatch.filter((e=>!r.has(e)))),this.setupWatchers(e.filter((e=>!t.has(e)))),this.foldersToWatch=e}isPrunedByExtensibilityScan(e){if(void 0!==this.canvasKitSkillRootDir&&hf(e,this.canvasKitSkillRootDir))return!1;const t=e.replace(/\\/g,"/");for(const e of this.foldersToWatch){const r=e.replace(/\\/g,"/");if(t.startsWith(`${r}/`))return t.slice(r.length+1).split("/").slice(0,-1).some((e=>e.startsWith(".")))}return!1}reloadAtPath(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Af(r,(0,$.VI)(e.withName("AgentSkillsCursorRulesService.reloadAtPath")),!1),o=function(e,t,r=s){for(const n of t){const t=r.relative(n,e);if(""!==t&&".."!==t&&!t.startsWith(`..${r.sep}`)&&!r.isAbsolute(t))return r.join(n,t)}return e}(t,this.foldersToWatch),i=o.endsWith("SKILL.md")?o:(0,s.join)(o,"SKILL.md");if(void 0!==this.seededLoaded&&this._loaded===this.seededLoaded&&!this.getAgentStoreSkillRoots().some((e=>tm(i,e))))return void(this.reloadRequestedDuringSeed=!0);if(this.getAgentStoreSkillRoots().some((e=>tm(i,e))))return void this.refreshAgentStoreSkills();if(this.foldersToWatch.some((e=>""===(0,s.relative)(e,o))))return void this.reload(n.ctx);const a=this._loaded,c=(async()=>{const e=await a,{realSkillFilePathsByFullPath:t}=e,r=function(e,t){const r=new Map(e.realSkillFilePathsByFullPath);for(const e of t)r.delete(e);return{rules:e.rules.filter((e=>!t.has(e.fullPath))),agentSkills:e.agentSkills.filter((e=>!t.has(e.fullPath))),realSkillFilePathsByFullPath:r}}(e,new Set([i]));if(this.isIgnoredSkillPath(i)||this.isPrunedByExtensibilityScan(i))return r;const o=t.get(i);if(void 0===o){try{await(0,fo.stat)(i)}catch{return r}return await this.loadAll(n.ctx)}let s;try{s=await(0,fo.realpath)(i)}catch{return await this.loadAll(n.ctx)}if(s!==o)return await this.loadAll(n.ctx);try{return Zf(r,{...await async function(e){const t=await Ti(e);return{skillFilePath:e,content:t,parsed:dd(t)}}(i),realSkillFilePath:s},this.surface,this.getEnabledSkills()),r}catch{return await this.loadAll(n.ctx)}})().catch(Yf("Failed to load Agent Skills at path"));this._loaded=c,this.notifyChanged()}catch(e){r.error=e,r.hasError=!0}finally{$f(r)}}async getAllAgentSkills(e){const[t]=await Promise.all([this._loaded,this.awaitAgentStoreSeed()]);return this.withAgentStoreSkills(t).agentSkills}withAgentStoreSkills(e){const t=this.settledAgentStoreSkills?.loaded;if(void 0===t||0===t.realSkillFilePathsByFullPath.size)return e;const r=new Set(e.realSkillFilePathsByFullPath.values()),n={rules:[...e.rules],agentSkills:[...e.agentSkills],realSkillFilePathsByFullPath:new Map(e.realSkillFilePathsByFullPath)},o=new Set;for(const[e,s]of t.realSkillFilePathsByFullPath)n.realSkillFilePathsByFullPath.has(e)||r.has(s)?o.add(e):n.realSkillFilePathsByFullPath.set(e,s);for(const e of t.rules)o.has(e.fullPath)||n.rules.push(e);for(const e of t.agentSkills)o.has(e.fullPath)||n.agentSkills.push(e);return n}refreshAgentStoreSkills(){const e=this.getAgentStoreSkillRoots().filter((e=>""!==e.trim())),t=++this.agentStoreLoadGeneration;var r,n;if(void 0===this.settledAgentStoreSkills||(r=this.settledAgentStoreSkills.roots,n=e,r.length===n.length&&r.every(((e,t)=>e===n[t])))||(this.settledAgentStoreSkills=void 0,this.notifyChanged()),0!==e.length){if(void 0===this.settledAgentStoreSkills){const r=this.seedAgentStoreSkills(e,t).finally((()=>{this.agentStoreSeedInFlight===r&&(this.agentStoreSeedInFlight=void 0)}));this.agentStoreSeedInFlight=r}void 0===this.agentStoreWalk?this.agentStoreWalk=(0,Dr.wj)(this.loadAgentStoreSkills(e),3e4,"Agent Store skills walk timed out").then((r=>{t===this.agentStoreLoadGeneration&&(this.settledAgentStoreSkills={roots:e,loaded:r},this.notifyChanged(),(r.rules.length>0||r.agentSkills.length>0)&&this.persistCatalog(em(this.surface,e),r))}),(e=>{Xf("Failed to load Agent Store skills: %O",e)})).finally((()=>{this.agentStoreWalk=void 0,this.agentStoreLoadRequestedWhileInFlight&&(this.agentStoreLoadRequestedWhileInFlight=!1,this.refreshAgentStoreSkills())})):this.agentStoreLoadRequestedWhileInFlight=!0}}async seedAgentStoreSkills(e,t){const r=await this.readCatalog(em(this.surface,e));void 0!==r&&t===this.agentStoreLoadGeneration&&void 0===this.settledAgentStoreSkills&&(this.settledAgentStoreSkills={roots:e,loaded:r},this.notifyChanged())}async loadAgentStoreSkills(e){const t=Qf(),r=(await Promise.all(e.map((e=>Ff(e))))).flat().filter((e=>!af(e))),n=await Promise.all(r.map((e=>Lf(e)))),o=new Set;for(const e of n)o.has(e.realSkillFilePath)||(o.add(e.realSkillFilePath),Zf(t,e,this.surface,this.getEnabledSkills()));return t}notifyChanged(){for(const e of Array.from(this.onChangeCallbacks))e()}onDidChangeSkills(e){return this.onDidChangeRules(e)}onDidChangeRules(e){return this.onChangeCallbacks.add(e),()=>{this.onChangeCallbacks.delete(e)}}dispose(){for(const e of this.watchersByFolder.values())e();this.watchersByFolder.clear()}async loadAll(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Af(r,(0,$.VI)(e.withName("AgentSkillsCursorRulesService.loadAll")),!1);await this.waitBeforeSkillLoad();const o=[],s=[],i=new Map,a=Promise.all(this.nestedExtensibilityEntries.map(((e,r)=>(t?.[r]??e.discover(n.ctx)).catch((e=>{Xf("Failed to discover nested agent skills: %O",e)}))))),c=new Set(this.getAgentStoreSkillRoots()),l=await Promise.all(this.foldersToWatch.filter((e=>!c.has(e))).map((async e=>{const t=(await Ff(e)).filter((e=>!this.isIgnoredSkillPath(e)));return Promise.all(t.map((e=>Lf(e))))}))),u=new Set;for(const e of l)for(const t of e)if(!u.has(t.realSkillFilePath))if(u.add(t.realSkillFilePath),"error"in t)i.set(t.skillFilePath,t.realSkillFilePath),Jf({rules:o,agentSkills:s,skillFilePath:t.skillFilePath,errorMessage:t.error});else{if(Hf(t.parsed,this.surface,this.getEnabledSkills()))continue;i.set(t.skillFilePath,t.realSkillFilePath),o.push(Vf(t)),zf(t.parsed)||s.push(Kf(t))}const d=(await a).flatMap((e=>e?.skills??[])).filter((e=>!af(e))),h=await Promise.all(d.map((e=>zo(e)))),p=[];for(const[e,t]of d.entries()){const r=h[e];u.has(r)||(u.add(r),p.push(t))}const f=await Promise.all(p.map((e=>Lf(e))));for(const e of f)if("error"in e)i.set(e.skillFilePath,e.realSkillFilePath),Jf({rules:o,agentSkills:s,skillFilePath:e.skillFilePath,errorMessage:e.error});else{if(Hf(e.parsed,this.surface,this.getEnabledSkills()))continue;i.set(e.skillFilePath,e.realSkillFilePath),o.push(Vf(e)),zf(e.parsed)||s.push(Kf(e))}return n.span.setAttribute("agent_skills.total",o.length),n.span.setAttribute("agent_skills_proto.total",s.length),{rules:o,agentSkills:s,realSkillFilePathsByFullPath:i}}catch(e){r.error=e,r.hasError=!0}finally{$f(r)}}}function am(e){let t;switch(e.type){case"global":t=new Gr.f5({type:{case:"global",value:new Gr.i9}});break;case"fileGlobbed":t=new Gr.f5({type:{case:"fileGlobbed",value:new Gr.uT({globs:e.globs??[]})}});break;case"agentFetched":t=new Gr.f5({type:{case:"agentFetched",value:new Gr.Xo({description:qf(e.description??"")})}});break;case"manuallyAttached":t=new Gr.f5({type:{case:"manuallyAttached",value:new Gr._u}});break;default:e.type,t=new Gr.f5({type:{case:"manuallyAttached",value:new Gr._u}})}return new Gr.DX({fullPath:e.fullPath,content:e.content,type:t,gitRemoteOrigin:e.gitRemoteOrigin,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId,environments:e.environments??[],disabledEnvironments:e.disabledEnvironments??[],scopedTo:[]})}class cm{constructor(e,t,r,n){this.getImportSettings=t,this.pluginsService=n,this._rules=Promise.resolve([]),this._agentSkills=Promise.resolve([]),this._lastLoaded={rules:[],agentSkills:[]},this._loadGeneration=0,this.onChangeCallbacks=new Set,this.currentImportSettings=this.getImportSettings();const o=performance.now();this.startLoad(e,!1,(t=>{try{Mf.info(e,"CursorPluginsAgentSkillsService load completed",{durationMs:Math.round(performance.now()-o),ruleCount:t.rules.length,skillCount:t.agentSkills.length})}catch{}}))}startLoad(e,t,r){const n=++this._loadGeneration,o=this.loadAll(e,t).catch((e=>((0,Fs.debuglog)("cursor-plugins-agent-skills")("Failed to load Cursor Plugins Agent Skills: %s",e instanceof Error?e.message:String(e)),{rules:[],agentSkills:[]}))).then((e=>(n===this._loadGeneration&&(this._lastLoaded=e,r?.(e)),e))),s=()=>(o.then((e=>{n===this._loadGeneration&&(this._rules=Promise.resolve(e.rules),this._agentSkills=Promise.resolve(e.agentSkills),this.notifyChange())})),this._lastLoaded),i=void 0!==this._overBudgetLoad?Promise.resolve(s()):(0,Dr.wj)(o,5e3,"Cursor plugin load did not finish within the rules wait budget").catch((t=>(Mf.warn(e,"Serving rules without plugin primitives while plugins load",{error:t instanceof Error?t.message:String(t),waitMs:5e3}),this._overBudgetLoad=o,o.then((()=>{this._overBudgetLoad===o&&(this._overBudgetLoad=void 0)})),s())));this._rules=i.then((e=>e.rules)),this._agentSkills=i.then((e=>e.agentSkills))}notifyChange(){for(const e of Array.from(this.onChangeCallbacks))e()}async getAllCursorRules(e){return await this._rules}async getAllAgentSkills(e){return await this._agentSkills}reload(e){const t=this.getImportSettings();this.currentImportSettings=t,this.startLoad(e,!0),this.notifyChange()}onDidChangeRules(e){return this.onChangeCallbacks.add(e),()=>{this.onChangeCallbacks.delete(e)}}onDidChangeSkills(e){return this.onDidChangeRules(e)}dispose(){this.onChangeCallbacks.clear()}async loadAll(e,t=!1){const r={stack:[],error:void 0,hasError:!1};try{const n=Af(r,(0,$.VI)(e.withName("CursorPluginsAgentSkillsService.loadAll")),!1),o=[],i=[];try{let e=t?await this.pluginsService.reload():await this.pluginsService.getAllEnabledPlugins();this.currentImportSettings.importThirdPartyPlugins||(e=e.filter((e=>"claude-plugin"!==e.identifier.source))),n.span.setAttribute("cursor_plugins.loaded",e.length);const r=function(e){return Jp(e,(e=>e.skills))}(e),a=function(e){return Jp(e,(e=>e.rules))}(e);for(const e of[...r,...a])o.push(am(e));for(const t of e){const e=`plugin:${rp(t.identifier)}`,r=np(t.identifier),n=op(t.identifier),o=sp(t.identifier),a=ip(t.identifier);for(const c of t.skills){if(!0===c.alwaysApply)continue;let l=!1;if(c.content?.includes("disable-model-invocation"))try{l=!0===dd(c.content).data?.["disable-model-invocation"]}catch{}i.push(new Zp.N({fullPath:(0,s.join)(t.installPath,c.path),content:c.content,description:qf(c.description??""),environments:c.environments??[],disabledEnvironments:c.disabledEnvironments??[],gitRemoteOrigin:e,plugin:r,marketplace:n,pluginId:o,marketplaceId:a,disableModelInvocation:l}))}}}catch(e){n.span.setAttribute("cursor_plugins.error",String(e))}return n.span.setAttribute("cursor_plugins.total",o.length),n.span.setAttribute("cursor_plugins_proto.total",i.length),{rules:o,agentSkills:i}}catch(e){r.error=e,r.hasError=!0}finally{$f(r)}}}var lm=r("../proto/dist/generated/agent/v1/subagents_pb.js");const um=(0,Fs.debuglog)("local-subagents");class dm{async getAllSubagents(){return[]}async reload(){return[]}}function hm(e){return"true"===(e??"").trim().toLowerCase()}function pm(e){const t=e.match(/^---\s*\n([\s\S]*?)\n---\s*\n?([\s\S]*)$/m);if(!t)return null;const r=t[1]??"",n=(t[2]??"").trim();if(0===n.length)return null;const o={};for(const e of r.split("\n")){const t=e.trim();if(0===t.length||t.startsWith("#"))continue;const r=t.indexOf(":");if(-1===r)continue;const n=t.slice(0,r).trim().toLowerCase(),s=t.slice(r+1).trim();0!==n.length&&(o[n]=s)}const s=o.name??"",i=o.description,a=o.model,c=hm(o["force-default-model"]),l="true"===(o.readonly??"").trim().toLowerCase()?lm.b$.READONLY:lm.b$.DEFAULT,u=hm(o.background??o.is_background),d=o.tools;return{name:s,description:i,tools:void 0!==d&&d.length>0?d.split(",").map((e=>e.trim())).filter((e=>e.length>0)):[],model:a,forceDefaultModel:c,prompt:n,permissionMode:l,isBackground:u}}function fm(e){const t=(0,s.extname)(e).toLowerCase();return".md"===t||".mdc"===t||".markdown"===t}function mm(e){return(0,s.basename)(e,(0,s.extname)(e)).replace(/[\s_]+/g,"-")}async function gm(e,t){return await Ef({rootDir:e,includeFile:fm,containmentRootDir:t})}class wm{constructor(e,t,r="workspace",n=!1,o){this.workspacePath=e,this.cursorAgentsSource=r,this.allowExternalAgentSymlinks=n,this.ignoreService=o,this.getThirdPartyExtensibilityEnabled=t??(()=>!0),this.subagents=this.load().catch((e=>(um("Failed to load subagents: %o",e),[])))}async getAllSubagents(){return this.subagents}async reload(){return this.subagents=this.load().catch((e=>(um("Failed to load subagents: %o",e),[]))),await this.subagents}computeAgentsDirs(){const e=(0,s.resolve)(this.workspacePath),t=[{dirPath:(0,s.join)(e,".cursor","agents"),source:this.cursorAgentsSource}];return this.getThirdPartyExtensibilityEnabled()&&(t.push({dirPath:(0,s.join)(e,".claude","agents"),source:"claude"}),t.push({dirPath:(0,s.join)(e,".grok","agents"),source:"grok"})),t}async load(){const e=this.computeAgentsDirs(),t=[];for(const{dirPath:r,source:n}of e){const e=await gm(r,this.allowExternalAgentSymlinks?void 0:this.workspacePath);for(const r of e){const e=(0,s.basename)(r);try{if(!(await(0,fo.stat)(r)).isFile())continue}catch(e){um("Skipping subagent file %s due to stat error: %o",r,e);continue}try{const o=pm(await Ti(r));if(!o)continue;t.push(new lm.zz({fullPath:r,name:o.name||mm(e),description:o.description??"",tools:o.tools,model:o.model??"inherit",forceDefaultModel:o.forceDefaultModel,prompt:o.prompt,permissionMode:o.permissionMode,isBackground:o.isBackground,source:n}))}catch(e){um("Failed to parse subagent file %s: %o",r,e)}}}return t}}const ym=new Set(["claude-code-tutor"]);class vm{constructor(e){this.subagentsServices=e}async getAllSubagents(){const e=await Promise.all(this.subagentsServices.map((e=>e.getAllSubagents().catch((e=>(um("Failed to load subagents from merged service: %o",e),[])))))),t=new Map;for(const r of e)for(const e of r)ym.has(e.name)||t.has(e.name)||t.set(e.name,e);return Array.from(t.values())}async reload(){return await Promise.all(this.subagentsServices.map((e=>e.reload()))),this.getAllSubagents()}}class bm{constructor(e,t){this.getSettings=e,this.pluginsService=t,this._subagentsCache=[],this._loadId=0,this._loadPromise=null,this._loadedOnce=!1,this.runLoadInBackground()}async getAllSubagents(){return this._loadPromise&&await this._loadPromise,this._loadedOnce||await this.reload(),[...this._subagentsCache]}async reload(){return this.runLoadInBackground(!0),this._loadPromise&&await this._loadPromise,this._subagentsCache}runLoadInBackground(e=!1){const t=++this._loadId;this._loadPromise=this.load(e).then((e=>{t===this._loadId&&(this._subagentsCache=e,this._loadedOnce=!0)})).catch((e=>{t===this._loadId&&(um("Failed to load Cursor plugin subagents: %o",e),this._subagentsCache=[],this._loadedOnce=!0)})).finally((()=>{t===this._loadId&&(this._loadPromise=null)}))}dispose(){}async load(e){const t=[];try{let r=e?await this.pluginsService.reload():await this.pluginsService.getAllEnabledPlugins();this.getSettings().importThirdPartyPlugins||(r=r.filter((e=>"claude-plugin"!==e.identifier.source)));const n=function(e,t={stripModel:!0,stripTools:!0}){const r=[];for(const n of e){const e=np(n.identifier),o=op(n.identifier),i=sp(n.identifier),a=ip(n.identifier);for(const c of n.agents){const l=Kp(c,t),u=(0,s.join)(n.installPath,l.path);r.push({name:l.name,description:l.description??"",prompt:l.prompt,fullPath:u,permissionMode:"readonly"===l.permissionMode?"readonly":"default",plugin:e,marketplace:o,pluginId:i,marketplaceId:a})}}return r}(r,{stripModel:!0,stripTools:!0});for(const e of n){const r="readonly"===e.permissionMode?lm.b$.READONLY:lm.b$.DEFAULT;t.push(new lm.zz({name:e.name,description:e.description,tools:[],model:"inherit",prompt:e.prompt,fullPath:e.fullPath,permissionMode:r,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId,source:"plugin"}))}}catch{}return t}}class Sm{constructor(e){this.pastElements=[],this.closed=!1,this.forks=new Set,this.consume(e)}async consume(e){try{for await(const t of e){this.pastElements.push(t);const e=[];for(const r of this.forks)e.push(r.write(t).catch((()=>{})));await Promise.allSettled(e)}}catch(e){this.error=e instanceof Error?e:new Error(String(e))}finally{this.closed=!0;for(const e of this.forks)this.error?e.throw(this.error):e.close();this.forks.clear()}}fork(){if(this.closed){const e=this.pastElements,t=this.error;return async function*(){for(const t of e)yield t;if(t)throw t}()}const e=(0,h.Jt)(),t=this.pastElements.slice();this.forks.add(e);const r=this;return async function*(){for(const e of t)yield e;try{for await(const t of e)yield t}finally{r.forks.delete(e)}}()}}function km(e,t){return`${e}:${(0,lo.createHash)("sha256").update(t.toBinary()).digest("hex")}`}function _m(e){return new mo.q({max:e?.max??10,ttl:e?.ttl})}function Cm(e,t,r=_m(t)){return{async execute(t,n,o){if(!o?.execId)return e.execute(t,n,o);const s=km(o.execId,n),i=r.get(s);if(void 0!==i)return i;const a=await e.execute(t,n,o);return r.set(s,a),a}}}var Em=r("../proto/dist/generated/agent/v1/computer_use_tool_pb.js");r("node:readline"),Error,r("node:timers/promises");const xm=gl.execFile;function Pm(e,t,r){return new Promise(((n,o)=>{r?.signal?.throwIfAborted();const s={timeout:r?.timeoutMs??3e4,env:r?.env?{...process.env,...r.env}:void 0,signal:r?.signal};(0,wl.D9)(xm,e,t.map(String),{...s,encoding:"utf8"},((e,t)=>{e?o(e):n(t)}))}))}Em.w3.UNSPECIFIED,Em.w3.LEFT,Em.w3.MIDDLE,Em.w3.RIGHT,Em.w3.BACK,Em.w3.FORWARD,Em.Dh.UNSPECIFIED,Em.Dh.UP,Em.Dh.DOWN,Em.Dh.LEFT,Em.Dh.RIGHT;const Im=(0,Fs.promisify)(gl.execFile);function Rm(e,t,r,n){const o=function(e={}){const t=e.displayWidth??1920,r=e.displayHeight??1200,n=e.apiWidth??1280;return{width:n,height:Math.round(n*r/t)}}({displayWidth:e,displayHeight:t,apiWidth:r});return{display:{width:e,height:t},api:{width:o.width,height:n??o.height}}}async function Tm(e){const{stdout:t}=await(0,wl.D9)(Im,"xrandr",["--display",e],{timeout:5e3,encoding:"utf8"}),r=function(e){let t,r,n;for(const o of e.split("\n"))if(o.includes("*")){const e=o.trim().match(/^(\d+)x(\d+)/);e&&(t=parseInt(e[1],10),r=parseInt(e[2],10));const s=o.match(/(\d+(?:\.\d+)?)\*(?:\+)?/);if(s){const e=parseFloat(s[1]);e>0&&e<=500&&(n=Math.round(e))}if(t&&r)break}if(!t||!r){const n=e.match(/current\s+(\d+)\s*x\s*(\d+)/i);n&&(t=parseInt(n[1],10),r=parseInt(n[2],10))}if(!t||!r)throw new Error(`Could not detect display resolution from xrandr output.\nExpected a line with '*' indicating active mode, or 'current WxH'.\nxrandr output:\n${e}`);return n||(n=60),{width:t,height:r,refreshRate:n}}(t);return{display:r,resolution:Rm(r.width,r.height),resolutionString:`${r.width}x${r.height}`}}Em.w3.UNSPECIFIED,Em.w3.LEFT,Em.w3.MIDDLE,Em.w3.RIGHT,Em.w3.BACK,Em.w3.FORWARD,Em.Dh.UNSPECIFIED,Em.Dh.UP,Em.Dh.DOWN,Em.Dh.LEFT,Em.Dh.RIGHT;const Am={pattern:"[\\w-]{1,64}",next:e=>e},$m={pattern:"[0-9a-f-]{36}",next:()=>lo.randomUUID()},Mm={pattern:"webp",next:()=>"webp"},Dm={native:[$m,Mm],agent:[Am,$m,Mm],legacyNative:[$m,{pattern:"png",next:()=>"png"}]};new RegExp(`^(?:${Object.values(Dm).map((e=>e.map((e=>e.pattern)).join("\\."))).join("|")})$`),new RegExp(`^${Am.pattern}$`),Em.Z8.NATIVE_X11,Em.Z8.XDOTOOL,(0,u.v5)("computer_use.session.duration_ms",{description:"Duration of computer-use session in milliseconds"}),(0,u.v5)("computer_use.session.action_count",{description:"Number of actions executed in a computer-use session"}),(0,u.Pu)("computer_use.session.result",{description:"Result status of computer-use session",labelNames:["outcome"]}),(0,u.Pu)("computer_use.session.action_kind",{description:"Requested computer-use actions by bounded kind",labelNames:["kind"]}),(0,l.h)("computer-use"),Math.floor(35927136),["Skip changes that cannot affect what runs in any deployed environment:","- documentation-only changes (Markdown, docs sites, code comments, changelogs)","- formatting, lint, or typo fixes with no behavior change","- test-only changes (test files, fixtures, snapshots)","Monitor everything else, including dependency bumps, configuration, and infrastructure changes."].join("\n"),Error,(0,u.Pu)("computer_use.desktop_lease.check",{description:"Desktop lease action-gate outcomes",labelNames:["outcome","reason"]});var Om=r("../proto/dist/runtime/compact.js");Om.HL;var Fm=(0,Om.QT)(we.proto3,"agent.v1.","CursorType",[[0,"UNSPECIFIED"],[1,"ARROW"],[2,"POINTER"],[3,"TEXT"],[4,"WAIT"],[5,"CROSSHAIR"],[6,"MOVE"],[7,"RESIZE_NS"],[8,"RESIZE_EW"],[9,"RESIZE_NWSE"],[10,"RESIZE_NESW"],[11,"NOT_ALLOWED"],[12,"GRAB"],[13,"GRABBING"]],1);we.proto3,we.proto3,we.proto3,we.proto3;class Nm{constructor(e){this.config=e;const t=e.display.width/e.display.height,r=e.api.width/e.api.height;if(Math.abs(t-r)>.02)throw new Error(`Aspect ratio mismatch: display=${t.toFixed(3)}, api=${r.toFixed(3)}`);this.xScaleUp=e.display.width/e.api.width,this.yScaleUp=e.display.height/e.api.height,this.xScaleDown=e.api.width/e.display.width,this.yScaleDown=e.api.height/e.display.height}apiToDisplay(e,t){return{x:Math.round(e*this.xScaleUp),y:Math.round(t*this.yScaleUp)}}displayToApi(e,t){return{x:Math.round(e*this.xScaleDown),y:Math.round(t*this.yScaleDown)}}get apiWidth(){return this.config.api.width}get apiHeight(){return this.config.api.height}get displayWidth(){return this.config.display.width}get displayHeight(){return this.config.display.height}}const Lm={left_ptr:Fm.ARROW,arrow:Fm.ARROW,default:Fm.ARROW,top_left_arrow:Fm.ARROW,hand:Fm.POINTER,hand1:Fm.POINTER,hand2:Fm.POINTER,pointer:Fm.POINTER,pointing_hand:Fm.POINTER,xterm:Fm.TEXT,ibeam:Fm.TEXT,text:Fm.TEXT,watch:Fm.WAIT,wait:Fm.WAIT,progress:Fm.WAIT,left_ptr_watch:Fm.WAIT,crosshair:Fm.CROSSHAIR,cross:Fm.CROSSHAIR,tcross:Fm.CROSSHAIR,move:Fm.MOVE,fleur:Fm.MOVE,size_all:Fm.MOVE,sb_v_double_arrow:Fm.RESIZE_NS,v_double_arrow:Fm.RESIZE_NS,ns_resize:Fm.RESIZE_NS,row_resize:Fm.RESIZE_NS,top_side:Fm.RESIZE_NS,bottom_side:Fm.RESIZE_NS,sb_h_double_arrow:Fm.RESIZE_EW,h_double_arrow:Fm.RESIZE_EW,ew_resize:Fm.RESIZE_EW,col_resize:Fm.RESIZE_EW,left_side:Fm.RESIZE_EW,right_side:Fm.RESIZE_EW,top_left_corner:Fm.RESIZE_NWSE,bottom_right_corner:Fm.RESIZE_NWSE,nwse_resize:Fm.RESIZE_NWSE,size_fdiag:Fm.RESIZE_NWSE,top_right_corner:Fm.RESIZE_NESW,bottom_left_corner:Fm.RESIZE_NESW,nesw_resize:Fm.RESIZE_NESW,size_bdiag:Fm.RESIZE_NESW,not_allowed:Fm.NOT_ALLOWED,no_drop:Fm.NOT_ALLOWED,forbidden:Fm.NOT_ALLOWED,circle:Fm.NOT_ALLOWED,grab:Fm.GRAB,openhand:Fm.GRAB,grabbing:Fm.GRABBING,closedhand:Fm.GRABBING};class jm{constructor(e){this.events=[],this.recordingStartTime=0,this.lastKnownPosition={x:0,y:0},this.isRunning=!1,this.pending=Promise.resolve();const t=e.displayNum??1;this.env={DISPLAY:`:${t}`},this.scaler=new Nm(e.resolution)}async start(){this.events=[],this.recordingStartTime=Date.now(),this.isRunning=!0,this.pending=Promise.resolve();try{this.lastKnownPosition=await this.captureCurrentPosition()}catch{this.lastKnownPosition={x:Math.floor(this.scaler.apiWidth/2),y:Math.floor(this.scaler.apiHeight/2)}}}logEvent(e,t,r){if(!this.isRunning)return;const n={...this.lastKnownPosition},o=this.getExpectedPositionAfterAction(e,n);this.lastKnownPosition=o;const s=async()=>{let s,i;try{[s,i]=await Promise.all([this.captureCurrentPosition(),this.detectCursorType()]),this.lastKnownPosition=s}catch{s=o,i=Fm.ARROW}const a={executionTimestampMs:r-this.recordingStartTime,action:e,commandDurationMs:r-t,positionBefore:n,positionAfter:s,cursorTypeAfter:i};this.events.push(a)};this.pending=this.pending.then((()=>s())).catch((()=>{}))}async stop(){return this.isRunning=!1,await this.pending,[...this.events]}getEvents(){return[...this.events]}getRecordingStartTime(){return this.recordingStartTime}getIsRunning(){return this.isRunning}async captureCurrentPosition(){const e=await Pm("xdotool",["getmouselocation","--shell"],{env:this.env}),t=e.match(/X=(\d+)/),r=e.match(/Y=(\d+)/);if(!t||!r)throw new Error(`Failed to parse cursor position: ${e}`);const n=parseInt(t[1],10),o=parseInt(r[1],10);return this.scaler.displayToApi(n,o)}async detectCursorType(){try{const e=(await Pm("xdotool",["getmouselocation","--shell"],{env:this.env})).match(/CURSOR=(\S+)/i);if(e){const t=e[1].toLowerCase();return Lm[t]??Fm.ARROW}try{const e=await Pm("xprop",["-root","_XSERVER_CURSOR"],{env:this.env,timeoutMs:500});for(const[t,r]of Object.entries(Lm))if(e.toLowerCase().includes(t))return r}catch{}return Fm.ARROW}catch{return Fm.ARROW}}getExpectedPositionAfterAction(e,t){const r=e.action;if(!r)return t;switch(r.case){case"mouseMove":{const e=r.value.coordinate;if(e)return{x:e.x,y:e.y};break}case"click":{const e=r.value.coordinate;if(e)return{x:e.x,y:e.y};break}case"drag":{const e=r.value.path;if(e.length>0){const t=e[e.length-1];return{x:t.x,y:t.y}}break}case"scroll":{const e=r.value.coordinate;if(e)return{x:e.x,y:e.y};break}}return t}}(0,l.h)("computer-use-lazy");var Um=r("node:net");function Bm(e){return!!e.includes(o.homedir())||e.includes("node_modules")||e.includes("Application Support")||/\.wasm\b/.test(e)||/(?:^|[\s'`"(=])(?:\/|\.{1,2}\/)/.test(e)||/(?:^|[\s'`"(=:])(?:[A-Za-z]:[\\/]|\\\\)/.test(e)||/\bS-1-5-21(?:-\d+){3,}/i.test(e)}class Wm extends Error{constructor(e){super(e),this.name="MacRPCProtocolError"}}const Hm=je.object({rpcSocketPath:je.string().min(1).optional(),appControlSocketPath:je.string().min(1).optional(),pid:je.number().int().positive().optional().catch(void 0),protocolMajor:je.number().int().positive().optional().catch(void 0)}).passthrough(),qm=je.object({data:je.string(),mimeType:je.string().min(1)}).strip(),zm=je.object({message:je.string(),screenshot:qm.optional(),screenshotBefore:qm.optional(),structuredContent:je.unknown().optional(),isError:je.boolean()}).strip(),Gm=je.object({accessibilityTrusted:je.boolean(),screenRecordingGranted:je.boolean()}).strip(),Vm=je.union([je.object({id:je.number().int(),result:zm,ok:je.never().optional(),error:je.never().optional(),errorCode:je.never().optional(),permissionStatus:je.never().optional(),sessionId:je.never().optional()}).strip(),je.object({id:je.number().int(),sessionId:je.string().min(1),ok:je.literal(!0).optional(),result:je.never().optional(),error:je.never().optional(),errorCode:je.never().optional(),permissionStatus:je.never().optional()}).strip(),je.object({id:je.number().int(),ok:je.literal(!0),result:je.never().optional(),error:je.never().optional(),errorCode:je.never().optional(),permissionStatus:je.never().optional(),sessionId:je.never().optional()}).strip(),je.object({id:je.number().int().nullable().optional(),error:je.string().min(1),errorCode:je.string().min(1).optional(),result:je.never().optional(),ok:je.never().optional(),permissionStatus:je.never().optional(),sessionId:je.never().optional()}).strip(),je.object({id:je.number().int(),permissionStatus:Gm,result:je.never().optional(),ok:je.never().optional(),error:je.never().optional(),errorCode:je.never().optional(),sessionId:je.never().optional()}).strip()]);function Km(e,t){try{return JSON.parse(e)}catch{throw new Wm(`local-cua ${t} is not valid JSON`)}}const Jm={responseMaxBytes:33554432,parseServiceState(e){const t=Hm.safeParse(Km(e,"service state")),r=t.success?t.data.rpcSocketPath??t.data.appControlSocketPath:void 0;if(!t.success||void 0===r)throw new Wm("local-cua service state is malformed");return{...t.data,rpcSocketPath:r}},parseResponse({line:e,expectedID:t}){const r=Vm.safeParse(Km(e.toString("utf8"),"RPC response"));if(!r.success)throw new Wm("local-cua RPC response is malformed");if(void 0!==r.data.id&&null!==r.data.id&&r.data.id!==t)throw new Wm("local-cua RPC response ID did not match");return r.data}};class Zm extends Error{constructor(e,t){super(e),this.name="MacComputerUseRPCError",this.code=t?.code,this.userFacing=!0===t?.userFacing,this.tool=t?.tool}}function Xm(e){return"object"==typeof e&&null!==e&&"code"in e&&"string"==typeof e.code?e.code:e instanceof Error?Bm(e.message)?e.name:e.message.length>0?`${e.name}: ${e.message}`:e.name:"unknown"}const Qm=new Map([["co.anysphere.cursor-computer-use","cursor-computer-use"],["co.anysphere.cursor-computer-use.dev","cursor-computer-use-dev"]]),Ym=/^[A-Za-z0-9][A-Za-z0-9._-]*$/;class eg{constructor(e){this.mode=e}static isInstalled(){if((0,go.existsSync)(eg.serviceExecutablePath()))return!0;let e;try{e=Jm.parseServiceState((0,go.readFileSync)(eg.serviceStatePath(),"utf8"))}catch{return!1}return void 0===e.pid||eg.isProcessAlive(e.pid)}static async runningHelperPid(){const e=await eg.readServiceState(),t=e?.pid;return void 0!==t&&eg.isProcessAlive(t)?t:void 0}static isProcessAlive(e){try{return process.kill(e,0),!0}catch{return!1}}static isExitedIncompatibleHelper(e){return void 0!==e.protocolMajor&&e.protocolMajor!==eg.protocolMajor&&void 0!==e.pid&&!eg.isProcessAlive(e.pid)}screenshot(e){return this.callTool(e,"computer_use_screenshot",{})}click(e,t){return this.callTool(e,"computer_use_click",{method:"coordinate",...void 0!==t.coordinate&&{x:t.coordinate.x,y:t.coordinate.y},button:t.button,count:t.count,modifier_keys:t.modifierKeys})}scroll(e,t){return this.callTool(e,"computer_use_scroll",{x:t.coordinate?.x,y:t.coordinate?.y,direction:t.direction,amount:t.amount,modifier_keys:t.modifierKeys})}move(e,t){return this.callTool(e,"computer_use_mouse_move",{x:t.x,y:t.y})}mouseButton(e,t){return this.callTool(e,"computer_use_mouse_button",{button:t.button,action:t.action})}drag(e,t){return this.callTool(e,"computer_use_drag",{button:t.button,path:t.path,modifier_keys:t.modifierKeys})}typeText(e,t){return this.callTool(e,"computer_use_typing",{value:t})}pressKey(e,t){return this.callTool(e,"computer_use_press_key",{key:t.key,hold_duration_ms:t.holdDurationMs})}checkPermissions(e){return this.callTool(e,"computer_use_check_permissions",{})}async startControl(e){if("remote"!==this.mode||void 0!==this.activeSessionId)return;eg.throwIfAborted(e.signal);const t=(0,lo.randomUUID)(),r=await this.sendWithRelaunchRetry(e,(()=>({id:eg.requestID,method:"control/start",requestID:t,mode:this.mode})),"control/start");if(void 0!==r.error)throw eg.rpcError(r);if(void 0===r.sessionId)throw new Zm("local-cua control/start returned no session");this.activeSessionId=r.sessionId}async releaseControl(e){const t=this.activeSessionId;if(void 0!==t){this.activeSessionId=void 0;try{const e=await eg.readServiceState();if(void 0===e)return;const r=await eg.sendOnce(eg.socketPathFrom(e),{id:eg.requestID,method:"control/release",requestID:(0,lo.randomUUID)(),mode:this.mode,sessionId:t},eg.defaultCallTimeoutMs);if(void 0!==r.error)throw eg.rpcError(r)}catch(t){eg.logger.warn(e,"local-cua control release failed",{error:Xm(t)})}}}async callTool(e,t,r){eg.throwIfAborted(e.signal);const n=eg.defaultCallTimeoutMs,o=await this.sendWithRelaunchRetry(e,(()=>{const e=Date.now()/1e3,o=this.activeSessionId;return{id:eg.requestID,method:"tools/call",requestID:(0,lo.randomUUID)(),name:t,arguments:r,timeoutSeconds:n/1e3,startedAtEpochSeconds:e,deadlineEpochSeconds:e+n/1e3,mode:this.mode,...void 0!==o&&{sessionId:o}}}),t);if(void 0!==o.error)throw eg.rpcError(o,t);const s=o.result;if(void 0===s)throw new Zm(`local-cua tool ${t} returned no result`,{tool:t});if(s.isError){const e=s.message.trim();throw new Zm(e.length>0?e:`local-cua tool ${t} reported an error`,{tool:t,userFacing:e.length>0})}return s}async sendWithRelaunchRetry(e,t,r){const n=eg.defaultCallTimeoutMs,o=await this.ensureSocketPath(e);eg.throwIfAborted(e.signal);try{return await eg.sendOnce(o,t(),n,e.signal)}catch(o){if(!eg.isPreDeliveryConnectionError(o))throw o;eg.logger.warn(e,"local-cua callTool failed; relaunching and retrying",{tool:r,error:eg.spawnErrorCode(o)});const s=await this.ensureSocketPath(e,!0);return eg.throwIfAborted(e.signal),void 0!==this.activeSessionId&&(this.activeSessionId=void 0,await this.startControl(e)),await eg.sendOnce(s,t(),n,e.signal)}}static rpcError(e,t){return new Zm(e.error,{code:e.errorCode,userFacing:!0,tool:t})}async ensureSocketPath(e,t=!1){if(eg.throwIfAborted(e.signal),!t){const e=await eg.readServiceState();if(e&&!eg.isExitedIncompatibleHelper(e))return eg.socketPathFrom(e)}await this.launchAndWait(e);const r=await eg.readServiceState();if(!r)throw new Zm("local-cua sidecar did not publish service.json after launch");return eg.socketPathFrom(r)}static setLaunchGuard(e){eg.launchGuard=e}async launchAndWait(e){const t=eg.serviceAppPath(),r=eg.launchGuard,n=()=>this.launchAppAndWait(e,t);await(void 0===r?n():r(t,n,e.signal))}async launchAppAndWait(e,t){eg.logger.info(e,"launching local-cua sidecar",eg.sidecarLaunchLogFields(t)),"1"===process.env[eg.directLaunchEnv]?await eg.spawnSidecarProcess(e,eg.serviceExecutablePath(),[],{detached:!0}):await eg.spawnSidecarProcess(e,"/usr/bin/open",["-g",t]);const r=Date.now()+eg.launchReadyTimeoutMs;for(;Date.now()<r;){eg.throwIfAborted(e.signal);const t=await eg.readServiceState();if(t&&!eg.isExitedIncompatibleHelper(t)){const r=eg.socketPathFrom(t);try{if("ok"in await eg.sendOnce(r,{id:eg.requestID,method:"ping"},2e3,e.signal))return}catch{}}await(0,Dr.cb)(eg.launchPollIntervalMs)}throw new Zm("local-cua sidecar did not become ready in time")}static isPreDeliveryConnectionError(e){const t=Xm(e);return"ENOENT"===t||"ECONNREFUSED"===t}static serviceStatePath(){return s.join(eg.helperIdentity().appSupportDirectory,"service.json")}static serviceAppPath(){const e=process.env[eg.serviceAppOverrideEnv];return e&&e.length>0?e:s.join(o.homedir(),...eg.sharedInstallRelativePath,`${eg.serviceAppBundleName}.app`)}static helperIdentity(){const e=eg.serviceAppPath(),t=process.env[eg.appSupportOverrideEnv],r=`${e}\0${t??""}`,n=eg.identityCache;if(n?.key===r)return n.identity;const i=function(e){let t;try{t=(0,go.readFileSync)(s.join(e,"Contents","Info.plist"),"utf8")}catch{return{}}const r=e=>{const r=new RegExp(`<key>${e}</key>\\s*<string>([^<]*)</string>`).exec(t)?.[1];return void 0!==r&&Ym.test(r.trim())?r.trim():void 0};return{executableName:r("CFBundleExecutable"),bundleIdentifier:r("CFBundleIdentifier")}}(e),a=s.join(e,"Contents","MacOS",i.executableName??eg.productionExecutableName),c={appPath:e,executablePath:a,appSupportDirectory:void 0!==t&&t.length>0?t:s.join(o.homedir(),"Library","Application Support",(void 0===i.bundleIdentifier?void 0:Qm.get(i.bundleIdentifier))??eg.appSupportFolder)};return(0,go.existsSync)(a)&&(eg.identityCache={key:r,identity:c}),c}static sidecarLaunchLogFields(e){const t=`${eg.serviceAppBundleName}.app`;return{appName:s.basename(e)===t?t:"custom",appPathHash:(0,lo.createHash)("sha256").update(e).digest("hex"),usingOverride:Boolean(process.env[eg.serviceAppOverrideEnv])}}static spawnErrorCode(e){return Xm(e)}static socketError(e){const t=Xm(e);return new Zm(`local-cua RPC connection failed: ${t}`,{code:t})}static serviceExecutablePath(){return eg.helperIdentity().executablePath}static spawnSidecarProcess(e,t,r,n){return new Promise(((o,s)=>{const i=(0,gl.spawn)(t,[...r],{detached:!0===n?.detached,stdio:"ignore"}),a=e=>{s(new Zm(`local-cua sidecar launch failed: ${eg.spawnErrorCode(e)}`))};i.once("error",a),i.once("spawn",(()=>{i.removeListener("error",a),i.on("error",(t=>{eg.logger.warn(e,"local-cua sidecar process error after launch",{error:eg.spawnErrorCode(t)})})),i.unref(),o()}))}))}static async readServiceState(){try{const e=await(0,fo.readFile)(eg.serviceStatePath(),"utf8");return Jm.parseServiceState(e)}catch(e){if(e instanceof Error&&"code"in e&&"ENOENT"===e.code)return;if(e instanceof Wm)return;throw new Zm("local-cua service state could not be read")}}static socketPathFrom(e){if(void 0!==e.protocolMajor&&e.protocolMajor!==eg.protocolMajor)throw new Zm(`The running Cursor Computer Use speaks protocol ${e.protocolMajor}, and this Cursor CLI speaks protocol ${eg.protocolMajor}. Update the Cursor CLI.`,{userFacing:!0});return e.rpcSocketPath}static abortError(e){return e.reason instanceof Error?e.reason:new Zm("local-cua RPC aborted")}static throwIfAborted(e){if(e.aborted)throw eg.abortError(e)}static sendOnce(e,t,r,n){return n?.aborted?Promise.reject(eg.abortError(n)):new Promise(((o,s)=>{let i=!1,a=[],c=0,l=!1;const u=(0,Um.createConnection)({path:e}),d=e=>{i||(i=!0,clearTimeout(p),n?.removeEventListener("abort",h),u.destroy(),e())},h=()=>{d((()=>s(void 0===n?new Zm("local-cua RPC aborted"):eg.abortError(n))))},p=setTimeout((()=>{d((()=>s(new Zm(`local-cua RPC timed out after ${r}ms`))))}),r);n?.addEventListener("abort",h,{once:!0}),n?.aborted?h():(u.on("connect",(()=>{u.write(`${JSON.stringify(t)}\n`,(e=>{null==e?l=!0:d((()=>s(eg.socketError(e))))}))})),u.on("data",(e=>{const t=e.indexOf(10),r=c+(t<0?e.length:t);if(r>Jm.responseMaxBytes)return void d((()=>s(new Zm("local-cua RPC response exceeded the size limit"))));if(t<0)return a.push(e),void(c+=e.length);a.push(e.subarray(0,t));const n=Buffer.concat(a,r);a=[],c=0;try{const e=Jm.parseResponse({line:n,expectedID:eg.requestID});d((()=>o(e)))}catch(e){d((()=>s(e)))}})),u.on("error",(e=>{d(l?()=>s(new Zm("local-cua RPC connection failed after request delivery")):()=>s(eg.socketError(e)))})),u.on("close",(()=>{const e=c>0?"local-cua RPC response ended without a newline":l?"local-cua RPC connection closed after request delivery":"local-cua RPC connection closed";d((()=>s(new Zm(e))))})))}))}}let tg;function rg(){if(void 0===tg){const e=async function(){const[{createJimp:e},{default:t},{default:n},{default:o,msBmp:s},{default:i},{default:a},{methods:c}]=await Promise.all([Promise.all([r.e(731),r.e(250)]).then(r.bind(r,"../../node_modules/.pnpm/@jimp+core@1.6.0/node_modules/@jimp/core/dist/esm/index.js")),r.e(690).then(r.bind(r,"../../node_modules/.pnpm/@jimp+js-png@1.6.0/node_modules/@jimp/js-png/dist/esm/index.js")),r.e(831).then(r.bind(r,"../../node_modules/.pnpm/@jimp+js-jpeg@1.6.0/node_modules/@jimp/js-jpeg/dist/esm/index.js")),Promise.all([r.e(731),r.e(284)]).then(r.bind(r,"../../node_modules/.pnpm/@jimp+js-bmp@1.6.0/node_modules/@jimp/js-bmp/dist/esm/index.js")),r.e(295).then(r.bind(r,"../../node_modules/.pnpm/@jimp+js-gif@1.6.0/node_modules/@jimp/js-gif/dist/esm/index.js")),r.e(181).then(r.bind(r,"../../node_modules/.pnpm/@jimp+js-tiff@1.6.0/node_modules/@jimp/js-tiff/dist/esm/index.js")),r.e(162).then(r.bind(r,"../../node_modules/.pnpm/@jimp+plugin-resize@1.6.0/node_modules/@jimp/plugin-resize/dist/esm/index.js"))]);return e({formats:[t,n,o,s,i,a],plugins:[c]})}().catch((t=>{throw tg===e&&(tg=void 0),t}));tg=e}return tg}eg.logger=(0,l.h)("local-cua:rpc"),eg.serviceAppBundleName="Cursor Computer Use",eg.appSupportFolder="cursor-computer-use",eg.productionExecutableName="CUCursorService",eg.sharedInstallRelativePath=[".cursor","computer-use-sidecar"],eg.appSupportOverrideEnv="CUA_APP_SUPPORT_DIR",eg.serviceAppOverrideEnv="CUA_SERVICE_APP",eg.directLaunchEnv="CUA_DIRECT_LAUNCH",eg.protocolMajor=1,eg.defaultCallTimeoutMs=45e3,eg.launchReadyTimeoutMs=8e3,eg.launchPollIntervalMs=200,eg.requestID=1;var ng=r("node:module");const og="mac-webp-runtime.cjs";function sg(e){return"function"==typeof e}function ig(e){return"object"==typeof e&&null!==e&&"getFileName"in e&&"function"==typeof e.getFileName}function ag(){const e=(new Error).stack;return Array.isArray(e)?e.filter(ig):[]}let cg,lg;function ug(){return cg??=(()=>{const e=Error.prepareStackTrace;try{Error.prepareStackTrace=(e,t)=>t;const e=ag()[0]?.getFileName();return function(){const e=ng;if("createRequire"in e&&sg(e.createRequire))return e.createRequire;if("default"in e&&"object"==typeof e.default&&null!==e.default&&"createRequire"in e.default&&sg(e.default.createRequire))return e.default.createRequire;throw new Error("node:module createRequire is unavailable")}()("string"==typeof e&&e.length>0?e:(0,s.join)(process.cwd(),"package.json"))}finally{Error.prepareStackTrace=e}})(),cg}function dg(){const e=globalThis.__MAC_WEBP_IMPORT__;return"function"==typeof e?t=>Promise.resolve(e(t)):(lg??=function(){const e=[],t=new Set,r=r=>{t.has(r)||(t.add(r),e.push(r))};for(const e of function(){const e=Error.prepareStackTrace;try{Error.prepareStackTrace=(e,t)=>t;const e=[];for(const t of ag()){const r=t.getFileName();"string"==typeof r&&r.length>0&&e.push(r)}return e}finally{Error.prepareStackTrace=e}}()){const t=(0,s.dirname)((n=e).startsWith("file:")?(0,Fu.fileURLToPath)(n):n);r((0,s.join)(t,og)),r((0,s.join)(t,"..","..","src","computer-use",og))}var n;"string"==typeof process.argv[1]&&process.argv[1].length>0&&r((0,s.join)((0,s.dirname)(process.argv[1]),og)),r((0,s.join)(process.cwd(),"src","computer-use",og)),r((0,s.join)(process.cwd(),"computer-use",og));try{const e=(0,s.dirname)(ug().resolve("@anysphere/local-exec/package.json"));r((0,s.join)(e,"src","computer-use",og)),r((0,s.join)(e,"dist","computer-use",og))}catch{}for(const t of e)try{const e=ug()(t);if("object"==typeof e&&null!==e&&"importFile"in e&&"function"==typeof e.importFile)return e.importFile.bind(e)}catch{}throw new Error("mac-webp runtime importer was not found next to the bundle")}(),lg)}function hg(...e){return t=["@jsquash","webp",...e].join("/"),ug().resolve(t);var t}async function pg(...e){var t;return await(t=(0,Fu.pathToFileURL)(hg(...e)).href,dg()(t))}const fg=e=>{let t;return()=>{if(void 0===t){const r=e();r.catch((()=>{t===r&&(t=void 0)})),t=r}return t}},mg=(fg((async()=>{const e=await pg("decode.js");return await e.init({wasmBinary:await go.promises.readFile(hg("codec","dec","webp_dec.wasm"))}),e})),fg((async()=>{const[e,t,r]=await Promise.all([pg("utils.js"),pg("meta.js"),pg("codec","enc","webp_enc.js")]);return{module:await e.initEmscriptenModule(r.default,void 0,{wasmBinary:await go.promises.readFile(hg("codec","enc","webp_enc.wasm"))}),defaultOptions:t.defaultOptions}}))),gg="image/png",wg={async normalize(e){if(e.mimeType!==gg)throw new Error(`Mac screenshot must be ${gg}, received ${e.mimeType}`);const t=await rg(),r=await t.read(Buffer.from(e.data,"base64"));return(await(n={data:r.bitmap.data,width:r.bitmap.width,height:r.bitmap.height},(async e=>{const{module:t,defaultOptions:r}=await mg(),n=new Uint8ClampedArray(e.data.buffer,e.data.byteOffset,e.data.byteLength);return Buffer.from(t.encode(n,e.width,e.height,{...r,lossless:1,exact:1}))})(n))).toString("base64");var n}},yg={userFacing:function(e){if(e instanceof Zm&&e.userFacing&&e.message.trim().length>0&&!Bm(e.message))return e.message.trim()},isCaptureBlocked:function(e){return e instanceof Zm&&("computer_use_screenshot"===e.tool||"permission_required"===e.code)}},vg=new Set(["keys"]),bg=new Set(["matched","mismatch","unchecked"]),Sg=new Set(["no_text","password","control_keys","too_long","unreadable","moved","chromium","gecko"]),kg=new Set(["matched"]),_g=new Set(["too_long"]),Cg=new Set(["watched","fell_back","unavailable","over_budget"]);class Eg{constructor({ctx:e,actions:t,sidecar:r,errors:n,reportTyping:o}){this.startTime=Date.now(),this.typingNotes=[],this.typing=[],this.geometryPrimed=!1,this.actionCount=0,this.hasCompletedActuation=!1,this.staleAfterWait=!1,this.ctx=e,this.actions=t,this.sidecar=r,this.errors=n??yg,this.reportTyping=!0===o}async execute(){const e=this.actions.some((e=>Eg.isInputAction(e.action.case)));try{this.throwIfAborted(),e&&await this.sidecar.startControl(this.ctx);for(const e of this.actions){this.throwIfAborted();const t=e.action;if(void 0===t.case)throw new Error("Computer use action case is undefined");switch(this.actionCount+=1,t.case){case"screenshot":case"cursorPosition":await this.captureScreen();break;case"click":void 0!==t.value.coordinate&&await this.ensureGeometryCached(),this.recordActuation(await this.sidecar.click(this.ctx,{coordinate:t.value.coordinate,button:Eg.mouseButtonName(t.value.button),count:t.value.count>0?t.value.count:1,modifierKeys:t.value.modifierKeys}),t.value.coordinate);break;case"scroll":void 0!==t.value.coordinate&&await this.ensureGeometryCached(),this.recordActuation(await this.sidecar.scroll(this.ctx,{coordinate:t.value.coordinate,direction:Eg.scrollDirectionName(t.value.direction),amount:t.value.amount>0?t.value.amount:3,modifierKeys:t.value.modifierKeys}),t.value.coordinate);break;case"mouseMove":if(void 0===t.value.coordinate)throw new Error("MouseMoveAction requires coordinate");await this.ensureGeometryCached(),this.recordActuation(await this.sidecar.move(this.ctx,{x:t.value.coordinate.x,y:t.value.coordinate.y}),t.value.coordinate);break;case"mouseDown":this.recordActuation(await this.sidecar.mouseButton(this.ctx,{button:Eg.mouseButtonName(t.value.button),action:"down"}));break;case"mouseUp":this.recordActuation(await this.sidecar.mouseButton(this.ctx,{button:Eg.mouseButtonName(t.value.button),action:"up"}));break;case"drag":{const e=t.value.path.map((e=>({x:e.x,y:e.y})));await this.ensureGeometryCached(),this.recordActuation(await this.sidecar.drag(this.ctx,{button:Eg.mouseButtonName(t.value.button),path:e,modifierKeys:t.value.modifierKeys}),e.at(-1));break}case"type":{const e=await this.sidecar.typeText(this.ctx,t.value.text);this.recordActuation(e),this.recordTyping(e);break}case"key":if(t.value.stroke===Em.EB.DOWN||t.value.stroke===Em.EB.UP)throw new Error("Held keys (KeyAction.stroke DOWN/UP) are not supported by the computer-use sidecar; use hold_duration_ms");this.recordActuation(await this.sidecar.pressKey(this.ctx,{key:t.value.key,holdDurationMs:t.value.holdDurationMs}));break;case"wait":await this.delay(Math.max(0,t.value.durationMs)),this.staleAfterWait=!0;break;default:{const e=t;throw new Error(`Unknown computer use action: ${JSON.stringify(e)}`)}}}this.throwIfAborted(),(void 0===this.screenshot||this.staleAfterWait)&&await this.captureScreen(),this.throwIfAborted();const t=await this.normalizeRetainedScreenshots();return t.screenshotFailed&&!this.hasCompletedActuation?this.screenshotUnavailableResult(t.failureReason):(this.throwIfAborted(),new Em.ks({result:{case:"success",value:new Em.Wd({actionCount:this.actionCount,durationMs:Date.now()-this.startTime,screenshot:t.screenshot,cursorPosition:this.cursor,log:this.log(t.screenshotFailed?"Screenshot unavailable":void 0),typing:this.typing})}}))}catch(e){return this.ctx.signal.aborted?this.abortedResult():this.errorResult(e)}finally{e&&await this.sidecar.releaseControl(this.ctx)}}static isInputAction(e){switch(e){case"click":case"scroll":case"mouseMove":case"mouseDown":case"mouseUp":case"drag":case"type":case"key":return!0;default:return!1}}async captureScreen(){const e=await this.sidecar.screenshot(this.ctx);this.screenshot=e.screenshot,this.cursor=Eg.cursorFromResult(e)??this.cursor,this.geometryPrimed=!0,this.staleAfterWait=!1}async ensureGeometryCached(){this.geometryPrimed||await this.captureScreen()}recordActuation(e,t){this.screenshot=e.screenshot,this.hasCompletedActuation=!0,this.staleAfterWait=!1,void 0!==e.screenshot&&(this.geometryPrimed=!0),this.cursor=Eg.cursorFromResult(e)??Eg.coordinateFromPoint(t)??this.cursor}recordTyping(e){if(!this.reportTyping)return;const t=e.message.trim();""!==t&&this.typingNotes.push(t);const r=Eg.typingFromResult(e);void 0!==r&&this.typing.push(r)}log(e){const t=void 0===e?this.typingNotes:[...this.typingNotes,e];return 0===t.length?void 0:t.join("\n")}static typingFromResult(e){const t=e.structuredContent;if("object"!=typeof t||null===t||!("type"in t))return;const r=t.type;if("object"!=typeof r||null===r)return;const n=new Map(Object.entries(r)),o=(e,t)=>{const r=n.get(e);return"string"==typeof r&&t.has(r)?r:void 0},s=e=>{const t=n.get(e);return"number"==typeof t&&Number.isInteger(t)&&t>=0?t:void 0},i=o("check",bg),a=o("unchecked",Sg),c=void 0!==n.get("unchecked")&&null!==n.get("unchecked"),l=void 0!==i&&kg.has(i)&&!c||"unchecked"===i&&void 0!==a&&_g.has(a);return new Em.qA({method:o("method",vg)??"",chars:l?s("chars")??0:0,atoms:l?s("atoms")??0:0,typedAtoms:l?s("typedAtoms")??0:0,aborted:!0===n.get("aborted"),check:i,verified:l?s("verified"):void 0,unchecked:a,landing:o("landing",Cg)})}async errorResult(e){let t;if(Eg.logger.error(this.ctx,"local-cua execute failed",void 0,{error:Xm(e)}),!this.errors.isCaptureBlocked(e))try{const e=await this.sidecar.screenshot(this.ctx);t=(await this.normalizeScreenshot(e.screenshot,"error")).data}catch(e){Eg.logger.warn(this.ctx,"local-cua error screenshot capture failed",{error:Xm(e)})}const r=this.errors.userFacing(e);return new Em.ks({result:{case:"error",value:new Em.Jb({error:void 0===r?"Computer use failed":`Computer use failed: ${r}`,actionCount:this.actionCount,durationMs:Date.now()-this.startTime,screenshot:t,log:this.log(),typing:this.typing})}})}screenshotUnavailableResult(e){return new Em.ks({result:{case:"error",value:new Em.Jb({error:"Screenshot unavailable",actionCount:this.actionCount,durationMs:Date.now()-this.startTime,log:e})}})}abortedResult(){return new Em.ks({result:{case:"error",value:new Em.Jb({error:"Computer use aborted",actionCount:this.actionCount,durationMs:Date.now()-this.startTime,log:this.log(),typing:this.typing})}})}static mouseButtonName(e){return Eg.mouseButtonNames[e]??"left"}static scrollDirectionName(e){return Eg.scrollDirectionNames[e]??"down"}async normalizeRetainedScreenshots(){const e=await this.normalizeScreenshot(this.screenshot,"post-action");return{screenshot:e.data,screenshotFailed:void 0===this.screenshot||e.failed,failureReason:void 0===this.screenshot?"sidecar returned no image":e.reason}}async normalizeScreenshot(e,t){if(void 0===e)return{failed:!1};try{return{data:await wg.normalize(e),failed:!1}}catch(r){const n=Xm(r);return Eg.logger.error(this.ctx,"local-cua screenshot conversion failed",void 0,{frame:t,error:n}),"image/png"===e.mimeType&&e.data.length>0?{data:e.data,failed:!1}:{failed:!0,reason:n}}}static coordinateFromPoint(e){if(void 0!==e&&Number.isFinite(e.x)&&Number.isFinite(e.y))return new Em.xp({x:Math.round(e.x),y:Math.round(e.y)})}static cursorFromResult(e){const t=e.structuredContent;if("object"!=typeof t||null===t||!("cursor"in t))return;const r=t.cursor;return"object"==typeof r&&null!==r&&"x"in r&&"y"in r&&"number"==typeof r.x&&"number"==typeof r.y&&Number.isFinite(r.x)&&Number.isFinite(r.y)?new Em.xp({x:Math.round(r.x),y:Math.round(r.y)}):void 0}throwIfAborted(){if(this.ctx.signal.aborted)throw this.ctx.signal.reason??new Error("Computer use aborted")}delay(e){return this.throwIfAborted(),new Promise(((t,r)=>{const n=()=>{clearTimeout(o),r(this.ctx.signal.reason??new Error("Computer use aborted"))},o=setTimeout((()=>{this.ctx.signal.removeEventListener("abort",n),t()}),e);this.ctx.signal.addEventListener("abort",n,{once:!0}),this.ctx.signal.aborted&&n()}))}}Eg.logger=(0,l.h)("local-cua:actions"),Eg.mouseButtonNames={[Em.w3.UNSPECIFIED]:"left",[Em.w3.LEFT]:"left",[Em.w3.RIGHT]:"right",[Em.w3.MIDDLE]:"middle",[Em.w3.BACK]:"left",[Em.w3.FORWARD]:"left"},Eg.scrollDirectionNames={[Em.Dh.UNSPECIFIED]:"down",[Em.Dh.UP]:"up",[Em.Dh.DOWN]:"down",[Em.Dh.LEFT]:"left",[Em.Dh.RIGHT]:"right"},s.default.join(o.default.tmpdir(),"computer-use"),(0,l.h)("local-cua:windows");Error,Buffer.from([137,80,78,71,13,10,26,10]),new Set(["capture_failed","secure_desktop","input_desktop_unavailable","sidecar_unavailable","user_aborted","session_busy","canvas_mismatch"]);var xg,Pg=r("../proto/dist/generated/agent/v1/delete_exec_pb.js");function Ig({encoding:e,bom:t,lineEnding:r}){return{encoding:e,bom:t,lineEnding:r}}class Rg{constructor(e){this.workspacePath=e,this.changes=new Map,this.listeners=new Set}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}notify(e){for(const t of this.listeners)t(e)}async trackChange(e,t,r,n,o){const s=this.changes.get(e);if(s){const t=s.before,o=n||s.metadata;if(t===r||void 0===t&&void 0===r)this.changes.delete(e),this.notify();else{const n={path:e,before:t,after:r,metadata:o,...void 0===s.beforeFormat?{}:{beforeFormat:s.beforeFormat}};this.changes.set(e,n),this.notify(n)}}else{const s={path:e,before:t,after:r,metadata:n,...void 0===o?{}:{beforeFormat:o}};this.changes.set(e,s),this.notify(s)}}getChanges(){return Array.from(this.changes.values())}getChange(e){return this.changes.get(e)}hasChange(e){return this.changes.has(e)}accept(e){const t=this.changes.get(e);this.changes.delete(e),this.notify(t)}acceptAll(){this.changes.clear(),this.notify()}async reject(e){const t=this.changes.get(e);if(t)try{void 0===t.before&&void 0!==t.after?await(0,fo.unlink)(e):(void 0!==t.before&&void 0===t.after||void 0!==t.before&&void 0!==t.after)&&await async function(e,t,r,n){const{buffer:o,format:s}=await Mi(e,t,r,n);await(0,fo.writeFile)(e,o),await $i(e,{buffer:o,encoding:s.encoding})}(e,t.before,this.workspacePath)}catch{}finally{this.changes.delete(e),this.notify(t)}}async rejectAll(){const e=Array.from(this.changes.keys());await Promise.all(e.map((e=>this.reject(e))))}clear(){const e=this.changes.values().next().value;this.changes.clear(),this.notify(e)}get size(){return this.changes.size}dispose(){this.changes.clear(),this.listeners.clear()}}!function(e){e.Write="write",e.Read="read",e.Shell="shell",e.Delete="delete",e.Mcp="mcp"}(xg||(xg={}));var Tg=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class Ag{constructor(e,t,r,n,o,s){this.pendingDecisionProvider=e,this.fileChangeTracker=t,this.permissionsService=r,this.workspacePath=n,this.onDeleteForAiTracking=o,this.agentFileViews=s}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,$.VI)(e.withName("LocalDeleteExecutor.execute")),!1);const n=t.path;if(""===n.trim())return new Pg.Pi({result:{case:"error",value:new Pg.GU({path:n,error:qo})}});const o=(0,Ho.o1)(n,this.workspacePath),i=await this.permissionsService.shouldBlockWrite(e,o,"");if(i){const e=await lu(i,{onNeedsApproval:async(e,t)=>null,onUserRejected:e=>new Pg.Pi({result:{case:"rejected",value:new Pg.iq({path:o,reason:e||""})}}),onPermissionDenied:(e,t)=>new Pg.Pi({result:{case:"permissionDenied",value:new Pg.QG({path:o,clientVisibleError:e,isReadonly:t?.isReadonly??!1})}})});if(null!==e)return e}const a=await async function(e,t){const r=await(0,fo.realpath)((0,s.dirname)(e)).catch((()=>{}));if(void 0===r)return e;if(void 0!==t){const n=await(0,fo.realpath)(t).catch((()=>{}));if(void 0!==n&&(0,Ho.BJ)(r,n))return(0,s.resolve)(t,(0,s.relative)(n,r),(0,s.basename)(e))}return(0,s.join)(r,(0,s.basename)(e))}(o,this.workspacePath),c=await this.pendingDecisionProvider.requestApproval({type:xg.Delete,details:{path:a},toolCallId:t.toolCallId});if(!c.approved)return new Pg.Pi({result:{case:"rejected",value:new Pg.iq({path:o,reason:c.reason||""})}});let l;try{l=await(0,fo.stat)(o)}catch(e){return"ENOENT"===Ua(e)?new Pg.Pi({result:{case:"fileNotFound",value:new Pg.n0({path:o})}}):new Pg.Pi({result:{case:"error",value:new Pg.GU({path:o,error:Ba(e)})}})}if(!l.isFile()){const e=l.isDirectory()?"directory":"other";return new Pg.Pi({result:{case:"notFile",value:new Pg.LX({path:o,actualType:e})}})}const u=l.size;let d,h;if(u<=Vo)try{const e=await Ai(o);d=e.text,h=Ig(e)}catch{}const p=d??"",f=await(0,fo.realpath)(o).catch((()=>o)),m=await(0,fo.stat)(o).catch((()=>{}));if(m?.dev!==l.dev||m.ino!==l.ino)return new Pg.Pi({result:{case:"error",value:new Pg.GU({path:o,error:"File changed while deleting; nothing was removed"})}});e.signal.throwIfAborted();try{await(0,fo.unlink)(o),this.agentFileViews?.recordDelete(o)}catch(e){return"EACCES"===Ua(e)?new Pg.Pi({result:{case:"permissionDenied",value:new Pg.QG({path:o,clientVisibleError:"Permission denied"})}}):"EBUSY"===Ua(e)?new Pg.Pi({result:{case:"fileBusy",value:new Pg.vX({path:o})}}):new Pg.Pi({result:{case:"error",value:new Pg.GU({path:o,error:Ba(e)})}})}if(this.fileChangeTracker&&void 0!==d){const e={...t.toolCallId?{toolCallId:t.toolCallId}:{},...f===o?{}:{writtenPath:f},beforeMode:511&l.mode};await this.fileChangeTracker.trackChange(o,d,void 0,e,h)}return this.onDeleteForAiTracking&&this.onDeleteForAiTracking({path:o}).catch((()=>{})),new Pg.Pi({result:{case:"success",value:new Pg.fl({path:o,deletedFile:o,fileSize:BigInt(u),prevContent:p})}})}catch(e){r.error=e,r.hasError=!0}finally{Tg(r)}}}class $g{constructor(e,t){this.inner=e,this.extraTools=t}async getTools(e){return[...await this.inner.getTools(e).catch((()=>[])),...this.extraTools]}async getToolsForServers(e,t){const r=await this.inner.getToolsForServers(e,t).catch((()=>[])),n=new Set(t);return[...r,...this.extraTools.filter((e=>n.has(e.clientKey)||n.has(e.providerIdentifier)))]}async getClients(e){return this.inner.getClients(e)}async getClient(e,t){return this.inner.getClient(e,t)}async getInstructions(e){const t=await this.inner.getInstructions(e).catch((()=>[])),r=this.extraTools.filter((e=>e.providerIdentifier===Nn));if(0===r.length)return t;const n=r.map((e=>{const t="string"==typeof e.description&&e.description.length>0?e.description:"(no description provided)";return`- ${e.toolName}: ${t}`})).join("\n");return[...t,new fn.I0({serverIdentifier:Nn,serverName:Nn,instructions:`User-defined tools for this session (server "${Nn}"). Discover schemas via MCP meta-tool discovery for that server, then invoke via the MCP invocation meta-tool.\n\nAvailable tools:\n${n}`})]}async getToolSet(e){return this.inner.getToolSet(e)}}class Mg extends $g{constructor(e,t){super(e,t),this.observableInner=e}onDidChange(e){return this.observableInner.onDidChange(e)}}var Dg=r("../proto/dist/generated/agent/v1/fetch_exec_pb.js"),Og=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Fg=/;\s*charset\s*=\s*"?([^";\s]+)/i;class Ng{constructor(e){this.encodingSlices=e?.encodingSlices}async readText(e,t){if(!Qc(this.encodingSlices,e))return await t.text();const r=async function(e,t){if(void 0===e)return"unseen";try{return(0,n.isUtf8)(await e.arrayBuffer())?"utf8_valid":t?"declared_other":"utf8_invalid"}catch{return"unseen"}}(function(e){try{return e.clone()}catch{return}}(t),function(e){const t=Fg.exec(e.headers.get("content-type")??"")?.[1];return void 0!==t&&!/^utf-?8$/i.test(t)}(t)),o=await t.text();return this.recordFetched(e,o,r),o}async recordFetched(e,t,r){try{dl(this.encodingSlices,e,{layer:"exec_web_fetch",evidence:await r},t)}catch{}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,$.VI)(e.withName("LocalFetchExecutor.execute")),!1);const n=t.url;try{const t=await fetch(n),r=await this.readText(e,t),o=t.headers.get("content-type")||"text/plain";return new Dg.uN({result:{case:"success",value:new Dg.Uk({url:n,content:r,statusCode:t.status,contentType:o})}})}catch(e){return new Dg.uN({result:{case:"error",value:new Dg.fk({url:n,error:Ba(e)})}})}}catch(e){r.error=e,r.hasError=!0}finally{Og(r)}}}const Lg=[["safe.bareRepository","explicit"]],jg=[["core.fsmonitor","false"],["core.hooksPath",o.devNull],["core.attributesFile",o.devNull]],Ug=[["core.quotePath","false"]];function Bg(e){const t="allow-hooks"===e?jg.filter((([e])=>"core.hooksPath"!==e)):jg;return[...Lg,...t]}const Wg=(0,Fs.promisify)(gl.execFile),Hg=new Set(["-c","-C","--git-dir","--work-tree","--namespace","--super-prefix","--config-env","--attr-source"]),qg=new Set(["diff","show","blame","log","whatchanged"]);function zg(e){for(let t=0;t<e.length;t++){const r=e[t];if(Hg.has(r))t++;else if(!r.startsWith("-"))return t}return-1}function Gg(e){const t=zg(e);return-1===t?void 0:e[t]}function Vg(e){const t=zg(e);if(-1===t||!qg.has(e[t]))return e.slice();const r=[...e.slice(0,t+1),"--no-ext-diff","--no-textconv"];for(let n=t+1;n<e.length;n++){const t=e[n];"--ext-diff"!==t&&"--no-ext-diff"!==t&&"--textconv"!==t&&"--no-textconv"!==t&&r.push(t)}return r}function Kg(e,t){return function(e){const t={...process.env,...e.spawnerEnv,LC_ALL:"en_US.UTF-8",LANG:"en_US.UTF-8",GIT_PAGER:"cat",...e.optionsEnv};return void 0!==e.command?t.VSCODE_GIT_COMMAND=e.command:delete t.VSCODE_GIT_COMMAND,function(e,t){const r=function(e){const t=e.GIT_CONFIG_COUNT;if(void 0===t||""===t)return 0;const r=Number.parseInt(t,10);return!Number.isFinite(r)||r<0?0:r}(e),n={...e},o=new Set;for(let e=0;e<r;e++){const r=n[`GIT_CONFIG_KEY_${e}`];for(const[s,i]of t)r===s&&(n[`GIT_CONFIG_VALUE_${e}`]=i,o.add(s))}let s=r;for(const[e,r]of t)o.has(e)||(n[`GIT_CONFIG_KEY_${s}`]=e,n[`GIT_CONFIG_VALUE_${s}`]=r,s++);return s!==r&&(n.GIT_CONFIG_COUNT=String(s)),n}(t,[...Bg(e.repoConfigExecution??"block"),...Ug])}({command:Gg(e),optionsEnv:t})}async function Jg(e,t,r){const{env:n,encoding:o="utf8",...s}=r??{},i=Vg(t),a=await Wg(e,i,{...s,encoding:o,env:Kg(i,n)});return{stdout:a.stdout,stderr:a.stderr}}class Zg extends Error{constructor(e,t){super(`git did not run: repository config refused (${e})`),this.name="GitRepoConfigRefusedError",this.reason=e,this.exitCode=t}}const Xg=new Map([["status",[!0,!0]],["diff",[!0,!0]],["worktree",[!0,!1]],["read-tree",[!0,!1]],["ls-files",[!0,!1]],["branch",[!1,!1]],["check-attr",[!1,!1]],["check-ignore",[!1,!1]],["config",[!1,!1]],["merge-base",[!1,!1]],["patch-id",[!1,!1]],["remote",[!1,!1]],["rev-parse",[!1,!1]],["show",[!1,!1]],["symbolic-ref",[!1,!1]],["write-tree",[!1,!1]]]),Qg=["recurse-submodules","submodule","remerge-diff","diff-merges","alternate-refs"],Yg=/^[A-Za-z0-9][A-Za-z0-9_-]*$/,ew=/^filter\.(.*)\.(?:clean|smudge|process)$/s,tw=new Set(["system","global","command"]),rw={GIT_ALLOW_PROTOCOL:"",GIT_NO_LAZY_FETCH:"1",GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"",GIT_SSH_COMMAND:"ssh -o BatchMode=yes",GCM_INTERACTIVE:"Never",GIT_EDITOR:":",GIT_SEQUENCE_EDITOR:":",GIT_OPTIONAL_LOCKS:"0",GIT_LFS_SKIP_SMUDGE:"1",GIT_CONFIG:void 0};function nw(e){return e.flatMap((([e,t])=>["-c",`${e}=${t}`]))}const ow=nw([...Bg("block"),["submodule.recurse","false"],["fetch.recurseSubmodules","false"],["diff.submodule","short"],["status.submoduleSummary","false"],["log.showSignature","false"],["log.diffMerges","separate"],["gpg.openpgp.program",o.devNull],["gpg.x509.program",o.devNull],["gpg.ssh.program",o.devNull]]);function sw(e){const t=e?.timeout??0,r=Number.isFinite(t)&&t>0?Math.min(t,2147483647):6e4;return performance.now()+r}function iw(e,t=2147483647){return Math.max(1,Math.ceil(Math.min(t,e-performance.now())))}function aw(){const e=new Map;return{async exec(t,r,n){const o=sw(n);return Jg("git",await cw(e,t,r,o),{cwd:t,env:rw,windowsHide:!0,killSignal:"SIGTERM",timeout:iw(o)})},async run(t,r,n){const o=sw(n);return function(e,t,r,n){return new Promise(((o,s)=>{const i=function(e,t,r){const{env:n,...o}=r??{},s=Vg(t);return(0,gl.spawn)("git",s,{...o,env:Kg(s,n)})}(0,t,{cwd:e,env:rw,windowsHide:!0,stdio:[void 0===n?"ignore":"pipe","pipe","pipe"]}),a=[],c=[];let l=!1;const u=()=>{const e=!l;return l=!0,clearTimeout(d),e},d=setTimeout((()=>{u()&&(i.kill("SIGTERM"),i.stdin?.destroy(),i.stdout?.destroy(),i.stderr?.destroy(),s(Object.assign(new Error("git timed out"),{code:null,killed:!0,signal:"SIGTERM"})))}),iw(r));i.stdout?.on("data",(e=>{a.push(e)})),i.stderr?.on("data",(e=>{c.push(e)}));for(const e of[i.stdout,i.stderr])e?.on("error",(e=>{u()&&(i.kill("SIGTERM"),s(e))}));i.on("error",(e=>{u()&&s(e)})),i.on("close",((e,t)=>{u()&&(null!==e?o({exitCode:e,stdout:Buffer.concat(a).toString("utf8"),stderr:Buffer.concat(c).toString("utf8")}):s(Object.assign(new Error(`git was killed by ${String(t)}`),{code:e,killed:!1,signal:t})))})),void 0!==n&&null!==i.stdin&&(i.stdin.on("error",(()=>{})),i.stdin.end(n))}))}(t,await cw(e,t,r,o),o,n?.input)}}}async function cw(e,t,r,n){const{prefix:o,tail:s,readsConfig:i}=function(e){const t=Vg(e),r=zg(t),n=t.findIndex(((e,t)=>t>r&&("--"===e||"--end-of-options"===e))),o=t.slice(0,-1===n?t.length:n);if(o.includes("--help")||o.includes("-h"))throw new TypeError("git help is refused: it starts the repository's man viewer");if(-1===r)return{prefix:[],tail:t,readsConfig:!1};const s=t[r],i=Xg.get(s);if(void 0===i)throw new TypeError(`git ${s} is refused: the pins cover only a fixed set of verbs`);const[a,c]=i,l=o.find((e=>function(e,t,r){const n=r.startsWith("--")?r.slice(2).split("=",1)[0]:"",o=[...Qg,..."status"===e?["verbose"]:[],..."worktree"===e?["checkout","no-force"]:[],...t?["ignore-submodules","no-ignore-submodules"]:[]];return""!==n&&o.some((e=>e.startsWith(n)))||"status"===e&&/^-[^-]*v/.test(r)}(s,c,e)));if(void 0!==l)throw new TypeError(`git ${s} ${l} is refused: it can start a program the pins miss`);const u=t.slice(r+1),d="worktree"===s?u.find((e=>!e.startsWith("-"))):void 0;if("remove"===d&&!o.includes("--force")&&!o.includes("-f"))throw new TypeError("git worktree remove is refused without --force");if("add"===d&&"--no-checkout"!==u[u.indexOf("add")+1])throw new TypeError("git worktree add is refused unless --no-checkout follows add");return{prefix:[...t.slice(0,r),...ow],tail:[s,...c?["--ignore-submodules=dirty"]:[],...u],readsConfig:a}}(r),a=i?await function(e,t,r,n){const o=`${t}\0${r.join("\0")}`,s=e.get(o);if(void 0!==s)return s;const i=async function(e,t,r){let n;try{n=(await Jg("git",[...t,"config","--list","--show-scope","--includes","-z"],{cwd:e,env:rw,windowsHide:!0,killSignal:"SIGTERM",timeout:iw(r,1e4),maxBuffer:16777216})).stdout}catch(e){throw function(e){if(!(e instanceof Error))return new Zg("read-failed");if("syscall"in e&&"string"==typeof e.syscall&&e.syscall.startsWith("spawn"))return e;if("killed"in e&&!0===e.killed)return new Zg("timed-out");const t="code"in e&&"number"==typeof e.code?e.code:void 0;return new Zg("read-failed",t)}(e)}if(performance.now()>=r)throw new Zg("timed-out");return function(e){if(""===e)return[];const t=e.split("\0");if(""!==t.pop()||t.length%2!=0)throw new Zg("read-failed");const r=new Set;for(let e=0;e<t.length;e+=2){if(tw.has(t[e]))continue;const n=t[e+1].split("\n",1)[0],o=ew.exec(n)?.[1];if(void 0!==o){if(!Yg.test(o))throw new Zg("unpinnable");r.add(o)}else(n.startsWith("lfs.extension.")||"lfs.storage"===n)&&r.add("lfs")}return[...r].sort().flatMap((e=>nw([[`filter.${e}.clean`,""],[`filter.${e}.smudge`,""],[`filter.${e}.process`,""],[`filter.${e}.required`,"false"]])))}(n)}(t,r,n);return e.set(o,i),i}(e,t,o,n):[];return[...o,...a,...s]}function lw(e,t,r){return aw().exec(e,t,r)}var uw=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class dw{async exec(e,t,r,n){return hw(e,t,r,n,lw)}forRequest(){const e=aw();return{exec:(t,r,n,o)=>hw(t,r,n,o,((t,r,n)=>e.exec(t,r,n)))}}}async function hw(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(s,(0,$.VI)(e.withName("LocalGitExecutor.exec"),{attributes:{"git.cwd":t,"git.args":r,"git.caller":n?.caller}}),!1);const{stdout:i,stderr:a}=await o(t,r,{timeout:n?.timeout});return{exitCode:0,stdout:i,stderr:a}}catch(e){s.error=e,s.hasError=!0}finally{uw(s)}}var pw=r("../proto/dist/generated/agent/v1/grep_exec_pb.js");class fw{constructor(){this.lineEnd=0,this.nextStart=0}}function mw(e,t,r){const n=e.length;if(t>=n)return!1;const o=e.indexOf("\n",t);if(-1!==o){const n=o>t&&13===e.charCodeAt(o-1);return r.lineEnd=n?o-1:o,r.nextStart=o+1,!0}return r.lineEnd=n,r.nextStart=n,!0}function gw(e,t,r,n,o,s){const i=e.indexOf("\0",t);if(-1===i||i>=r)return;let a=i+1;for(;a<r&&e.charCodeAt(a)>=48&&e.charCodeAt(a)<=57;)a++;if(a===i+1||a>=r)return;const c=e.charCodeAt(a);if(58!==c&&45!==c)return;const l=n.indexOf(0,o);if(-1===l||l>=s)return;const u=l+(a-i);return u>=s||n.toString("latin1",l+1,u+1)!==e.slice(i+1,a+1)?void 0:{file:e.slice(t,i),contentStart:a+1,contentEnd:r,contentBytesStart:u+1,contentBytesEnd:s}}const ww=-(2**31),yw=2**31-1;function vw(e){return Number.isNaN(e)?0:e<ww?ww:e>yw?yw:e}function bw(e){if("number"==typeof e&&Number.isFinite(e)&&!(e<0))return vw(Math.trunc(e))}function Sw(e){const t=e.replace(/\s/g,"_").replace(/[^a-zA-Z0-9_.-]/g,"").replace(/\.+/g,".");return"."===t||".."===t?t.replace(/\./g,"_"):0===t.length?"_":t}async function kw(e,t){const r=Sw(t),n=(0,s.join)(e,"mcps",r,"tools");let o;try{o=await(0,fo.readdir)(n)}catch(e){if("ENOENT"===Ua(e))return{toolNames:[],toolsDirExists:!1};throw e}const i=await Promise.all(o.map((async e=>{if(e.endsWith(".json"))try{return function(e){try{const t=JSON.parse(e);return"string"==typeof t.name&&t.name.length>0?t.name:"string"==typeof t.toolName&&t.toolName.length>0?t.toolName:void 0}catch{return}}(await(0,fo.readFile)((0,s.join)(n,e),"utf8"))}catch{return}}))),a=new Set;for(const e of i)e&&a.add(e);return{toolNames:Array.from(a).sort(((e,t)=>e.localeCompare(t))),toolsDirExists:!0}}const _w=(0,l.h)("local-exec:mcp-disk-freshness-on-access"),Cw="/mcps/",Ew=(0,u.Pu)("mcp.discovery_freshness.check",{description:"MCP discovery surface freshness comparison outcome against canonical live tools",labelNames:["surface","outcome"]}),xw=(0,u.v5)("mcp.discovery_freshness.missing_tools",{description:"Number of tools present in canonical live state but missing from the observed discovery surface",labelNames:["surface"]}),Pw=(0,u.v5)("mcp.discovery_freshness.extra_tools",{description:"Number of tools present on the observed discovery surface but absent from canonical live state",labelNames:["surface"]}),Iw=(0,u.v5)("mcp.discovery_freshness.symmetric_difference",{description:"Total symmetric difference between canonical live tools and the observed discovery surface",labelNames:["surface"]}),Rw=new Map;function Tw(e){const t=e.replace(/\\/g,"/");return t.endsWith("/mcps")?`${t}/`:t}async function Aw({ctx:e,mcpStateAccessor:t,projectDir:r,sanitizedServerFolder:n,readDiskCatalog:o,state:s}){let i=s;if(void 0===i)try{i=await t.getState(e)}catch(t){return void _w.warn(e,"mcp_disk_state_read_failed",{error_type:t instanceof Error?t.name:typeof t})}const a=i.servers.find((e=>Sw(e.serverIdentifier)===n));if(void 0===a)return;let c;try{c=await o(r,a.serverIdentifier)}catch(t){return void _w.warn(e,"mcp_disk_catalog_read_failed",{error_type:t instanceof Error?t.name:typeof t})}if(!c.toolsDirExists)return;const l=a.tools.map((e=>e.toolName)).filter((e=>e.length>0)).sort(((e,t)=>e.localeCompare(t)));!function({ctx:e,serverIdentifier:t,canonicalToolNames:r,observedToolNames:n}){const o=new Set(n),s=new Set(r),i=r.filter((e=>!o.has(e))),a=n.filter((e=>!s.has(e))),c=0===i.length&&0===a.length?"match":"mismatch",l={surface:"disk"};Ew.increment(e,1,{...l,outcome:c}),xw.histogram(e,i.length,l),Pw.histogram(e,a.length,l),Iw.histogram(e,i.length+a.length,l),"mismatch"===c&&_w.warn(e,"mcp_disk_discovery_freshness_mismatch",{server_identifier:t,missing_tool_count:i.length,extra_tool_count:a.length})}({ctx:e,serverIdentifier:a.serverIdentifier,canonicalToolNames:l,observedToolNames:c.toolNames})}function $w(e,t,r,n=kw){if(void 0===r||(void 0===(o=r)||!Tw(o).includes(Cw)))return;var o;const s=function(e){const t=Tw(e),r=t.indexOf(Cw);if(-1===r)return;const n=t.slice(0,r),o=t.slice(r+6).split("/").filter(Boolean);return 0!==n.length?0===o.length?{projectDir:n,kind:"mcps_root"}:{projectDir:n,kind:"server",sanitizedServerFolder:o[0]}:void 0}(r);if(void 0===s)return;let i,a;const c="mcps_root"===s.kind;"mcps_root"===s.kind?(i=`${s.projectDir}\0__mcps_root__`,a=void 0):(i=`${s.projectDir}\0${s.sanitizedServerFolder}`,a=s.sanitizedServerFolder);const l=Rw.get(i);void 0!==l&&clearTimeout(l);const u=e,d=setTimeout((()=>{Rw.delete(i),(async()=>{if(c){const e=await t.getState(u);for(const r of e.servers){const o=Sw(r.serverIdentifier);await Aw({ctx:u,mcpStateAccessor:t,projectDir:s.projectDir,sanitizedServerFolder:o,readDiskCatalog:n,state:e})}}else void 0!==a&&await Aw({ctx:u,mcpStateAccessor:t,projectDir:s.projectDir,sanitizedServerFolder:a,readDiskCatalog:n})})().catch((e=>{_w.warn(u,"mcp_disk_discovery_freshness_schedule_failed",{error_type:e instanceof Error?e.name:typeof e})}))}),2e3);Rw.set(i,d)}async function Mw(e){try{return(await(0,fo.stat)(e,{bigint:!0})).mtimeNs}catch{return}}function Dw(e,t,r){const n=e.map(((e,n)=>({file:e,mtime:t[n],segments:e.path.split(r)})));return n.sort(((e,t)=>e.mtime!==t.mtime?void 0===e.mtime?1:void 0===t.mtime||e.mtime>t.mtime?-1:1:function({left:e,right:t}){const r=Math.min(e.length,t.length);for(let n=0;n<r;n++){const r=e[n]??"",o=t[n]??"";if(r!==o)return r<o?-1:1}return e.length-t.length}({left:e.segments,right:t.segments}))),n.map((e=>e.file))}async function Ow(e,t,r=Mw){const n=e.map((e=>({item:e,path:t(e)})));let o;try{o=await(0,Dr.wj)(Promise.all(n.map((({path:e})=>r(e)))),2e3,"stat timed out")}catch(t){if(t instanceof Dr.MU)return{items:[...e],statTimedOut:!0};throw t}return{items:Dw(n,o,s.sep).map((({item:e})=>e)),statTimedOut:!1}}var Fw=r("../proto/dist/generated/agent/v1/read_exec_pb.js");const Nw=Buffer.from([137,80,78,71,13,10,26,10]),Lw=Buffer.from([0,0,0,0,73,69,78,68,174,66,96,130]),jw=e=>{if(e.length<Nw.length+25+Lw.length||!e.subarray(0,Nw.length).equals(Nw)||13!==e.readUInt32BE(8)||"IHDR"!==e.toString("ascii",12,16)||!(e=>e.subarray(e.length-Lw.length).equals(Lw)||(e=>{let t=Nw.length+25;for(;t+Lw.length<=e.length;){const r=e.readUInt32BE(t);if(r>e.length-t-Lw.length)return!1;if("IEND"===e.toString("ascii",t+4,t+8))return e.subarray(t,t+Lw.length).equals(Lw);t+=Lw.length+r}return!1})(e))(e))return;const t=e.readUInt32BE(16),r=e.readUInt32BE(20);return t<1||r<1?void 0:{width:t,height:r,colorType:e.readUInt8(25)}},Uw=e=>1===e||e>=208&&e<=216,Bw=e=>192===e||193===e||194===e,Ww=e=>e>=195&&e<=207&&196!==e&&200!==e&&204!==e,Hw=e=>0===e||e>=208&&e<=215,qw=(e,t)=>{let r=e.indexOf(255,t);for(;-1!==r&&r+1<e.length;){const t=e[r+1];if(255!==t){if(!Hw(t))return r;r=e.indexOf(255,r+2)}else r+=1}},zw=e=>(e=>{const t=jw(e);if(void 0!==t)return{mimeType:"image/png",width:t.width,height:t.height}})(e)??(e=>{if(e.length<4||255!==e[0]||216!==e[1]||!(e=>255===e[e.length-2]&&217===e[e.length-1]||(e=>{let t=2;for(;t+2<=e.length;){if(255!==e[t])return!1;const r=e[t+1];if(255===r){t+=1;continue}if(217===r)return!0;if(Uw(r)){t+=2;continue}if(t+4>e.length)return!1;const n=e.readUInt16BE(t+2);if(n<2)return!1;const o=t+2+n;if(218!==r){t=o;continue}const s=qw(e,o);if(void 0===s)return!1;t=s}return!1})(e))(e))return;let t=2;for(;t+4<=e.length;){if(255!==e[t])return;const r=e[t+1];if(255===r){t+=1;continue}if(Uw(r)){t+=2;continue}if(218===r||217===r||Ww(r))return;const n=e.readUInt16BE(t+2);if(n<2)return;if(Bw(r)){if(n<8||t+9>e.length)return;const r=e.readUInt16BE(t+5),o=e.readUInt16BE(t+7);if(o<1||r<1)return;return{mimeType:"image/jpeg",width:o,height:r}}t+=2+n}})(e),Gw=(e,t)=>({width:Math.max(e?.width??0,t.width),height:Math.max(e?.height??0,t.height)}),Vw=(e,t)=>{for(;t<e.length&&0!==e[t];)t+=1+e[t];return t+1},Kw=e=>{const t=e.toString("latin1",0,6);return e.subarray(0,Nw.length).equals(Nw)?"png":t.startsWith("ÿØÿ")?"jpeg":"GIF87a"===t||"GIF89a"===t?"gif":t.startsWith("BM")?"bmp":t.startsWith("II*\0")||t.startsWith("MM\0*")?"tiff":t.startsWith("ID3")?"id3":void 0},Jw={0:1,2:3,4:2,6:4},Zw=({filter:e,row:t,previous:r,bytesPerPixel:n})=>{if(0!==e)for(let o=0;o<t.length;o++){const s=o>=n?t[o-n]:0,i=r[o];switch(e){case 1:t[o]+=s;break;case 2:t[o]+=i;break;case 3:t[o]+=s+i>>1;break;case 4:{const e=o>=n?r[o-n]:0,a=s+i-e,c=Math.abs(a-s),l=Math.abs(a-i),u=Math.abs(a-e);t[o]+=c<=l&&c<=u?s:l<=u?i:e;break}default:throw new Error(`unknown PNG filter type ${e}`)}}},Xw=({row:e,channels:t,columnOf:r,sums:n,counts:o})=>{const s=t<3;for(let i=0,a=0;i<r.length;i++,a+=t){const c=e[a],l=s?c:e[a+1],u=s?c:e[a+2],d=2===t?e[a+1]:4===t?e[a+3]:255,h=4*r[i];n[h]+=c*d,n[h+1]+=l*d,n[h+2]+=u*d,n[h+3]+=d,o[r[i]]++}},Qw=({out:e,outY:t,width:r,sums:n,counts:o})=>{for(let s=0;s<r;s++){const i=4*s,a=n[i+3],c=4*(t*r+s);a>0&&(e[c]=Math.round(n[i]/a),e[c+1]=Math.round(n[i+1]/a),e[c+2]=Math.round(n[i+2]/a),e[c+3]=Math.round(a/o[s]))}n.fill(0),o.fill(0)},Yw={0:1,2:3,3:1,4:2,6:4},ey=[1,2,4,8,16],ty=[[0,0,8,8],[4,0,8,8],[0,4,4,8],[2,0,4,4],[0,2,2,4],[1,0,2,2],[0,1,1,2]],ry=async e=>{const t=ny(e);if(void 0===t)return;const r=oy(t);let n=0;const o=Hh.Readable.from(t.idat).pipe((0,zh.createInflate)());for await(const e of o)if(n+=e.length,n>=r)return void o.destroy();throw new Error(`PNG pixel data ends after ${n} of ${r} bytes`)},ny=e=>{let t;const r=[];let n=8;for(;n+12<=e.length;){const o=e.readUInt32BE(n),s=e.toString("ascii",n+4,n+8),i=e.subarray(n+8,n+8+o);if("IHDR"===s&&void 0===t&&13===i.length){const e=Yw[i[9]];if(void 0===e||!ey.includes(i[8])||i[12]>1)return;t={width:i.readUInt32BE(0),height:i.readUInt32BE(4),bitsPerPixel:e*i[8],interlaced:1===i[12]}}else if("IDAT"===s)r.push(i);else if("IEND"===s)break;n+=o+12}return void 0===t||0===r.length?void 0:{...t,idat:r}},oy=({width:e,height:t,bitsPerPixel:r,interlaced:n})=>{const o=(e,t)=>e<=0||t<=0?0:t*(1+Math.ceil(e*r/8));return n?ty.reduce(((r,[n,s,i,a])=>r+o(Math.ceil((e-n)/i),Math.ceil((t-s)/a))),0):o(e,t)};const sy=()=>{throw new Error("webp codec not registered: registerWebpCodec() must be called by a Node server before decoding/encoding webp")},iy=e=>e.length>=12&&"RIFF"===e.toString("ascii",0,4)&&"WEBP"===e.toString("ascii",8,12),ay=e=>{if(!iy(e)||e.length<16)return;const t=e.toString("ascii",12,16);if("VP8 "===t){if(e.length<30||157!==e[23]||1!==e[24]||42!==e[25])return;return{width:16383&(e[26]|e[27]<<8),height:16383&(e[28]|e[29]<<8)}}if("VP8L"===t){if(e.length<25||47!==e[20])return;const t=(e[21]|e[22]<<8|e[23]<<16|e[24]<<24)>>>0;return{width:1+(16383&t),height:1+(t>>14&16383)}}if("VP8X"===t){if(e.length<30)return;return{width:1+(e[24]|e[25]<<8|e[26]<<16),height:1+(e[27]|e[28]<<8|e[29]<<16)}}},cy=e=>sy().decode(e);async function ly(e){((e,t)=>{if(!Number.isSafeInteger(e)||e<1||e>t)throw new Error("pngByteBudgetBytes must be a positive integer at most MAX_IMAGE_SIZE_BYTES")})(e.budgetBytes,e.maxImageBytes);zw(e.data);return e.resizeWithoutBudget(e.data)}const uy=[{width:1280,height:800},{width:1456,height:840}],dy=1048576,hy=e=>{const t=e.buffer;return t instanceof ArrayBuffer?new Uint8Array(t,e.byteOffset,e.byteLength):Uint8Array.from(e)};function py(e,t,r=1024){if(e<1||t<1)return{width:e,height:t,needsResize:!1};const n=Math.max(e,t);if(n<=r)return{width:e,height:t,needsResize:!1};const o=Math.min(e,t);if(o<8)return{width:e,height:t,needsResize:!1};let s=r/n,i=Math.max(1,Math.round(e*s)),a=Math.max(1,Math.round(t*s));return(i<8||a<8)&&(s=8/o,i=Math.max(8,Math.round(e*s)),a=Math.max(8,Math.round(t*s))),{width:i,height:a,needsResize:i!==e||a!==t}}const fy=(e,t,r=1024)=>py(e,t,r),my=(e,t,r)=>{e.resize({w:t,h:r})};function gy(e){if(void 0===e)throw new Error("image dimensions could not be read before decoding");const{width:t,height:r}=e;if(!(t*r<=178956970))throw new Error(`image dimensions ${t}x${r} exceed the 178956970 pixel decode limit`);if(!(Math.max(t,r)<=1e6))throw new Error(`image dimensions ${t}x${r} exceed the 1000000 pixel side limit`)}const wy=(e,t)=>{switch(t){case"tiff":throw new Error("TIFF images are not supported; convert the image to PNG or JPEG");case"id3":throw new Error("images that start with an ID3 tag are not supported");case"jpeg":return;default:gy(((e,t)=>{switch(t){case"png":return(e=>{let t,r=Nw.length;for(;r+16<=e.length;)"IHDR"===e.toString("ascii",r+4,r+8)&&(t=Gw(t,{width:e.readUInt32BE(r+8),height:e.readUInt32BE(r+12)})),r+=12+e.readUInt32BE(r);return t})(e);case"gif":return(e=>{if(e.length<13)return;const t={width:e.readUInt16LE(6),height:e.readUInt16LE(8)};let r=13+(128&(n=e[10])?3<<1+(7&n):0);for(var n;r<e.length;){const n=r;if(44===e[n]&&n+10<=e.length)return Gw(t,{width:e.readUInt16LE(n+5),height:e.readUInt16LE(n+7)});if(33===e[n]&&249===e[n+1])r=n+8;else if(33===e[n]&&254===e[n+1])r=Vw(e,n+2);else{if(33!==e[n]||255!==e[n+1])break;r=11===e[n+2]?Vw(e,n+14):n+19}}return t})(e);case"bmp":return(e=>e.length<26?void 0:{width:e.readUInt32LE(18),height:Math.abs(e.readInt32LE(22))})(e)}})(e,t))}},yy=(e,t)=>{if(t)return{width:e.width,height:e.height};const{width:r,height:n}=fy(e.width,e.height,1280);return{width:r,height:n}},vy=async(e,t)=>{let{width:r,height:n}=e,o=await t({width:r,height:n});for(;o.length>dy&&r>8&&n>8;)r=Math.max(8,Math.round(.8*r)),n=Math.max(8,Math.round(.8*n)),o=await t({width:r,height:n});return{data:hy(o),mimeType:"image/webp",reencoded:!0}};const by=async(e,t)=>{if(void 0!==t?.pngByteBudgetBytes){const{pngByteBudgetBytes:r,...n}=t;return ly({data:e,budgetBytes:r,maxImageBytes:dy,fitImage:py,resizeWithoutBudget:e=>by(e,n)})}if(iy(e))return(async(e,t)=>{const r=ay(e);if(!0===t?.preserveWebpDimensions&&void 0!==r)return{data:hy(e),mimeType:"image/webp"};const n=void 0!==r&&uy.some((e=>e.width===r.width&&e.height===r.height));if(void 0!==r&&(n||!fy(r.width,r.height,1280).needsResize)&&e.length<=dy)return{data:hy(e),mimeType:"image/webp"};if("passthrough"===t?.webpWithoutCodec)return{data:hy(e),mimeType:"image/webp"};gy(r);const o=void 0;if(void 0!==o)return vy(yy(r,n),(t=>o({data:e,...t})));const s=await cy(e),i=(await rg()).fromBitmap({data:Buffer.from(s.data),width:s.width,height:s.height});return vy(yy(i.bitmap,n),(async e=>{return i.bitmap.width===e.width&&i.bitmap.height===e.height||my(i,e.width,e.height),t={data:i.bitmap.data,width:i.bitmap.width,height:i.bitmap.height},sy().encode(t);var t}))})(e,t);const r=zw(e);if(void 0!==r&&e.length<=dy&&!fy(r.width,r.height).needsResize)return{data:hy(e),mimeType:r.mimeType};const n=Kw(e);void 0!==n&&wy(e,n);const o=void 0===r?void 0:fy(r.width,r.height),s="image/png"===r?.mimeType&&!0===o?.needsResize?await(async({data:e,width:t,height:r})=>{const n=(e=>{let t;const r=[];let n=8;for(;n+12<=e.length;){const o=e.readUInt32BE(n),s=e.toString("ascii",n+4,n+8),i=e.subarray(n+8,n+8+o);if(i.length!==o)return;if("IHDR"===s){const e=Jw[i[9]];if(void 0!==t||13!==o||8!==i[8]||0!==i[12]||void 0===e)return;t={width:i.readUInt32BE(0),height:i.readUInt32BE(4),channels:e}}else if("IDAT"===s)r.push(i);else{if("tRNS"===s)return;if("IEND"===s)break}n+=o+12}return void 0===t||0===r.length?void 0:{...t,idat:r}})(e);if(void 0===n||t>n.width||r>n.height)return;const o=n.width*n.channels,s=new Uint32Array(n.width);for(let e=0;e<n.width;e++)s[e]=Math.floor(e*t/n.width);const i=new Float64Array(4*t),a=new Uint32Array(t),c=Buffer.alloc(t*r*4);let l=new Uint8Array(o),u=new Uint8Array(o),d=-1,h=0,p=0;const f=Hh.Readable.from(n.idat).pipe((0,zh.createInflate)());for await(const e of f){let f=0;for(;f<e.length&&p<n.height;){if(d<0){d=e[f++];continue}const m=Math.min(o-h,e.length-f);if(u.set(e.subarray(f,f+m),h),h+=m,f+=m,h<o)continue;Zw({filter:d,row:u,previous:l,bytesPerPixel:n.channels}),Xw({row:u,channels:n.channels,columnOf:s,sums:i,counts:a});const g=Math.floor(p*r/n.height);p++,p!==n.height&&Math.floor(p*r/n.height)===g||Qw({out:c,outY:g,width:t,sums:i,counts:a}),[l,u]=[u,l],d=-1,h=0}if(p===n.height)break}return p===n.height?{data:c,width:t,height:r}:void 0})({data:e,width:o.width,height:o.height}).catch((()=>{})):void 0;void 0===s&&"png"===n&&await ry(e);const i=await rg(),a=void 0===s?await i.read(e):i.fromBitmap(s),c=(e=>{switch(e.mime){case"image/png":default:return"image/png";case"image/bmp":return"image/bmp";case"image/tiff":return"image/tiff";case"image/x-ms-bmp":return"image/x-ms-bmp";case"image/gif":return"image/gif";case"image/jpeg":return"image/jpeg"}})(a),l=!0===t?.convertUnsupportedModelFormatsToPng&&"image/png"!==c&&"image/jpeg"!==c?"image/png":c,{width:u,height:d,needsResize:h}=fy(a.width,a.height);if(void 0===s&&!h&&e.length<=dy&&l===c)return{data:hy(e),mimeType:c};let p=u,f=d;h&&my(a,p,f);let m=await a.getBuffer(l);for(;m.length>dy&&p>8&&f>8;)p=Math.max(8,Math.round(.8*p)),f=Math.max(8,Math.round(.8*f)),my(a,p,f),m=await a.getBuffer(l);return{data:hy(m),mimeType:l,reencoded:!0}},Sy=async e=>{const t=Buffer.from(e.buffer,e.byteOffset,e.byteLength),r=Kw(t);let n;if(iy(t))return{kind:"unchecked"};if(void 0===r)return{kind:"unchecked"};{wy(t,r);const e=await rg();n=async()=>("png"===r&&await ry(t),e.read(t))}try{return await n(),{kind:"decodes"}}catch(e){return{kind:"undecodable",reason:e instanceof Error?e.message:String(e)}}},ky=BigInt(0),_y=BigInt(8),Cy=BigInt(16),Ey=BigInt(65535);function xy(e){const t=e.trim().toLowerCase();return t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t}function Py(e){const t=e.split(".");if(4!==t.length)return;let r=ky;for(const e of t){if(!/^\d{1,3}$/.test(e))return;const t=Number(e);if(!Number.isInteger(t)||t<0||t>255)return;r=r<<_y|BigInt(t)}return{version:4,value:r}}function Iy(e){if(0===e.length)return[];const t=[],r=e.split(":");for(let e=0;e<r.length;e++){const n=r[e];if(0===n.length)return;if(n.includes(".")){if(e!==r.length-1)return;const o=Py(n);if(!o)return;t.push(Number(o.value>>Cy&Ey)),t.push(Number(o.value&Ey))}else{if(!/^[0-9a-f]{1,4}$/i.test(n))return;t.push(Number.parseInt(n,16))}}return t}function Ry(e){return Py(e)??function(e){const t=xy(e);if(0===t.length||t.includes(":::"))return;const r=t.indexOf("::");if(-1===r){const e=Iy(t);if(!e||8!==e.length)return;return{version:6,value:e.reduce(((e,t)=>e<<Cy|BigInt(t)),ky)}}if(-1!==t.indexOf("::",r+1))return;const n=t.slice(0,r),o=t.slice(r+2),s=Iy(n),i=Iy(o);if(!s||!i)return;const a=s.length+i.length;return a>7?void 0:{version:6,value:[...s,...new Array(8-a).fill(0),...i].reduce(((e,t)=>e<<Cy|BigInt(t)),ky)}}(e)}function Ty(e,t){const r=xy(e),n=xy(t);if("*"===n)return!0;if(n.includes("/"))return function(e,t){const r=t.lastIndexOf("/");if(r<=0||r===t.length-1)return!1;const n=Ry(t.slice(0,r)),o=Ry(e);if(!n||!o||n.version!==o.version)return!1;const s=Number(t.slice(r+1)),i=4===n.version?32:128;if(!Number.isInteger(s)||s<0||s>i)return!1;const a=BigInt(i-s);return o.value>>a==n.value>>a}(r,n);if(n.startsWith("*.")){const e=n.slice(2);return r===e||r.endsWith(`.${e}`)}return r===n}function Ay(e,t){const r=function(e){const t=e.trim();if(0===t.length)return;const r=t.includes("://")?t:`https://${t}`;try{return new URL(r)}catch{return}}(e);return!!r&&function(e,t){return t.some((t=>Ty(e,t)))}(r.hostname,t)}new Set([1,2]);const $y="cursor/requiresConfirmation",My="https://grok.com/connectors-oauth-exchange-code/",Dy="https://x.com/i/connectors/oauth_callback",Oy="https://chat.x.com/connectors/oauth_callback",Fy="https://lite.x.com/i/connectors/oauth_callback",Ny={provider:"google-workspace",clientRegistration:"static",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!0,authorizationParams:{access_type:"offline",prompt:"select_account consent"}},Ly={provider:"x-money",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0,registeredAppRedirectUris:[My,Dy]},jy="x-cursor-auth";function Uy(e){if(void 0===e)return;let t;try{t=new URL(e)}catch{return}const r=/^\/rest-mcp\/([^/]+)\/mcp\/?$/.exec(t.pathname);return r?.[1]}new Set(Object.values({notConnected:"scm_not_connected",tokenUnavailable:"scm_token_unavailable",tokenRejected:"scm_token_rejected",repoNotAccessible:"scm_repo_not_accessible",orgBlocked:"scm_org_blocked"})),new Set(Object.values({originNotEnabled:"origin_not_enabled",teamDisabled:"team_disabled",admissionRejected:"admission_rejected"}));const By="https://mcp.shop.com",Wy={provider:"grok-connectors",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,scopes:["grok-plugins:access","offline_access"]},Hy=new Map([["mcp.slack.com",{displayName:"Slack",baseScopes:["canvases:read","canvases:write","channels:history","channels:read","channels:write","chat:write","emoji:read","files:read","files:write","groups:history","groups:read","im:history","im:read","im:write","lists:read","lists:write","mpim:history","mpim:read","mpim:write","reactions:read","reactions:write","search:read.files","search:read.im","search:read.mpim","search:read.private","search:read.public","search:read.users","users:read","users:read.email"],stepUpScopes:{"groups:write":{action:"create private channels",tools:[{name:"slack_create_conversation",args:{is_private:!0}}]}},missingScopeAnswer:/\bmissing_scope\b/}]]),qy=new Map([["gmailmcp.googleapis.com",{...Ny,scopes:["https://www.googleapis.com/auth/gmail.readonly","https://www.googleapis.com/auth/gmail.compose","https://www.googleapis.com/auth/gmail.modify"]}],["drivemcp.googleapis.com",{...Ny,scopes:["https://www.googleapis.com/auth/drive.readonly","https://www.googleapis.com/auth/drive.file"]}],["calendarmcp.googleapis.com",{...Ny,scopes:["https://www.googleapis.com/auth/calendar.events","https://www.googleapis.com/auth/calendar.calendarlist.readonly","https://www.googleapis.com/auth/calendar.events.readonly","https://www.googleapis.com/auth/calendar.events.freebusy"]}],["docsmcp.googleapis.com",{...Ny,scopes:["https://www.googleapis.com/auth/documents"]}],["sheetsmcp.googleapis.com",{...Ny,scopes:["https://www.googleapis.com/auth/spreadsheets"]}],["slidesmcp.googleapis.com",{...Ny,scopes:["https://www.googleapis.com/auth/presentations"]}],["bigquery.googleapis.com",{...Ny,scopes:["https://www.googleapis.com/auth/bigquery"]}],["api.x.com",{provider:"x",clientRegistration:"static",unauthenticatedConnect:!1,rejectsCustomSchemeRedirects:!1,pinsScopesOverConfiguredScopes:!0}],["mcp.money-dev.x.com",Ly],["mcp.money-staging.x.com",Ly],["mcp.money.x.com",Ly],["connectors-gateway.grok.gcp.mouseion.dev",Wy],["connectors-gateway.grok.com",Wy],["mcp.hubspot.com",{provider:"hubspot",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0}],["mcp.box.com",{provider:"box",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0}],["mcp.asana.com",{provider:"asana",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0,configuredSecretStaysOnBackend:!0}],["mcp.quickbooks.intuit.com",{provider:"quickbooks-online",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,requiresHostedCallback:!0,unauthenticatedConnect:!1,unauthenticatedEndpointBlocked:!0,backendOnlyTokenExchange:!0,scopes:["com.intuit.quickbooks.accounting","foundations.tools.businessreports.read","foundations.tools.bi-dashboard","foundations.tools.transactions.write","foundations.tools.companyprofile.read","foundations.tools.companyprofile.write","payroll.tools.tax.read","payroll.tools.employer.read","payroll.tools.employer.manage","payroll.tools.run.read","payroll.tools.run.manage","payroll.tools.employee.read","payroll.tools.employee.manage","worker-mgmt.tools.employee.read","worker-mgmt.tools.employee.manage","time-tracking.tools.timeentry.read","sales.tools.invoice.read","sales.tools.invoice","sales.tools.estimate.read","sales.tools.estimate","sales.tools.payment-link.read","sales.tools.payment-link","sales.tools.settings.read","sales.tools.settings","sales.tools.salesorder.read","sales.tools.salesorder","contact.tools.customer.read","contact.tools.customer","catalog.tools.item.read","catalog.tools.item","lending.tools.servicing.read","money-onboarding.tools.application"]}],["setup.shopify.com",{provider:"shopify",clientRegistration:"static",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!1}],["mcp.cloudflare.com",{provider:"cloudflare",clientRegistration:"dynamic",unauthenticatedConnect:!1,rejectsCustomSchemeRedirects:!1,scopes:["user:read","account:read","offline_access","d1.metadata_read","d1.read","d1.write","workers-scripts.read","workers-scripts.write","workers-routes.read","workers-routes.write","workers-tail.read","workers-kv-storage.metadata_read","workers-kv-storage.read","workers-kv-storage.write","workers-r2.metadata_read","workers-r2.read","workers-r2.write","workers-r2-bucket-item.read","workers-r2-bucket-item.write","workers-observability.read","workers-observability.write","dns.read","dns.write","zone.read","zone.write"],pinsScopesOverConfiguredScopes:!0,scopesPinGate:"mcp_cloudflare_api_oauth_scopes"}],["mcp.shop.com",{provider:"shop",clientRegistration:"static",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!0,requiresHostedCallback:!0,backendOnlyTokenExchange:!0,scopes:["openid","personal_agent"],pinsScopesOverConfiguredScopes:!0,authorizationParams:{resource:By}}],["api.elections.kalshi.com",{provider:"kalshi",clientRegistration:"dynamic",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!0}],["mcp.squarespace.com",{provider:"squarespace",clientRegistration:"dynamic",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!0}]]),zy=[".databricks.com",".azuredatabricks.net"];const Gy=/^\/sncapps\/mcp-server\/mcp\/[^/]+$/,Vy={provider:"databricks",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,requiresHostedCallback:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0,scopes:["ai-gateway","offline_access"],pinsScopesOverConfiguredScopes:!0},Ky={provider:"servicenow",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,unauthenticatedEndpointBlocked:!0,backendOnlyTokenExchange:!0,ownMcpJsonClientMayExchange:!0};function Jy(e){if(void 0===e)return;let t;try{t=new URL(e)}catch{return}return function(e){return"https:"===e.protocol&&""===e.port&&""===e.username&&""===e.password&&function(e){const t=e.toLowerCase();return!(!/^[a-z0-9.-]+$/.test(t)||t.includes("..")||t.startsWith("."))&&zy.some((e=>t.endsWith(e)&&t.length>e.length))}(e.hostname)&&"/ai-gateway/mcp-services/system.ai.genie_one_mcp"===e.pathname.replace(/\/+$/,"")}(t)?Vy:function(e){return"https:"===e.protocol&&""===e.port&&""===e.username&&""===e.password&&Gy.test(e.pathname.replace(/\/+$/,""))}(t)?Ky:(r=t.hostname,qy.get(r.toLowerCase()));var r}function Zy(e){return e.endsWith("/")?e:`${e}/`}async function Xy(e,t){if(void 0===t)return;const r=new URL(e),n=new URL(t);if(r.origin!==n.origin||!Zy(r.pathname).startsWith(Zy(n.pathname)))throw new Error(`Protected resource ${t} does not match expected ${r.href} (or origin)`);return n}const Qy=/^\/shops\/[A-Za-z0-9-]+\/mcp$/;function Yy(e){if(void 0!==e)try{return new URL(e)}catch{return}}async function ev(e,t){if(void 0===t)return;const r=new URL(e),n=Yy(t);if(void 0===n||n.origin!==r.origin||n.pathname!==r.pathname&&!Qy.test(n.pathname))throw new Error(`Protected resource ${t} does not match expected ${r.href} (or origin)`);return n}function tv(e){const t=Yy(e);return void 0===t?void 0:Hy.get(t.hostname.toLowerCase())}const rv=new Set([...qy].filter((([,e])=>"google-workspace"===e.provider)).map((([e])=>e))),nv="https://www.cursor.com/bot/mcp/oauth/callback",ov={portal:"https://www.cursor.com/agents/mcp/oauth/callback",grokBotBounce:nv},sv="tailnet_";new Set([`${sv}waiting_for_approval`,`${sv}tailnet_locked`,`${sv}joining`]);const iv="grokbot://mcp/oauth/callback",av="http://localhost:8787/callback",cv="gb";function lv(e){const t=new URL(av);return t.port=String(e),t.toString()}function uv(e){try{const t=new URL(e);if("http:"!==t.protocol)return!1;const r=t.hostname;return"localhost"===r||"127.0.0.1"===r||"[::1]"===r}catch{return!1}}function dv(e){const t=e.redirectUrl??av;if(!0!==e.loopbackIpv4||!uv(t))return t;const r=new URL(t);return r.hostname="127.0.0.1",r.toString()}function hv(e,t=ov){const r=new Set,n=void 0!==e&&uv(e);return e&&!n&&r.add(e),r.add(t.portal),e===iv&&r.add(t.grokBotBounce),r.add(av),e&&n&&r.add(e),Array.from(r)}function pv(e){var t;if(void 0!==e&&0!==e.length)try{const r=JSON.parse(e);if("object"==typeof(t=r)&&null!==t&&!Array.isArray(t))return r}catch{}}function fv(e){if(void 0===e)return{};const t={};"string"==typeof e.title&&e.title.length>0&&(t.title=No(e.title,256));for(const r of["readOnlyHint","destructiveHint","idempotentHint","openWorldHint"])"boolean"==typeof e[r]&&(t[r]=e[r]);return function(e){return!0===e?.[$y]}(e)&&(t[$y]=!0),0===Object.keys(t).length?{}:{annotationsJson:JSON.stringify(t)}}new Map([[cv,iv],["gw",My],["gd",av],["xa",Dy],["xc",Oy],["xl",Fy],...[18787,28787,31787].map((e=>[`gd${e}`,lv(e)]))]),new Map([[iv,cv],[nv,cv],[My,"gw"],[Dy,"xa"],[Oy,"xc"],[Fy,"xl"]]),dv({loopbackIpv4:!0});var mv=r("../mcp-core/dist/transport/mcp-url-utils.js");function gv(e){return e.trim().toLowerCase()}const wv="<no-mcp-tool-allowed>";function yv({mode:e,tools:t}){const r=(t??[]).map(gv).filter((e=>e.length>0)),n=void 0===e?void 0:gv(e);return"all"===n?{mode:"all"}:"reads"===n?{mode:"reads"}:r.length>0?{mode:"custom",tools:r}:{mode:"all"}}function vv(e,t){switch(e.mode){case"all":return!0;case"custom":return function(e,t){const r=gv(e);return 0!==r.length&&r!==wv&&t.some((e=>gv(e)===r))}(t.name,e.tools);case"reads":return void 0!==(r=t.annotations)&&!0!==r.destructiveHint&&!0===r.readOnlyHint;default:return e}var r}function bv(e,t){switch(t.mode){case"all":return[`${e}:*`];case"custom":return t.tools.filter((e=>gv(e)!==wv)).map((t=>`${e}:${t}`));case"reads":return[];default:return t}}const Sv=new Set(["ash","bash","csh","dash","fish","ksh","powershell","pwsh","sh","tcsh","zsh","cmd"]);function kv(e){return e.trim().split(/\s+/).filter(Boolean)}function _v(e){const t=function(e){const t=e.trim(),r=t[0];if('"'===r||"'"===r){const e=t.indexOf(r,1);if(-1!==e)return t.slice(0,e+1)}return kv(t)[0]}(e);if(!t)return!1;const r=t.replace(/^["']|["']$/g,"").replaceAll("\\","/").split("/"),n=(r[r.length-1]??"").replace(/\.exe$/i,"").toLowerCase();return Sv.has(n)}function Cv(e,t){if(e.length>t.length)return!1;for(let r=0;r<e.length;r++)if(e[r]!==t[r])return!1;return!0}function Ev(e,t){return e.commandName.localeCompare(t.commandName)}function xv(e){return e.split(" ")[0]??e}function Pv(e,t){return function(e,t){const r=function(e){const t=new Set,r=[];for(const n of e){const e=n.trim();if(!e||t.has(e))continue;t.add(e);const o=kv(e),s=o[0]??e;r.push({id:e,label:e,value:e,commandName:s,tokenCount:o.length,indentLevel:0,tokens:o,ancestorIds:[e]})}r.sort(Ev);for(let e=0;e<r.length;e++){const t=r[e],n=new Set(t.tokens);let o,s=!1;for(let i=0;i<e;i++){const e=r[i];if(e.commandName!==t.commandName)continue;if(e.tokenCount>=t.tokenCount)continue;let a=!0;for(const t of e.tokens)if(!n.has(t)){a=!1;break}if(!a)continue;const c=Cv(e.tokens,t.tokens);void 0!==o?e.tokenCount>o.tokenCount?(o=e,s=c):e.tokenCount===o.tokenCount&&c&&!s&&(o=e,s=!0):(o=e,s=c)}void 0!==o&&(t.indentLevel=o.indentLevel+1,t.ancestorIds=[...o.ancestorIds,t.id])}const n=r.filter((e=>!r.some((t=>t.id!==e.id&&t.tokenCount<e.tokenCount&&Cv(t.tokens,e.tokens))))).map((e=>e.id));return{options:r,defaultSelectedOptionIds:n}}(e),n=[...r.defaultSelectedOptionIds];if(!t||0===t.length)return{defaultSelectedOptionIds:n,hasClassifierSuggestions:!1};const o=[],s=new Set;for(const e of t){const t=r.options.find((t=>t.id===e));if(t){o.push(t.id),s.add(xv(t.id));continue}const n=r.options.filter((t=>t.id.startsWith(`${e} `)||t.id===e)),i=r.options.filter((t=>e.startsWith(`${t.id} `)||e===t.id));if(i.length>0){const e=i.reduce(((e,t)=>e.id.length>t.id.length?e:t));o.push(e.id),s.add(xv(e.id))}else if(n.length>0){const e=n.reduce(((e,t)=>e.id.length<t.id.length?e:t));o.push(e.id),s.add(xv(e.id))}}if(0===o.length)return{defaultSelectedOptionIds:n,hasClassifierSuggestions:!1};const i=n.filter((e=>!s.has(xv(e))));return{defaultSelectedOptionIds:[...new Set([...i,...o])],hasClassifierSuggestions:!0}}(e,t).defaultSelectedOptionIds}const Iv=["com.todesktop.230313mzl4w4u92","co.anysphere.cursor","com.anysphere.molten-glass"],Rv=["cursor","molten glass"];function Tv(e){return Iv.some((t=>e===t||e.startsWith(`${t}.`)))}const Av=[{bundleId:"com.apple.scripteditor2",name:"Script Editor"},{bundleId:"com.apple.automator",name:"Automator"},{bundleId:"com.apple.shortcuts",name:"Shortcuts"}],$v=[{bundleId:"com.apple.terminal",name:"Terminal"},{bundleId:"com.googlecode.iterm2",name:"iTerm",aliases:["iTerm2"]},{bundleId:"dev.warp.warp-stable",name:"Warp"},{bundleId:"dev.warp.warp-preview",name:"WarpPreview",aliases:["Warp Preview"]},{bundleId:"com.mitchellh.ghostty",name:"Ghostty"},{bundleId:"org.alacritty",name:"Alacritty"},{bundleId:"net.kovidgoyal.kitty",name:"kitty"},{bundleId:"com.github.wez.wezterm",name:"WezTerm"},{bundleId:"co.zeit.hyper",name:"Hyper"},{bundleId:"org.tabby",name:"Tabby"},...Av,{bundleId:Iv[0],name:"Cursor"}];function Mv(e){const t=e.toLowerCase(),r=(0,s.basename)(e,".app").toLowerCase(),n=$v.find((({bundleId:e,name:n,aliases:o=[]})=>e===t||[n,...o].some((e=>{const n=e.toLowerCase();return n===t||n===r}))));return void 0!==n?{bundleId:n.bundleId,name:n.name}:Tv(t)?{bundleId:t,name:"Cursor"}:[t,r].some((e=>Rv.some((t=>e===t||e.startsWith(`${t} `)))))?{bundleId:Iv[0],name:"Cursor"}:void 0}const Dv=new Set(["com.apple.systempreferences","com.apple.keychainaccess","com.apple.passwords","com.1password.1password","com.agilebits.onepassword7","com.bitwarden.desktop","com.lastpass.lastpass","org.keepassxc.keepassxc"]);function Ov(e){return Dv.has(e.toLowerCase())}function Fv(e){return`app/${e}`}function Nv(e){return"object"==typeof e&&null!==e}function Lv(e){return Uv.includes(e)}function jv(e){if(!Nv(e))return;const{appArg:t,appSelectorArgs:r,capturesScreen:n}=e;if("boolean"==typeof n){if(void 0!==r){if(void 0!==t||!Nv(r))return;const e={};for(const[t,n]of Object.entries(r)){if(!Lv(t)||"string"!=typeof n||0===n.length)return;e[t]=n}if(0===Object.keys(e).length)return;return{appSelectorArgs:e,capturesScreen:n}}return void 0===t?{capturesScreen:n}:"string"==typeof t&&t.length>0?{appArg:t,capturesScreen:n}:void 0}}const Uv=["pid","bundleId","path","appName"],Bv=/^[+-]?\d+$/;var Wv=r("../../node_modules/.pnpm/diff@8.0.3/node_modules/diff/libesm/patch/create.js");const Hv=".cursor/worktrees",qv=".grok/build-desktop/worktrees",zv="win32"===process.platform||"darwin"===process.platform,Gv=new Map;function Vv(e,t){if(!(0,Ho.BJ)(t,e))return;const r=(zv?(0,s.relative)(e.toLowerCase(),t.toLowerCase()):(0,s.relative)(e,t)).split(s.sep).filter(Boolean);return r.length>0?r:void 0}function Kv(e,t){const r=Vv(e,t);if(void 0!==r)return r;const n=function(e){if(Gv.has(e))return Gv.get(e);const t=[];let r,n=e;for(;;)try{const e=go.realpathSync.native(n);r=0===t.length?e:(0,s.join)(e,...t);break}catch(e){const r=Ua(e);if("ENOENT"!==r&&"ENOTDIR"!==r)break;const o=(0,s.dirname)(n);if(o===n)break;t.unshift((0,s.basename)(n)),n=o}return Gv.size>=64&&Gv.clear(),Gv.set(e,r),r}(e);var o,i;return void 0!==n&&(o=n,i=e,zv?o.toLowerCase()!==i.toLowerCase():o!==i)?Vv(n,t):void 0}function Jv(e){const t=e?.trim();return t&&".cursor"!==t?[".cursor",t]:[".cursor"]}function Zv(e,t){const r=(0,o.homedir)();return Jv(t?.dataFolderName).some((t=>void 0!==Kv((0,s.join)(r,t,"projects"),e)))}function Xv(e){const t=(0,o.homedir)();return[Hv,qv].some((r=>void 0!==Kv((0,s.join)(t,...r.split("/")),e)))}function Qv(e,t,r){const n=function(e,t){const r=(0,o.homedir)();for(const n of Jv(t?.dataFolderName)){const t=Kv((0,s.join)(r,n,"projects"),e);if(void 0!==t&&t.length>=2)return t[1]}}(e,r);return void 0!==n&&(zv?t.some((e=>e.toLowerCase()===n.toLowerCase())):t.includes(n))}function Yv(e,t,r){const n=Kv(e,t);if(void 0===n)return!1;const o=n[0];return zv?r.some((e=>e.toLowerCase()===o.toLowerCase())):r.includes(o)}const eb=/[\s"'`=/\\:;()[\]{},&|<>]/,tb="win32"===process.platform||"darwin"===process.platform;async function rb(e,t,r,n){const o=cb(await ab((0,s.join)(e,"gitdir")),"");if(void 0===o)return;const i=(0,s.resolve)(e,o);if(".git"!==(0,s.basename)(i)||(0,Os.$f)(i))return;const a=(0,s.dirname)(i);if(r&&Xv(a))return;const c=await lb(i);if(void 0===c)return;const l=(0,s.dirname)(c);if(r&&Xv(l))return;if(void 0!==n&&(u=db(a,l)?[l]:[a,l],d=n.command,!(void 0!==(h=n.realWorkingDirectory)&&u.some((e=>(0,Ho.BJ)(h,e)))||void 0!==d&&u.some((e=>{const t=(0,s.basename)(e);return t.length>0&&function(e,t){const r=tb?e.toLowerCase():e,n=tb?t.toLowerCase():t;let o=0;for(;;){const e=r.indexOf(n,o);if(-1===e)return!1;const t=0===e||eb.test(r[e-1]),s=e+n.length,i=s===r.length||eb.test(r[s]);if(t&&i)return!0;o=e+1}}(d,t)})))))return;var u,d,h;const p=await ib(i,c);return void 0!==p&&db(p.commonDir,t)?l:void 0}async function nb(e,t){const r=await(0,fo.readdir)(e).catch(ub);return void 0===r?[]:r.sort().slice(0,t)}function ob(e,t){return t.some((t=>(0,Ho.BJ)(t,e)))}async function sb(e){for(let t=e;;t=(0,s.dirname)(t)){if((0,Os.$f)(t))return;const e=(0,s.join)(t,".git"),r=await(0,fo.lstat)(e).catch(ub);if(r?.isFile())return(await ib(e))?.commonDir;if(r?.isDirectory())return e;if(void 0!==r||(0,s.dirname)(t)===t)return}}async function ib(e,t){const r=cb(await ab(e),"gitdir: ");if(void 0===r)return;const n=await lb((0,s.resolve)((0,s.dirname)(e),r));if(void 0===n||"worktrees"!==(0,s.basename)((0,s.dirname)(n)))return;const o=(0,s.dirname)((0,s.dirname)(n));if(".git"!==(0,s.basename)(o))return;const i=cb(await ab((0,s.join)(n,"commondir")),"");if(void 0===i)return;const a=await lb((0,s.resolve)(n,i));if(void 0===a||!db(a,o))return;const c=cb(await ab((0,s.join)(n,"gitdir")),"");if(void 0===c)return;const[l,u]=await Promise.all([lb((0,s.resolve)(n,c)),t??lb(e)]);return void 0!==l&&void 0!==u&&db(l,u)?{commonDir:o,realDotGit:u}:void 0}async function ab(e){const t=await(0,fo.lstat)(e).catch(ub);if(void 0!==t&&t.isFile()&&!(t.size>4096))return(0,fo.readFile)(e,"utf8").catch(ub)}function cb(e,t){const r=e?.split("\n",1)[0]?.replace(/\r$/,"");if(void 0===r||!r.startsWith(t))return;const n=r.slice(t.length);return n.length>0&&!n.includes("\0")?n:void 0}async function lb(e){if(!(0,Os.$f)(e))return(0,fo.realpath)(e).catch(ub)}function ub(e){const t=Ua(e);if(void 0===t||t.startsWith("ERR_"))throw e}function db(e,t){return tb?e.toLowerCase()===t.toLowerCase():e===t}function hb(e,t,r){return{resolvedPath:e,originalPath:t,resolution:r}}function pb(e){const t=Ua(e);switch(t){case"ENOENT":return{status:"newFile"};case"EACCES":case"EPERM":return{status:"permissionDenied",errno:t};case"ELOOP":return{status:"symlinkLoop",errno:t};default:return{status:"unknownError",errno:t??"UNKNOWN",message:Ba(e)}}}async function fb(e,t){const r=(0,Ho.o1)(e,t);try{return hb(await(0,fo.realpath)(r),r,{status:"resolved"})}catch(e){if("ENOENT"!==Ua(e))return hb(r,r,pb(e));try{if((await(0,fo.lstat)(r)).isSymbolicLink()){let e=null;try{e=await(0,fo.readlink)(r)}catch{}return hb(r,r,{status:"danglingSymlink",symlinkTarget:e})}try{return hb(await(0,fo.realpath)(r),r,{status:"resolved"})}catch(e){if("ENOENT"!==Ua(e))return hb(r,r,pb(e))}return hb(r,r,{status:"unknownError",errno:"ENOENT",message:"realpath returned ENOENT but lstat found a non-symlink entry"})}catch(e){return"ENOENT"===Ua(e)?async function(e){let t=(0,s.dirname)(e);const r=[(0,s.basename)(e)];for(;(0,s.dirname)(t)!==t;){try{const n=await(0,fo.realpath)(t);return hb((0,s.join)(n,...r),e,{status:"newFile"})}catch(t){if("ENOENT"!==Ua(t))return hb(e,e,pb(t))}r.unshift((0,s.basename)(t)),t=(0,s.dirname)(t)}return hb(e,e,{status:"newFile"})}(r):hb(r,r,pb(e))}}}function mb(e){return"resolved"===e.status||"newFile"===e.status}function gb(e,t){switch(t.status){case"resolved":case"newFile":return"";case"danglingSymlink":return`Write blocked: \`${e}\` is a dangling symlink${t.symlinkTarget?` (target: ${t.symlinkTarget})`:""}. Cannot verify it does not point to a protected file.`;case"permissionDenied":return`Write blocked: cannot verify \`${e}\` -- permission denied resolving symlinks (${t.errno}).`;case"symlinkLoop":return`Write blocked: \`${e}\` has a symlink loop (${t.errno}). Cannot verify target.`;case"unknownError":return`Write blocked: cannot verify \`${e}\` -- ${t.errno}: ${t.message}.`;default:return`Write blocked: unknown resolution status for \`${e}\`.`}}function wb({realAbsolutePath:e,setting:t,resolvedWorkspaceRoots:r,resolvedAllowFolders:n,resolvedAllowGlobs:o}){return!("workspace"!==t.boundary||yb(e,r)||yb(e,n)||bb(e,t.allowPaths)||bb(e,o))}function yb(e,t){return t.some((t=>(0,Ho.BJ)(e,t)))}function vb(e){return e.flatMap((e=>{const t=(0,Ho.jl)(e.trim());return!t.includes("*")&&(0,s.isAbsolute)(t)?[(0,s.resolve)(t)]:[]}))}function bb(e,t){const r="win32"===process.platform?Ho.oL:e=>e,n=r(e);return t.some((e=>{const t=(0,Ho.jl)(e.trim());return!(!t.includes("*")&&(0,s.isAbsolute)(t))&&is(r(t),n)}))}const Sb={caffeinate:{flags:["-d","-i","-m","-s","-u"],valueOptions:["-t","-w"]},command:{flags:["-p"],valueOptions:[],lookupFlags:["-v","-V"]},env:{flags:["-","-i","-0","-v","--ignore-environment","--null","--debug"],valueOptions:["-u","-C","--unset","--chdir"],assignments:!0,directoryOptions:["-C","--chdir"]},nice:{flags:[],valueOptions:["-n","--adjustment"],numericOption:!0},nohup:{flags:[],valueOptions:[]},stdbuf:{flags:[],valueOptions:["-i","-o","-e","--input","--output","--error"]},time:{flags:["-p"],valueOptions:[]},timeout:{flags:["-f","-p","-v","--foreground","--preserve-status","--verbose"],valueOptions:["-k","-s","--kill-after","--signal"],operands:1},xargs:{flags:["-0","-o","-p","-r","-t","-x","--null","--open-tty","--interactive","--no-run-if-empty","--verbose","--exit","--show-limits"],valueOptions:["-a","-d","-E","-I","-J","-L","-n","-P","-R","-S","-s","--arg-file","--delimiter","--max-args","--max-procs","--max-chars","--process-slot-var"],attachedValueOptions:["-e","-i","-l","--eof","--replace","--max-lines"],readsArguments:!0}};function kb(e){const t=[];let r=!0,n=!1,o=e;for(;;){const e=Sb[s.posix.basename(o.name)];if(void 0===e)return{command:o,wrapperForms:t,allowlistable:r,readsArguments:n};const i=_b(o.args,e);if("unreadable"===i)return{command:o,wrapperForms:t,allowlistable:!1,readsArguments:n};if("none"===i)return{command:o,wrapperForms:t,allowlistable:r,readsArguments:n};const[a,...c]=o.args.slice(i);if(void 0===a||!Ib(a))return{command:o,wrapperForms:t,allowlistable:!1,readsArguments:n};(o.name.includes("/")||o.args.slice(0,i).some((t=>Cb(t,e)||Eb(t.value,e))))&&(r=!1),n||=!0===e.readsArguments,t.push(o.fullText.trim()),o=new he.Pv({name:a.value,args:c,fullText:[a.value,...c.map((e=>e.value))].join(" ")})}}function _b(e,t){let r=0;for(;r<e.length;){const n=e[r];if(Cb(n,t))break;if(void 0===n||!Ib(n))return"unreadable";const o=n.value;if("--"===o){r++;break}if(!o.startsWith("-")||"-"===o&&!t.flags.includes("-"))break;if(t.lookupFlags?.includes(o))return"none";if(t.numericOption&&/^-[+-]?\d+$/.test(o)){r++;continue}const s=xb(o,e[r+1],t);if(void 0===s)return"unreadable";r+=s}const n=r+(t.operands??0);if(!e.slice(0,n).every(Pb))return"unreadable";for(r=n;r<e.length&&Cb(e[r],t);)r++;return r<e.length?r:"none"}function Cb(e,t){return!0===t.assignments&&/^[A-Za-z_][A-Za-z0-9_]*=/.test(e?.value??"")}function Eb(e,t){return(t.directoryOptions??[]).some((t=>t.startsWith("--")?e===t||e.startsWith(`${t}=`):/^-[^-]/.test(e)&&e.includes(t.slice(1))))}function xb(e,t,r){const n=e=>!0===r.attachedValueOptions?.includes(e);if(r.flags.includes(e)||n(e))return 1;if(e.startsWith("--")){const o=e.indexOf("=");if(-1!==o){const t=e.slice(0,o);return r.valueOptions.includes(t)||n(t)?1:void 0}if(!r.valueOptions.includes(e))return;return void 0===t?void 0:2}for(let o=1;o<e.length;o++){const s=`-${e[o]}`;if(n(s))return 1;if(r.valueOptions.includes(s))return o<e.length-1?1:void 0===t?void 0:2;if(!r.flags.includes(s))return}return 1}function Pb(e){return"raw_string"===e.type||!/[$`]/.test(e.value)&&("string"===e.type||!/[*?[]|\{[^}]*(,|\.\.)/.test(e.value))}function Ib(e){return("word"===e.type||"number"===e.type)&&!/[$`]/.test(e.value)}const Rb=/(?<![\w-])(?:rm|rmdir|rd|del|erase|ri|remove-item)(?![\w-])/i,Tb=/\s(?:-[dfiv]*r[dfiv]*|--recursive|-recurse|-recurs|-recur|-recu|-rec|-re)(?![\w-])/i;function Ab(e,t,r){const n=t.exec(e);return null!==n&&r.test(e.slice(n.index+n[0].length))}var $b=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},Mb=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Db=(0,l.h)("permissions-service"),Ob=(0,u.Pu)("local_exec.permissions.mcp_allowlist_check.result",{description:"Result of MCP allowlist checks at user and team levels per tool call. A fail falls through to approval; it is not a refusal.",labelNames:["allowlist_scope","outcome"]}),Fb=(0,u.Pu)("local_exec.permissions.mcp_admin_tool_limit.refused",{description:"MCP tool calls refused because the team's limit for the server leaves them out.",labelNames:["reason"]}),Nb=/[\p{Cc}\p{Bidi_Control}\p{Cs}]/gu,Lb=/^[\p{M}\p{Cf}\p{Default_Ignorable_Code_Point}\s]+/u,jb=/[^\p{M}\p{Cf}\p{Default_Ignorable_Code_Point}\s\u2800]/u;function Ub(e,t){for(const r of[e?.title,t?.title]){if("string"!=typeof r)continue;const e=No(r,1024).replace(Nb," ").replace(/\s+/g," ").replace(Lb,"").trim(),t=No(e,256).trimEnd();if(jb.test(t))return t}}function Bb(e,t){return{toolTitle:Ub(e,t),destructiveHint:"boolean"==typeof t?.destructiveHint?t.destructiveHint:void 0}}function Wb(e){return Promise.all(e.map((async e=>{const t=await fb(e);return mb(t.resolution)?t.resolvedPath:(0,Ho.o1)(e)})))}function Hb(e,t,r){return`${e} blocked: cannot verify ${t} \`${r}\` while resolving symlinks. This can happen when access is denied or the path contains a symlink loop.`}function qb(e){return[...new Set(e)]}function zb(){return{fdTargets:new Map([[0,"original-stdin"],[1,"original-stdout"],[2,"original-stderr"]])}}function Gb({basePath:e,targetPath:t,pathModule:r}){const n=r.resolve(e),o=r.resolve(t),s=r.relative(n,o);return""===s||".."!==s&&!s.startsWith(`..${r.sep}`)&&!r.isAbsolute(s)}function Vb(e){return">"===e||">>"===e||">|"===e||"&>"===e||"&>>"===e}function Kb(e){return"<"!==e.operator&&"<&"!==e.operator}function Jb(e){if(void 0===e||e.trim()!==e)return;const t=Number(e);return Number.isInteger(t)&&t>=0?t:void 0}function Zb(e){return"<<"===e.operator&&"heredoc_redirect"===e.targetNodeType&&1===e.destinationFds.length&&0===Number(e.destinationFds[0])&&void 0!==e.targetText}function Xb(e,t){return!(/^=|[~*?[{(#^`]/.test(e)||"\\"!==t.sep&&e.includes("\\"))}function Qb(e){return"word"===e.type||"number"===e.type?Xb(e.value,s)?e.value:void 0:"raw_string"===e.type||"string"===e.type&&!/[$`\\]/.test(e.value)?e.value.slice(1,-1):void 0}function Yb({command:e,readsArguments:t}){if(!function(e){const t=e.replace(/["']/g,"");return[t,t.replace(/\\/g,"")].some((e=>/^tee(?:-object)?(?:\.exe)?$/i.test(e.slice(Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"))+1))))}(e.name))return[];const r=e.args.map(Qb);return t?[...r,void 0]:r}async function eS({targetText:e,workingDirectory:t,rootDirectories:r,allowTmpRedirects:n,resolvePathForPermissions:o,pathModule:s,tempPathOptions:i}){if(""!==s.parse(e).root&&!s.isAbsolute(e))return;const a=await o(e,t);if(!mb(a.resolution))return;const c=[];for(const e of r){const t=await o(e);mb(t.resolution)&&c.push(t.resolvedPath)}return await async function({targetPath:e,rootPaths:t,pathModule:r}){if(e.split(r.sep).some((e=>".git"===e.toLowerCase())))return!0;for(const r of t)if(await(0,Eo.OK)(e,r).catch((()=>!0)))return!0;return!1}({targetPath:a.resolvedPath,rootPaths:c,pathModule:s})?void 0:c.some((e=>Gb({basePath:e,targetPath:a.resolvedPath,pathModule:s})))?"workspace-file":n&&!(0,Eo.dA)(a.originalPath)&&pS(a.resolvedPath,i)?"tmp-file":void 0}async function tS({parsingResult:e,workingDirectory:t,rootDirectories:r,allowTmpRedirects:n}){for(const i of e.executableCommands.map(kb).flatMap(Yb))if("/dev/null"!==i&&(void 0===i||!await eS({targetText:i,workingDirectory:t,rootDirectories:r,allowTmpRedirects:n,resolvePathForPermissions:fb,pathModule:s,tempPathOptions:{platform:process.platform,env:process.env,pathModule:s,homeDirectory:(0,o.homedir)()}})))return!1;return!0}function rS(e){return qb(e.map((e=>e.trim())).filter(Boolean))}function nS(e){const t=e.name.trim();if(!t)return[];const r=e.arguments.map((e=>e.trim())).filter(Boolean),n=r.length>0?`${t} ${r.join(" ")}`:t,o=e.subcommandTokens.map((e=>e.trim())).filter(Boolean);if(0===o.length)return[n];const s=`${t} ${o.join(" ")}`;return s===n?[n]:[n,s]}function oS(e,t){const r=t.trim();return!!r&&e.some((e=>e===r||e.startsWith(`${r} `)))}function sS(e){const t=e.name.trim(),r=e.arguments.map((e=>e.trim())).filter(Boolean).map((e=>new he.r6({type:"word",value:e})));return new he.Pv({name:t,args:r,fullText:[t,...r.map((e=>e.value))].join(" ").trim()})}function iS(e,t={}){return{type:e,...t}}function aS(e){return void 0!==e&&("deny"===e.default||void 0!==e.allow&&e.allow.length>0||void 0!==e.deny&&e.deny.length>0)}function cS(...e){return e.filter((e=>void 0!==e)).join(" • ")}function lS(e){const t=[];for(const r of e){const e=r.match(/^\s*Read\s*\((.*)\)\s*$/);e&&t.push((e[1]??"").trim())}return t}function uS(e,t){if("workspace"===e&&void 0!==t)return t}const dS={workspace:0,system:1};function hS(e){const t=e.match(/^\s*(Shell|Bash)\s*\((.*)\)\s*$/);if(!t)return null;const r=t[1];if("Shell"!==r&&"Bash"!==r)return null;const n=t[2]?.trim()??"",o=n.indexOf(":");return-1!==o?{shellType:r,fullPattern:n,commandPattern:n.slice(0,o).trim(),argsPattern:n.slice(o+1).trim()}:{shellType:r,fullPattern:n,commandPattern:n,argsPattern:null}}function pS(e,{platform:t,env:r,pathModule:n,homeDirectory:o}){if((0,Eo.dA)(e))return!1;if("win32"===t){const t=r.TEMP??r.TMP;if(t){const r=n.normalize(t).toLowerCase(),o=n.normalize(e).toLowerCase(),s=r.endsWith(n.sep)?r:r+n.sep;return o===r||o.startsWith(s)}return!1}const s=e=>{const r=n.normalize(e);return"darwin"!==t?r:"/tmp"===r||r.startsWith("/tmp/")||"/var"===r||r.startsWith("/var/")?`/private${r}`:r},i=s(e);return(void 0===o||!Gb({basePath:s(o),targetPath:i,pathModule:n}))&&("darwin"===t?["/private/tmp/","/private/var/folders/"].some((e=>i.startsWith(e))):["/tmp/","/private/tmp/","/var/folders/","/private/var/folders/","/var/tmp/"].some((e=>i.startsWith(e))))}function fS(e,t){if("insecure_none"===t.type)return!0;if("insecure_none"===e.type)return!1;const r=(0,Eo.$b)(e.networkPolicy),n=(0,Eo.$b)(t.networkPolicy);if(r&&!n)return!1;const o=(0,Eo._B)(e.networkPolicy),s=(0,Eo._B)(t.networkPolicy);if(o&&n&&!s)return!1;if("workspace_readonly"===e.type&&"workspace_readwrite"===t.type)return!0;if("workspace_readwrite"===e.type&&"workspace_readonly"===t.type)return!1;const i=e.readBoundary??"system",a=t.readBoundary??"system";return!(dS[i]>dS[a])}function mS(e){return{wrapperForms:e.flatMap((e=>e.wrapperForms)),allowlistable:e.every((e=>e.allowlistable)),readsArguments:e.some((e=>e.readsArguments))}}function gS(e){return[...e.wrapperForms,e.command.fullText.trim()].filter(Boolean)}class wS{constructor(e,t,r,n,o){this.command=e,this.requestedPolicy=t,this.wrapperForms=o?.wrapperForms??[],this.allowlistable=o?.allowlistable??!0,this.readsArguments=o?.readsArguments??!1;const s=void 0!==r&&fS(t,r);this.state=s?"preapproved":"approvable";const i=[e.fullText.trim()].filter(Boolean);this.matchForms=n&&n.length>0?[...n]:i}approveWithPolicy(e){"approvable"!==this.state&&"preapproved"!==this.state||!fS(this.requestedPolicy,e)||(this.state="allowlisted")}deny(){this.state="denied"}isRunnable(){return"preapproved"===this.state||"allowlisted"===this.state}}function yS(e){return e?.type??"undefined"}const vS=["skills","skills-cursor","rules","plugins"],bS=["assets","agent-notes","agent-tools","swarm-agents"];async function SS(e,t,r){return e.shouldBlockFileRead?.(t,r)??e.shouldBlockRead(t,r)}function kS(e){const t=e.lastIndexOf("::mcpScope:");return-1===t?e:e.slice(0,t)}function _S({server:e,tool:t}){const r=e=>e.length>0&&e.length<=256&&!/[:*]/.test(e),n=e.trim().toLowerCase(),o=t.trim().toLowerCase();return r(n)&&r(o)?`${n}:${o}`:void 0}const CS=/^\s*Read\s*\((.*)\)\s*$/,ES=/^\s*Write\s*\((.*)\)\s*$/;class xS{constructor(e,t,r,n,i,a=!1,c){this.ignoreService=e,this.pendingDecisionStore=t,this.permissionsProvider=r,this.teamSettingsService=n,this.adminNetworkControlsEnabled=a,this.computerUseAppsAllowedForSession=[],this.rootDirectories=Array.isArray(i)?i:[i??process.cwd()],this.projectDir=c?.projectDir,this.perUserSandboxConfigPath=c?.perUserSandboxConfigPath??(0,s.join)((0,o.homedir)(),".cursor","sandbox.json"),this.mcpAllowlistLog=c?.mcpAllowlistLog,this.computerUse=c?.computerUse,this.computerUseAdminPolicy=c?.computerUseAdminPolicy,this.enforceMcpAdminToolLimits=c?.enforceMcpAdminToolLimits,this.onMcpAdminToolLimitCheck=c?.onMcpAdminToolLimitCheck}async shouldBlockRead(e,t={}){return this.shouldBlockReadInternal(e,t,!1)}async shouldBlockFileRead(e,t={}){return this.shouldBlockReadInternal(e,t,!0)}async getFileReadBoundaryBlocker(){const{perms:e,setting:t}=await this.readControlSetting(),r=e.deny.filter((e=>this.isPathEntry("Read",e))),n="workspace"===t.boundary&&"unrestricted"!==e.approvalMode;if(!n&&0===r.length)return;const[o,s,i]=n?await Promise.all([this.resolveWorkspaceReadRoots(e.userSandboxDataFolderName),this.resolvedReadAllowFolders(t.allowPaths),this.resolvedReadAllowGlobs(t.allowPaths)]):[[],[],[]],a=r.map((e=>this.compileReadDenyMatcher(e))),c=e=>a.some((t=>t(e)));return async(e,r)=>c(e)||c(r)||n&&wb({realAbsolutePath:r,setting:t,resolvedWorkspaceRoots:o,resolvedAllowFolders:s,resolvedAllowGlobs:i})}async readControlSetting(){const e=await this.getPermissions(),{enabled:t,...r}=await this.adminReadControls(e);return{perms:e,setting:function(e){if(!e.enabled)return{boundary:"system",allowPaths:[],enforcedByAdmin:!1};const t="workspace"===e.admin.boundary,r=t||"workspace"===e.local.boundary?"workspace":"system",n=t?e.admin.allowPaths:[];return{boundary:r,allowPaths:t&&!1===e.admin.allowUserOverride?[...n]:[...new Set([...n,...e.local.allowPaths])],enforcedByAdmin:t}}({enabled:t,admin:r,local:{boundary:e.readBoundary,allowPaths:lS(e.allow)}})}}async adminReadControls(e){const t=e.teamAdminPolicy,r=this.teamSettingsService.isReadControlEnabled?.()??!0;if(void 0!==t&&"unavailable"!==t){const e=await r;return"workspace"!==t.readBoundary?{enabled:e,boundary:void 0,allowPaths:[],allowUserOverride:void 0}:{enabled:e,boundary:"workspace",allowPaths:t.additionalReadPaths??[],allowUserOverride:t.allowUserOverrideReadPaths}}const[n,o]=await Promise.all([r,this.teamSettingsService.getSandboxingControls()]);return{enabled:n,boundary:o.readBoundary,allowPaths:o.readAllowlistPaths??[],allowUserOverride:o.allowUserOverrideReadAllowlist}}resolvedReadAllowFolders(e){return Wb([...vb(e),...(0,Eo.r5)()])}async resolvedReadAllowGlobs(e){const t=function(e){return e.flatMap((e=>{const t=(0,Ho.jl)(e.trim()),r=t.indexOf("*");if(r<0||!(0,s.isAbsolute)(t))return[];const n="win32"===process.platform?Math.max(t.lastIndexOf("/",r),t.lastIndexOf("\\",r)):t.lastIndexOf("/",r);return n>=(0,s.parse)(t).root.length?[{folder:t.slice(0,n),rest:t.slice(n)}]:[]}))}(e),r=await Wb(t.map((({folder:e})=>e)));return t.map((({rest:e},t)=>function(e,t,r={parse:s.parse}){return r.parse(e).root===e&&/[\\/]$/.test(e)?`${e}${t.slice(1)}`:`${e}${t}`}(r[t],e)))}async resolveWorkspaceReadRoots(e){const t=(0,s.join)((0,o.homedir)(),void 0!==e&&e.length>0?e:".cursor"),r=[...this.rootDirectories.map((e=>(0,s.join)(t,"projects",(0,uo.r_)(e)))),...vS.map((e=>(0,s.join)(t,e)))],n=this.rootDirectories.flatMap((e=>(0,Eo.W1)(e)??[]));return Wb([...this.rootDirectories,...r,...n,...void 0===this.projectDir?[]:[this.projectDir]])}async shouldBlockReadInternal(e,{cursorIgnoreChecked:t=!1},r){const n=(0,Ho.o1)(e),o=await Ha(n);if(null===o)return{type:"unsafeResolution",message:Hb("Read","path",n)};if(await this.ignoreService.isRepoBlocked(o))return{type:"adminBlock",source:"Team repo blocklist"};if(await this.isPathExplicitlyDenied("Read",n))return{type:"permissionsConfig"};if(!t&&!Xv(o)&&!Zv(o,{dataFolderName:(await this.getPermissions()).userSandboxDataFolderName})&&await this.ignoreService.isCursorIgnored(o))return{type:"cursorIgnore"};if(r){const e=await this.shouldBlockReadForBoundary(o);if(e)return e}return!1}async shouldBlockReadForBoundary(e){const{perms:t,setting:r}=await this.readControlSetting();if("workspace"!==r.boundary||"unrestricted"===t.approvalMode)return!1;const n=await this.resolveWorkspaceReadRoots(t.userSandboxDataFolderName);if(yb(e,n))return!1;const[o,s]=await Promise.all([this.resolvedReadAllowFolders(r.allowPaths),this.resolvedReadAllowGlobs(r.allowPaths)]);return!!wb({realAbsolutePath:e,setting:r,resolvedWorkspaceRoots:n,resolvedAllowFolders:o,resolvedAllowGlobs:s})&&{type:"needsApproval",approvalReason:r.enforcedByAdmin?"This reads a file outside your workspace and requires approval under your team's read policy.":"This reads a file outside your workspace.",approvalDetails:{type:"fileRead",path:e}}}async isProjectDirInternalPath(e,t){if(void 0===this.projectDir)return!1;const r=await fb(this.projectDir);return!!mb(r.resolution)&&Yv(r.resolvedPath,e,t)}async isFreelyWritableOutsideWorkspace(e,t){return function(e){return pS(e,{platform:process.platform,env:process.env,pathModule:s,homeDirectory:(0,o.homedir)()})}(e)||Qv(e,bS,{dataFolderName:t})||await this.isProjectDirInternalPath(e,bS)}async shouldBlockWrite(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{$b(n,(0,$.VI)(e.withName("InteractivePermissionsService.shouldBlockWrite")),!1).ctx;const i=await fb(t);if(!mb(i.resolution))return{type:"unsafeResolution",message:gb(i.originalPath,i.resolution)};const a=i.resolvedPath,c=a;if(await this.ignoreService.isRepoBlocked(c))return{type:"adminBlock",source:"Team repo blocklist"};if(await this.isPathExplicitlyDenied("Write",a))return{type:"permissionsConfig"};const l=i.originalPath.split(s.sep).pop()?.toLowerCase()??"",u=a.split(s.sep).pop()?.toLowerCase()??"";if(".cursorignore"===l||".cursorignore"===u)return{type:"permissionsConfig"};if((0,Eo.dA)(i.originalPath)||(0,Eo.dA)(a))return{type:"permissionsConfig"};const d=await this.getPermissions();if(!Xv(c)&&!Zv(c,{dataFolderName:d.userSandboxDataFolderName})&&await this.ignoreService.isCursorIgnored(c))return{type:"cursorIgnore"};if("workspace_readonly"===d.userConfiguredPolicy.type)return{type:"permissionsConfig",isReadonly:!0};if(await this.isPathExplicitlyAllowed("Write",a))return!1;if("unrestricted"===d.approvalMode)return!1;const h=async()=>{let e,t,n="";try{n=await Ti(a),e=!1}catch{e=!0}if(e)t=r;else{const e=e=>e.endsWith("\n")?e:`${e}\n`,{hunks:o}=(0,Wv.YB)("a","b",e(n),e(r),"","",{context:2});t=o.map((e=>e.lines.map((e=>e.length>0?`${e[0]} ${e.slice(1)}`:e)).join("\n"))).join("\n...\n")}return{isNewFile:e,diffString:t}};let p;const f=[];for(const e of this.rootDirectories){const t=await fb(e);if(mb(t.resolution)){if((0,Ho.BJ)(a,t.resolvedPath)){p=t.resolvedPath;break}f.push(t.resolvedPath)}}const m=void 0===p?await async function(e,t,r={}){if(0===t.length)return;let n;for(let o=(0,s.dirname)(e);;o=(0,s.dirname)(o)){if((0,Os.$f)(o))return;const e=(0,s.join)(o,".git"),i=await(0,fo.lstat)(e).catch(ub);if(i?.isFile()){const s=await ib(e);if(void 0!==s){const{commonDir:e}=s;if(ob(o,t))return;if(t.some((t=>(0,Ho.BJ)(e,t))))return{root:o,commonDir:e};if(!await(r.isUntrustedExternalGitDir?.(e))&&(await(n??=Promise.all(t.map((e=>sb(e)))),n)).some((t=>void 0!==t&&db(t,e))))return{root:o,commonDir:e}}}if((0,s.dirname)(o)===o)return}}(a,f,{isUntrustedExternalGitDir:e=>this.isFreelyWritableOutsideWorkspace(e,d.userSandboxDataFolderName)}):void 0;let g=!1;const w=p??m?.root;if(void 0!==w){const e=(0,s.relative)(w,a),t=e.split(s.sep).map((e=>"win32"===process.platform&&e.includes(":")?e.split(":")[0]:e));if(g=function(e){const t=e.replace(/\\/g,"/");return/(^|\/)\.cursor\/debug(?:-[a-zA-Z0-9-]+)?\.log$/i.test(t)}(e),!g){const e=await this.checkCursorFileProtection(t);if(e)return e}if("win32"===process.platform&&t.some((e=>e.includes("~")))){const{isNewFile:e,diffString:r}=await h();return{type:"needsApproval",approvalReason:`Protected config file: ${t[t.length-1]??""}`,approvalDetails:{type:"fileEdit",isNewFile:e,diffString:r,blockReason:"protectedConfig"}}}if(await(0,Eo.OK)(a,w)){const e=t[t.length-1]?.toLowerCase()??"",{isNewFile:r,diffString:n}=await h();return{type:"needsApproval",approvalReason:`Protected config file: ${e}`,approvalDetails:{type:"fileEdit",isNewFile:r,diffString:n,blockReason:"protectedConfig"}}}}if(void 0===p&&(void 0===m||"workspace"===(await this.readControlSetting()).setting.boundary)){if(await this.isFreelyWritableOutsideWorkspace(a,d.userSandboxDataFolderName))return!1;const e=`${(0,o.homedir)()}${s.sep}.cursor${s.sep}`;if(a.startsWith(e)){const e=a.split(s.sep).pop()?.toLowerCase()??"";if(e.endsWith(".md")||e.endsWith(".mdc")||".cursorrules"===e)return!1}const{isNewFile:t,diffString:r}=await h();return{type:"needsApproval",approvalReason:"Out of workspace",approvalDetails:{type:"fileEdit",isNewFile:t,diffString:r,blockReason:"outOfWorkspace"}}}if(g)return!1;if(!0===d.promptWorkspaceWrites){const{isNewFile:e,diffString:t}=await h();return{type:"needsApproval",approvalReason:"Workspace write",approvalDetails:{type:"fileEdit",isNewFile:e,diffString:t,blockReason:"workspaceWrite"}}}return!1}catch(e){n.error=e,n.hasError=!0}finally{Mb(n)}}async shouldEnforceShellInvariantBlocks(e,t,r){const n=await this.getAdminCommandDenylistBlock(e,{command:t.command,parsingResult:t.parsingResult,toolCallId:t.toolCallId});if(void 0!==n)return{kind:"block",reason:n};const o=await Ha(t.workingDirectory);if(null===o){if(!0!==t.skipUnsafeWorkingDirectoryBlock)return{kind:"block",reason:{type:"unsafeResolution",message:Hb("Command","working directory",t.workingDirectory)}}}else if(await this.ignoreService.isRepoBlocked(o))return{kind:"block",reason:{type:"adminBlock",source:"Team repo blocklist"}};const s=(await this.getPermissions()).userConfiguredPolicy,i=r??s;return"workspace_readonly"===s.type&&"workspace_readonly"!==i.type?{kind:"block",reason:{type:"permissionsConfig",isReadonly:!0}}:void 0!==r?{kind:"allow",policy:r}:!0!==t.resolveSkippedApprovalPolicy||"workspace_readonly"!==s.type?{kind:"allow",policy:void 0}:{kind:"allow",policy:await this.applyServerAndAdminPolicies({...s,skipStatsigDefaults:s.skipStatsigDefaults??!0})}}async shouldBlockShellCommand(e,t,r,n){const o="insecure_none"===n?.type,s=await this.shouldEnforceShellInvariantBlocks(e,{workingDirectory:r.workingDirectory,command:t,parsingResult:r.parsingResult,toolCallId:r.toolCallId},n);if("block"===s.kind)return s;const i=await this.getPermissions(),a=i.approvalMode,c="unrestricted"===a,l=i.userConfiguredPolicy,u=!i.dashboardTerminalAllowlistOverriddenByPermissionsFile;if(Db.info(e,"Shell permissions: evaluating shell command",{toolCallId:r.toolCallId,approvalMode:a,userConfiguredPolicyType:yS(l),requestedPolicyType:yS(n),effectiveRequestedPolicyType:yS(n??l),smartAllowlistEnabled:!0===i.smartAllowlistEnabled,hasSmartModeApprovalReason:void 0!==r.smartModeApprovalReason,hasSmartModeApprovalRequestId:void 0!==r.smartModeApprovalRequestId,hookForcesPrompt:ko(r.hookApprovalRequirement),classifierClassificationFailed:!0===r.classifierResult?.classificationFailed,classifierCommandCount:r.classifierResult?.commands.length??0,parserCommandCount:r.parsingResult.executableCommands.length,parsingFailed:r.parsingResult.parsingFailed,hasRedirects:r.parsingResult.hasRedirects,commandLength:t.length}),await this.shouldPromptForEmptyPlainShellAllowlist(t,i))return Db.info(e,"Shell permissions: prompting for empty allowlist",{toolCallId:r.toolCallId,approvalMode:a,userConfiguredPolicyType:yS(l),requestedPolicyType:yS(n),hasSmartModeApprovalReason:void 0!==r.smartModeApprovalReason,hasSmartModeApprovalRequestId:void 0!==r.smartModeApprovalRequestId}),await this.requestApprovalForEmptyShellAllowlist(t,r,n??l);const d=r.parsingResult.executableCommands,h=r.parsingResult.parsingFailed,p=r.classifierResult,f=r.smartModeApprovalReason,m=r.smartModeApprovalRequestId,g=void 0!==p&&!p.classificationFailed&&p.commands.length>0?p:void 0,w="allowlist"===a&&i.smartAllowlistEnabled?g?.commands:void 0,y=void 0!==w,v=d.map(kb),b=w?w.map(sS):v.map((e=>e.command)),S=void 0!==w?w.map(nS):b.map((e=>[e.fullText.trim()].filter(Boolean))),k=void 0!==g?g.commands.map(nS):v.map(gS);if(n||(n=i.userConfiguredPolicy),"insecure_none"!==n.type&&void 0===n.skipStatsigDefaults&&"insecure_none"!==l.type&&(n={...n,skipStatsigDefaults:l.skipStatsigDefaults??!0}),"insecure_none"!==l.type&&(0,Eo.$b)(l.networkPolicy)&&"insecure_none"!==n.type&&!(0,Eo._B)(n.networkPolicy)){const e=l.networkPolicy,t=n.networkPolicy?.allow;if(void 0!==t&&t.length>0&&e){const r=[...new Set([...e.allow??[],...t])];n={...n,networkPolicy:{...e,allow:r}}}else n={...n,networkPolicy:e}}let _;n=function({requestedPolicy:e,userConfiguredPolicy:t}){if("insecure_none"===e.type||"insecure_none"===t.type)return e;const r=(0,Eo.XX)(e.readBoundary,t.readBoundary),n="workspace"===r?(0,Eo.wG)(uS(e.readBoundary,e.additionalReadPaths),uS(t.readBoundary,t.additionalReadPaths)):void 0;return{...e,readBoundary:r,additionalReadPaths:n}}({requestedPolicy:n,userConfiguredPolicy:l}),p&&Db.info(e,"Smart allowlist: classifier result received",{classificationFailed:p.classificationFailed,suggestedSandboxMode:p.suggestedSandboxMode,commandCount:p.commands.length,suggestedAllowlistEntryCount:p.commands.filter((e=>e.suggestedAllowlistEntry)).length});const C=[],E=[];let x=[],P=[],I=[];const R=rS(i.smartAllowlistDenylist??[]);if(R.length>0){P=[];const t=k.map((e=>e[0]??""));for(let e=0;e<k.length;e++){const r=k[e];if(r&&0!==r.length&&R.some((e=>oS(r,e)))){const r=t[e];r&&P.push(r)}}P.length>0&&(Db.info(e,"Command blocklist: commands require approval",{count:P.length}),C.push(`In blocklist: ${P.join(", ")}`))}if(y&&p){const t=S.map((e=>e[0]??"")),r=i.allow.filter((e=>this.isShellEntry(e)));Db.info(e,"Smart allowlist: checking commands against lists",{commandCount:t.length,allowlistCount:r.length,commandBlocklistCount:R.length});const n=S.map((e=>r.some((t=>e.some((e=>this.matchesShell(t,e))))))),o=n.every(Boolean),s=[];for(let e=0;e<p.commands.length;e++){if(n[e])continue;const t=p.commands[e];t&&s.push(t)}if(x=rS(s.flatMap((e=>function(e){const t=e.name.trim();if(!t)return[];if(_v(t))return[];const r=e.subcommandTokens.map((e=>e.trim())).filter(Boolean),n=e.arguments.map((e=>e.trim())).filter(Boolean),o=[t],s=[t];for(const e of r)s.push(e),o.push(s.join(" "));const i=[t,...n].join(" ");return o.includes(i)||o.push(i),rS(o)}(e)))),I=s.map((e=>e.suggestedAllowlistEntry)).filter((e=>"string"==typeof e)).filter((e=>x.includes(e))),x.length>0){const e=Pv(x,I),t=e.length>0?e.join(", "):x.join(", ");E.push(`Not in allowlist: ${t}`)}_=o&&0===P.length,_&&Db.info(e,"Smart allowlist: all commands in allowlist, will check security",{commandCount:t.length})}const T="ask-every-time"===a||"insecure_none"===n.type&&"allowlist"===a?void 0:l,A=mS(v),$=b.map(((e,t)=>new wS(e,n,T,S[t],y?A:v[t])));if((0===b.length||h&&!y)&&!c){Db.info(e,"Shell permissions: prompting after parser miss",{toolCallId:r.toolCallId,approvalMode:a,requestedPolicyType:yS(n),userConfiguredPolicyType:yS(l),isSmartAllowlistActive:y,parsingFailed:h,parserCommandCount:b.length,hasSmartModeApprovalReason:void 0!==f,hasSmartModeApprovalRequestId:void 0!==m});const o={type:xg.Shell,toolCallId:r.toolCallId,details:{command:t,workingDirectory:r.workingDirectory,timeout:r.timeout,reason:cS(f??(h?"Parser failed to parse command (possible bypass)":"Parser found no commands (possible bypass)"),await this.adminNetworkLimitReason(n)),isSandboxAvailable:!1,isSandboxEnabled:!1,canAllowlist:!1,notAllowedCommands:[],smartModeApprovalReason:f,smartModeApprovalRequestId:m}};r.onApprovalRequested?.();const s=await this.pendingDecisionStore.requestApproval(o);return s.approved?{kind:"allow",policy:await this.applyServerAndAdminPolicies(n)}:{kind:"block",reason:{type:"userRejected",reason:s.reason}}}if(await this.hasHardDeny(e,$))return{kind:"block",reason:{type:"permissionsConfig",..."workspace_readonly"===l.type?{isReadonly:!0}:{}}};const{allowlistOfferSafe:M,redirectsAllowlistSafe:D}=await this.computeRedirectAllowlistSafety(r.parsingResult,r.workingDirectory,"insecure_none"===l.type||"workspace"!==l.readBoundary),O=await this.teamSettingsService.getAutoRunControls(),F={type:"insecure_none"};for(const e of $)await this.cmdIsAllowedByAllowlist(e,{redirectsAllowlistSafe:D,autoRunControls:O,applyTeamAllowlist:u})&&e.approveWithPolicy(F);for(const e of $)O&&this.isInTeamBlocklist(O,e)&&e.deny();const N=await this.teamSettingsService.getDeleteFileProtection();if(N)for(const e of $)"rm"===e.command.name&&e.deny();const L=this.buildShellApprovalDecisionFacts({commands:$,autoRunControls:O,shouldApplyTeamShellAllowlist:u,deleteProtectionEnabled:N,softDenylistedCommands:P});if("workspace_readonly"===l.type&&"workspace_readonly"!==n.type)return Db.info(e,"Shell permissions: blocked by readonly mode"),{kind:"block",reason:{type:"permissionsConfig",isReadonly:!0}};const j=ko(r.hookApprovalRequirement),U=r.hookApprovalRequirement?.reason,B=o&&"insecure_none"!==l.type&&function(e){if(/\brimraf\b/i.test(e))return!0;for(const t of e.replace(/[\\`^]\r?\n/g," ").split(/(?<![>|])&|\|\||[;\n]/)){let e=!1;for(const r of t.split("|")){if(e&&Rb.test(r)||Ab(r,Rb,Tb)||Ab(r,/(?<![\w-])(?:rmdir|rd|del|erase)(?![\w-])/i,/\/s(?![\w-])/i)||Ab(r,/(?<![\w-])find(?![\w-])/i,/\s-delete\b/i))return!0;e||=Ab(r,/(?<![\w-])(?:get-childitem|gci|ls|dir)(?![\w-])/i,Tb)}}return!1}(t);let W=j||B?void 0:this.getShellAutoApprovalPolicy({approvalMode:a,isUnrestricted:c,requestedPolicy:n,facts:L,preserveRequestedPolicyForAllowlistedCommands:y});const H=void 0!==W&&L.allCommandsAllowlisted&&"insecure_none"===W.type&&"allowlistEscalated"in W&&!0===W.allowlistEscalated;if("insecure_none"===W?.type){const{readBoundary:e}=await this.getAdminReadSandboxing();"workspace"===e&&(o?W=void 0:"insecure_none"!==n.type&&(W=n))}const q=void 0!==W&&H;if(W&&(c||void 0===f||q)){y&&L.allCommandsPreapproved&&!L.allCommandsAllowlisted&&Db.info(e,"Shell permissions: all commands allowed by sandbox policy");const t=await this.applyServerAndAdminPolicies(W);return Db.info(e,"Shell permissions: auto-approved shell command",{toolCallId:r.toolCallId,approvalMode:a,requestedPolicyType:yS(n),userConfiguredPolicyType:yS(l),autoApprovalPolicyType:yS(W),mergedPolicyType:yS(t),isSmartAllowlistActive:y,smartModeApprovalBypassedByAllowlist:q,allCommandsRunnable:L.allCommandsRunnable,allCommandsAllowlisted:L.allCommandsAllowlisted,allCommandsPreapproved:L.allCommandsPreapproved,hasSmartModeApprovalReason:void 0!==f,commandCount:$.length}),{kind:"allow",policy:t}}let z=(y||M)&&("allowlist"===a||"ask-every-time"===a)&&L.canAllowlistInPrompt;const G=[],V=void 0!==f,K=L.notInTeamAllowlist.length>0&&(L.hasSecurityDenies||L.hasSoftDenies||!L.allCommandsRunnable);if(void 0!==f&&G.push(f),j&&(V||G.push(U?`Hook requested approval: ${U}`:"Hook requested approval"),z=!1),B&&(V||G.push("Recursive delete outside the sandbox"),z=!1),C.length>0&&(V||G.push(...C),z=!1),!V)if(y&&E.length>0)G.push(...E);else if(L.unapprovedCommands.length>0){const e=Pv(this.generateAllowlistPatterns(L.unapprovedCommands)),t=e.length>0?e.join(", "):L.unapprovedCommands.map((e=>e.command.fullText)).join(", ");G.push(`Not in allowlist: ${t}`)}if(L.hasSecurityDenies&&(V||(L.rmDeniedByDeleteProtection.length>0&&G.push("Delete protection is enabled"),L.teamBlocklistedCommands.length>0&&G.push(`In team blocklist: ${L.teamBlocklistedCommands.map((e=>e.command.name)).join(", ")}`)),z=!1),K){const t=L.notInTeamAllowlist.map((e=>e.command.fullText)).join(", ");Db.info(e,"Shell permissions: commands not in team allowlist",{commandCount:L.notInTeamAllowlist.length}),V||G.push(`Not in team allowlist: ${t}`),z=!1}const J="unrestricted"===a&&"workspace_readonly"===n.type,Z="unrestricted"!==a||J?n:{type:"insecure_none"},X=cS(...G,await this.adminNetworkLimitReason(Z)),Q=[];if(z){const e=void 0!==f?$.filter((e=>"allowlisted"!==e.state)):L.unapprovedCommands;Q.push(...this.generateAllowlistPatterns(e))}const Y=y&&E.length>0,ee=Y?x:Q,te=Y&&I.length>0?I:void 0,re="insecure_none"!==n.type&&"insecure_none"!==l.type,ne="insecure_none"!==n.type,oe=[void 0!==f?"smart_mode_approval":void 0,j?"hook_forces_prompt":void 0,B?"unsandboxed_recursive_delete":void 0,C.length>0?"command_blocklist":void 0,y&&E.length>0?"smart_allowlist_miss":void 0,L.unapprovedCommands.length>0?"unapproved_commands":void 0,L.hasSecurityDenies?"security_denies":void 0,K?"team_allowlist_miss":void 0].filter((e=>void 0!==e));Db.info(e,"Shell permissions: requesting shell approval",{toolCallId:r.toolCallId,approvalMode:a,requestedPolicyType:yS(n),userConfiguredPolicyType:yS(l),isSandboxAvailable:re,isSandboxEnabled:ne,canAllowlist:z,isSmartAllowlistActive:y,hasSmartModeApprovalReason:void 0!==f,hasSmartModeApprovalRequestId:void 0!==m,hookForcesPrompt:j,approvalReasonTypes:oe,commandCount:$.length,unapprovedCommandCount:L.unapprovedCommands.length,deniedCommandCount:L.deniedCommands.length,notInTeamAllowlistCount:L.notInTeamAllowlist.length,notAllowedCommandCount:ee.length,suggestedAllowlistEntryCount:te?.length??0,allCommandsRunnable:L.allCommandsRunnable,allCommandsAllowlisted:L.allCommandsAllowlisted,allCommandsPreapproved:L.allCommandsPreapproved,hasSecurityDenies:L.hasSecurityDenies,hasSoftDenies:L.hasSoftDenies});const se={type:xg.Shell,toolCallId:r.toolCallId,details:{command:t,workingDirectory:r.workingDirectory,timeout:r.timeout,reason:X,isSandboxAvailable:"allowlist"===a&&re,isSandboxEnabled:!("allowlist"!==a&&!J)&&ne,canAllowlist:z,notAllowedCommands:ee,suggestedAllowlistEntries:te,smartModeApprovalReason:f,smartModeApprovalRequestId:m}};r.onApprovalRequested?.();const ie=await this.pendingDecisionStore.requestApproval(se);return ie.approved?{kind:"allow",policy:await this.applyServerAndAdminPolicies(Z)}:{kind:"block",reason:{type:"userRejected",reason:ie.reason}}}async isShellCommandFullyAllowlisted(e,t,r){const n=e.withName("InteractivePermissionsService.isShellCommandFullyAllowlisted"),o=await this.getPermissions(),s=!o.dashboardTerminalAllowlistOverriddenByPermissionsFile;if("allowlist"!==o.approvalMode)return!1;if("workspace_readonly"===o.userConfiguredPolicy.type)return!1;const{redirectsAllowlistSafe:i}=await this.computeRedirectAllowlistSafety(r.parsingResult,r.workingDirectory,"insecure_none"===o.userConfiguredPolicy.type||"workspace"!==o.userConfiguredPolicy.readBoundary);if(!i)return!1;const a=r.classifierResult,c=void 0!==a&&!a.classificationFailed&&a.commands.length>0?a:void 0,l=(o.smartAllowlistEnabled??!1)&&void 0!==c;if(r.parsingResult.parsingFailed&&!l)return!1;const u=r.parsingResult.executableCommands.map(kb),d=l?c.commands.map(sS):u.map((e=>e.command));if(0===d.length)return!1;const h=l?c.commands.map(nS):d.map((e=>[e.fullText.trim()].filter(Boolean))),p=void 0!==c?c.commands.map(nS):u.map(gS),f={type:"insecure_none"},m=mS(u),g=d.map(((e,t)=>new wS(e,f,void 0,h[t],l?m:u[t])));if(await this.hasHardDeny(n,g))return!1;const w=rS(o.smartAllowlistDenylist??[]);if(w.length>0)for(const e of p)if(e&&0!==e.length&&w.some((t=>oS(e,t))))return!1;if(await this.teamSettingsService.getDeleteFileProtection()&&g.some((e=>"rm"===e.command.name)))return!1;const y=await this.teamSettingsService.getAutoRunControls();if(void 0!==y&&g.some((e=>this.isInTeamBlocklist(y,e))))return!1;for(const e of g)if(!await this.cmdIsAllowedByAllowlist(e,{redirectsAllowlistSafe:i,autoRunControls:y,applyTeamAllowlist:s}))return!1;return!0}async applyServerAndAdminPolicies(e){if("insecure_none"===e.type)return e;const t=this.rootDirectories.at(0)??(0,o.homedir)(),{userSandboxDataFolderName:r,teamAdminPolicy:n}=await this.getPermissions(),i=void 0!==r&&r.length>0?(0,s.join)((0,o.homedir)(),r,"sandbox.json"):this.perUserSandboxConfigPath,a=await this.foldPerUserFilePolicy(e,i),c=a.skipStatsigDefaults?a:await this.applyStatsigDefaults(a),l=await this.loadPerRepoFilePolicy(c.type,t),u=await this.resolveTeamAdminLayer(n);if("unavailable"===u){const{policy:e}=await(0,Eo.resolveSandboxPolicyForWorkspace)(t,{perUser:c,perRepo:l});return function(e){return"insecure_none"===e.type?e:{...e,networkPolicy:(0,Eo.Po)(),readBoundary:"workspace",additionalReadPaths:[]}}(e)}const d=void 0===u?void 0:iS(c.type,u),h=(0,Eo._B)(e.networkPolicy)&&!aS(d?.networkPolicy),{policy:p}=await(0,Eo.resolveSandboxPolicyForWorkspace)(t,{perUser:c,perRepo:l,teamAdmin:d});return h?{...p,networkPolicy:(0,Eo.T6)()}:p}async resolveLinkedWorktreeSandboxGrants(e,t){if("workspace_readwrite"!==e.type||"workspace"===e.readBoundary)return;const{perms:r,setting:n}=await this.readControlSetting();if("workspace"===n.boundary||"unavailable"===r.teamAdminPolicy)return;const i=r.userSandboxDataFolderName;if(void 0===e.readBoundary){const t=this.rootDirectories.at(0)??(0,o.homedir)(),n=void 0!==i&&i.length>0?(0,s.join)((0,o.homedir)(),i,"sandbox.json"):this.perUserSandboxConfigPath,a="readBoundary"in r.userConfiguredPolicy&&void 0!==r.userConfiguredPolicy.readBoundary?{...e,readBoundary:r.userConfiguredPolicy.readBoundary}:e,[c,l]=await Promise.all([this.foldPerUserFilePolicy(a,n),this.loadPerRepoFilePolicy(e.type,t)]);if("workspace"===(l?.readBoundary??c.readBoundary))return}const a=[];for(const e of this.rootDirectories){if((0,Os.$f)(e))continue;const t=await fb(e);mb(t.resolution)&&!Xv(t.resolvedPath)&&a.push(t.resolvedPath)}if(0===a.length)return;let c;if(!(0,Os.$f)(t.workingDirectory)){const e=await fb(t.workingDirectory);mb(e.resolution)&&(c=e.resolvedPath)}return async function(e,t={}){if(0===e.length)return;const r=await Promise.all(e.map((e=>sb(e)))),n=[];for(const o of r)void 0===o||n.some((e=>db(e,o)))||!e.some((e=>(0,Ho.BJ)(o,e)))&&await(t.isUntrustedExternalGitDir?.(o))||n.push(o);if(0===n.length)return;const o=[],i=[],a=void 0!==t.command||void 0!==t.realWorkingDirectory;for(const r of n){const n=await nb((0,s.join)(r,"worktrees"),256),c=await(0,Dr.PH)(n,(e=>rb((0,s.join)(r,"worktrees",e),r,!0===t.excludeAgentWorktrees,a?{command:t.command,realWorkingDirectory:t.realWorkingDirectory}:void 0)),{max:16});let l=!1;for(const r of c){if(o.length>=16)break;void 0===r||o.some((e=>db(e,r)))||e.some((e=>(0,Ho.BJ)(r,e)))||ob(r,e)||await(t.isExcludedWorktreeRoot?.(r))||(o.push(r),l=!0)}l&&i.push(r)}return 0===o.length?void 0:{roots:o,commonDirs:i}}(a,{command:t.command,realWorkingDirectory:c,excludeAgentWorktrees:!0,isUntrustedExternalGitDir:e=>this.isFreelyWritableOutsideWorkspace(e,i),isExcludedWorktreeRoot:async e=>await this.isFreelyWritableOutsideWorkspace(e,i)||await this.ignoreService.isRepoBlocked(e)})}async foldPerUserFilePolicy(e,t=this.perUserSandboxConfigPath){const r=await(0,Eo.tv)(t,(0,o.homedir)());if(!r||"insecure_none"===r.type)return e;let n=(0,Eo.fZ)(r.networkPolicy,e.networkPolicy);n&&void 0!==e.networkPolicy?.default&&(n={...n,default:e.networkPolicy.default});const s=(0,Eo.s9)(r.additionalReadonlyPaths,e.additionalReadonlyPaths),i={...e,networkPolicy:n,additionalReadonlyPaths:s.length>0?s:void 0,readBoundary:r.readBoundary??e.readBoundary,additionalReadPaths:void 0!==r.additionalReadPaths?r.additionalReadPaths:e.additionalReadPaths};if("workspace_readwrite"===e.type&&"workspace_readwrite"===r.type){const t=(0,Eo.s9)(r.additionalReadwritePaths,e.additionalReadwritePaths);return{...i,additionalReadwritePaths:t.length>0?t:void 0}}return i}async applyStatsigDefaults(e){const t=await this.teamSettingsService.getDefaultNetworkAllowlist();if(!t.available||0===t.allowlist.length)return e;if((0,Eo._B)(e.networkPolicy))return e;const r={default:"deny",allow:qb(t.allowlist)};return{...e,networkPolicy:(0,Eo.fZ)(e.networkPolicy,r)}}async loadPerRepoFilePolicy(e,t){const r=await(0,Eo.tv)((0,s.join)(t,".cursor","sandbox.json"),t);if(r&&"insecure_none"!==r.type)return r.type!==e?iS(e,{networkPolicy:r.networkPolicy,additionalReadonlyPaths:r.additionalReadonlyPaths,..."additionalReadwritePaths"in r?{additionalReadwritePaths:r.additionalReadwritePaths}:{},disableTmpWrite:r.disableTmpWrite,networkPolicyStrict:r.networkPolicyStrict,readBoundary:r.readBoundary,additionalReadPaths:r.additionalReadPaths}):r}async resolveTeamAdminLayer(e){return void 0!==e?"unavailable"===e?"unavailable":"workspace"===(t=e).readBoundary?t:void 0===t.networkPolicy?{}:{networkPolicy:t.networkPolicy}:async function(e){const{teamSettings:t}=e,r=e.adminNetworkControlsEnabled?(i=await t.getNetworkAccessControls()).available?0!==i.allowlist.length||0!==i.denylist.length?{...i.allowlist.length>0?{default:"deny",allow:qb(i.allowlist)}:{},...i.denylist.length>0?{deny:qb(i.denylist)}:{}}:void 0:(0,Eo.Po)():void 0,[n,o]=await Promise.all([t.isReadControlEnabled?.()??!0,t.getSandboxingControls()]),s=void 0===r?{}:{networkPolicy:r};var i;return n&&"workspace"===o.readBoundary?{...s,readBoundary:"workspace",additionalReadPaths:o.readAllowlistPaths??[],allowUserOverrideReadPaths:o.allowUserOverrideReadAllowlist}:void 0===r?void 0:s}({teamSettings:this.teamSettingsService,adminNetworkControlsEnabled:this.adminNetworkControlsEnabled});var t}async adminNetworkLimitReason(e){if("insecure_none"===e.type||!(0,Eo._B)(e.networkPolicy))return;const{teamAdminPolicy:t}=await this.getPermissions(),r=await this.resolveTeamAdminLayer(t);return function(e){if(aS(e))return void 0!==e.allow&&e.allow.length>0?"Network access limited to your admin's allowlist":"deny"===e.default?"Network access limited by your admin":"Network access excludes domains your admin blocks"}("unavailable"===r?(0,Eo.Po)():r?.networkPolicy)}async getAdminReadSandboxing(){const e=await this.getPermissions();if("unavailable"===e.teamAdminPolicy)return{readBoundary:"workspace"};const{enabled:t,boundary:r}=await this.adminReadControls(e);return{readBoundary:t&&"workspace"===r?"workspace":void 0}}async isInShellAllowlist(e){if(!e.allowlistable)return!1;const t=await this.getPermissions(),r=e.readsArguments?e.matchForms.map((e=>`${e} \0`)):e.matchForms;return t.allow.some((e=>this.isShellEntry(e)&&r.some((t=>this.matchesShell(e,t)))))}isInTeamBlocklist(e,t){const r=[...t.wrapperForms,t.command.fullText];return e.blocked.some((e=>r.some((t=>this.matchesAutoRunCommand(t,e)))))}isInTeamAllowlist(e,t){return!!t.allowlistable&&e.allowed.some((e=>this.matchesAutoRunCommand(t.command.fullText,e)))}async computeRedirectAllowlistSafety(e,t,r){const n=e.hasRedirects,i=e.parsingFailed,a=!0===e.allRedirectsAreDevNull,c=!(!n||a||i)&&await async function({parsingResult:e,workingDirectory:t,rootDirectories:r,allowTmpRedirects:n=!0,resolvePathForPermissions:i=fb,pathModule:a=s,tempPathOptions:c={platform:process.platform,env:process.env,pathModule:a,homeDirectory:(0,o.homedir)()}}){if(!e.hasRedirects)return!0;const l=e.redirects;if(0===l.length)return!1;const u=e.executableCommands.length>1,d=zb();for(const e of l){if(Zb(e))continue;const o=u?zb():d,{operator:s,targetText:l}=e,p=e.destinationFds;if(">&"===s){const e=Jb(l),t=void 0===e?void 0:o.fdTargets.get(e);if("original-stdout"!==(h=t)&&"original-stderr"!==h&&"dev-null"!==h&&"workspace-file"!==h&&"tmp-file"!==h){for(const e of p)o.fdTargets.set(e,"unsafe");return!1}for(const e of p)o.fdTargets.set(e,t);continue}if("<&"===s){const e=Jb(l),t=void 0===e?void 0:o.fdTargets.get(e);if("dev-null"!==t){for(const e of p)o.fdTargets.set(e,"unsafe");return!1}for(const e of p)o.fdTargets.set(e,t);continue}if("/dev/null"===l){for(const e of p)o.fdTargets.set(e,"dev-null");continue}if(!Vb(s)||void 0===l||"word"===e.targetNodeType&&!Xb(l,a)){for(const e of p)o.fdTargets.set(e,"unsafe");return!1}const f=await eS({targetText:l,workingDirectory:t,rootDirectories:r,allowTmpRedirects:n,resolvePathForPermissions:i,pathModule:a,tempPathOptions:c});if(!f){for(const e of p)o.fdTargets.set(e,"unsafe");return!1}for(const e of p)o.fdTargets.set(e,f)}var h;return!0}({parsingResult:e,workingDirectory:t,rootDirectories:this.rootDirectories,allowTmpRedirects:r}),l=await tS({parsingResult:e,workingDirectory:t,rootDirectories:this.rootDirectories,allowTmpRedirects:r}),u=!function({parsingResult:e,hasRedirects:t,parsingFailed:r,allRedirectsAreAllowlistSafe:n,allRedirectsAreWorkspaceFileSafe:o}){return!(!t||r||n||o)&&(0===e.redirects.length||e.redirects.some(Kb))}({parsingResult:e,hasRedirects:n,parsingFailed:i,allRedirectsAreAllowlistSafe:a,allRedirectsAreWorkspaceFileSafe:c})&&l;return{allowlistOfferSafe:(!n||a||c)&&l&&!i,redirectsAllowlistSafe:u}}async cmdIsAllowedByAllowlist(e,t){return!!t.redirectsAllowlistSafe&&(!!await this.isInShellAllowlist(e)||t.applyTeamAllowlist&&void 0!==t.autoRunControls&&this.isInTeamAllowlist(t.autoRunControls,e))}buildShellApprovalDecisionFacts({commands:e,softDenylistedCommands:t,autoRunControls:r,shouldApplyTeamShellAllowlist:n,deleteProtectionEnabled:o}){const s=e.filter((e=>"denied"===e.state)),i=e.filter((e=>"approvable"===e.state)),a=n&&r?.enabled?e.filter((e=>!this.isInTeamAllowlist(r,e))):[],c=s.filter((e=>void 0!==r&&this.isInTeamBlocklist(r,e))),l=o?s.filter((e=>"rm"===e.command.name)):[];return{hasSecurityDenies:s.length>0,hasSoftDenies:t.length>0,hasTeamAllowlistMisses:a.length>0,allCommandsRunnable:e.every((e=>e.isRunnable())),allCommandsAllowlisted:e.every((e=>"allowlisted"===e.state)),allCommandsPreapproved:e.every((e=>"preapproved"===e.state)),canAllowlistInPrompt:0===s.length&&0===a.length,unapprovedCommands:i,deniedCommands:s,notInTeamAllowlist:a,teamBlocklistedCommands:c,rmDeniedByDeleteProtection:l}}getShellAutoApprovalPolicy({approvalMode:e,isUnrestricted:t,requestedPolicy:r,facts:n,preserveRequestedPolicyForAllowlistedCommands:o}){if(!n.hasSecurityDenies&&!n.hasSoftDenies&&n.allCommandsRunnable){if(t)return"workspace_readonly"===r.type?r:{type:"insecure_none"};if("allowlist"===e)return n.allCommandsAllowlisted&&!o&&"workspace_readonly"!==r.type?{type:"insecure_none",allowlistEscalated:!0}:r}}async getPermissions(){return await this.permissionsProvider.getPermissions()}hasLocalShellControls(e){return e.allow.some((e=>this.isShellEntry(e)))||e.deny.some((e=>this.isShellEntry(e)))||(e.smartAllowlistDenylist?.length??0)>0}hasTeamShellControls(e,t=!0){return void 0!==e&&(t&&(e.enabled||e.allowed.length>0)||e.blocked.length>0)}async shouldPromptForEmptyPlainShellAllowlist(e,t){if("allowlist"!==t.approvalMode||"insecure_none"!==t.userConfiguredPolicy.type||0===e.trim().length||this.hasLocalShellControls(t))return!1;const[r,n]=await Promise.all([this.teamSettingsService.getAutoRunControls(),this.teamSettingsService.getDeleteFileProtection()]);return!this.hasTeamShellControls(r,!t.dashboardTerminalAllowlistOverriddenByPermissionsFile)&&!n}async requestApprovalForEmptyShellAllowlist(e,t,r){const n=await this.getEmptyShellAllowlistCandidates(t);t.onApprovalRequested?.();const o=await this.pendingDecisionStore.requestApproval({type:xg.Shell,toolCallId:t.toolCallId,details:{command:e,workingDirectory:t.workingDirectory,timeout:t.timeout,reason:cS(t.smartModeApprovalReason??"Shell allowlist is empty",await this.adminNetworkLimitReason(r)),isSandboxAvailable:!1,isSandboxEnabled:!1,canAllowlist:n.length>0,notAllowedCommands:n,smartModeApprovalReason:t.smartModeApprovalReason,smartModeApprovalRequestId:t.smartModeApprovalRequestId}});return o.approved?{kind:"allow",policy:await this.applyServerAndAdminPolicies(r)}:{kind:"block",reason:{type:"userRejected",reason:o.reason}}}async getEmptyShellAllowlistCandidates(e){const t=e.parsingResult;return t.parsingFailed||0===t.executableCommands.length||t.hasRedirects&&!0!==t.allRedirectsAreDevNull||!await tS({parsingResult:t,workingDirectory:e.workingDirectory,rootDirectories:this.rootDirectories,allowTmpRedirects:!0})?[]:this.generateAllowlistPatterns(t.executableCommands.map(kb))}async getAdminCommandDenylistBlock(e,t){const r=(await this.teamSettingsService.getAdminCommandDenylist()).rules;if(0===r.length)return;const n=ds({matchForms:t.parsingResult?as({command:t.command,parsingResult:t.parsingResult}):[t.command],blockedCommands:r});return void 0!==n?(Db.info(e,"Admin command denylist hard-blocked shell at execution time",{toolCallId:t.toolCallId,parsingFailed:t.parsingResult?.parsingFailed??!0,parserCommandCount:t.parsingResult?.executableCommands.length??0}),{type:"adminCommandDenylist",pattern:n}):void 0}async hasHardDeny(e,t){const r=await this.getPermissions();return t.some((e=>r.deny.some((t=>this.isShellEntry(t)&&[...e.wrapperForms,...e.matchForms].some((e=>this.matchesShell(t,e)))))))}isShellEntry(e){return null!==hS(e)}isPathEntry(e,t){return new RegExp(`^\\s*${e}\\s*\\(`).test(t)}matchesShell(e,t){const r=hS(e);if(!r)return!1;const n=t.trim(),o=this.extractBaseCommand(n);if(null!==r.argsPattern){const e=n.includes(" ")?n.slice(n.indexOf(" ")+1).trim():"",t=this.matchGlob(r.commandPattern,o)||this.matchGlob(r.commandPattern,n),s=this.matchGlob(r.argsPattern,e);if(t&&s)return!0}return!!this.matchGlob(r.fullPattern,n)||!!n.startsWith(`${r.fullPattern} `)||!!this.matchGlob(r.fullPattern,o)||o===r.fullPattern}async checkCursorFileProtection(e){if(!e.some((e=>".cursor"===e.toLowerCase()||".vscode"===e.toLowerCase())))return null;const t=e[e.length-1]?.toLowerCase()??"";return t.endsWith(".md")||t.endsWith(".mdc")||".cursorrules"===t?null:await this.teamSettingsService.getDotCursorProtection()?{type:"permissionsConfig"}:null}extractBaseCommand(e){const t=e.trim(),r=t.indexOf(" ");return-1===r?t:t.substring(0,r)}generateAllowlistPatterns(e){const t=[],r=["git","npm","yarn","pnpm","docker","pip","systemctl","uv","cargo","bun","npx"];for(const{command:n,allowlistable:o}of e)o&&!_v(n.name)&&(r.includes(n.name)&&n.args.length>0&&"word"===n.args[0].type?t.push(`${n.name} ${n.args[0].value}`):t.push(n.name));return[...new Set(t)]}pathEntryRawPattern(e,t){const r=t.match(function(e){return"Read"===e?CS:ES}(e));if(r)return(r[1]??"").trim()}compileReadDenyMatcher(e){try{const t=this.pathEntryRawPattern("Read",e);if(void 0===t)return()=>!1;const r=function(e){const{trimmedPattern:t,regexSource:r}=ss(e);let n;try{n=new RegExp(r)}catch{return e=>t===e}return e=>{try{return n.test(e)}catch{return t===e}}}((0,Ho.jl)(t));return e=>r(e)}catch(e){return()=>{throw e}}}matchesPathEntry(e,t,r){const n=this.pathEntryRawPattern(e,t);return void 0!==n&&this.matchGlob((0,Ho.jl)(n),r)}async isPathExplicitlyDenied(e,t){return(await this.getPermissions()).deny.some((r=>this.isPathEntry(e,r)&&this.matchesPathEntry(e,r,t)))}async isPathExplicitlyAllowed(e,t){return(await this.getPermissions()).allow.some((r=>this.isPathEntry(e,r)&&this.matchesPathEntry(e,r,t)))}matchGlob(e,t){return is(e,t)}async addToAllowList(e,t,r){const n=`${t}(${r})`;await this.permissionsProvider.updatePermissions((e=>{const t=e.allow.includes(n)?e.allow:[...e.allow,n];return{...e,allow:t}}))}async addToDenyList(e,t,r){const n=`${t}(${r})`;await this.permissionsProvider.updatePermissions((e=>{const t=e.deny.includes(n)?e.deny:[...e.deny,n];return{...e,deny:t}}))}async shouldBlockMcp(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{$b(o,(0,$.VI)(e.withName("InteractivePermissionsService.shouldBlockMcp")),!1);const{name:s,toolName:i,providerIdentifier:a,args:c}=t,l=function(e,t){if(void 0!==t)return t;const r=e;return void 0!==r.annotations?r.annotations:pv(r.annotationsJson)}(t,r?.annotations),u=e=>{this.mcpAllowlistLog?.(e)};if(u(`[permissions-service] shouldBlockMcp: toolName="${i}", providerIdentifier="${a}"`),await this.isComputerUseDisabledByAdminFor(a))return u(`[permissions-service] shouldBlockMcp: BLOCKED (Computer Use off for team) toolName="${i}", providerIdentifier="${a}"`),{type:"unsafeResolution",message:"Computer Use is turned off by your team admin. Ask the user to do it instead."};const d=await this.mcpAdminToolLimitRefusal(e,{resolvedTool:n?.resolvedTool,toolName:i});if(void 0!==d)return u(`[permissions-service] shouldBlockMcp: BLOCKED (team tool limit) toolName="${i}", providerIdentifier="${a}"`),{type:"unsafeResolution",message:d};const h=await this.computerUseDecision(t,r);if(await this.isMcpExplicitlyDenied(e,a,i))return u(`[permissions-service] shouldBlockMcp: BLOCKED (explicitly denied) toolName="${i}", providerIdentifier="${a}"`),{type:"permissionsConfig"};const p=await this.getPermissions(),f="workspace_readonly"===p.userConfiguredPolicy.type&&"unrestricted"!==p.approvalMode;if(!0===n?.alreadyApproved&&!f&&"block"!==h.kind&&"askEachCall"!==h.kind)return!1;const m=await this.teamSettingsService.getMcpToolControls(),g=!0===m?.enabled&&!(void 0!==n?.client&&!0===await(this.teamSettingsService.isHostMcpBridgeClient?.(n.client))),w=g&&"block"!==h.kind?{kind:"notComputerUse"}:h,y=void 0!==t.smartModeApproval?.reason&&f,v=_S({server:kS(a),tool:i});let b,S,k;switch(w.kind){case"block":return u(`[permissions-service] shouldBlockMcp: BLOCKED (Computer Use app) toolName="${i}", providerIdentifier="${a}"`),{type:"unsafeResolution",message:w.message};case"noAccess":if(!f&&!await this.teamSettingsService.getShouldBlockMcp())return u(`[permissions-service] shouldBlockMcp: ALLOWED (Computer Use no access) toolName="${i}", providerIdentifier="${a}"`),!1;b=v,k=!0;break;case"app":if(!y&&(this.computerUseAppsAllowedForSession.includes(w.entry)||await this.isComputerUseAppSaved(w.entry)))return u(`[permissions-service] shouldBlockMcp: ALLOWED (Computer Use app grant) toolName="${i}", providerIdentifier="${a}"`),!1;b=w.entry,S=w.app,k=!1;break;case"askEachCall":b=void 0,S=w.app&&{...w.app,allowOnce:!0},k=!1;break;case"notComputerUse":b=v,k=!0}const _=k||void 0!==b,C=t.smartModeApproval?.reason;if(void 0!==C)return"workspace_readonly"===p.userConfiguredPolicy.type&&"unrestricted"!==p.approvalMode?(u(`[permissions-service] shouldBlockMcp: BLOCKED (readonly mode, Smart Mode forced approval) toolName="${i}", providerIdentifier="${a}"`),{type:"permissionsConfig",isReadonly:!0}):(u(`[permissions-service] shouldBlockMcp: needsApproval (Smart Mode) toolName="${i}", providerIdentifier="${a}"`),!(g?this.isMcpInTeamAllowlist(m,{providerIdentifier:a,toolName:i,annotations:l}):k&&await this.isMcpExplicitlyAllowed(e,a,i))&&!("unrestricted"===p.approvalMode&&!await this.teamSettingsService.getShouldBlockMcp())&&{type:"needsApproval",approvalReason:C,approvalDetails:{type:"mcp",name:s,toolName:i,...Bb(r,l),providerIdentifier:a,args:c,reason:"smartMode",canAllowlist:_&&!this.isComputerUseServer(a),smartModeApprovalReason:C,smartModeApprovalRequestId:t.smartModeApproval?.requestId,allowlistEntry:b,computerUseApp:S}});if(g){const t=this.isMcpInTeamAllowlist(m,{providerIdentifier:a,toolName:i,annotations:l});if(this.recordMcpAllowlistCheckResult(e,{allowlistScope:"team",outcome:t?"pass":"fail"}),t)return u(`[permissions-service] shouldBlockMcp: ALLOWED (in admin MCP allowlist) toolName="${i}", providerIdentifier="${a}"`),!1}else if(k){const t=await this.isMcpExplicitlyAllowed(e,a,i);if(this.recordMcpAllowlistCheckResult(e,{allowlistScope:"user",outcome:t?"pass":"fail"}),t)return u(`[permissions-service] shouldBlockMcp: ALLOWED (explicitly in allowlist) toolName="${i}", providerIdentifier="${a}"`),!1}if("workspace_readonly"===p.userConfiguredPolicy.type&&"unrestricted"!==p.approvalMode)return u(`[permissions-service] shouldBlockMcp: BLOCKED (readonly mode) toolName="${i}", providerIdentifier="${a}"`),{type:"permissionsConfig",isReadonly:!0};if("unrestricted"===p.approvalMode){if(!await this.teamSettingsService.getShouldBlockMcp())return u(`[permissions-service] shouldBlockMcp: ALLOWED (auto-run, no team block) toolName="${i}", providerIdentifier="${a}"`),!1;u(`[permissions-service] shouldBlockMcp: needsApproval (auto-run but team blocks MCP) toolName="${i}", providerIdentifier="${a}"`)}return u(`[permissions-service] shouldBlockMcp: needsApproval (not in allowlist) toolName="${i}", providerIdentifier="${a}", approvalMode="${p.approvalMode}"`),{type:"needsApproval",approvalReason:`MCP tool: ${i}`,approvalDetails:{type:"mcp",name:s,toolName:i,...Bb(r,l),providerIdentifier:a,args:c,canAllowlist:_,allowlistEntry:b,computerUseApp:S}}}catch(e){o.error=e,o.hasError=!0}finally{Mb(o)}}async mcpAdminToolLimitRefusal(e,{resolvedTool:t,toolName:r}){if(void 0===t||void 0===this.enforceMcpAdminToolLimits)return;if(!await this.enforcesMcpAdminToolLimits())return void(void 0!==this.onMcpAdminToolLimitCheck&&this.judgeMcpAdminToolLimit(t,r).then((e=>this.reportMcpAdminToolLimitCheck("shadow",e)),(()=>{})));const n=await this.judgeMcpAdminToolLimit(t,r);switch(this.reportMcpAdminToolLimitCheck("enforce",n),n){case void 0:case"within_limit":return;case"outside_limit":return Fb.increment(e,1,{reason:"outside_limit"}),"Your team's admin limits this MCP tool";case"settings_unavailable":return Fb.increment(e,1,{reason:"settings_unavailable"}),"Your team's MCP settings could not be read, so this MCP tool can't run right now";case"unknown_server":return Fb.increment(e,1,{reason:"unknown_server"}),"Your team's MCP rules could not be checked for this MCP server, so this MCP tool can't run right now";default:return n}}async judgeMcpAdminToolLimit(e,t){if("unresolved"===e)return"unknown_server";const r=await(this.teamSettingsService.getMcpAdminToolLimit?.(e.client));if(void 0!==r)switch(r.kind){case"none":return;case"settings_unavailable":return"settings_unavailable";case"unknown_server":return"unknown_server";case"limit":return vv(r.policy,{name:t,annotations:e.annotations})?"within_limit":"outside_limit";default:return r}}reportMcpAdminToolLimitCheck(e,t){if(void 0!==t)try{this.onMcpAdminToolLimitCheck?.({mode:e,outcome:t})}catch{}}async enforcesMcpAdminToolLimits(){if(void 0===this.enforceMcpAdminToolLimits)return!1;try{return await this.enforceMcpAdminToolLimits()}catch{return!1}}async computerUseDecision(e,t){const r=this.computerUse;if(void 0===r||!this.isComputerUseServer(e.providerIdentifier))return{kind:"notComputerUse"};const n=await r.isOwnServer(kS(e.serverIdentifier||e.providerIdentifier),t);if(!1===n)return{kind:"notComputerUse"};const o=await async function(e,t){const r=jv(e.meta?.["cursor/computerUseScope"])??jv(t.toolScopes?.[e.toolName]);if(void 0===r)return{kind:"screen"};let n;if(void 0!==r.appSelectorArgs){const t=Object.entries(r.appSelectorArgs).flatMap((([t,r])=>Lv(t)&&void 0!==r&&void 0!==e.args[r]&&null!==e.args[r]?[{selector:t,value:e.args[r]}]:[]));if(0===t.length){const t=new Intl.ListFormat("en",{type:"disjunction"}).format(Object.values(r.appSelectorArgs).filter((e=>void 0!==e)));return{kind:"noAppSelector",message:`${e.toolName} needs exactly one of ${t} to name the app. Call it again with one of them.`}}const o=t.filter((({selector:e,value:t})=>function(e,t){return"pid"===e?"number"==typeof t&&Number.isInteger(t)||"string"==typeof t&&Bv.test(t):"string"==typeof t&&t.length>0}(e,t)));if(1!==o.length){for(const{value:e}of t){const t="string"==typeof e?Mv(e.trim()):void 0;if(void 0!==t)return{kind:"app",app:t}}return{kind:"unknownApp"}}n=function(e,t){if("pid"===e){const e="string"==typeof t&&Bv.test(t)?Number(t):t;return"number"==typeof e&&Number.isSafeInteger(e)&&e>0?{pid:e}:void 0}const r="string"==typeof t?t.trim():"";if(0!==r.length)return"bundleId"===e?{bundleId:r}:"path"===e?{path:r}:{appName:r}}(o[0].selector,o[0].value)}else{if(void 0===r.appArg)return r.capturesScreen?{kind:"screen"}:{kind:"none"};{const t=e.args[r.appArg];if(null==t||function(e){return"object"==typeof e&&null!==e&&"screen"===e.scope}(t))return{kind:"screen"};n=function(e){if("string"==typeof e){const t=e.trim();return t.length>0?{name:t}:void 0}if("object"!=typeof e||null===e)return;const{scope:t,pid:r}=e;return"app"===t&&"number"==typeof r&&Number.isInteger(r)&&r>0?{pid:r}:void 0}(t)}}if(void 0===n)return{kind:"unknownApp"};const o=function(e){return"pid"in e?void 0:"name"in e?e.name:"bundleId"in e?e.bundleId:"path"in e?e.path:e.appName}(n),s=await t.describeApp(n)??(void 0===o?void 0:Mv(o));return void 0===s?{kind:"unknownApp"}:{kind:"app",app:s}}({toolName:e.toolName,args:Object.fromEntries(Object.entries(e.args).map((([e,t])=>[e,t.toJson()]))),meta:t?._meta},r);if(void 0===n&&"app"!==o.kind)return{kind:"askEachCall"};switch(o.kind){case"none":return{kind:"noAccess"};case"screen":return{kind:"notComputerUse"};case"unknownApp":return{kind:"askEachCall"};case"noAppSelector":return{kind:"block",message:o.message};case"app":{const e=function(e){const t=e.toLowerCase();return Tv(t)?"Computer Use doesn't control Cursor itself, including its approval cards. Ask the user to do it instead.":Av.some((e=>e.bundleId===t))?"Computer Use doesn't control apps that run scripts, such as Script Editor, Automator and Shortcuts. Ask the user to do it instead.":$v.some((e=>e.bundleId===t))?"Computer Use doesn't control terminal apps. Use your shell tool to run commands instead.":void 0}(o.app.bundleId);if(void 0!==e)return{kind:"block",message:e};if(void 0===n)return{kind:"askEachCall"};const t=Ov(o.app.bundleId)?void 0:_S({server:r.serverId,tool:Fv(o.app.bundleId)});return void 0===t?{kind:"askEachCall",app:o.app}:{kind:"app",app:o.app,entry:t}}}throw new Error("unreachable computer-use subject")}isComputerUseServer(e){const t=kS(e);return!0===this.computerUse?.providerIdentifiers.has(t)}async isComputerUseDisabledByAdminFor(e){const t=this.computerUseAdminPolicy;return t?.providerIdentifiers.has(kS(e))?await t.isDisabledByAdmin():!!this.isComputerUseServer(e)&&!0===await(this.teamSettingsService.isComputerUseDisabledByAdmin?.())}allowComputerUseAppForSession({bundleId:e}){const t=void 0===this.computerUse||Ov(e)?void 0:_S({server:this.computerUse.serverId,tool:Fv(e)});void 0!==t&&this.computerUseAppsAllowedForSession.push(t)}async isMcpFullyAllowlisted(e,t){const r=e.withName("InteractivePermissionsService.isMcpFullyAllowlisted"),{providerIdentifier:n,toolName:o}=t,s=t.annotations??pv(t.annotationsJson);if(await this.isMcpExplicitlyDenied(r,n,o)||await this.isComputerUseDisabledByAdminFor(n))return!1;const i=await this.teamSettingsService.getMcpToolControls();return!0===i?.enabled?!!this.isMcpInTeamAllowlist(i,{providerIdentifier:n,toolName:o,annotations:s}):!this.isComputerUseServer(n)&&await this.isMcpExplicitlyAllowed(r,n,o)}async isWebFetchFullyAllowlisted(e,t){const r=await this.getPermissions();if("allowlist"!==r.approvalMode)return!1;let n;try{n=new URL(t.url)}catch{return!1}const o=n.hostname;return!r.deny.some((e=>this.matchesWebFetchEntry(e,o)))&&r.allow.some((e=>this.matchesWebFetchEntry(e,o)))}matchesAutoRunCommand(e,t){const r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`^${r}(\\s|$)`).test(e.trim())}matchesMcpPattern({pattern:e,providerIdentifier:t,toolName:r,logLabel:n}){const o=e.indexOf(":");if(-1===o)return!1;const s=e.slice(0,o).trim().toLowerCase(),i=e.slice(o+1).trim().toLowerCase(),a=kS(t).toLowerCase().trim(),c=r.toLowerCase().trim(),l="*"===s||this.matchGlob(s,a),u="*"===i||this.matchGlob(i,c),d=l&&u,h=`[permissions-service] ${n}: serverPattern="${s}", toolPattern="${i}", normalizedProviderIdentifier="${a}", normalizedToolName="${c}", serverMatches=${l}, toolMatches=${u}, result=${d}`;return this.mcpAllowlistLog?.(h),d}recordMcpAllowlistCheckResult(e,{allowlistScope:t,outcome:r}){Ob.increment(e,1,{allowlist_scope:t,outcome:r})}matchesMcpEntry(e,t,r){const n=e.match(/^\s*Mcp\s*\((.*)\)\s*$/);if(!n)return!1;const o=n[1]?.trim()??"";return this.matchesMcpPattern({pattern:o,providerIdentifier:t,toolName:r,logLabel:"matchesMcpEntry"})}matchesWebFetchEntry(e,t){const r=e.match(/^\s*WebFetch\s*\((.*)\)\s*$/);return!!r&&Ty(t,r[1]?.trim()??"")}matchesMcpEntryBare({pattern:e,providerIdentifier:t,toolName:r}){return this.matchesMcpPattern({pattern:e,providerIdentifier:t,toolName:r,logLabel:"matchesMcpEntryBare"})}isMcpInTeamAllowlist(e,{providerIdentifier:t,toolName:r,annotations:n}){if(e.mcpToolAllowlist.some((e=>this.matchesMcpEntryBare({pattern:e,providerIdentifier:t,toolName:r}))))return!0;const o=this.findTeamMcpServerPolicy(e,t);return void 0!==o&&"reads"===o.mode&&vv(o,{name:r,annotations:n})}findTeamMcpServerPolicy(e,t){for(const r of e.serverPolicies??[])if(this.matchesMcpEntryBare({pattern:`${r.name}:*`,providerIdentifier:t,toolName:""}))return r.policy}async isMcpExplicitlyDenied(e,t,r){return(await this.getPermissions()).deny.some((e=>this.matchesMcpEntry(e,t,r)))}async isComputerUseAppSaved(e){return(await this.getPermissions()).allow.some((t=>t.match(/^\s*Mcp\s*\((.*)\)\s*$/)?.[1]?.trim().toLowerCase()===e))}async isMcpExplicitlyAllowed(e,t,r){return(await this.getPermissions()).allow.some((e=>this.matchesMcpEntry(e,t,r)))}}var PS=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const IS=65536,RS=1048576,TS=(0,l.h)("LocalReadExecutor"),AS=async(e,t,r,n)=>{const o=setTimeout((()=>{TS.warn(e,`[watchdog, LocalReadExecutor] ${t} still not completed after ${r}ms`)}),r);try{return await n()}finally{clearTimeout(o)}};function $S(e){return BigInt(Math.min(e,4294967295))}async function MS(e,t){if(0===t)return(0,fo.readFile)(e);if(t>2147483647)throw new RangeError(`File size (${t}) is greater than 2 GiB`);const r=await(0,fo.open)(e,"r");try{const e=Buffer.allocUnsafe(t);let n=0;for(;n<t;){const{bytesRead:o}=await r.read(e,n,t-n,n);if(0===o)break;n+=o}return e.subarray(0,n)}finally{await r.close()}}function DS(e){if(e.length<5||45!==e[0]||45!==e[1]||45!==e[2]||10!==e[3])return 0;const t=Buffer.from("\n---\n"),r=e.indexOf(t,4);return-1===r?0:r+t.length}function OS(e){return e>=32&&e<=126||9===e||10===e||13===e}function FS(e){if(e.length>=2){if(255===e[0]&&254===e[1])return"utf-16le";if(254===e[0]&&255===e[1])return"utf-16be"}const t=Math.min(4096,e.length);if(t<16)return"utf-8";let r=0,n=0;for(let o=0;o+1<t;o+=2){const t=e[o],s=e[o+1];0===s&&OS(t)&&r++,0===t&&OS(s)&&n++}return r>=8&&r>=4*Math.max(1,n)?"utf-16le":n>=8&&n>=4*Math.max(1,r)?"utf-16be":"utf-8"}const NS=Buffer.from("\n---\n");function LS(e,t){const r=e.length;if(r<2*NS.length)return r;if(10!==e[r-1]||45!==e[r-2]||45!==e[r-3]||45!==e[r-4]||10!==e[r-5])return r;const n=Math.max(t,r-4096),o=e.lastIndexOf(NS,r-NS.length-1);return-1===o||o<n?r:function(e){for(let t=0;t<e.length;t++){const r=e.charCodeAt(t);if(10!==r&&(r<32||r>126))return!1}const t=e.split("\n").filter((e=>e.length>0));if(t.length<2||t.length>3)return!1;const r=t[0],n=t[t.length-1];return!(!/^(exit_code: (?:-?\d+|unknown)|error: .+)$/.test(r)||!n.startsWith("ended_at: ")||3===t.length&&!/^elapsed_ms: \d+$/.test(t[1]))}(e.subarray(o+NS.length,r-4).toString("utf-8"))?o:r}const jS=[Buffer.from("%PDF-","ascii"),Buffer.from([208,207,17,224,161,177,26,225]),Buffer.from([80,75,3,4]),Buffer.from([80,75,5,6]),Buffer.from([80,75,7,8]),Buffer.from([127,69,76,70]),Buffer.from([254,237,250,206]),Buffer.from([254,237,250,207]),Buffer.from([206,250,237,254]),Buffer.from([207,250,237,254]),Buffer.from([77,90,144]),Buffer.from([0,97,115,109]),Buffer.from([137,80,78,71,13,10,26,10]),Buffer.from([255,216,255]),Buffer.from("GIF87a","ascii"),Buffer.from("GIF89a","ascii"),Buffer.from("SQLite format 3\0","ascii"),Buffer.from([31,139]),Buffer.from("BZh","ascii"),Buffer.from([253,55,122,88,90,0]),Buffer.from([40,181,47,253]),Buffer.from([55,122,188,175,39,28]),Buffer.from([82,97,114,33,26,7,0]),Buffer.from([82,97,114,33,26,7,1,0])];function US(e){return new Fw.sV({result:{case:"invalidFile",value:new Fw.cW({path:e,reason:"File content is binary data, not text"})}})}function BS(e,t,r){if(void 0===r.offset&&void 0===r.limit)return{applied:!1};if(t)return{applied:!1};const n=r.offset??1,o=r.limit??(n<0?Math.abs(n):e),s=n<0?Math.max(0,e+n):Math.max(0,n-1);if(s>=e)return{applied:!1};const i=Math.min(e,s+o),a=WS(s,e),c=WS(i,e);return{applied:!0,start:a,end:Math.max(a,c)}}function WS(e,t){if(Number.isNaN(e)||0===e)return 0;if(e===Number.POSITIVE_INFINITY)return t;if(e===Number.NEGATIVE_INFINITY)return 0;const r=Math.trunc(e);return r<0?Math.max(t+r,0):Math.min(r,t)}function HS(e){return-1===e.indexOf("\r\n")?e:e.replaceAll("\r\n","\n")}function qS(e,t,r,n,o,s){if(n>=o)return{from:0,to:0};let i=0,a=0,c=0===n,l=0;for(;i<o;){const t=e(l);if(t<0)break;if(i++,i===n&&(a=t+1,c=!0),i===o)return{from:a,to:s&&t>a&&13===r(t)?t-1:t};l=t+1}return c?{from:a,to:t}:{from:t,to:t}}function zS(e,t,r){const n=qS((t=>e.indexOf("\n",t)),e.length,(t=>e.charCodeAt(t-1)),t,r,!1);return 0===n.from&&n.to===e.length?e:n.from>=n.to?"":e.slice(n.from,n.to)}function GS(e,t,r,n,o){if(t>=r)return{text:"",truncated:!1};const s=n>=0?n+3:-1;let i=t;if(n>=0&&i>=n&&i<s&&(i=s),i>=r)return{text:"",truncated:!1};const a=function(e,t,r,n){if(r>=n)return n;if(r<=t)return t;const o=Math.max(t,r-3);let s=r;for(;s>o;){if(128!=(192&(e[s]??0)))return s;s--}return 192&~(e[s]??0)?r:s}(e,i,Math.min(r,i+3*(o+1)+3),r);let c=HS(function(e,t,r,n){if(t>=r)return"";if(n<0)return e.toString("utf8",t,r);const o=n+3;return r<=n||t>=o?e.toString("utf8",t,r):t>=n&&r<=o?"":(t<n?e.toString("utf8",t,Math.min(r,n)):"")+(r>o?e.toString("utf8",Math.max(t,o),r):"")}(e,i,a,n));const l=c.length>o||a<r;return c.length>o&&(c=No(c,o)),{text:c,truncated:l}}function VS(e,t,r,n){if(t>=r)return{text:"",truncated:!1};const o=Math.min(r,t+2*n+1);let s=HS(e.slice(t,o));const i=s.length>n||o<r;return s.length>n&&(s=No(s,n)),s.length<e.length&&(s=uk(s)),{text:s,truncated:i}}function KS(e,t,r=8388608){if(0===t.length)return e;const n=r-e.text.length;return n<=0?{text:e.text,truncated:!0}:t.length>n?{text:e.text+No(t,n),truncated:!0}:{text:e.text+t,truncated:e.truncated}}function JS(e,t){if(e.truncated)return e;const r=KS(e,t);return{text:r.text,truncated:r.truncated}}function ZS(e,t,r){let n=e;return t.forEach(((e,t)=>{const o=function(e,t){const{line:r,hasNewline:n}=e;return t&&n&&r.text.endsWith("\r")?{...r,text:r.text.slice(0,-1)}:r}(e,r);t>0&&(n=KS(n,"\n")),n=KS(n,o.text),o.truncated&&(n={text:n.text,truncated:!0})})),n}function XS(e){const t=e.toLowerCase();return"utf-8"===t?"utf8":"utf-8-bom"===t||"utf-8 bom"===t?"utf8bom":"latin-1"===t?"latin1":t}function QS(e){return void 0===e.maxChars||void 0!==e.offset||void 0!==e.limit?Ns:Math.min(Ns,e.maxChars+2)}function YS(e,t,r){if(!t||void 0===r.maxChars||e.length-1<=r.maxChars)return e;const n=e.charCodeAt(e.length-1);return n>=55296&&n<=56319?e.slice(0,-1):e}class ek extends Error{constructor(){super("Invalid UTF-8 while streaming read"),this.name="InvalidUtf8Error"}}function tk(e){for(let t=1;t<=Math.min(3,e.length);t++){const r=e[e.length-t]??0;if(128!=(192&r))return rk(r)>t?t:0}return 0}function rk(e){return e>=240?4:e>=224?3:e>=192?2:1}class nk{constructor(e,t,r){this.previousEndsWithCr=e,this.carry=t,this.strict=r,this.lines=0,this.crlfCount=0,this.lfOnlyCount=0,this.continuesLine=t.length>0}count(e){this.strict&&this.validate(e),0===this.lines&&e.length>0&&10!==e[0]&&(this.continuesLine=!0);for(let t=e.indexOf(10);-1!==t;t=e.indexOf(10,t+1))(t>0?13===e[t-1]:this.previousEndsWithCr)?this.crlfCount++:this.lfOnlyCount++,this.lines++;e.length>0&&(this.previousEndsWithCr=13===e[e.length-1])}finish(){if(this.strict&&this.carry.length>0)throw new ek}validate(e){let t=e;if(this.carry.length>0){const r=rk(this.carry[0]??0)-this.carry.length;if(e.length<r)return void(this.carry=Buffer.concat([this.carry,e]));if(!(0,n.isUtf8)(Buffer.concat([this.carry,e.subarray(0,r)])))throw new ek;t=e.subarray(r)}const r=tk(t);if(!(0,n.isUtf8)(t.subarray(0,t.length-r)))throw new ek;this.carry=Buffer.from(t.subarray(t.length-r))}}function ok(e,t){const r=function({file:e,stats:t,format:r},n){return XS(n??Hi(e,t)??r.encoding)}(e,t),n=function(e){const t=XS(e);return"utf8bom"===t?"utf8":t}(r);return"utf8"===n?{kind:"strictUtf8",cacheEncoding:"utf8"}:Ls.encodingExists(n)?{kind:"iconv",decoderEncoding:n,cacheEncoding:r}:{kind:"strictUtf8",cacheEncoding:"utf8"}}function sk(e){const t=DS(e),r=LS(e,t);return"utf-8"!==FS(e.subarray(t,r))?"other_encoding":function(e){if((0,n.isUtf8)(e))return"utf8_valid";const t=el(e);return t>0&&(0,n.isUtf8)(e.subarray(0,e.length-t))?"utf8_cut":"utf8_invalid"}(e)}async function ik(e,t){const r=t>0?Math.min(t,RS):RS,o=await MS(e,r);return o.length===t&&(0,n.isUtf8)(o)||Ys(new Fs.TextDecoder("utf-8",{fatal:!1}).decode(o,{stream:o.length===RS&&o.length!==t}))?{kind:"lossyUtf8",cacheEncoding:"utf8"}:{kind:"iconv",decoderEncoding:"latin1",cacheEncoding:"latin1"}}async function ak(e){const t=await(0,fo.stat)(e),r=await Di(e);if(r.isBinaryFile)return;const n=ok({file:e,stats:t,format:r},void 0);if("iconv"===n.kind)return n.decoderEncoding;const o=await ik(e,t.size);return"iconv"===o.kind?o.decoderEncoding:void 0}async function ck(e,{file:t,stats:r},n,o,s){const i=r.size,a=void 0!==n.offset||void 0!==n.limit,c=(n.offset??1)<0,l=n.offset??1,u=Math.max(0,l-1),d=void 0===n.limit?void 0:u+n.limit,h=c?Math.abs(l):0,p=a?1/0:n.maxChars??1/0,f=a&&!c?n.maxChars??1/0:1/0;let m=[],g=0,w=!1,y=0,v=!1,b=!(c||a&&u<=0),S=!1;const k=[];let _,C=0,E=!1,x=0,P=!1,I=[],R=0,T=0,A=0,$=!1,M={text:"",truncated:!1},D=!1,O=!1,F=0,N=0,L=0,j=!1,U=!1;const B=e=>{let t=e;return!j&&t.length>0&&(j=!0,65279===t.charCodeAt(0)&&(U=!0,t=t.slice(1))),t},W=(e,t)=>t&&13===e.text.charCodeAt(e.text.length-1),H=()=>P||E&&C>=Ns,q=()=>v||w&&g>=Ns,z=(e,t)=>{if(H())return;const r=k.length>0?1:0;let n=Ns-C;if(r>0){if(n<=0)return void(E=!0);n--}const o=e.text.length>n?{line:{text:No(e.text,n),truncated:!0},hasNewline:t}:{line:e,hasNewline:t};k.push(o),C+=r+(o.line.truncated?n:o.line.text.length),e.truncated&&(E=!0),o.line.truncated&&(E=!0),W(o.line,t)&&x++,C-x>f&&(P=!0,_=F)},G=(e,t)=>{if(q())return;const r=m.length>0?1:0;let n=Ns-g;if(r>0){if(n<=0)return void(w=!0);n--}const o=e.text.length>n?{line:{text:No(e.text,n),truncated:!0},hasNewline:t}:{line:e,hasNewline:t};m.push(o),g+=r+(o.line.truncated?n:o.line.text.length),(e.truncated||o.line.truncated)&&(w=!0),W(o.line,t)&&y++,g-y>p&&(v=!0,_=F)},V=(e,t)=>{e&&(t?N++:L++),F++},K=()=>{const e=I[R];void 0!==e&&(A-=e.line.text.length+1),I[R]=void 0,R=(R+1)%I.length,T--},J=(e,t,r)=>{const n=F;if(0===n&&(S=0===e.text.length),!c&&a&&b&&n>=u&&(b=!1,m=[]),b&&G(e,t),c){if(h>0)for(T===h&&K(),(e=>{if(T===I.length){const e=new Array(Math.min(h,Math.max(16,2*I.length)));for(let t=0;t<T;t++)e[t]=I[(R+t)%I.length];I=e,R=0}I[(R+T)%I.length]=e,T++})({line:e,hasNewline:t}),A+=e.text.length+1;T>1&&A>Ns;)K(),$=!0}else a&&n>=u&&(void 0===d||n<d)&&z(e,t);V(t,r)},Z=()=>!(D||(!b||q())&&(!a||0!==F)&&!(c?h>0:!(!a||H())&&F>=u&&F<(d??1/0))),X=()=>{const e=M.text.length-1;if(a){const t=!c&&F>=u&&F<(d??1/0),r=k.length>0?1:0;if(!t||C-x+r+e<=f)return;z(M,!1)}else{const t=m.length>0?1:0;if(g-y+t+e<=p)return;G(M,!1)}M={text:"",truncated:!1},D=!0};let Q;const Y=e=>{if(void 0===n.maxChars||c)return;if(!(a?H()||F>=(d??1/0):q()))return;const t=e.subarray(e.length-tk(e));return Q=new nk(ee,Buffer.from(t),"strictUtf8"===o.kind),Q};let ee=!1;for await(const r of async function*(e,t,r,n,o){const s=function(e){return e>0?{start:0,end:e-1}:{}}(n);if("strictUtf8"===r.kind||"lossyUtf8"===r.kind){const n=new Fs.TextDecoder("utf-8",{fatal:"strictUtf8"===r.kind,ignoreBOM:!0}),i=(0,go.createReadStream)(t,{highWaterMark:IS,signal:e.signal,...s});let a;try{for await(const e of i){if(void 0!==a){a.count(e);continue}const t=n.decode(e,{stream:!0});t.length>0&&(yield t),e.length>=4&&(a=o?.(e))}if(void 0!==a)return void a.finish();const e=n.decode();e.length>0&&(yield e)}catch(e){if(e instanceof TypeError)throw new ek;throw e}return}const i=(0,go.createReadStream)(t,{highWaterMark:IS,signal:e.signal,...s}).pipe(Ls.decodeStream(r.decoderEncoding));for await(const e of i)yield"string"==typeof e?e:String(e)}(e,t,o,i,Y)){const e=B(r);let t=0,n=e.indexOf("\n",t);for(;-1!==n;){const r=n>t?13===e.charCodeAt(n-1):ee;Z()?(M=JS(M,e.slice(t,n)),J(M,!0,r)):(D&&n>t&&(O=!0),V(!0,r)),M={text:"",truncated:!1},D=!1,ee=!1,t=n+1,n=e.indexOf("\n",t)}t<e.length&&(Z()?(M=JS(M,e.slice(t)),X()):D&&(O=!0),ee=13===e.charCodeAt(e.length-1))}void 0!==Q&&(F+=Q.lines,N+=Q.crlfCount,L+=Q.lfOnlyCount,D&&Q.continuesLine&&(O=!0)),Z()?J(M,!1,!1):V(!1,!1);const te=N+L,re=te>0&&N/te*100>=5,ne="utf8"===o.cacheEncoding&&U?"utf8bom":o.cacheEncoding;s&&qi(t,r,ne);const oe=Math.min(F,a?d??1/0:1/0),se=void 0!==_&&(O||oe>_+1),ie=(n.maxChars??1/0)+IS,ae=e=>e.text.length>ie?{text:No(e.text,ie),truncated:!0}:e,ce=()=>ZS({text:"",truncated:w||se},m,re);if(!a){const e=ae(ce());return{content:e.text,totalLines:F,truncated:e.truncated,rangeApplied:!1}}if(F<=1&&S)return{content:"",totalLines:F,truncated:!1,rangeApplied:!1};if(c){const e=n.limit??h,t=[];for(let e=0;e<T;e++){const r=I[(R+e)%I.length];void 0!==r&&t.push(r)}let r={text:"",truncated:$};return r=ZS(r,t.slice(0,e),re),{content:r.text,totalLines:F,truncated:r.truncated,rangeApplied:!0}}if(u>=F){const e=ce();return{content:e.text,totalLines:F,truncated:e.truncated,rangeApplied:!1}}const le=ae(ZS({text:"",truncated:E||se},k,re));return{content:le.text,totalLines:F,truncated:le.truncated,rangeApplied:!0}}class lk{constructor(e,t,r){this.permissionsService=e,this.workspacePath=t,this.terminalReads=new cl,this.mcpStateAccessor=r?.mcpStateAccessor,this.useStreamingRead=r?.useStreamingRead,this.pendingDecisionProvider=r?.pendingDecisionProvider,this.encodingSlices=r?.encodingSlices}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,$.VI)(e.withName("LocalReadExecutor.execute")),!1);const o=t.path;if(""===o.trim())return new Fw.sV({result:{case:"error",value:new Fw.F_({path:o,error:qo})}});const i=(0,Ho.o1)(o,this.workspacePath),a=await AS(e,"permissionsService.shouldBlockFileRead",3e3,(()=>SS(this.permissionsService,i)));if(a){const r=await AS(e,"resolveFileReadBlock",3e3,(()=>async function(e,t){return await lu(e,{onNeedsApproval:async(e,r)=>{const n=t.pendingDecisionProvider?.requestReadApproval?.bind(t.pendingDecisionProvider);if("fileRead"!==r.type||!n)return{kind:"denied",message:"Blocked by permissions configuration"};const o=await n({type:xg.Read,details:{path:r.path,reason:e},toolCallId:t.toolCallId});return o.approved?null:{kind:"rejected",reason:o.reason}},onUserRejected:e=>({kind:"rejected",reason:e}),onPermissionDenied:e=>({kind:"denied",message:e})})??{kind:"proceed"}}(a,{pendingDecisionProvider:this.pendingDecisionProvider,toolCallId:t.toolCallId})));if("rejected"===r.kind)return new Fw.sV({result:{case:"rejected",value:new Fw.f4({path:i,reason:r.reason??""})}});if("denied"===r.kind)return new Fw.sV({result:{case:"permissionDenied",value:new Fw.lW({path:i})}})}void 0!==this.mcpStateAccessor&&$w(e,this.mcpStateAccessor,i);try{const r=await AS(e,"stat",3e3,(()=>(0,fo.stat)(i)));if(r.isDirectory())return new Fw.sV({result:{case:"invalidFile",value:new Fw.cW({path:i,reason:"Path is a directory, not a file"})}});if(!r.isFile())return new Fw.sV({result:{case:"invalidFile",value:new Fw.cW({path:i,reason:"Path is neither a file nor a directory"})}});const o=function(e){return null!==function(e){const t=Gh(e,"terminals");if(!t||1!==t.remainingPath.length)return null;const r=t.remainingPath[0],n=/^(\d+)\.txt$/.exec(r);if(!n)return null;const o=Number.parseInt(n[1],10);return Number.isNaN(o)?null:{id:o}}(e)}(i),a=function(e){const t=Gh(e,"agent-tools");return null!==t&&1===t.remainingPath.length&&t.remainingPath[0].endsWith(".txt")}(i);if(o||a)return await this.readTerminalFile(e,i,r,t,a&&!o);const c=await AS(e,"getFormatForFile",3e3,(()=>Di(i))),l=c.isImageFile,u=function(e){return".pdf"===(0,s.extname)(e).toLowerCase()}(i),d=Ii(i);if(l){const t=await AS(e,"prepareImageForModel",3e3,(async()=>(async e=>{let t;try{t=await by(e)}catch(t){const r=await Sy(e);if("undecodable"===r.kind)return r;throw t}if(!0===t.reencoded)return{kind:"image",image:t};const r=await Sy(t.data);return"undecodable"===r.kind?r:{kind:"image",image:t}})(await(0,fo.readFile)(i))));return"undecodable"===t.kind?new Fw.sV({result:{case:"invalidFile",value:new Fw.cW({path:i,reason:(n=t.reason,`File is not a valid image: its data could not be decoded (${n}). A truncated or hand-copied file does this; write it again from the original bytes with code.`)})}}):new Fw.sV({result:{case:"success",value:new Fw.mE({path:i,output:{case:"data",value:t.image.data},totalLines:0,fileSize:$S(r.size),truncated:!1})}})}if(u){const t=await AS(e,"readPdfBinary",3e3,(()=>(0,fo.readFile)(i)));return new Fw.sV({result:{case:"success",value:new Fw.mE({path:i,output:{case:"data",value:t},totalLines:0,fileSize:$S(r.size),truncated:!1})}})}if(c.isBinaryFile&&d){if(void 0!==t.maxVideoBytes&&r.size>t.maxVideoBytes)return new Fw.sV({result:{case:"success",value:new Fw.mE({path:i,totalLines:0,fileSize:$S(r.size),truncated:!0})}});const n=await AS(e,"readBinaryFile",3e3,(()=>(0,fo.readFile)(i)));return new Fw.sV({result:{case:"success",value:new Fw.mE({path:i,output:{case:"data",value:n},totalLines:0,fileSize:$S(r.size),truncated:!1})}})}if(c.isBinaryFile)return US(i);{const n=this.useStreamingRead,o=!n||await AS(e,"useStreamingRead",3e3,(()=>n()));if(o||r.size>Ns){const n=await AS(e,"readTextStreaming",7e3,(()=>async function(e,t,r,n){const o=ok(t,r.encodingHint);try{return{...await ck(e,t,r,o,n),decoder:o.kind}}catch(o){if(o instanceof ek){const o=await ik(t.file,t.stats.size);return{...await ck(e,t,r,o,n),decoder:o.kind}}throw o}}(e,{file:i,stats:r,format:c},t,o))),s=YS(n.content,n.truncated,t);return Qc(this.encodingSlices,e)&&this.recordStreamedRead(e,i,r.size,n,s),new Fw.sV({result:{case:"success",value:new Fw.mE({path:i,output:{case:"content",value:s},totalLines:n.totalLines,fileSize:$S(r.size),truncated:n.truncated,rangeApplied:n.rangeApplied})}})}const s=await AS(e,"readText",3e3,(()=>Ti(i,t.encodingHint))),a=await AS(e,"countLines",3e3,(()=>Us(s))),l=function(e,t,r){const n=BS(t,""===e,r);return n.applied?n.start>=n.end?{content:"",rangeApplied:!0}:{content:zS(e,n.start,n.end),rangeApplied:!0}:{content:e,rangeApplied:!1}}(s,a,t);let u=l.content,d=!1;const h=QS(t);return u.length>h&&(u=YS(u.substring(0,h),!0,t),d=!0),u.length<s.length&&(u=uk(u)),dl(this.encodingSlices,e,{layer:"exec_read"},u),new Fw.sV({result:{case:"success",value:new Fw.mE({path:i,output:{case:"content",value:u},totalLines:a,fileSize:$S(r.size),truncated:d,rangeApplied:l.rangeApplied})}})}}catch(e){const t=Ua(e);return"ENOENT"===t?new Fw.sV({result:{case:"fileNotFound",value:new Fw.Ko({path:i})}}):"EACCES"===t||"EPERM"===t?new Fw.sV({result:{case:"permissionDenied",value:new Fw.lW({path:i})}}):new Fw.sV({result:{case:"error",value:new Fw.F_({path:i,error:e instanceof Error?e.message:"Unknown error occurred"})}})}}catch(e){r.error=e,r.hasError=!0}finally{PS(r)}var n}async recordStreamedRead(e,t,r,o,s){try{const i=function(e){try{const t=new al;return t.note(e),t.kind()}catch{return}}(s);if(void 0===i)return;let a=function(e){switch(e){case"strictUtf8":return"utf8_valid";case"lossyUtf8":return"utf8_invalid";case"iconv":return"other_encoding";default:return e}}(o.decoder);"other_encoding"===a&&"clean"!==i&&(a=await async function(e,t){if(t<=0||t>16777216)return"other_encoding";try{return r=await MS(e,t),!(0,n.isAscii)(r)&&(0,n.isUtf8)(r)?"utf8_as_other":"other_encoding"}catch{return"other_encoding"}var r}(t,r)),hl(this.encodingSlices,e,{layer:"exec_read",evidence:a,partial:o.rangeApplied||o.truncated},i)}catch{}}async readTerminalFile(e,t,r,n,o){const s=await AS(e,"readTerminalFile",3e3,(()=>MS(t,r.size)));if(o&&(i=s,jS.some((e=>function(e,t){return e.length>=t.length&&e.subarray(0,t.length).equals(t)}(i,e)))))return US(t);var i;const a=function(e,t,r=8388608){if(0===e.length)return{content:"",totalLines:1,rangeApplied:!1,truncated:!1};const n=DS(e),o=LS(e,n);if("utf-8"!==FS(e.subarray(n,o)))return function(e,t,r){const n=0===e.length,o=function(e){let t=0,r=0;const n=e.length;for(;r<n;){const n=e.indexOf("\n",r);if(n<0)break;t++,r=n+1}return t}(e)+1,s=BS(o,n,t);if(!s.applied){const t=VS(e,0,e.length,r);return{content:t.text,totalLines:o,rangeApplied:!1,truncated:t.truncated}}if(s.start>=s.end)return{content:"",totalLines:o,rangeApplied:!0,truncated:!1};const i=qS((t=>e.indexOf("\n",t)),e.length,(t=>e.charCodeAt(t-1)),s.start,s.end,!0),a=VS(e,i.from,i.to,r);return{content:a.text,totalLines:o,rangeApplied:!0,truncated:a.truncated}}(function(e){const t=DS(e),r=t>0?e.subarray(0,t).toString("utf-8"):"",n=LS(e,t),o=n<e.length?e.subarray(n).toString("utf-8"):"",s=e.subarray(t,n),i=FS(s);let a;if("utf-16le"===i)a=s.toString("utf16le");else if("utf-16be"===i){const e=s.length-s.length%2,t=Buffer.from(s.subarray(0,e));t.swap16(),a=t.toString("utf16le")}else a=s.toString("utf-8");return 65279===a.charCodeAt(0)&&(a=a.slice(1)),r+a+o}(e),t,r);const s=function(e,t,r){return t+3>r?-1:239===e[t]&&187===e[t+1]&&191===e[t+2]?t:-1}(e,n,o);return function(e,t,r,n){const o=e.length-(t>=0?3:0)==0,s=function(e){let t=0,r=0;const n=e.length;for(;r<n;){const n=e.indexOf(10,r);if(n<0)break;t++,r=n+1}return t}(e)+1,i=BS(s,o,r);if(!i.applied){if(o)return{content:"",totalLines:s,rangeApplied:!1,truncated:!1};const r=GS(e,0,e.length,t,n);return{content:r.text,totalLines:s,rangeApplied:!1,truncated:r.truncated}}if(i.start>=i.end)return{content:"",totalLines:s,rangeApplied:!0,truncated:!1};const a=qS((t=>e.indexOf(10,t)),e.length,(t=>e[t-1]??0),i.start,i.end,!0),c=GS(e,a.from,a.to,t,n);return{content:c.text,totalLines:s,rangeApplied:!0,truncated:c.truncated}}(e,s,t,r)}(s,n,QS(n)),c=YS(a.content,a.truncated,n);return Qc(this.encodingSlices,e)&&(o||this.terminalReads.firstRead(n.toolCallId,t))&&dl(this.encodingSlices,e,{layer:o?"exec_read":"exec_terminal_context",evidence:sk(s),partial:a.rangeApplied||a.truncated},c),new Fw.sV({result:{case:"success",value:new Fw.mE({path:t,output:{case:"content",value:c},totalLines:a.totalLines,fileSize:$S(r.size),truncated:a.truncated,rangeApplied:a.rangeApplied})}})}}function uk(e){return Buffer.from(e,"utf16le").toString("utf16le")}var dk=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},hk=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function pk(e){return`Path '${e}' could not be verified while resolving symlinks. This can happen when access is denied or the path contains a symlink loop.`}function fk(e){return`Path '${e}' is neither a file nor a directory`}async function mk(e){const t=await(0,fo.stat)(e).catch((()=>{}));return void 0!==t&&!t.isFile()&&!t.isDirectory()}function gk(e,t,r){const n=function(e,t){let r;for(const n of t)(0,Ho.ZU)({basePath:n,targetPath:e})&&(void 0===r||n.length>r.length)&&(r=n);return r}((0,s.resolve)(e,t),r);return void 0===n||n===e}class wk extends Error{}function yk(e){const t=new AbortController,r=setTimeout((()=>t.abort()),e);return{signal:t.signal,clear:()=>clearTimeout(r)}}function vk(e){switch(e.result.case){case"content":return e.result.value.matches.length>0;case"files":return e.result.value.files.length>0;case"count":return e.result.value.counts.length>0;case void 0:return!1;default:{const t=e.result;throw new Error(`Unknown grep result: ${String(t)}`)}}}function bk(e){switch(e){case"content":return new pw.vD({result:{case:"content",value:new pw.Zp({ripgrepTruncated:!0})}});case"files_with_matches":return new pw.vD({result:{case:"files",value:new pw.T7({ripgrepTruncated:!0})}});case"count":return new pw.vD({result:{case:"count",value:new pw.xA({ripgrepTruncated:!0})}});default:throw new Error(`Unknown output mode: ${String(e)}`)}}function Sk(e){return"success"===e.result.case&&Object.values(e.result.value.workspaceResults).some((e=>!0===e.result.value?.clientTruncated))}function kk(e,t,r){let n=Buffer.concat(e);t&&(n=n.subarray(0,n.lastIndexOf(10)+1)),r?.note(n);const o=n.toString("utf8");return o.includes("�")?{stdout:o,stdoutBytes:n}:{stdout:o}}function _k(e){return/^(utf-?16|ucs-?2)/i.test(e)}const Ck=(0,l.h)("local-exec/grep"),Ek=(0,u.Pu)("local_exec.grep.deadline_reached",{description:"Grep and Glob searches the search deadline stopped, by whether they kept what was found",labelNames:["output_mode","outcome","streaming"]}),xk=(0,u.Pu)("local_exec.grep.newest_first_stat_fallback",{description:"Grep and Glob results left in ripgrep's order because stat was too slow to sort them",labelNames:["output_mode"]}),Pk=(0,u.v5)("local_exec.grep.rg.spawn_ms",{description:"Time to start the ripgrep process for one Grep or Glob search",labelNames:["sandboxed"]}),Ik=(0,u.v5)("local_exec.grep.rg.search_ms",{description:"Time ripgrep took to search and exit after it started, for runs it finished",labelNames:["output_mode","sandboxed"]});function Rk(e){return e instanceof Error&&e.message.includes("ENOENT")&&e.message.includes("spawn")}function Tk(e){try{return(0,go.existsSync)(e)}catch{return"check_failed"}}function Ak(e){if("object"==typeof e&&null!==e&&"errno"in e){const t=e.errno;if("number"==typeof t)return t}}function $k(e,t){if("object"==typeof e&&null!==e)return"syscall"===t&&"syscall"in e&&"string"==typeof e.syscall?e.syscall:"path"===t&&"path"in e&&"string"==typeof e.path?e.path:void 0}function Mk(e,t,r,n){return{...Ok(e),...n,cwd:t,cwdExists:Tk(t),errorMessage:Ba(r),errorCode:Ua(r),errno:Ak(r),syscall:$k(r,"syscall"),errorPath:$k(r,"path")}}function Dk(e){return new Error(`Path does not exist: ${e}`)}function Ok(e){const t={rgPath:e,platform:process.platform,arch:process.arch,pid:process.pid,uptimeSeconds:Math.round(process.uptime()),execPath:process.execPath};try{t.rgPathExists=(0,go.existsSync)(e)}catch(e){t.rgPathExists=!1,t.rgPathExistsError=e instanceof Error?e.message:String(e)}try{const r=(0,go.lstatSync)(e);t.rgIsSymlink=r.isSymbolicLink(),r.isSymbolicLink()&&!t.rgPathExists&&(t.rgBrokenSymlink=!0)}catch{t.rgLstatFailed=!0}const r=(0,s.dirname)(e);try{t.parentDirExists=(0,go.existsSync)(r),t.parentDirExists&&(t.parentDirContents=(0,go.readdirSync)(r).slice(0,50))}catch(e){t.parentDirError=e instanceof Error?e.message:String(e)}const n=(0,s.dirname)(r);try{t.grandparentDirExists=(0,go.existsSync)(n),t.grandparentDirExists&&(t.grandparentDirContents=(0,go.readdirSync)(n).slice(0,50))}catch(e){t.grandparentDirError=e instanceof Error?e.message:String(e)}if(t.rgPathExists)try{const r=(0,go.statSync)(e);t.rgFileSize=r.size,t.rgFileMode=r.mode.toString(8),t.rgIsFile=r.isFile(),t.rgModifiedMs=r.mtimeMs}catch(e){t.rgStatError=e instanceof Error?e.message:String(e)}const o="node_modules.asar.unpacked";if(e.includes(o)){const r=e.split(o)[0];if(r){const n=r.concat("node_modules.asar");try{t.asarExists=(0,go.existsSync)(n)}catch{t.asarExists="check_failed"}const i=r.concat(o);try{if(t.asarUnpackedDirExists=(0,go.existsSync)(i),t.asarUnpackedDirExists){const r=(0,s.dirname)((0,s.dirname)(e));t.ripgrepPkgDirExists=(0,go.existsSync)(r)}}catch{t.asarUnpackedDirExists="check_failed"}}}return t}class Fk{constructor(e,t,r,n){this.ignoreService=e,this.grepProvider=t,this.workspacePath=r,this.stdoutDecodes=new WeakMap;const o=Array.isArray(this.workspacePath)?this.workspacePath[0]:this.workspacePath;this.singleWorkspacePath=Array.isArray(this.workspacePath)&&this.workspacePath.length>1?void 0:o,this.mcpStateAccessor=n?.mcpStateAccessor,this.permissionsService=n?.permissionsService,this.useStreamingGrep=n?.useStreamingGrep,this.encodingSlices=n?.encodingSlices}computeRelativeTarget(e,t){const r=(0,Ho.o1)(e,this.singleWorkspacePath??t);return r===t?".":(0,s.relative)(t,r)}isRootIndependentSearchPath(e){return(0,s.isAbsolute)(e)||/^~(?=$|[/\\])/.test(e)||e.startsWith("file://")}resolveSearchTargets(e,t){const r=this.isRootIndependentSearchPath(e);return t.map((t=>{const n=(0,s.resolve)(t);return{root:t,resolvedRoot:n,target:(0,Ho.o1)(e,r?void 0:n)}}))}findOutsideTargets(e,t){if(void 0===e||""===e)return;const r=this.resolveSearchTargets(e,t);return r.some((({resolvedRoot:e,target:t})=>(0,Ho.BJ)(t,e)))?void 0:[...new Set(r.map((({target:e})=>e)))]}searchTarget(e,t){if(!t.path)return".";const r=(0,Ho.o1)(t.path,this.singleWorkspacePath??e);return(0,Ho.BJ)(r,(0,s.resolve)(e))?this.computeRelativeTarget(t.path,e):r}sortsAfterRipgrep(e,t,r){return void 0===t.sort&&(r?!0!==t.sortAscending:(0,s.isAbsolute)(this.searchTarget(e,t)))}async buildArgs(e,t,r,n){const o=[],s=function(e,t){return"files_with_matches"===t&&""===e.pattern&&Boolean(e.glob)}(t,r),i=await oa(await this.ignoreService.listCursorIgnoreFilesByRoot(e));for(const e of i)o.push("--cursor-ignore",e);if("content"===r)o.push("--line-number","--with-filename","--no-heading","-0"),void 0!==t.contextBefore&&o.push("--before-context",String(t.contextBefore)),void 0!==t.contextAfter&&o.push("--after-context",String(t.contextAfter)),o.push("--max-columns",String(1e3),"--max-columns-preview"),void 0!==t.context&&void 0===t.contextBefore&&void 0===t.contextAfter&&o.push("--before-context",String(t.context),"--after-context",String(t.context));else if("files_with_matches"===r)o.push(s?"--files":"-l");else{if("count"!==r)throw new Error(`Unknown output mode: ${String(r)}`);o.push("-c","--with-filename")}!0===t.caseInsensitive?o.push("--ignore-case"):o.push("--case-sensitive"),t.type&&o.push("--type",t.type),t.glob&&(o.push("--iglob",t.glob),s&&o.push("--iglob","!**/.git")),t.multiline&&o.push("--multiline","--multiline-dotall");const a=n?"none":t.sort??"modified";if(n&&o.push("--line-buffered"),"none"!==a){const e=!0===t.sortAscending?"--sort":"--sortr";o.push(e,a)}o.push("--no-config","--color=never"),o.push("--hidden"),o.push("--follow");const c=this.searchTarget(e,t);if(t.path){const t=await async function(e){try{if(!(await(0,fo.stat)(e)).isFile())return;const{encoding:t}=await Di(e);return _k(t)?t.toLowerCase():void 0}catch{return}}((0,Ho.o1)(c,e));void 0!==t&&o.push("--encoding",t)}return s||o.push("--regexp",t.pattern),o.push("--"),o.push(c),o}async filterBlockedFiles(e,t){const r=new Map,n=await(this.permissionsService?.getFileReadBoundaryBlocker?.()),o=[];for(const s of e){const e=(0,Ho.o1)(s.file,t),i=await Ha(e);null===i||await this.isPostRipgrepBlocked(i,r)||void 0!==n&&await n(e,i)||o.push(s)}return o}async isPostRipgrepBlocked(e,t){const[r,n]=await Promise.all([this.ignoreService.isCursorIgnored(e,t),this.ignoreService.isRepoBlocked(e)]);return r||n}throwOnRipgrepFailure(e,t,r){if((""!==e.stderr||2===e.exitCode)&&""===e.stdout.trim()&&!function({stderr:e,target:t}){return e.trim().split(/\r?\n/).every((e=>{if(/^rg: .+: line \d+: /.test(e))return!0;const r=/^rg: (.+?): .*\(os error (?:13|5|2|1)\)$/.exec(e)?.[1]??/^rg: File system loop found: (.+) points to an ancestor /.exec(e)?.[1];return void 0!==r&&r!==t}))}({stderr:e.stderr,target:this.searchTarget(t,r)}))throw new Error(e.stderr||`ripgrep exited with code ${e.exitCode}`)}async orderNewestFirst(e,t,r,n,o){const s=await Ow(t,(e=>(0,Ho.o1)(n(e),r)));return s.statTimedOut&&(Ck.info(e,"newest_first.stat_timeout_fallback",{toolCallId:o.toolCallId,execId:o.execId,outputMode:o.outputMode,fileCount:t.length}),xk.increment(e,1,{output_mode:o.outputMode})),s.items}async keepNewestPage(e,t,r,n,o){return(await this.orderNewestFirst(e,t,r,n,o)).slice(0,Fk.CLIENT_LIMIT_LINES)}async runFilesMode(e,t,r,n,o,s,i){const a={stack:[],error:void 0,hasError:!1};try{const d=dk(a,(0,$.VI)(e.withName("LocalGrepExecutor.runFilesMode")),!1),h=await this.buildArgs(t,r,"files_with_matches",n),p=await this.executeRg(d.ctx,t,h,void 0,o,s,i);this.throwOnRipgrepFailure(p,t,r);const f=(c=p.stdout,l=n?Fk.HARD_MAX_OUTPUT_LINES:Fk.CLIENT_LIMIT_LINES,u=Fk.HARD_MAX_OUTPUT_LINES,function(e,t,r){const n=e.trim();if(""===n)return{files:[],totalFiles:0,clientTruncated:!1,ripgrepTruncated:!1};const o=new fw;let s=0,i=0,a=0;for(;mw(n,a,o);)a=o.nextStart,s<t&&(i=o.nextStart),s++;const c=s>t?Buffer.from(n.slice(0,i)).toString():n,l=[];for(a=0;l.length<t&&mw(c,a,o);)l.push(c.slice(a,o.lineEnd)),a=o.nextStart;return{files:l,totalFiles:vw(s),clientTruncated:s>t,ripgrepTruncated:s>=r}}(c,l,u)),m=f.totalFiles>Fk.CLIENT_LIMIT_LINES;let g=f.files;n&&(g=await this.keepNewestPage(d.ctx,g,t,(e=>e),i),m&&(g=g.join("\0").split("\0")));const w=(await this.filterBlockedFiles(g.map((e=>({file:e}))),t)).map((({file:e})=>e)),y=g.length-w.length,v=new pw.T7({files:w,totalFiles:vw(f.totalFiles-y),clientTruncated:m,ripgrepTruncated:f.ripgrepTruncated||p.timedOut||p.stdoutByteCapped});return{result:new pw.vD({result:{case:"files",value:v}}),timedOut:p.timedOut}}catch(e){a.error=e,a.hasError=!0}finally{hk(a)}var c,l,u}async runCountMode(e,t,r,n,o,s,i){const a={stack:[],error:void 0,hasError:!1};try{const d=dk(a,(0,$.VI)(e.withName("LocalGrepExecutor.runCountMode")),!1),h=await this.buildArgs(t,r,"count",n),p=await this.executeRg(d.ctx,t,h,void 0,o,s,i);this.throwOnRipgrepFailure(p,t,r);const f=(c=p.stdout,l=n?Fk.HARD_MAX_OUTPUT_LINES:Fk.CLIENT_LIMIT_LINES,u=Fk.HARD_MAX_OUTPUT_LINES,function(e,t,r){const n=e.trim();if(""===n)return{counts:[],totalFiles:0,totalMatches:0,clientTruncated:!1,ripgrepTruncated:!1};const o=[],s=new fw;let i=0;for(;mw(n,i,s);){const e=i,t=s.lineEnd;if(i=s.nextStart,t===e)continue;const r=n.lastIndexOf(":",t-1);if(r<e||r===e)continue;const a=n.slice(r+1,t).trim(),c=parseInt(a,10);Number.isFinite(c)&&o.push({file:n.slice(e,r),count:c})}const a=o.length;let c=0;for(let e=0;e<o.length;e++){const t=o[e];void 0!==t&&(c+=t.count)}const l=[],u=a<t?a:t;for(let e=0;e<u;e++){const t=o[e];void 0!==t&&l.push(t)}return{counts:l,totalFiles:vw(a),totalMatches:vw(c),clientTruncated:a>t,ripgrepTruncated:a>=r}}(c,l,u)),m=n?await this.keepNewestPage(d.ctx,f.counts,t,(e=>e.file),i):f.counts,g=await this.filterBlockedFiles(m,t),w=g.reduce(((e,t)=>e+t.count),0),y=m.length-g.length,v=m.reduce(((e,t)=>e+t.count),0)-w,b=new pw.xA({counts:g.map((e=>new pw.sS({file:e.file,count:vw(e.count)}))),totalFiles:vw(f.totalFiles-y),totalMatches:vw(f.totalMatches-v),clientTruncated:f.totalFiles>Fk.CLIENT_LIMIT_LINES,ripgrepTruncated:f.ripgrepTruncated||p.timedOut||p.stdoutByteCapped});return{result:new pw.vD({result:{case:"count",value:b}}),timedOut:p.timedOut}}catch(e){a.error=e,a.hasError=!0}finally{hk(a)}var c,l,u}async runContentMode(e,t,r,n,o,s,i){const a={stack:[],error:void 0,hasError:!1};try{const c=dk(a,(0,$.VI)(e.withName("LocalGrepExecutor.runContentMode")),!1),l=await this.buildArgs(t,r,"content",n),u=void 0!==r.context||void 0!==r.contextBefore||void 0!==r.contextAfter,d=Fk.CLIENT_LIMIT_LINES*(u?2:1),h=await this.executeRg(c.ctx,t,l,d,o,s,i);this.throwOnRipgrepFailure(h,t,r);const p=await this.decodeLinesAsRead(c.ctx,h,t,i),{byFile:f,totalLines:m,totalMatchedLines:g,clientTruncated:w,ripgrepTruncated:y}=function(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{return dk(o,(0,$.VI)(n.withName("parseContentOutput")),!1),function(e,t,r){const n={byFile:new Map,totalLines:0,totalMatchedLines:0,totalFiles:0,clientTruncated:!1,ripgrepTruncated:!1};if(""===e.trim())return n;const o=new Map,s=new Set,i=new fw;let a=0,c=0,l=0,u=0;for(;mw(e,u,i);){const r=u,n=i.lineEnd;if(u=i.nextStart,l++,d=e,n-(h=r)==2&&45===d.charCodeAt(h)&&45===d.charCodeAt(h+1))continue;let p=-1;for(let t=r;t<n;t++)if(0===e.charCodeAt(t)){p=t;break}if(-1===p)continue;let f=p+1;if(f>=n)continue;let m=0,g=0;for(;f<n;){const t=e.charCodeAt(f);if(t<48||t>57)break;m=10*m+(t-48),g++,f++}if(0===g||f>=n||!Number.isFinite(m))continue;const w=e.charCodeAt(f);if(58!==w&&45!==w)continue;const y=45===w;y||a++;const v=e.slice(r,p);if(s.has(v)||s.add(v),c>=t)continue;const b=e.slice(f+1,n);let S=o.get(v);void 0===S&&(S={file:v,matches:[]},o.set(v,S)),S.matches.push({lineNumber:m,content:b,isContextLine:y}),c++}var d,h;return{byFile:o,totalLines:vw(l),totalMatchedLines:vw(a),totalFiles:vw(s.size),clientTruncated:c>=t,ripgrepTruncated:l>=r}}(e,t,r)}catch(e){o.error=e,o.hasError=!0}finally{hk(o)}}(p,Fk.CLIENT_LIMIT_LINES,d,c.ctx),v=Array.from(f.values()),b=await this.filterBlockedFiles(v,t),S=v.filter((e=>!b.includes(e))),k=S.reduce(((e,t)=>e+t.matches.length),0),_=S.reduce(((e,t)=>e+t.matches.filter((e=>!e.isContextLine)).length),0),C=n?await this.orderNewestFirst(c.ctx,b,t,(e=>e.file),i):b,E=new pw.Zp({matches:C.map((e=>new pw.uI({file:e.file,matches:e.matches.map((e=>new pw.dx({lineNumber:e.lineNumber,content:e.content,isContextLine:e.isContextLine})))}))),totalLines:vw(m-k),totalMatchedLines:vw(g-_),clientTruncated:w,ripgrepTruncated:y||h.timedOut||h.stdoutByteCapped});return{result:new pw.vD({result:{case:"content",value:E}}),timedOut:h.timedOut}}catch(e){a.error=e,a.hasError=!0}finally{hk(a)}}async decodeLinesAsRead(e,t,r,o){const s={stack:[],error:void 0,hasError:!1};try{const i=t.stdoutBytes;if(void 0===i)return t.stdout;const a=dk(s,(0,$.VI)(e.withName("LocalGrepExecutor.decodeLinesAsRead")),!1),c=function(e,t){const r=[],o=new fw;let s=0,i=0,a=e.indexOf("�");for(;-1!==a&&mw(e,s,o);){const{lineEnd:c,nextStart:l}=o,u=t.indexOf(10,i),d=-1===u?t.length:u+1;let h=-1===u?t.length:u;if(h>i&&-1!==u&&13===t[h-1]&&h--,a<l){const o=gw(e,s,c,t,i,h);void 0===o||(0,n.isUtf8)(t.subarray(o.contentBytesStart,o.contentBytesEnd))||r.push(o),a=e.indexOf("�",l)}s=l,i=d}return r}(t.stdout,i),l=[...new Set(c.map((e=>e.file)))],u=new Map,d=performance.now()+Fk.LINE_ENCODING_TIMEOUT_MS;let h=0;for(;h<l.length;h++){const e=d-performance.now();if(e<=0)break;let t;try{t=await(0,Dr.wj)(ak((0,Ho.o1)(l[h],r)),e,"encoding detection timed out")}catch(e){if(e instanceof Dr.MU)break;continue}void 0===t||_k(t)||u.set(l[h],t)}return h<l.length&&Ck.info(a.ctx,"line_encoding.detection_timeout",{toolCallId:o.toolCallId,execId:o.execId,fileCount:l.length,examinedFileCount:h}),function(e,t,r,n){const o=[];let s=0;for(const i of r){const r=n.get(i.file);void 0!==r&&(o.push(e.slice(s,i.contentStart),Ls.decode(t.subarray(i.contentBytesStart,i.contentBytesEnd),r,{stripBOM:!1})),s=i.contentEnd)}return 0===o.length?e:(o.push(e.slice(s)),o.join(""))}(t.stdout,i,c,u)}catch(e){s.error=e,s.hasError=!0}finally{hk(s)}}runMode(e,t,r,n,o,s,i,a){const c=this.sortsAfterRipgrep(r,n,o);switch(t){case"content":return this.runContentMode(e,r,n,c,s,i,a);case"files_with_matches":return this.runFilesMode(e,r,n,c,s,i,a);case"count":return this.runCountMode(e,r,n,c,s,i,a);default:throw new Error(`Unknown output mode: ${String(t)}`)}}async streamingEnabled(e,t){const r=this.useStreamingGrep;if(void 0===r)return!0;try{return await r()}catch(r){return Ck.warn(e,"streaming_grep_flag.read_failed",{toolCallId:t.toolCallId,execId:t.execId,errorName:r instanceof Error?r.name:typeof r}),!0}}reportDeadlineReached(e,t,r){Ck.info(e,"ripgrep.deadline_reached",{toolCallId:t.toolCallId,execId:t.execId,outputMode:t.outputMode,...r}),Ek.increment(e,1,{output_mode:t.outputMode,outcome:r.outcome,streaming:String(r.streaming)})}async executeIndexedGrepWithTimeout(e,t,r,n){if(void 0===this.grepProvider.executeIndexedGrep)return;const[o,s]=e.withTimeoutAndCancel(Fk.INDEXED_GREP_CONTEXT_TIMEOUT_MS),i={phase:"provider"},a=performance.now();try{return await(0,Dr.wj)(this.grepProvider.executeIndexedGrep(o,t,r,i),Fk.INDEXED_GREP_TIMEOUT_MS,`Indexed grep timed out after ${Fk.INDEXED_GREP_TIMEOUT_MS/1e3}s`)}catch(t){if(t instanceof Dr.MU)return s(t),void Ck.debug(e,"indexed_grep.timeout_fallback",{...n,totalMs:Math.round(performance.now()-a),...i});throw t}finally{s()}}static ripgrepTimeoutError(){return new wk(`Timed out after ${Fk.MAIN_TIMEOUT_MS/1e3}s`)}async executeRg(e,t,r,n,o,s,i){const a=(0,$.VI)(e.withName("LocalGrepExecutor.executeRg")),c=8388608;return n=n??Fk.HARD_MAX_OUTPUT_LINES,new Promise(((l,u)=>{let d=!1,h=!1;const p=()=>{h||(h=!0,a.span.end())};if(e.signal.aborted)return p(),void u(new Error("Grep was cancelled"));if(o.aborted)return p(),void u(Fk.ripgrepTimeoutError());let f;const m="insecure_none"===s.type?"false":"true",g=performance.now();let w=g;try{const e=s;f=(0,Eo.spawnInSandbox)((0,Eo.Ko)(),r,{cwd:t},e),w=performance.now(),0}catch(r){if(p(),Rk(r)){const n=(0,Eo.Ko)();if(Ck.error(e,"rg_diagnostics.spawn_throw",void 0,Mk(n,t,r,i)),!1===Tk(t))return u(Dk(t))}return u(r)}const y=[],v=[];let b=0,S=0,k=0,_=!1,C=!1,E=!1;const x=()=>{if(!d)try{p(),E=!0;const e=kk(y,!0,this.stdoutDecodes.get(i));""===e.stdout?u(Fk.ripgrepTimeoutError()):l({...e,stderr:"",exitCode:0,timedOut:!0,stdoutByteCapped:C}),f.kill()}catch{}};o.addEventListener("abort",x,{once:!0});const P=()=>{o.removeEventListener("abort",x),p(),u(new Error("Grep was cancelled"));try{f.kill()}catch{}};e.signal.addEventListener("abort",P,{once:!0}),f.stdout?.on("data",(e=>{if(!C&&!_)if(b+=e.length,b>c){C=!0;try{f.kill()}catch{}}else if(void 0!==n){let t=-1,r=0;for(let o=0;o<e.length;o++)if(10===e[o]&&(r++,k+r>=n)){t=o+1,_=!0;try{f.kill()}catch{}break}k+=r;const o=t>=0?e.subarray(0,t):e;y.push(o)}else y.push(e)})),f.stderr?.on("data",(e=>{S+=e.length,S<=c&&v.push(e)})),f.on("error",(r=>{if(o.removeEventListener("abort",x),e.signal.removeEventListener("abort",P),p(),Rk(r)){const n=(0,Eo.Ko)();if(Ck.error(e,"rg_diagnostics.spawn_enoent",void 0,Mk(n,t,r,i)),!1===Tk(t))return void u(Dk(t))}u(r)})),f.on("close",(t=>{const r=performance.now()-w;d=!0,o.removeEventListener("abort",x),e.signal.removeEventListener("abort",P);const n=kk(y,C,E?void 0:this.stdoutDecodes.get(i)),s=Buffer.concat(v).toString("utf8");p(),l({...n,stderr:s,exitCode:t??0,timedOut:!1,stdoutByteCapped:C}),Pk.histogram(e,w-g,{sandboxed:m}),C||_||o.aborted||e.signal.aborted||0!==t&&1!==t||Ik.histogram(e,r,{output_mode:i.outputMode,sandboxed:m})}))}))}async checkOutsideTarget(e,t){if(1!==t.length||void 0===t[0])return{error:`Path '${e}' points to a different folder from each workspace root; use an absolute path`};const r=await Ha(t[0]);return null===r?{error:pk(e)}:await this.ignoreService.isCursorIgnored(r)?{error:`Path '${e}' is filtered out by .cursorignore`}:await mk(t[0])?{error:fk(e)}:{resolvedTarget:r}}async execute(e,t,r){if(!Qc(this.encodingSlices,e))return this.search(e,t,r,void 0);const n=new pl,o=await this.search(e,t,r,n);return"success"===o.result.case&&dl(this.encodingSlices,e,{layer:"exec_grep",evidence:n.evidence(),partial:Sk(o)},o),o}async search(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{const a=dk(o,(0,$.VI)(e.withName("LocalGrepExecutor.execute")),!1),c=Array.isArray(this.workspacePath)?this.workspacePath:[this.workspacePath??process.cwd()],l=t.outputMode??"content";if("content"!==(i=l)&&"files_with_matches"!==i&&"count"!==i)throw new Error(`Unknown output mode: ${l}`);const u=l,d={toolCallId:t.toolCallId,execId:r?.execId,outputMode:u,targetPath:t.path,workspacePaths:c};void 0!==n&&this.stdoutDecodes.set(d,n);const h=Yo(t.sandboxPolicy),p=this.grepProvider.getWorktreeGuardInfo?.(c);if((0,Ho.fl)({targetPath:t.path,workspacePaths:c,mainWorktreePath:p?.mainWorktreePath}))return new pw.Ud({result:{case:"error",value:new pw.ts({error:Ho.PS})}});const f=this.findOutsideTargets(t.path,c);let m=t,g=c;try{if(t.path&&void 0!==f){const r=await this.checkOutsideTarget(t.path,f);if("error"in r)return new pw.Ud({result:{case:"error",value:new pw.ts({error:r.error})}});void 0!==this.mcpStateAccessor&&$w(e,this.mcpStateAccessor,r.resolvedTarget),g=c.slice(0,1),m=t.clone(),m.path=f[0]}else if(m.path){const t=[];let r=!1;for(const{root:n,resolvedRoot:o,target:s}of this.resolveSearchTargets(m.path,c)){if(!(0,Ho.BJ)(s,o))continue;const i=await Ha(s);if(null!==i)if(await this.ignoreService.isCursorIgnored(i))r=!0;else{if(await mk(s))return new pw.Ud({result:{case:"error",value:new pw.ts({error:fk(m.path)})}});t.push(n),void 0!==this.mcpStateAccessor&&$w(e,this.mcpStateAccessor,i)}}if(0===t.length){const e=r?`Path '${m.path}' is filtered out by .cursorignore`:pk(m.path);return new pw.Ud({result:{case:"error",value:new pw.ts({error:e})}})}g=t}let r={};const n=void 0===f?await this.executeIndexedGrepWithTimeout(a.ctx,g,m,d):void 0;if(void 0!==n){r=n;for(const[e,t]of Object.entries(r)){const r=t.result;switch(r.case){case"content":r.value.matches=await this.filterBlockedFiles(r.value.matches,e);break;case"files":r.value.files=(await this.filterBlockedFiles(r.value.files.map((e=>({file:e}))),e)).map((({file:e})=>e));break;case"count":r.value.counts=await this.filterBlockedFiles(r.value.counts,e)}}}else{const e=await this.streamingEnabled(a.ctx,d),t=e?yk(Fk.MAIN_TIMEOUT_MS):void 0;let n=0,o=!1;try{for(const s of g){if(!0===t?.signal.aborted){r[s]=bk(u),n++,o=!0;continue}if(!1===Tk(s))return new pw.Ud({result:{case:"error",value:new pw.ts({error:`Path does not exist: ${s}`})}});const i=t??yk(Fk.MAIN_TIMEOUT_MS);try{const t=await this.runMode(a.ctx,u,s,m,e,i.signal,h,d);r[s]=t.result,t.timedOut&&n++}catch(t){if(!(t instanceof wk))throw t;if(r[s]=bk(u),n++,o=!0,!e)break}finally{i!==t&&i.clear()}}}finally{t?.clear()}if(n>0){const t=o&&(!e||!Object.values(r).some(vk));if(this.reportDeadlineReached(a.ctx,d,{streaming:e,folderCount:g.length,stoppedFolderCount:n,outcome:t?"failed":"partial"}),t)throw Fk.ripgrepTimeoutError()}}const o=function(e,t){if(t.length<=1)return e;const r=[...new Set(t.map((e=>(0,s.resolve)(e))))],n={};for(const[t,o]of Object.entries(e)){const e=(0,s.resolve)(t),i=t=>gk(e,t,r),a=o.result;switch(a.case){case"content":{const e=a.value,r=[];let o=0,s=0;for(const t of e.matches)i(t.file)?r.push(t):(o+=t.matches.length,s+=t.matches.filter((e=>!e.isContextLine)).length);const c=e.clone();c.matches=r,c.totalLines=Math.max(0,e.totalLines-o),c.totalMatchedLines=Math.max(0,e.totalMatchedLines-s),n[t]=new pw.vD({result:{case:"content",value:c}});break}case"files":{const e=a.value,r=e.files.filter((e=>i(e))),o=e.clone();o.files=r,o.totalFiles=Math.max(0,e.totalFiles-(e.files.length-r.length)),n[t]=new pw.vD({result:{case:"files",value:o}});break}case"count":{const e=a.value,r=[];let o=0;for(const t of e.counts)i(t.file)?r.push(t):o+=t.count;const s=e.clone();s.counts=r,s.totalFiles=Math.max(0,e.totalFiles-(e.counts.length-r.length)),s.totalMatches=Math.max(0,e.totalMatches-o),n[t]=new pw.vD({result:{case:"count",value:s}});break}default:n[t]=o}}return n}(r,g),i=new pw._0({pattern:m.pattern,path:void 0!==m.path&&this.isRootIndependentSearchPath(m.path)?(0,Ho.o1)(m.path):m.path,outputMode:u,workspaceResults:o});return new pw.Ud({result:{case:"success",value:i}})}catch(e){if(m.path){const e=(0,Ho.o1)(m.path,this.singleWorkspacePath);try{await(0,fo.stat)(e)}catch(t){return new pw.Ud({result:{case:"error",value:new pw.ts({error:`Path does not exist: ${e}`})}})}}return new pw.Ud({result:{case:"error",value:new pw.ts({error:e instanceof Error?e.message:String(e)})}})}}catch(e){o.error=e,o.hasError=!0}finally{hk(o)}var i}}Fk.MAIN_TIMEOUT_MS=25e3,Fk.INDEXED_GREP_TIMEOUT_MS=25e3,Fk.INDEXED_GREP_CONTEXT_TIMEOUT_MS=Fk.INDEXED_GREP_TIMEOUT_MS+100,Fk.HARD_MAX_OUTPUT_LINES=1e4,Fk.CLIENT_LIMIT_LINES=2e3,Fk.LINE_ENCODING_TIMEOUT_MS=2e3,je.object({record_v:je.number().int().nullish(),pid:je.number().int().nonnegative().nullish(),version:je.string().nullish(),started_at:je.number().nullish(),control_sock:je.string().nullish(),runtime_dir:je.string().nullish(),data_dir:je.string().nullish(),config_path:je.string().nullish(),log_path:je.string().nullish(),metrics_addr:je.string().nullish(),exe:je.string().nullish()}),je.object({mountpoint:je.string().nullish(),capabilities:je.array(je.string()).nullish(),nfs_transport:je.string().nullish(),bind_ignored:je.object({active:je.array(je.string()).nullish()}).passthrough().nullish()});const Nk=je.object({daemon_alive:je.boolean().nullish(),mounts:je.array(je.unknown()).nullish(),data_plane:je.object({enabled:je.boolean().nullish()}).passthrough().nullish()});je.object({daemon_alive:je.boolean().nullish(),daemon_version:je.string().nullish(),capabilities:je.array(je.string()).nullish()}),Nk.extend({memory:je.object({anon_bytes:je.number()}).nullish().catch(null)});const Lk=je.number().int().nonnegative(),jk=je.object({line_no:je.number().int().positive(),kind:je.enum(["match","before","after"]),text:je.string().optional(),bytes:je.string().regex(/^(?:[0-9a-fA-F]{2})*$/).optional(),truncated:je.boolean().default(!1)}).refine((e=>void 0!==e.text||void 0!==e.bytes));je.object({type:je.literal("file"),path:je.string(),lines:je.array(jk)}),je.object({type:je.literal("summary"),files_searched:Lk,more:je.boolean(),stop_reason:je.string().nullable(),skipped:je.object({over_size:Lk,size_unknown:Lk,budget_exhausted:Lk,fetch_failed:Lk,unreadable:Lk})}),je.object({type:je.string()}),(0,l.h)("local-exec/grove-grep"),(0,u.Pu)("local_exec.grep.grove",{description:"Grep searches Grove served, or declined to ripgrep, by decline reason",labelNames:["outcome","reason"]}),(0,u.v5)("local_exec.grep.grove.served_ms",{description:"Time Grove took to answer a Grep search it served"});var Uk=r("../proto/dist/generated/agent/v1/ls_exec_pb.js"),Bk=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},Wk=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class Hk{constructor(e,t,r){this.permissionsService=e,this.ignoreService=t,this.workspacePath=r}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{Bk(r,(0,$.VI)(e.withName("LocalLsExecutor.execute")),!1).ctx;const n=(0,Ho.o1)(t.path,this.workspacePath);try{let r;try{r=await(0,fo.stat)(n)}catch(e){return"ENOENT"===Ua(e)?function(e){const t=Gh(e,"terminals");return null!==t&&0===t.remainingPath.length}(n)?new Uk.fv({result:{case:"error",value:new Uk.uj({path:n,error:"No active terminals."})}}):new Uk.fv({result:{case:"error",value:new Uk.uj({path:n,error:`Path does not exist: ${n}`})}}):new Uk.fv({result:{case:"error",value:new Uk.uj({path:n,error:Ba(e)})}})}if(!r.isDirectory())return new Uk.fv({result:{case:"error",value:new Uk.uj({path:n,error:`Path is not a directory: ${n}`})}});const o=Yo(t.sandboxPolicy),s=t.timeoutMs??5e3,i=e.withTimeout(s),{tree:a,didTimeout:c}=await this.getDirectoryTree(i,n,t.ignore,o);return c?new Uk.fv({result:{case:"timeout",value:new Uk.ze({directoryTreeRoot:a})}}):new Uk.fv({result:{case:"success",value:new Uk.PC({directoryTreeRoot:a})}})}catch(e){return new Uk.fv({result:{case:"error",value:new Uk.uj({path:n,error:e instanceof Error?e.message:"Unknown error occurred"})}})}}catch(e){r.error=e,r.hasError=!0}finally{Wk(r)}}async getDirectoryTree(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{return Bk(o,(0,$.VI)(e.withName("LocalLsExecutor.getDirectoryTree")),!1),await this.buildTreeFromRipgrepStream(e,t,r,n,2500)}catch(e){o.error=e,o.hasError=!0}finally{Wk(o)}}async buildTreeFromRipgrepStream(e,t,r,n,o){const i={stack:[],error:void 0,hasError:!1};try{Bk(i,(0,$.VI)(e.withName("LocalLsExecutor.buildTreeFromRipgrepStream")),!1);const a=(0,s.resolve)(t),c=new Uk.vq({absPath:a,childrenDirs:[],childrenFiles:[],childrenWereProcessed:!0,fullSubtreeExtensionCounts:{}}),l=new Map;l.set(a,c);const u={charactersUsed:a.length,budgetExceeded:!1},[d,h]=await Promise.all([this.ignoreService.listCursorIgnoreFilesByRoot(t),this.ignoreService.getRepoBlockExcludeGlobs(t)]),p=[...r,...h],{lines:f,didTimeout:m}=aa(e,{root:t,excludeGlobs:p,caseSensitive:!0,cursorIgnoreFiles:d,sandboxPolicy:n,source:"ls"});for await(const e of f){if(!e)continue;const r=(0,s.resolve)(t,e),n=await Ha(r);null===n||await this.ignoreService.isCursorIgnored(n)||await this.ignoreService.isRepoBlocked(n)||this.addPathToTree(r,a,l,u,o)}return this.sortTreeChildren(c),{tree:c,didTimeout:await m}}catch(e){i.error=e,i.hasError=!0}finally{Wk(i)}}addPathToTree(e,t,r,n,o){const i=(0,s.basename)(e),a=(0,s.dirname)(e);this.ensureDirectoryPath(a,t,r,n.budgetExceeded);const c=r.get(a);if(!c)return;const l=i.length;if(!n.budgetExceeded&&n.charactersUsed+l<=o){const e=new Uk.ur({name:i});c.childrenFiles.push(e),n.charactersUsed+=l}else{if(!n.budgetExceeded){n.budgetExceeded=!0;let e=a;for(;e.startsWith(t);){const t=r.get(e);t&&(t.childrenWereProcessed=!1);const n=(0,s.dirname)(e);if(n===e)break;e=n}}let o=n.overflowChain;if(n.overflowDir!==a||void 0===o){o=[];let e=a;for(;e.startsWith(t);){const t=r.get(e);t&&o.push(t);const n=(0,s.dirname)(e);if(n===e)break;e=n}n.overflowDir=a,n.overflowChain=o}const i=(0,s.extname)(e);for(const e of o)e.fullSubtreeExtensionCounts[i]??=0,e.fullSubtreeExtensionCounts[i]=vw(e.fullSubtreeExtensionCounts[i]+1),e.numFiles??=0,e.numFiles=vw(e.numFiles+1)}}ensureDirectoryPath(e,t,r,n){if(r.has(e)||e===t)return;const o=(0,s.dirname)(e);o!==e&&o.startsWith(t)&&this.ensureDirectoryPath(o,t,r,n);const i=new Uk.vq({absPath:e,childrenDirs:[],childrenFiles:[],childrenWereProcessed:!n,fullSubtreeExtensionCounts:{}});r.set(e,i);const a=r.get(o);a&&a.childrenDirs.push(i)}sortTreeChildren(e){e.childrenDirs.sort(((e,t)=>(0,s.basename)(e.absPath).localeCompare((0,s.basename)(t.absPath)))),e.childrenFiles.sort(((e,t)=>e.name.localeCompare(t.name)));for(const t of e.childrenDirs)this.sortTreeChildren(t)}}class qk extends Error{constructor(e,t){super(`Tool ${e} not found, available tools: ${t.join(", ")}`),this.toolName=e,this.availableTools=t,this.name="McpToolNotFoundError"}}function zk(e){if(e instanceof qk)return!0;if(!(e instanceof Error)||"McpToolNotFoundError"!==e.name)return!1;const t=e;return"string"==typeof t.toolName&&Array.isArray(t.availableTools)}function Gk(e){return!0===e.url?.startsWith("mcp-provider://")}function Vk(e){const t=e?.trim();return void 0===t||0===t.length?void 0:t}function Kk(e){const t=e?.trim();return void 0===t||0===t.length?void 0:t}function Jk(e,t){return(t??[]).some((t=>{const r=Vk(t.command),n=Kk(t.serverUrl);if(void 0===r&&void 0===n)return!1;const o=void 0===r||void 0!==e.command&&(0,mv.mD)(r,e.command),s=void 0===n||void 0!==e.url&&(0,mv.eA)(n,e.url);return o&&s}))}function Zk(e,t){if(Gk(e))return!1;const r=t?.rules??[];return r.length>0&&Jk(e,r)}var Xk=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class Qk extends Error{constructor(e){super(`MCP server "${e}" is disabled`),this.name="McpServerDisabledError"}}class Yk extends Error{constructor(e){super(`MCP server "${e}" has not been approved`),this.serverName=e,this.name="McpServerNotApprovedError"}}class e_ extends Error{constructor(e,t){super(`MCP server "${e}" is overridden by ${t}`),this.serverName=e,this.overridingConfigPath=t,this.name="McpServerOverriddenError"}}class t_{constructor(e){this.disabledService=e}async load(e,t,r,n,o){if(await this.disabledService.isServerDisabled(t))throw new Qk(t);return await o(e,r)}}class r_{constructor(e){this.approvalService=e}async load(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{if(function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(s,(0,$.VI)(e.withName("ServerApprovalMiddleware.load")),!1),!await this.approvalService.isServerApproved(t,r,n))throw new Yk(t);return await o(e,r)}catch(e){s.error=e,s.hasError=!0}finally{Xk(s)}}}class n_{constructor(e,t){this.approvalsPath=e,this.cwd=t,this.approvalsPromise=this.loadApprovals()}async isServerApproved(e,t,r){const n=function(e,t,r){const n={path:r,server:t};return`${e}-${(0,lo.createHash)("sha256").update(JSON.stringify(n)).digest("hex").substring(0,16)}`}(e,t,this.cwd);return(await this.getApprovals()).includes(n)}async loadApprovals(){try{const e=await(0,fo.readFile)(this.approvalsPath,"utf8"),t=JSON.parse(e);return Array.isArray(t)?t:(await this.saveApprovalsToFile([]),[])}catch(e){if(e instanceof Error&&e.message.includes("ENOENT"))return[];throw e}}async getApprovals(){return this.approvalsPromise}async addApproval(e){const t=await this.approvalsPromise;t.includes(e)||(t.push(e),await this.saveApprovals(t))}async addApprovals(e){const t=await this.approvalsPromise,r=e.filter((e=>!t.includes(e)));r.length>0&&(t.push(...r),await this.saveApprovals(t))}async removeApproval(e){const t=await this.approvalsPromise,r=t.filter((t=>t!==e));r.length!==t.length&&await this.saveApprovals(r)}async clearApprovals(e){const t=await this.approvalsPromise,r=e?t.filter((t=>!e(t))):[];r.length!==t.length&&await this.saveApprovals(r)}async saveApprovalsToFile(e){await(0,fo.mkdir)(s.default.dirname(this.approvalsPath),{recursive:!0}),await(0,fo.writeFile)(this.approvalsPath,JSON.stringify(e,null,2))}async saveApprovals(e){await this.saveApprovalsToFile(e),this.approvalsPromise=Promise.resolve(e)}}var o_=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},s_=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class i_{async load(e,t,r,n,o){const s=o(e,r);return new c_(e,t,s,r)}}function a_(e){let t;return e.then((e=>{t=e})).catch((()=>{})),t}class c_{constructor(e,t,r,n){this.serverName=t,this.clientPromise=r,this.config=n,this.clientPromiseTraceId=(0,$.fU)(e)?.spanContext()?.traceId,this.toolsPromise=this.clientPromise.then((async t=>null===t?[]:await t.getTools(e))),this.resourcesPromise=this.clientPromise.then((async t=>null===t?[]:(await t.listResources(e)).resources)),this.promptsPromise=this.clientPromise.then((async t=>null===t?[]:await t.listPrompts(e))),this.toolsPromise.catch((()=>{})),this.resourcesPromise.catch((()=>{})),this.promptsPromise.catch((()=>{}))}async getTools(e){const t={stack:[],error:void 0,hasError:!1};try{const r=o_(t,(0,$.VI)(e.withName("CachedMcpClient.getTools")),!1);r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("cacheTraceId",this.clientPromiseTraceId??"undefined");const n=a_(this.toolsPromise);return void 0!==n?n:await this.toolsPromise}catch(e){t.error=e,t.hasError=!0}finally{s_(t)}}async callTool(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{const i=o_(s,(0,$.VI)(e.withName("CachedMcpClient.callTool")),!1),a=await this.getClient(i.ctx);if(null===a)throw new Error("Client is not ready");return a.callTool(i.ctx,t,r,n,o)}catch(e){s.error=e,s.hasError=!0}finally{s_(s)}}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{const r=o_(t,(0,$.VI)(e.withName("CachedMcpClient.getInstructions")),!1),n=await this.getClient(r.ctx);if(null===n)return;return await n.getInstructions(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{s_(t)}}async getClient(e){const t={stack:[],error:void 0,hasError:!1};try{const r=o_(t,(0,$.VI)(e.withName("CachedMcpClient.getClient")),!1);return r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("cacheTraceId",this.clientPromiseTraceId??"undefined"),await this.clientPromise}catch(e){t.error=e,t.hasError=!0}finally{s_(t)}}async listResources(e){const t={stack:[],error:void 0,hasError:!1};try{const r=o_(t,(0,$.VI)(e.withName("CachedMcpClient.listResources")),!1);r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("cacheTraceId",this.clientPromiseTraceId??"undefined");const n=a_(this.resourcesPromise);return void 0!==n?{resources:n}:{resources:await this.resourcesPromise}}catch(e){t.error=e,t.hasError=!0}finally{s_(t)}}async readResource(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=o_(r,(0,$.VI)(e.withName("CachedMcpClient.readResource")),!1),o=await this.getClient(n.ctx);return null===o?{contents:[]}:o.readResource(n.ctx,t)}catch(e){r.error=e,r.hasError=!0}finally{s_(r)}}async listPrompts(e){const t={stack:[],error:void 0,hasError:!1};try{const r=o_(t,(0,$.VI)(e.withName("CachedMcpClient.listPrompts")),!1);r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("cacheTraceId",this.clientPromiseTraceId??"undefined");const n=a_(this.promptsPromise);return void 0!==n?n:await this.promptsPromise}catch(e){t.error=e,t.hasError=!0}finally{s_(t)}}async getPrompt(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=o_(n,(0,$.VI)(e.withName("CachedMcpClient.getPrompt")),!1),s=await this.getClient(o.ctx);return null===s?{messages:[]}:s.getPrompt(o.ctx,t,r)}catch(e){n.error=e,n.hasError=!0}finally{s_(n)}}async getState(e){const t={stack:[],error:void 0,hasError:!1};try{const r=o_(t,(0,$.VI)(e.withName("CachedMcpClient.getState")),!1);r.span.setAttribute("serverName",this.serverName);const n=await this.getClient(r.ctx);if(null===n)throw new Error("Client is not ready");return await n.getState(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{s_(t)}}async close(){try{const e=await this.clientPromise;await(e?.close?.())}catch{}}}function l_(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function u_(e,t){if("string"==typeof e)return e;if("number"==typeof e||"boolean"==typeof e||"bigint"==typeof e)return String(e);if(null==e)return t;try{const r=JSON.stringify(e);return"string"==typeof r?r:t}catch{return t}}function d_(e){return e?` (${u_(e,"")})`:""}function h_(e){if(null===e||"string"==typeof e||"boolean"==typeof e)return e;if("number"==typeof e)return Number.isFinite(e)?e:void 0;if(Array.isArray(e)){const t=[];for(const r of e){if(void 0===r){t.push(null);continue}const e=h_(r);if(void 0===e)return;t.push(e)}return t}if("object"!=typeof e)return;const t=Object.getPrototypeOf(e);if(t!==Object.prototype&&null!==t)return;const r={};for(const[t,n]of Object.entries(e)){if(void 0===n)continue;const e=h_(n);if(void 0===e)return;r[t]=e}return r}function p_(e){const t=h_(e);if(null!=t&&"object"==typeof t&&!Array.isArray(t))return t}const f_=new TextDecoder("utf-8",{fatal:!0});function m_(e){return"string"==typeof e?e.split(";")[0]?.trim().toLowerCase()??"":""}function g_(e,t){const r=Buffer.from(t,"base64"),n=function(e){try{const t=f_.decode(e);return t.includes("\0")?void 0:t}catch{return}}(r)??(function(e){const t=m_(e);return t.startsWith("text/")||"application/xml"===t||t.endsWith("+xml")}(e.mimeType)?r.toString("utf8").replace(/^\uFEFF/,""):void 0);if(void 0!==n)return{text:n,binary:!1};const o="string"==typeof e.mimeType&&e.mimeType.length>0?e.mimeType:"unknown type";return{text:`[Binary resource: ${u_(e.uri,"unknown")} (${o}, ${r.byteLength} bytes). The file is not text, so its contents are not included.]`,binary:!0}}const w_=new Set(["image/png","image/jpeg","image/jpg","image/gif","image/webp"]);function y_(e){return"string"==typeof e.text&&e.text.length>0?e.text:void 0}function v_(e){if(!l_(e))return;const t=e.resource;return l_(t)&&void 0===y_(t)&&"string"==typeof t.blob&&w_.has(m_(t.mimeType))?t.blob:void 0}function b_(e){const t=e,r=t.resource;if(l_(r)){const e=y_(r);return void 0!==e?e:"string"==typeof r.blob?g_(r,r.blob).text:`Resource: ${u_(r.uri,"unknown")}${d_(r.name)}`}return t.uri?`Resource: ${u_(t.uri,"unknown")}${d_(t.name)}`:`Unsupported content type "${e.type}": ${JSON.stringify(e)}`}function S_(e){const t=p_(e);if(void 0!==t&&0!==Object.keys(t).length)try{return Buffer.byteLength(JSON.stringify(t))<=262144?t:void 0}catch{return}}var k_=r("zod/v4-mini");const __=k_.object({CLIENT_ID:k_.string(),CLIENT_SECRET:k_.optional(k_.string()),scopes:k_.optional(k_.array(k_.string()))}),C_=k_.strictObject({caBundle:k_.string().check(k_.trim(),k_.minLength(1),k_.maxLength(131072))}),E_=k_.object({type:k_.optional(k_.literal("stdio")),command:k_.string(),args:k_.optional(k_.array(k_.string())),env:k_.optional(k_.record(k_.string(),k_.string())),envFile:k_.optional(k_.string()),cwd:k_.optional(k_.string()),enabledTools:k_.optional(k_.array(k_.string())),startupTimeoutSec:k_.catch(k_.optional(k_.number().check(k_.positive())),void 0)}),x_=k_.object({type:k_.optional(k_.enum(["http","sse"])),url:k_.string(),headers:k_.optional(k_.record(k_.string(),k_.string())),auth:k_.optional(__),tls:k_.optional(C_),placement:k_.optional(k_.enum(["server","client"])),enabledTools:k_.optional(k_.array(k_.string()))}),P_=k_.union([E_,x_]),I_=k_.object({mcpServers:k_.record(k_.string(),P_)});Error;const R_=/\$\{(?:env:([A-Za-z_][A-Za-z0-9_]*)|([^:}]+)(?::-([^}]*))?)\}/g;function T_(e,t){if("string"==typeof e)return function(e,t){return e.replace(R_,((e,r,n,o)=>{if(void 0!==r){const n=t(r);return void 0!==n?n:e}if(void 0===n)return e;const s=t(n);return void 0!==s?s:void 0!==o?o:e}))}(e,t);if(Array.isArray(e))return e.map((e=>T_(e,t)));if(null!==e&&"object"==typeof e){const r={};for(const[n,o]of Object.entries(e))r[n]=T_(o,t);return r}return e}r("../../node_modules/.pnpm/smol-toml@1.9.0/node_modules/smol-toml/dist/index.js");Symbol("invalid");function A_(e){const t=Object.entries(e);return{jsonKeyOf:new Map(t.map((([e,t])=>[t,e]))),tomlKeyOf:new Map(t)}}const $_=A_({CLIENT_ID:"client_id",CLIENT_SECRET:"client_secret",scopes:"scopes"}),M_=A_({caBundle:"ca_bundle"}),D_=A_({type:"type",command:"command",args:"args",env:"env",envFile:"env_file",cwd:"cwd",enabledTools:"enabled_tools",startupTimeoutSec:"startup_timeout_sec"}),O_=A_({type:"type",url:"url",headers:"http_headers",auth:"auth",tls:"tls",placement:"placement",enabledTools:"enabled_tools"}),F_=(new Map([["auth",{keys:$_,unknownKeyIsError:!1}],["tls",{keys:M_,unknownKeyIsError:!0}]]),"enabled");new Set([...D_.jsonKeyOf.keys(),...O_.jsonKeyOf.keys(),F_]);Symbol("disabled");const N_=(0,l.h)("McpConfig");async function L_(e,t=e=>process.env[e]){try{const r=await(0,fo.readFile)(e,"utf8"),n=T_((0,ah.qg)(r),t);return I_.parse(n)}catch{return{mcpServers:{}}}}async function j_(e,t=e=>process.env[e]){const r={config:{mcpServers:{}},diagnostics:[]};return r}async function U_(e,t=e=>process.env[e]){const{config:r,diagnostics:n}=await j_(0,t);return n.length>0&&N_.warn((0,y.q6)(),"[mcp config] problems in MCP config; `agent mcp list` shows them",{errorCount:n.filter((e=>"error"===e.severity)).length,warningCount:n.filter((e=>"warning"===e.severity)).length,fileNames:[...new Set(n.map((e=>s.default.basename(e.file))))]}),r}const B_=["enterprise","project","user","env"];function W_(e){return"project"===e||"env"===e}const H_=["0.0.0.0/0","::/0"];function q_(e){const t=(e??[]).filter((e=>e.trim().length>0)),r=t.flatMap((e=>{const t=(0,mv.bi)(e);return void 0===t?[]:[t]}));return{hasInvalidEntries:r.length!==t.length,entries:r}}function z_(e){const t=!0===e.enabled,r=q_(e.mcpNetworkDenylist),n="deny_all"===e.mcpNetworkMode||r.entries.includes("*")||r.hasInvalidEntries,o=t?function(e){if("allow_all"===e.mcpNetworkMode)return[...H_];const t=q_(e.mcpNetworkAllowlist);if("allowlist"===e.mcpNetworkMode)return t.entries.includes("*")?[...H_]:t.entries;if(!function(e){return(e.mcpNetworkAllowlist??[]).some((e=>e.trim().length>0))}(e))return[...H_];const r=(0,mv.b6)(e);return r.includes("*")?[...H_]:r}(e):[],s=t?n?["*"]:r.entries:[];return JSON.stringify({enabled:t,mode:e.mcpNetworkMode,allow:n?[]:o,deny:s})}class G_ extends Error{constructor(e,t){super(`MCP server "${e}" wasn't started: your team's MCP settings require it to run in a sandbox, and the sandbox isn't supported on this machine. Ask a team admin to review the team's MCP settings for this server.`),this.serverName=e,this.name="McpSandboxUnavailableError",void 0!==t&&(this.cause=t)}}const V_=new Set(["invalid_auth","not_authed","account_inactive","token_revoked","token_expired"]);class K_ extends Error{constructor(){super("Your organization admin only allows Slack workspaces your company manages. Connect your company Slack workspace instead."),this.name="SlackWorkspaceNotManagedError"}}class J_ extends Error{constructor(){super("Slack couldn't confirm which workspace this connection is for, and your organization admin only allows the Slack workspaces your company manages. Try again in a moment."),this.name="SlackWorkspaceUnconfirmedError"}}function Z_(e){return URL.canParse(e)&&"mcp.slack.com"===new URL(e).hostname.toLowerCase()}function X_(e,t){const r=new Map,n=t.lookUpWorkspace??(t=>async function(e,t){let r;try{const n=await e("https://slack.com/api/auth.test",{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/x-www-form-urlencoded"},signal:AbortSignal.timeout(5e3)});r=await n.json()}catch{return{kind:"unavailable"}}if("object"!=typeof r||null===r)return{kind:"unavailable"};if("object"!=typeof(n=r)||null===n||Array.isArray(n))return{kind:"unavailable"};var n;const o=r;return!0!==o.ok?"string"==typeof o.error&&V_.has(o.error)?{kind:"dead"}:{kind:"unavailable"}:"string"!=typeof o.team_id||0===o.team_id.length?{kind:"unavailable"}:"string"==typeof o.enterprise_id&&o.enterprise_id.length>0?{kind:"found",slackTeamId:o.team_id,slackEnterpriseId:o.enterprise_id}:{kind:"found",slackTeamId:o.team_id}}(e,t));let o,s=[];return async(i,a)=>{if(!Z_(function(e){return"string"==typeof e?e:e instanceof URL?e.href:e.url}(i)))return e(i,a);const c=function(e,t){const r=new Headers(t?.headers??(e instanceof Request?e.headers:void 0)),n=/^Bearer\s+(.+)$/i.exec(r.get("authorization")??"");return n?.[1]?.trim()||void 0}(i,a);if(void 0===c)return e(i,a);const l=await((void 0===o||Date.now()-o.atMs>=3e4)&&(o={atMs:Date.now(),lists:t.managedSlackWorkspaceLists().then((e=>"unconfirmed"===e?e:(s=e.filter((e=>e.length>0)).map((e=>e.map((e=>e.toUpperCase())))),s)),(()=>s))}),o.lists);if("unconfirmed"===l)throw new J_;if(0===l.length)return e(i,a);let u=r.get(c);if(void 0===u){const t=await n(c);if("dead"===t.kind)return e(i,a);if("unavailable"===t.kind)throw new J_;r.size>=64&&r.clear(),r.set(c,t),u=t}const d=[u.slackTeamId,u.slackEnterpriseId].flatMap((e=>void 0===e?[]:[e.toUpperCase()]));if(!l.every((e=>d.some((t=>e.includes(t))))))throw new K_;return e(i,a)}}function Q_(e,t,r){if("string"==typeof e)return t(e);if(!(e instanceof Error))return e;if(r.results.has(e))return r.results.get(e)===e&&r.cycled.add(e),r.results.get(e);r.results.set(e,e);const n=Object.isFrozen(e)&&aC(e,t)?new Error:void 0;void 0!==n&&r.results.set(e,n);const o=t(e.message),s="string"==typeof e.stack?t(e.stack):void 0,i=Object.keys(e).flatMap((n=>{if("cause"===n)return[];const o=tC(e,n),s=sC(o,t,r);return Object.is(s,o)?[]:[[n,s]]})),a=Object.getOwnPropertyDescriptor(e,"cause"),c=void 0===a?void 0:tC(e,"cause"),l=sC(c,t,r),u=e instanceof AggregateError?tC(e,"errors"):void 0,d=function(e,t,r){if(!Array.isArray(e))return e;const n=e.map((e=>sC(e,t,r)));if(n.every(((t,r)=>Object.is(t,e[r]))))return e;try{return n.forEach(((t,r)=>{e[r]=t})),e}catch{return n}}(u,t,r),h=[...i,...Object.is(l,c)?[]:[["cause",l]],...Object.is(d,u)?[]:[["errors",d]]];let p=!1;if(void 0===n)try{o!==e.message&&(e.message=o),void 0!==s&&s!==e.stack&&(e.stack=s),p=e.message===o&&(void 0===s||e.stack===s)&&h.every((([t,r])=>eC(e,t,r)))}catch{}if(p)return e;const f=Object.defineProperties(n??new Error,{message:{value:o,writable:!0,enumerable:!1,configurable:!0},...Object.getOwnPropertyDescriptors(nC(e,new Map(i)))});Array.isArray(d)&&Object.defineProperty(f,"errors",{value:d,writable:!0,enumerable:!1,configurable:!0}),void 0!==a&&Object.defineProperty(f,"cause",{value:l,writable:!0,enumerable:!0===a.enumerable,configurable:!0});const m=Object.getPrototypeOf(e);null!==m&&"object"==typeof m&&m!==Error.prototype&&(Object.setPrototypeOf(f,m),function(e){try{let t=Object.getPrototypeOf(e);for(let r=0;r<8&&null!==t&&"object"==typeof t&&t!==Error.prototype&&t!==Object.prototype;r++){for(const r of Reflect.ownKeys(t)){const n=Object.getOwnPropertyDescriptor(t,r)?.get;void 0!==n&&Reflect.apply(n,e,[])}t=Object.getPrototypeOf(t)}String(e);const r=e;"function"==typeof r.toJSON&&Reflect.apply(r.toJSON,e,[""]);const n=r[rC];return"function"==typeof n&&Reflect.apply(n,e,[0,{depth:0,stylize:String},String]),!0}catch{return!1}}(f)||Object.setPrototypeOf(f,Error.prototype));const g=uC(e);return void 0!==g&&uC(f)!==g&&Object.defineProperty(f,"name",{value:g,writable:!0,configurable:!0,enumerable:!1}),void 0!==s&&(f.stack=s),r.results.set(e,f),f}function Y_(e,t){if(e instanceof Error)return t.get(e)??e;if(!Array.isArray(e)||!Object.isFrozen(e))return e;const r=e.map((e=>e instanceof Error?t.get(e)??e:e));return r.every(((t,r)=>Object.is(t,e[r])))?e:r}function eC(e,t,r){const n=Object.getOwnPropertyDescriptor(e,t);return!0===n?.writable&&Reflect.defineProperty(e,t,{...n,value:r})}function tC(e,t){try{const r=Object.getOwnPropertyDescriptor(e,t);return void 0===r?.get?r?.value:r.get.call(e)}catch{return}}const rC=Symbol.for("nodejs.util.inspect.custom");function nC(e,t){const r={};for(const n of Object.keys(e))try{const o=Object.getOwnPropertyDescriptor(e,n),s=void 0===o?.get?o?.value:o.get.call(e);Object.defineProperty(r,n,{value:t.has(n)?t.get(n):s,writable:!0,enumerable:!0,configurable:!0})}catch{}return r}function oC(e,t,r,n){if("string"==typeof e)return t(e);if("object"!=typeof e||null===e)return e;if(e instanceof Error)return Q_(e,t,n);if(Array.isArray(e)){if(r>=4)return;return e.slice(0,64).map((e=>oC(e,t,r+1,n)))}const o=Object.getPrototypeOf(e);return o!==Object.prototype&&null!==o?e:r>=4?void 0:function(e,t,r,n){const o={};for(const s of Object.keys(e).slice(0,64))try{const i=Object.getOwnPropertyDescriptor(e,s),a=void 0===i?.get?i?.value:i.get.call(e);Object.defineProperty(o,s,{value:oC(a,t,r,n),writable:!0,enumerable:!0,configurable:!0})}catch{}return o}(e,t,r+1,n)}function sC(e,t,r){if(e instanceof Error)return Q_(e,t,r);try{return aC(e,t)?oC(e,t,1,r):e}catch{return}}const iC=4096;function aC(e,t){const r=new Set,n=[e];for(let o=0;n.length>0;o++){if(o>=iC||n.length>iC)return cC(e,t);const s=n.pop();if("string"==typeof s){if(t(s)!==s)return!0}else if((lC(s)||s instanceof Error)&&!r.has(s)){r.add(s),s instanceof Error&&(n.push(tC(s,"message"),tC(s,"stack"),tC(s,"cause")),s instanceof AggregateError&&n.push(tC(s,"errors")));for(const e of Object.keys(s))n.push(tC(s,e))}}return!1}function cC(e,t){const r=new Set;let n;try{n=JSON.stringify(e,((e,t)=>{return"bigint"==typeof t?t.toString():"object"!=typeof t||null===t?t:r.has(t)?void 0:(r.add(t),t instanceof Error?(n=t,{...Object.fromEntries(Object.keys(n).map((e=>[e,tC(n,e)]))),message:tC(n,"message"),stack:tC(n,"stack"),cause:tC(n,"cause"),...n instanceof AggregateError?{errors:tC(n,"errors")}:{}}):t);var n}))}catch{return!0}return void 0!==n&&t(n)!==n}function lC(e){if(Array.isArray(e))return!0;if("object"!=typeof e||null===e)return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}function uC(e){try{return"string"==typeof e.name?e.name:void 0}catch{return}}const dC=/spt_[A-Za-z0-9_]{6,}/g,hC=/[A-Z0-9]/;function pC(e){return function(e){return e.replace(dC,(e=>function(e){return e.slice(4).split("_").some((e=>e.length>=8&&hC.test(e)))}(e)?"[redacted Link shared payment token]":e))}(e)}var fC=r("../../node_modules/.pnpm/string-argv@0.3.2/node_modules/string-argv/index.js");new Set(["EAI_AGAIN","ECONNABORTED","ECONNREFUSED","ECONNRESET","EHOSTUNREACH","ENETDOWN","ENETUNREACH","ENOTFOUND","EPIPE","ETIMEDOUT","EADDRNOTAVAIL","UND_ERR_CONNECT_TIMEOUT"]),new Set(["ECONNRESET","EPIPE"]);const mC=new Set([429,502,503,504]);function gC(e){return"object"==typeof e&&null!==e}function wC(e){const t=gC(e)?e.code:void 0,r=(e instanceof Error||gC(e)&&"string"==typeof e.message?e.message:"").match(/\(HTTP (\d+)\)|Non-200 status code \((\d+)\)|\bHTTP\s+(\d{3})\b/i),n=r?.[1]??r?.[2]??r?.[3],o=void 0!==n?parseInt(n,10):void 0;if("number"==typeof t&&t>=100)return void 0!==o&&mC.has(o)&&!mC.has(t)?o:t;if("string"==typeof t&&/^\d{3}$/.test(t)){const e=Number.parseInt(t,10);return e>=100&&e<=599?e:o}return o}new Set(["UND_ERR_SOCKET","UND_ERR_CLOSED","ECONNRESET"]);const yC=8192;function vC(e){return void 0===e?"unknown":"url"in e&&e.url.length>0?void 0!==Uy(e.url)?"rest_mcp":"streamable_http":"command"in e?"stdio":"unknown"}new Set(["ENOENT","EACCES","ENOTDIR","EPERM"]);const bC=/\$\{[^}]*\}/;function SC(e){if(void 0!==function(e){if(void 0===e)return;const t=e.trim();return 0!==t.length&&bC.test(t)?t:void 0}(e))return;const t=e?.trim();return t&&t.length>0?t:void 0}const kC=new Map;async function _C(e,t=fetch){if(void 0===Uy(e))return;const r=new URL(e),n=`${r.origin}/.well-known/oauth-protected-resource${r.pathname.replace(/\/+$/,"")}`,o=kC.get(n);if(void 0!==o&&o.expiresAtMs>Date.now())return o.metadata;let s;try{const e=await t(n);if(!e.ok)return;s=function(e){if("object"!=typeof(t=e)||null===t)return{};var t;const r=e,n="string"==typeof r.cursor_client_id&&r.cursor_client_id.length>0?r.cursor_client_id:void 0;let o;if("object"==typeof r.cursor_authorization_params&&null!==r.cursor_authorization_params){const e=Object.entries(r.cursor_authorization_params).filter((e=>"string"==typeof e[1]));e.length>0&&(o=Object.fromEntries(e))}return{...void 0!==n?{clientId:n}:{},...!0===r.cursor_omit_resource_indicator?{omitResourceIndicator:!0}:{},...!0===r.cursor_omit_consent_prompt?{omitConsentPrompt:!0}:{},...void 0!==o?{authorizationParams:o}:{},...!0===r.cursor_rejects_custom_scheme_redirects?{rejectsCustomSchemeRedirects:!0}:{},...!0===r.cursor_unauthenticated_connect?{unauthenticatedConnect:!0}:{},...!0===r.cursor_loopback_ipv4?{loopbackIpv4:!0}:{},...!0===r.cursor_backend_only_token_exchange?{backendOnlyTokenExchange:!0}:{}}}(await e.json())}catch{return}return kC.set(n,{metadata:s,expiresAtMs:Date.now()+3e5}),s}(0,fs.J)((function(){kC.clear()}));const CC={info:()=>{},warn:()=>{},error:()=>{},debug:()=>{}};function EC(e){return CC}const xC=/^[\x21\x23-\x5B\x5D-\x7E]+$/,PC=["invalid_request","invalid_token","insufficient_scope"];function IC(e){return PC.some((t=>t===e))}function RC(e){const t=new Set;for(const r of e)r.length<=200&&xC.test(r)&&t.add(r);return[...t]}const TC=/[!#$%&'*+.^_`|~0-9A-Za-z-]+/y,AC=/"((?:[^"\\]|\\.)*)"?/y,$C=/[^\s,]*/y;function MC(e,t){let r,n=0;const o=t=>{t.lastIndex=n;const r=t.exec(e);return null!==r&&(n=t.lastIndex),r};for(;n<e.length;){for(;n<e.length&&/[\s,]/.test(e[n]??"");)n+=1;const s=o(TC);if(null===s){n+=1;continue}for(;" "===e[n]||"\t"===e[n];)n+=1;if("="!==e[n]){r=s[0].toLowerCase();continue}for(n+=1;" "===e[n]||"\t"===e[n];)n+=1;const i='"'===e[n]?(o(AC)?.[1]??"").replace(/\\(.)/g,"$1"):o($C)?.[0]??"";if((void 0===r||"bearer"===r)&&s[0].toLowerCase()===t)return i}}const DC={stepUpScopes:[],signInMissing:[]};function OC(e){return Array.isArray(e)?e.filter((e=>"string"==typeof e&&e.length>0)):void 0}function FC(e){if("object"!=typeof e||null===e||Array.isArray(e))return DC;const t=OC("grantedScopes"in e?e.grantedScopes:void 0),r=OC("requestedScopes"in e?e.requestedScopes:void 0);return{...void 0!==t?{grantedScopes:t}:{},stepUpScopes:OC("stepUpScopes"in e?e.stepUpScopes:void 0)??[],signInMissing:OC("signInMissing"in e?e.signInMissing:void 0)??[],...void 0!==r?{requestedScopes:r}:{}}}function NC(e){return(e??"").split(/\s+/).filter((e=>e.length>0))}function LC(e,t){return e.filter((e=>!t.has(e)))}function jC(e){const t=tv(e.serverUrl),r=e.connectorName??t?.displayName??e.accountKey,n=EC(e.accountKey);let o;const s=async()=>FC(await e.readRecord()),i=async t=>{if(void 0!==t.grantedScopes)return t.grantedScopes;const r=NC(await e.readTokenScope());return r.length>0?r:void 0},a=(e,t)=>{n.info(`MCP OAuth scope step-up: ${e}`,{event:`mcp_oauth_scope_step_up_${e}`,...t})};return{accountKey:e.accountKey,connectorName:r,async decide(r){if(401!==r.status&&403!==r.status)return;const n=function(e){const t=e??"",r=MC(t,"error")?.toLowerCase(),n=MC(t,"resource_metadata");return{error:void 0===r||""===r?"none":IC(r)?r:"other",scopes:RC((MC(t,"scope")??"").split(/\s+/)),resourceMetadata:void 0===n||""===n?void 0:n}}(r.wwwAuthenticate);if("insufficient_scope"!==n.error||0===n.scopes.length)return;if(function(e){try{return rv.has(new URL(e).hostname.toLowerCase())}catch{return!1}}(e.serverUrl))return;const o=function(e,t){if(void 0!==t)try{return new URL(t).origin===new URL(e).origin?t:void 0}catch{return}}(e.serverUrl,n.resourceMetadata),c=void 0===t?await e.readScopesSupported(o).catch((()=>{})):void 0,l=await s(),u=await i(l),{accepted:d,dropped:h}=function(e){const t=new Set(e.granted??[]),r=[],n=[];for(const o of RC(e.named))e.allowlist.has(o)?t.has(o)||r.push(o):n.push(o);return{accepted:r,dropped:n}}({named:n.scopes,allowlist:(p={policy:t,scopesSupported:c,configuredScopes:e.configuredScopes},void 0!==p.policy?new Set([...p.policy.baseScopes,...Object.keys(p.policy.stepUpScopes)]):new Set([...p.scopesSupported??[],...p.configuredScopes??[]])),granted:u});var p;if(0===d.length)return void a("none_accepted",{status:r.status,namedCount:n.scopes.length,droppedCount:h.length});const f=new Set(l.signInMissing),m=d.every((e=>f.has(e)))?"blocked":"offer";return"offer"===m&&await e.writeRecord({...l,...void 0!==u?{grantedScopes:u}:{},stepUpScopes:[...new Set([...l.stepUpScopes,...d])]}),a(m,{status:r.status,acceptedCount:d.length,droppedCount:h.length}),{kind:m,status:r.status,scopes:d,dropped:h,toolName:r.toolName,resourceMetadataUrl:o}},signIn:async e=>(void 0===o&&(o=Promise.resolve().then(e).finally((()=>{o=void 0}))),o),get isSigningIn(){return void 0!==o},tokensForSdk(e){if(void 0===o||void 0===e?.refresh_token)return e;const{refresh_token:t,...r}=e;return r},async prepareAuthorization(){const t=await s();return{stepUpScopes:t.stepUpScopes.length>0?[...new Set([...await i(t)??[],...t.stepUpScopes])]:[],recordRequestedScopes:async t=>{await e.writeRecord({...await s(),requestedScopes:NC(t.searchParams.get("scope"))})}}},async recordTokens(t,{isRefresh:r}){const n=await e.readRecord();if(void 0===n)return;const o=FC(n),s=NC(t.scope);if(r)return void(s.length>0&&await e.writeRecord({...o,grantedScopes:s}));if(void 0===o.requestedScopes)return;const i=s.length>0?s:o.requestedScopes,c=new Set(i),l=LC(o.requestedScopes,c);await e.writeRecord({grantedScopes:i,stepUpScopes:LC(o.stepUpScopes,c),signInMissing:l}),a("sign_in_recorded",{grantedCount:i.length,signInMissingCount:l.length,scopeReported:s.length>0})},async clear(t){await e.writeRecord(!0===t?.keepPendingScopes?function(e){const{stepUpScopes:t}=FC(e);return t.length>0?{stepUpScopes:t,signInMissing:[]}:void 0}(await e.readRecord()):void 0)}}}function UC(e){const t=tv(e.serverUrl);for(const r of e.scopes){const e=t?.stepUpScopes[r]?.action;if(void 0!==e)return e}return e.toolTitle}function BC(e){const t=function(e){return void 0===e.action?`${e.connectorName} needs a permission its sign-in did not grant.`:`${e.connectorName} needs one more permission to ${e.action}.`}({connectorName:e.connectorName,action:UC(e)}),r="offer"===e.kind?`Authorize ${e.connectorName} again to approve it; the turn can continue once it's granted.`:`Its last sign-in did not grant ${1===e.scopes.length?"it":"them"}, so an admin or your consent is blocking this. Reconnect ${e.connectorName} from its MCP settings to ask again.`,n=function(e){if(0===e.length)return;const t=e.slice(0,3).join(", "),r=e.length-3;return`${1===e.length?"Permission":"Permissions"}: ${t}${r>0?` and ${r} more`:""}`}(e.scopes);return void 0===n?`${t} ${r}`:`${t} ${r}\n${n}`}class WC extends Error{constructor(e,t,r){super(BC({kind:e.kind,serverUrl:t,connectorName:r,scopes:e.scopes,toolTitle:e.toolName})),this.decision=e,this.serverUrl=t,this.connectorName=r,this.name="McpOAuthScopeStepUpError"}answerWithToolTitle(e){return BC({kind:this.decision.kind,serverUrl:this.serverUrl,connectorName:this.connectorName,scopes:this.decision.scopes,toolTitle:e??this.decision.toolName})}}function HC(e){if("string"!=typeof e)return;let t;try{t=JSON.parse(e)}catch{return}const r=Array.isArray(t)?t:[t];for(const e of r){if("object"!=typeof e||null===e||!("method"in e)||"tools/call"!==e.method)continue;const t="params"in e?e.params:void 0,r="object"==typeof t&&null!==t&&"name"in t?t.name:void 0;return"string"==typeof r?r:void 0}}function qC(e){return e instanceof Error&&/does not support dynamic client registration/i.test(e.message)}Error,Error;const zC=new Set(["UnauthorizedError","InvalidGrantError","InvalidTokenError","InvalidClientError","UnauthorizedClientError"]),GC=new Set(["invalid_grant","invalid_token","invalid_client","unauthorized_client"]),VC=[/\btoken (?:has |is )?expired\b/i,/\btoken (?:was|is) invalid\b/i,/\binvalid (?:refresh[ _]?)?token\b/i,/\btoken (?:has been |was )?revoked\b/i];var KC=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/types.js");const JC="2026-07-28",ZC=-32022,XC="io.modelcontextprotocol/protocolVersion",QC="io.modelcontextprotocol/clientCapabilities",YC="io.modelcontextprotocol/clientInfo",eE="io.modelcontextprotocol/serverInfo",tE={name:"cursor",version:"1.0.0"},rE=new Map;function nE(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function oE(e){const t=new URL(String(e));return t.hash="",t.href}function sE(e,t){const r=rE.get(e);return!(void 0===r||r<=t()&&(rE.delete(e),1))}function iE(e,t){try{return oE(e)===t}catch{return!1}}function aE(e){return(e.headers.get("content-type")??"").toLowerCase().includes("application/json")}const cE=new Set(["events/subscribe","events/unsubscribe","events/poll","events/stream"]);function lE(e,t,r,n,o=t.message){const s=new Headers(e?.headers);if(s.set("mcp-protocol-version",JC),s.set("mcp-method",r),s.delete("mcp-session-id"),!t.isRequest&&o===t.message)return{...e,headers:s};const i=nE(o.params)?o.params:{},a=nE(i._meta)?i._meta:{},c=function(e,t){const r="tools/call"===e||"prompts/get"===e||cE.has(e)?"name":"resources/read"===e?"uri":void 0,n=void 0===r?void 0:t[r];return"string"==typeof n?n:void 0}(r,i);void 0!==c&&s.set("mcp-name",c);const l=JSON.stringify({...o,params:{...i,_meta:{...a,[XC]:JC,[QC]:n.capabilities,[YC]:n.clientInfo}}});return{...e,headers:s,body:l}}function uE(e){return new Response(JSON.stringify({jsonrpc:"2.0",...e}),{status:200,headers:{"content-type":"application/json"}})}function dE(e,t){const r=oE(t.serverUrl),n=t.now??Date.now;let o={capabilities:{},clientInfo:{...tE}},s=!1;const i=()=>s||sE(r,n),a=async(t,i,a)=>{const{method:c,message:l}=t;if(void 0===c)return e(i,a);if("notifications/initialized"===c)return new Response(null,{status:202});if(t.isRequest&&"initialize"===c){const c={jsonrpc:"2.0",id:l.id,method:"server/discover",params:{}},u=await e(i,lE(a,t,"server/discover",o,c)),d=await async function(e,t,r){if(!e.ok||!aE(e))return e;let n;try{n=await e.clone().json()}catch{return e}if(!nE(n)||!nE(n.result))return e;const o=n.result,s=o.supportedVersions;if(!Array.isArray(s)||!s.includes(JC))return uE({id:t,error:{code:ZC,message:"Unsupported protocol version",data:{requested:JC,supported:s??[]}}});const i=nE(o._meta)?o._meta:{},a=nE(i[eE])?i[eE]:{name:new URL(r).hostname,version:"unknown"};return uE({id:t,result:{protocolVersion:KC.aE,capabilities:nE(o.capabilities)?o.capabilities:{},serverInfo:a,..."string"==typeof o.instructions?{instructions:o.instructions}:{}}})}(u,l.id,r);return d!==u&&(s=!0,function(e,t){rE.set(e,t()+6e5)}(r,n)),d}return e(i,lE(a,t,c,o))};return async(t,c)=>{const l=function(e,t,r){if("POST"!==(t?.method??"GET").toUpperCase()||"string"!=typeof t?.body||!iE(e,r))return;let n;try{n=JSON.parse(t.body)}catch{return}if(!nE(n)||"2.0"!==n.jsonrpc)return;const o="string"==typeof n.method?n.method:void 0;return{message:n,method:o,isRequest:void 0!==o&&"id"in n}}(t,c,r);if(void 0===l)return function(e,t,r){return"GET"===(t?.method??"GET").toUpperCase()&&iE(e,r)}(t,c,r)&&i()?new Response(null,{status:405}):e(t,c);if(l.isRequest&&"initialize"===l.method){const e=nE(l.message.params)?l.message.params:{};o={capabilities:nE(e.capabilities)?e.capabilities:{},clientInfo:nE(e.clientInfo)?e.clientInfo:o.clientInfo}}const u=l.isRequest&&"initialize"===l.method;if(u?sE(r,n):i())return a(l,t,c);if(u&&(s=!1),!l.isRequest)return e(t,c);const d=await e(t,c);if(u&&await async function(e){if(e.status>=500||!aE(e))return!1;const t=Number(e.headers.get("content-length"));if(Number.isFinite(t)&&t>4096)return!1;let r;try{r=await e.clone().json()}catch{return!1}if(!nE(r)||!nE(r.error))return!1;const n=r.error;if(n.code!==ZC||!nE(n.data))return!1;const o=n.data.supported;return Array.isArray(o)&&o.includes(JC)}(d)){const e=await a(l,t,c);return s?e:d}return d}}function hE(e,t){if(void 0===t)return{headers:t,cursorAuthHeaderValue:void 0,cursorAuthOrigin:void 0};const r=Object.entries(t),n=r.find((([e])=>e.toLowerCase()===jy));if(void 0===n)return{headers:t,cursorAuthHeaderValue:void 0,cursorAuthOrigin:void 0};let o;try{o=new URL(e).origin}catch{o=void 0}return{headers:Object.fromEntries(r.filter((([e])=>e.toLowerCase()!==jy))),cursorAuthHeaderValue:n[1],cursorAuthOrigin:o}}function pE(e,t,r){return async(n,o)=>{let s;try{s=new URL("string"==typeof n?n:n.toString()).origin}catch{return r(n,o)}if(s!==t)return r(n,o);const i=await e();if(void 0===i||0===i.length)return r(n,o);const a=new Headers(o?.headers);return a.set(jy,i),r(n,{...o,headers:a,redirect:"manual"})}}class fE{constructor(e=864e5){this.ttl=e,this.staleDirty=!1,this.refreshGeneration=0}async get(e){const t=performance.now();if(this.state&&this.state.expiresAt>t&&!this.staleDirty)return this.state.value;if(this.staleDirty&&this.state){const t=this.state.value;if(!this.refreshInFlight){const t=this.refreshGeneration;let r;r=(async()=>{try{const r=await e();if(t!==this.refreshGeneration)return;this.state={expiresAt:performance.now()+this.ttl,value:r},this.staleDirty=!1}catch{}finally{r&&this.refreshInFlight===r&&(this.refreshInFlight=void 0)}})(),this.refreshInFlight=r}return t}const r=this.refreshGeneration,n=await e();return r!==this.refreshGeneration||(this.state={expiresAt:performance.now()+this.ttl,value:n},this.staleDirty=!1),n}invalidate(){this.refreshGeneration++,this.state=void 0,this.staleDirty=!1,this.refreshInFlight=void 0}invalidateKeepingStale(){this.state&&(this.staleDirty=!0)}}var mE=r("crypto");function gE(e){const t={};for(const[r,n]of Object.entries(e))void 0!==n&&(t[r]=n);return t}function wE(e,t){const r=function(e){try{const t=new URL(e);return{host:t.host,origin:t.origin,pathname:t.pathname}}catch{return{host:null,origin:null,pathname:null}}}(e),n=!1!==t?.includePath;return{host:r.host,origin:r.origin,path:n?r.pathname:null}}function yE(e,t){return wE(e,t)}function vE(e){if(e)return(0,mE.createHash)("sha256").update(e).digest("hex").slice(0,12)}function bE(e){if(e&&0!==e.length)return vE(JSON.stringify([...e].sort()))}function SE(e){return{clientIdHash:vE(e?.client_id),hasClientSecret:(e?.client_secret??"").length>0,redirectUrisHash:bE(e?.redirect_uris),redirectUriCount:e?.redirect_uris?.length??0}}function kE(e){return"object"==typeof e&&null!==e}function _E(e,t){let r=e;for(const e of t){if(!kE(r)||!(e in r))return;r=r[e]}return r}function CE(e,t){for(const r of t){const t=_E(e,r.split("."));if("string"==typeof t)return t}}function EE(e){if(!e||"object"!=typeof e)return;const t=e.errorCode;return"string"==typeof t?t:void 0}function xE(e){if(!e)return;const t=e.match(/\(HTTP (\d+)\)|Non-200 status code \((\d+)\)|\bHTTP\s+(\d{3})\b/i),r=t?.[1]??t?.[2]??t?.[3];if(!r)return;const n=Number.parseInt(r,10);return Number.isNaN(n)?void 0:n}const PE=e=>e;function IE(e,t){if(e instanceof Error){const r=e.message;return r&&r!==e.name?OE(t(r)):void 0}if("string"==typeof e||"number"==typeof e||"boolean"==typeof e){const r=String(e);return r?OE(t(r)):void 0}}function RE(e){if(e&&"object"==typeof e)return kE(e)?e.cause:void 0}function TE(e,t,r=4){const n=[];let o=e;for(let e=0;e<r&&null!=o;e++){if(!(o instanceof Error)){"string"==typeof o||"number"==typeof o||"boolean"==typeof o?n.push(OE(t(String(o)))):kE(o)&&"string"==typeof o.message&&n.push(OE(t(o.message)));break}{const e=IE(o,t);n.push(e?`${o.name}: ${e}`:o.name),o=RE(o)}}return n.length>1?n.join(" > "):void 0}const AE="[REDACTED]",$E=/(^|_|-)(token|secret|password|assertion|authorization|verifier|challenge|code)(_|-|$)/i;function ME(e){return e.replace(/(authorization[^:=\r\n]{0,32}[:=]\s*["']?)(?:[A-Za-z][\w.~+/-]*[ \t]+)?[^"',\s&}]+/gi,`$1${AE}`).replace(/((?:access_token|refresh_token|id_token|client_secret|code|password|assertion|token|secret)[^:=\r\n]{0,32}[:=]\s*["']?)([^"',\s&}]+)/gi,`$1${AE}`).replace(/(\bBearer\s+)([A-Za-z0-9\-._~+/]+=*)/gi,`$1${AE}`)}function DE(e,t=256){return e.length>t?`${e.slice(0,Math.max(0,t-3))}...`:e}function OE(e,t){return DE(ME(e),t?.maxLength)}function FE(e,t=PE){if("string"==typeof e)return DE(ME(t(e)));if(void 0!==e)try{const r=JSON.stringify(e,((e,r)=>e&&function(e){const t=e.toLowerCase();return"code"===t||"authorization"===t||t.includes("token")||t.includes("secret")||t.includes("password")||t.includes("assertion")||t.includes("verifier")||t.includes("challenge")||$E.test(t)}(e)?AE:"string"==typeof r?ME(t(r)):r));if(!r)return;return DE(r)}catch{return}}function NE(e,t=PE){const r=RE(e),n=e instanceof Error?e.name:null!=e?typeof e:void 0,o=r instanceof Error?r.name:void 0,s=IE(r,t),i=IE(e,t)??s,a=CE(e,["code","cause.code"]),c=EE(e)??EE(r)??CE(e,["errorCode","error","cause.errorCode","cause.error","body.error","response.body.error"]),l=void 0===c?void 0:OE(t(c)),u=function(e){for(const t of["status","statusCode","response.status","response.statusCode","cause.status","cause.statusCode","cause.response.status","cause.response.statusCode"]){const r=_E(e,t.split("."));if("number"==typeof r&&Number.isFinite(r))return r}}(e)??xE(i)??xE(s),d=FE(_E(e,["response","body"])??_E(e,["body"])??_E(e,["data"])??_E(e,["cause","body"])??_E(e,["cause","response","body"]),t),h=function(e){const t=e.message?.toLowerCase(),r=e.code?.toLowerCase();return t?.includes("timed out")||t?.includes("timeout")||t?.includes("etimedout")||"etimedout"===r?"timeout":t?.includes("enotfound")||t?.includes("eai_again")||t?.includes("dns")||"enotfound"===r||"eai_again"===r?"dns":t?.includes("certificate")||t?.includes("tls")||t?.includes("ssl")?"tls":t?.includes("econnreset")||t?.includes("connection reset")||"econnreset"===r?"connection_reset":t?.includes("econnrefused")||t?.includes("connection refused")||"econnrefused"===r?"connection_refused":void 0}({message:i,code:a}),p=l?"oauth_error":h?"auth_transport_error":i?"generic_error":void 0;return gE({errorName:n,errorMessage:i,errorType:null!=e?typeof e:void 0,httpStatus:u,oauthErrorCode:l,errorResponseSummary:d,networkClassification:h,causeName:o,causeMessage:s,causeChain:TE(e,t),sdkErrorKind:p})}const LE={mcp_oauth_provider_initialized:"MCP OAuth provider initialized",mcp_oauth_tokens_loaded:"MCP OAuth tokens loaded",mcp_oauth_tokens_saved:"MCP OAuth tokens saved",mcp_oauth_callback_completion:"MCP OAuth callback exchange completed",mcp_oauth_client_info_loaded:"MCP OAuth client information loaded",mcp_oauth_client_info_saved:"MCP OAuth client information saved",mcp_oauth_refresh_prepare:"MCP OAuth refresh prepared",mcp_oauth_refresh_error_release:"MCP OAuth refresh error released",mcp_oauth_state_transition:"MCP OAuth state transition",mcp_oauth_credentials_invalidated:"MCP OAuth credentials invalidated"};function jE(e){const t=e.message??LE[e.event],r={event:e.event,cursorMcp:{oauth:gE({...e.metadata})}},n=e.level??"info";"error"!==n?"warn"!==n?"debug"!==n?e.logger.info?.(t,r):e.logger.debug?.(t,r):e.logger.warn?.(t,r):e.logger.error?.(t,e.error,r)}const UE=new Map(["AWS4-HMAC-SHA256","Api-Key","ApiKey","Basic","Bearer","Bot","DPoP","Digest","GNAP","HOBA","Key","Mutual","NTLM","Negotiate","OAuth","PrivateToken","SCRAM-SHA-1","SCRAM-SHA-256","Token","vapid"].map((e=>[e.toLowerCase(),e]))),BE=4096;function WE(e){return"object"==typeof e&&null!==e&&"url"in e&&"string"==typeof e.url}function HE(e){return"string"==typeof e?e:e instanceof URL?e.toString():e.url}function qE(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function zE(e){if(e instanceof Headers)return e;if(Array.isArray(e)){const t=[];for(const r of e){if(!Array.isArray(r)||"string"!=typeof r[0]||"string"!=typeof r[1])return;t.push([r[0],r[1]])}return t}if(qE(e)){const t={};for(const[r,n]of Object.entries(e)){if("string"!=typeof n)return;t[r]=n}return t}}function GE(e){const t=[];return e.forEach(((e,r)=>{t.push(r)})),t.sort()}function VE(e){if(null===e)return null;const t=Number.parseInt(e,10);return Number.isNaN(t)?null:t}function KE(e,t){if(null==e)return{kind:"none",bytes:0,contentLength:VE(t.get("content-length"))};if("string"==typeof e){const r=(new TextEncoder).encode(e).length;return{kind:"text",bytes:r,contentLength:VE(t.get("content-length"))??r}}if(e instanceof URLSearchParams){const r=e.toString(),n=(new TextEncoder).encode(r).length;return{kind:"text",bytes:n,contentLength:VE(t.get("content-length"))??n}}return e instanceof Blob?{kind:"blob",bytes:e.size,contentLength:VE(t.get("content-length"))??e.size}:e instanceof ArrayBuffer||ArrayBuffer.isView(e)?{kind:"binary",bytes:e.byteLength,contentLength:VE(t.get("content-length"))??e.byteLength}:"object"==typeof e&&null!==e&&("getReader"in e||Symbol.asyncIterator in e)?{kind:"stream",bytes:null,contentLength:VE(t.get("content-length"))}:{kind:"unknown",bytes:null,contentLength:VE(t.get("content-length"))}}function JE(e,t){if(null===e||!e.toLowerCase().startsWith("application/x-www-form-urlencoded"))return;const r="string"==typeof t?function(e){for(const t of e.split("&")){const e=t.indexOf("="),r=e>=0?t.slice(0,e):t;let n;try{n=decodeURIComponent(r.replaceAll("+"," "))}catch{return}if("grant_type"!==n)continue;const o=e>=0?t.slice(e+1):"";try{return decodeURIComponent(o.replaceAll("+"," "))}catch{return}}}(t):t instanceof URLSearchParams?t.get("grant_type")??void 0:void 0;return r?function(e){switch(e){case"authorization_code":case"refresh_token":case"client_credentials":case"urn:ietf:params:oauth:grant-type:jwt-bearer":case"urn:ietf:params:oauth:grant-type:token-exchange":return e;default:return"other"}}(r):void 0}function ZE(e){const{input:t,init:r}=e,n=wE(HE(t)),o=function(e,t){const r=new Headers(zE(WE(e)?e.headers:void 0));return new Headers(zE(t?.headers)).forEach(((e,t)=>{r.set(t,e)})),r}(t,r),s=GE(o),i=o.get("content-type"),a=vE(o.get("mcp-session-id")??void 0),c=function(e){if(!e)return null;const t=e.trim().split(/\s+/,1)[0]??"";return UE.get(t.toLowerCase())??"unrecognized"}(o.get("authorization"));return{method:(r?.method??(WE(t)?t.method:void 0)??"GET").toUpperCase(),url:n,headers:{names:s,count:s.length},contentType:i,body:KE(r?.body,o),sessionIdHash:a??null,authorizationScheme:c}}function XE(e,t){const r=GE(e.headers),n=VE(e.headers.get("content-length"));return{status:e.status,ok:e.ok,headers:{names:r,count:r.length},contentType:e.headers.get("content-type"),body:{kind:null===e.body?"none":"stream",bytes:null===e.body?0:n,contentLength:n,...void 0!==t?{errorSummary:t}:{}},sessionIdHash:vE(e.headers.get("mcp-session-id")??void 0)??null,wwwAuthenticateHash:vE(e.headers.get("www-authenticate")??void 0)??null,mcpProtocolVersion:e.headers.get("mcp-protocol-version")??null,requestId:e.headers.get("x-request-id")??null,retryAfter:QE(e.headers,"retry-after"),slackRateLimitType:QE(e.headers,"x-slack-ratelimit-type")}}function QE(e,t){return e.get(t)?.slice(0,64)??null}function YE(e){const t={};return void 0!==e.errorName&&(t.name=e.errorName),void 0!==e.errorMessage&&(t.message=e.errorMessage),void 0!==e.errorType&&(t.type=e.errorType),void 0!==e.oauthErrorCode&&(t.oauthErrorCode=e.oauthErrorCode),void 0!==e.errorResponseSummary&&(t.responseSummary=e.errorResponseSummary),void 0!==e.networkClassification&&(t.networkClassification=e.networkClassification),void 0!==e.sdkErrorKind&&(t.sdkErrorKind=e.sdkErrorKind),t}function ex(e,t){const r=ZE({input:e,init:t});if(void 0!==JE(r.contentType,t?.body))return!0;const n=r.url.path?.toLowerCase()??"";return n.endsWith("/token")||n.includes("/oauth/token")||n.includes("/connect/token")}const tx=e=>e;async function rx(e,t,r){try{const n=r(await e.clone().text());return n.length>t?n.slice(0,t):n}catch{return}}async function nx(e){if(!ex(e.input,e.init))return;const t=await rx(e.response,BE,e.redact);if(void 0!==t)try{return FE(JSON.parse(t))}catch{return OE(t,{maxLength:BE})}}async function ox(e){const t=await async function(e,t,r){try{if(t.ok)return;const n=t.headers.get("content-type")?.toLowerCase()??"";if(!n.includes("json")&&!n.includes("text"))return;const o=await rx(t,BE,r);if(void 0===o)return;return function(e){if("/mcp"!==(t=wE(HE(e.input)).path)&&!0!==t?.endsWith("/mcp"))return OE(e.rawText,{maxLength:BE});var t;try{const t=JSON.parse(e.rawText);return qE(t)?function(e){const t=e.error;if("string"==typeof t)return JSON.stringify({error:t});if("object"!=typeof t||null===t)return;if(!qE(t))return;const r=t,n="number"==typeof r.code||"string"==typeof r.code?r.code:void 0,o="string"==typeof r.message?OE(r.message,{maxLength:BE}):void 0;return void 0!==n||void 0!==o?JSON.stringify({...void 0!==n?{code:n}:{},...void 0!==o?{message:o}:{}}):void 0}(t):void 0}catch{return}}({input:e,rawText:o})}catch{return}}(e.input,e.response,e.redact);return{responseErrorSummary:t,oauthTokenErrorBodySummary:void 0===t?await nx({input:e.input,response:e.response,init:e.init,redact:e.redact}):void 0}}function sx(e,t,r){try{e()}catch{t.warn?.("MCP HTTP exchange logging failed",{event:"mcp_http_exchange_logging_failure",phase:r})}}function ix(e,t,r){if("string"==typeof e)return t(e);if("object"!=typeof e||null===e||r>12)return e;if(Array.isArray(e))return e.map((e=>ix(e,t,r+1)));const n=Object.getPrototypeOf(e);return n!==Object.prototype&&null!==n?e:Object.fromEntries(Object.entries(e).map((([e,n])=>[e,ix(n,t,r+1)])))}function ax(e,t){const r=e=>{const r=ix(e,t,0);return qE(r)?r:void 0};return{debug:(t,n)=>e.debug?.(t,r(n)),info:(t,n)=>e.info?.(t,r(n)),warn:(t,n)=>e.warn?.(t,r(n))}}function cx(e){const{fetch:t,logSuccessfulExchanges:r=!0,redactLogText:n}=e,o=void 0===n?e.logger:ax(e.logger,n);return async(s,i)=>{const a=Date.now(),c="function"==typeof e.metadata?e.metadata(s):e.metadata;try{const e=await t(s,i),{responseErrorSummary:l,oauthTokenErrorBodySummary:u}=e.ok?{}:await ox({input:s,init:i,response:e,redact:n??tx});return!r&&e.ok||sx((()=>{!function(e){const{logger:t,response:r}=e,n=function(e){const{input:t,init:r,response:n,durationMs:o,metadata:s,responseErrorSummary:i,oauthTokenErrorBodySummary:a}=e,c=ZE({input:t,init:r}),l=JE(c.contentType,r?.body);return{event:"mcp_http_exchange",outcome:n.ok?"success":"http_error",durationMs:o,cursorMcp:{transport:{...s,request:c,response:XE(n,i),...void 0!==l?{oauth:{grantType:l}}:{},...void 0!==a?{oauthTokenErrorBodySummary:a}:{}}}}}(e);r.ok?t.info?.("MCP HTTP exchange completed",n):function(e){return 401===e.response.status&&null===e.request.authorizationScheme&&e.response.headers.has("www-authenticate")&&!ex(e.input,e.init)}({response:r,request:n.cursorMcp.transport.request,input:e.input,init:e.init})?t.debug?.("MCP HTTP exchange completed",n):t.warn?.("MCP HTTP exchange completed",n)}({logger:o,input:s,init:i,response:e,durationMs:Date.now()-a,metadata:c,responseErrorSummary:l,oauthTokenErrorBodySummary:u})}),o,"success"),e}catch(e){const t=function(e){if(!kE(e))return;const t=kE(e.cause)?e.cause:void 0,r=[e.response,t?.response];for(const e of r)if("object"==typeof(n=e)&&null!==n&&"status"in n&&"number"==typeof n.status&&"headers"in n&&"object"==typeof n.headers&&null!==n.headers&&"get"in n.headers&&"function"==typeof n.headers.get)return e;var n}(e),{responseErrorSummary:r,oauthTokenErrorBodySummary:l}=t?await ox({input:s,init:i,response:t,redact:n??tx}):{};throw sx((()=>{!function(e){const{logger:t}=e;t.warn?.("MCP HTTP exchange failed",function(e){const{input:t,init:r,error:n,durationMs:o,metadata:s,responseFromError:i,responseErrorSummary:a,oauthTokenErrorBodySummary:c}=e,l=NE(n,e.redactLogText),u=ZE({input:t,init:r}),d=JE(u.contentType,r?.body);return{event:"mcp_http_exchange",outcome:"error",durationMs:o,cursorMcp:{transport:{...s,request:u,response:void 0!==i?XE(i,a):{status:l.httpStatus??null,ok:null,headers:{names:[],count:0},contentType:null,body:{kind:"none",bytes:null,contentLength:null,...void 0!==a?{errorSummary:a}:{}},requestId:null,sessionIdHash:null,wwwAuthenticateHash:null,mcpProtocolVersion:null,retryAfter:null,slackRateLimitType:null},...void 0!==d?{oauth:{grantType:d}}:{},...void 0!==c?{oauthTokenErrorBodySummary:c}:{},error:YE(l)}}}}(e))}({logger:o,input:s,init:i,error:e,durationMs:Date.now()-a,metadata:c,responseFromError:t,responseErrorSummary:r,oauthTokenErrorBodySummary:l,redactLogText:n})}),o,"failure"),e}}}function lx(e,t){const r=e?.access_token,n="string"==typeof r?r.length:0,o=Boolean(e?.refresh_token),s="number"==typeof e?.expires_in&&Number.isFinite(e.expires_in)?e.expires_in:null;return{accessTokenLen:n,refreshTokenPresent:o,expiresAtTimestamp:t?.expiresInIsFresh&&null!==s?Date.now()+Math.round(1e3*s):null,grantedScope:"string"==typeof e?.scope&&e.scope.length>0?e.scope:null}}function ux(e){const t=function(e){if(!e||"object"!=typeof e)return;const t=e.code;if("number"==typeof t&&t>=100&&t<=599)return t;if("string"==typeof t&&/^\d{3}$/.test(t)&&Number(t)>=100&&Number(t)<=599)return Number(t);const r=e instanceof Error||"object"==typeof e&&null!==e&&"message"in e&&"string"==typeof e.message?e.message:void 0;if(!r)return;const n=r.match(/\bHTTP\s+(\d{3})\b/i);if(!n?.[1])return;const o=Number.parseInt(n[1],10);return Number.isNaN(o)?void 0:o}(e);return void 0!==t?400===t||404===t||405===t:!!(e instanceof Error&&e.message.toLowerCase().includes("sessionid must be provided"))||function(e){if(!(e instanceof Error))return!1;const t="code"in e&&"string"==typeof e.code?e.code:void 0,r="cause"in e&&"object"==typeof e.cause&&null!==e.cause&&"code"in e.cause&&"string"==typeof e.cause.code?e.cause.code:void 0;return"ECONNREFUSED"===t||"ECONNREFUSED"===r||e.message.includes("ECONNREFUSED")}(e)}function dx(e,t=process.env){const r=t.TMPDIR,n={...void 0===r?{}:{TMPDIR:r},...e},{NODE_COMPILE_CACHE:o,...s}=n;return{...s,NODE_DISABLE_COMPILE_CACHE:"1"}}const hx=["PYTHONIOENCODING","PYTHONUTF8","PYTHONLEGACYWINDOWSSTDIO"],px=[".exe",".cmd",".bat"],fx=/^pythonw?(?:\d+(?:\.\d+)*t?)?$/,mx=new Set(["py","pyw"]),gx=new Set(["--cache-dir","--color","--allow-insecure-host","--directory","--project","--config-file"]),wx=new Set;function yx(e){return hx.some((t=>function(e,t){const r=t.toUpperCase();return Object.entries(e).some((([e,t])=>void 0!==t&&e.toUpperCase()===r))}(e,t)))}function vx(e,t){for(let r=0;r<e.length;r++){const n=e[r];if("--"===n)return;if(!n.startsWith("-"))return{value:n,rest:e.slice(r+1)};t.has(n)&&r++}}function bx(e,t=process.platform,r=process.env){const{command:n,args:o,env:i}=e;return"win32"!==t?i:function(e,t){const r=function(e){const t=s.win32.basename(function(e){const t=e[0];return('"'===t||"'"===t)&&e.length>=2&&e.endsWith(t)?e.slice(1,-1):e}(e.trim())).toLowerCase();for(const e of px)if(t.endsWith(e))return t.slice(0,-e.length);return t}(e);if(fx.test(r)||mx.has(r)||"uvx"===r)return!0;if("uv"===r){const e=vx(t,gx);return"run"===e?.value||"tool"===e?.value&&"run"===vx(e.rest,gx)?.value}return"pipx"===r&&"run"===vx(t,wx)?.value}(n,o)?yx(i)||yx(r)?i:{...i,PYTHONIOENCODING:"utf-8:surrogateescape"}:i}async function Sx(e){const t=[],r=new Set;let n;for(let o=1;;o++){const s=await e.fetchPage(n),i=e.itemsOf(s);t.push(...i);const a=e.nextCursorOf(s);if(!a||r.has(a))return t;if(o>=1e3)throw new Error("MCP list did not end after 1000 pages; refusing to keep paging");r.add(a),n=a}}var kx=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js"),_x=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/sse.js"),Cx=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.js"),Ex=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js");var xx=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js");function Px(e){return`${typeof e}:${String(e)}`}function Ix(e){const t=new Map,r=new Set,n=new Set,o=e=>{for(const t of n)t(e)},s=e=>{t.delete(e),r.delete(e)},i=e.send.bind(e);e.send=(e,n)=>((e=>{if("method"in e)if("tools/call"===e.method&&"id"in e){const r=e.params?.name;"string"==typeof r&&t.set(Px(e.id),r)}else if("notifications/cancelled"===e.method){const n=e.params?.requestId;if("string"!=typeof n&&"number"!=typeof n)return;const o=Px(n);if(!t.has(o))return;if(r.add(o),r.size>64){const e=r.values().next().value;void 0!==e&&s(e)}}})(e),i(e,n));const a=e.onmessage;return e.onmessage=(e,n)=>{(e=>{if("method"in e)return void("notifications/tools/list_changed"===e.method&&o({kind:"tools_list_changed"}));if(!("id"in e))return;const n=e.id;if("string"!=typeof n&&"number"!=typeof n)return;const i=Px(n),a=t.get(i);if(void 0===a)return;const c=r.has(i);if(s(i),!c)return;const l="error"in e||"object"==typeof e.result&&null!==e.result&&"isError"in e.result&&!0===e.result.isError;o({kind:"late_tool_result",toolName:a,isError:l})})(e),a?.(e,n)},{subscribe:e=>(n.add(e),()=>{n.delete(e)})}}function Rx(e){const t=Object.entries(e.headers??{}).map((([e,t])=>[e.toLowerCase(),t])).sort((([e],[t])=>e<t?-1:e>t?1:0));return(0,lo.createHash)("sha256").update(JSON.stringify([e.url,t,e.accessToken??null])).digest("hex")}class Tx{constructor(e,t){this.inner=e,this.initializeResult=t,e.onclose=()=>this.onclose?.(),e.onerror=e=>this.onerror?.(e),e.onmessage=e=>this.onmessage?.(e)}get sessionId(){return this.inner.sessionId}setProtocolVersion(e){this.inner.setProtocolVersion(e)}start(){return this.inner.start()}close(){return this.inner.close()}async send(e,t){if((0,KC.vo)(e)&&(0,KC.eK)(e)){const t={jsonrpc:"2.0",id:e.id,result:this.initializeResult};queueMicrotask((()=>this.onmessage?.(t)))}else(0,KC.wU)(e)||await this.inner.send(e,t)}}const Ax=je.object({tools:je.array(je.unknown()),nextCursor:je.unknown().optional()}),$x={typeFilled:0,toolDropped:0,outputStripped:0};function Mx(e){if(jx(e))return"string"==typeof e.name?e.name:void 0}function Dx(e){return Ox(e.issues.filter((e=>"outputSchema"===e.path[0])))}function Ox(e){return e.map((e=>`${e.path.map(String).join(".")}: ${e.message}`))}function Fx(e){if(!jx(e))return e;const t={...e};return delete t.outputSchema,t}function Nx(e){return jx(e)&&!("type"in e)}function Lx(e,t){return{...e,inputSchema:{type:"object",...t}}}function jx(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var Ux=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/ajv-provider.js");const Bx=new class{constructor({maxSchemasPerCompiler:e=2048,createCompiler:t=()=>new Ux.p}={}){this.compiled=new Map,this.maxSchemasPerCompiler=e,this.createCompiler=t,this.compiler=t()}get compiledSchemaCount(){return this.compiled.size}getValidator(e){let t;return r=>(t??=this.compile(e),t(r))}compile(e){const t=JSON.stringify(e),r=(0,lo.createHash)("sha256").update(t).digest("base64url"),n=this.compiled.get(r);if(void 0!==n)return n;this.compiled.size>=this.maxSchemasPerCompiler&&(this.compiler=this.createCompiler(),this.compiled.clear());const o=(t.includes('"$id"')?this.createCompiler():this.compiler).getValidator(e);return this.compiled.set(r,o),o}};class Wx{constructor(){this.decoder=new TextDecoder("utf-8"),this.captured="",this.capturedBytes=0}push(e){const t="string"==typeof e?e:this.decoder.decode(e,{stream:!0});return this.append(t),t}end(){const e=this.decoder.decode();return this.append(e),e}get text(){return this.captured}get full(){return this.capturedBytes>=yC}append(e){const t=yC-this.capturedBytes;if(t<=0||0===e.length)return;const r=function(e,t){if(!(t>0))return"";if(3*e.length<=t)return e;const{read:r}=Bo(e,Math.trunc(t));return r>=e.length?e:e.slice(0,r)}(e,t);this.captured+=r,this.capturedBytes=r.length<e.length?yC:this.capturedBytes+function(e){return Bo(e,1/0).written}(r)}}const Hx=new WeakMap;var qx=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},zx=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Gx=(0,l.h)("McpSdkClient"),Vx=(0,u.Pu)("mcp_tool.attempt",{description:"One MCP tools/call dial, split by payload, HTTP, and other dial failures",labelNames:["error_class","error_code","transport"]});function Kx(e,t,r){try{Vx.increment(e,1,function(e){const t=e.httpStatus??(void 0!==e.error?function(e){if(!e||"object"!=typeof e)return;const t=wC(e);if(void 0!==t)return t;const r=gC(e)?e.cause:void 0;return r&&"object"==typeof r?wC(r):void 0}(e.error):void 0);return void 0!==t&&Number.isInteger(t)&&t>=100&&t<=599?{error_class:"http",error_code:String(t),transport:e.transport}:void 0!==e.error||!0===e.failed?{error_class:"other",error_code:"exception",transport:e.transport}:!0===e.isError?{error_class:"payload",error_code:"is_error",transport:e.transport}:{error_class:"none",error_code:"none",transport:e.transport}}({transport:vC(t),...r}))}catch{}}const Jx=(0,u.Pu)("mcp_tool.oauth_scope_step_up",{description:"A tools/call refused for a missing OAuth scope, by step-up decision",labelNames:["decision","dropped"]});function Zx(e){return void 0===e?"unknown":"url"in e?"http":"stdio"}const Xx=["authorization_code","refresh_token"],Qx=["code"];class Yx{constructor(e){this._refreshInProgress=!1,this._identifier=e.identifier,this._redirectUrl=e.redirectUrl,this._serverUrl=e.serverUrl,this._restMcpProviderMetadata=e.restMcpProviderMetadata,this.validateResourceURL=!0===e.restMcpProviderMetadata?.omitResourceIndicator?async()=>{}:function(e,t){if(function(e,t){const r=t.gtmApiOrigin;if(void 0===e||void 0===r)return!1;let n,o;try{n=new URL(e),o=new URL(r)}catch{return!1}return n.protocol===o.protocol&&n.hostname===o.hostname&&""===n.port&&"/mcp"===n.pathname}(e,t))return async()=>{};const r=Yy(e);return void 0!==r&&function(e){return"https:"===e.protocol&&e.hostname===new URL(By).hostname}(r)?async()=>{}:void 0!==r&&function(e){return"https:"===e.protocol&&"setup.shopify.com"===e.hostname&&""===e.port&&"/mcp"===e.pathname}(r)?ev:Xy}(e.serverUrl,e.gtmMcpMatch),this._clientMetadata=e.clientMetadata,this._scopes=e.scopes,this._isScopePinGateEnabled=e.isScopePinGateEnabled,this.scopeStepUp=e.scopeStepUp,this._tokens=e.tokens,this._clientInformation=e.clientInformation,this._saveTokens=e.saveTokens,this._prepareForRefresh=e.prepareForRefresh,this._releaseRefreshLeaseOnError=e.releaseRefreshLeaseOnError,this._invalidateCredentials=e.invalidateCredentials,this._saveClientInformation=e.saveClientInformation,this.addClientAuthentication=e.addClientAuthentication}get redirectUrl(){return this._redirectUrl}get clientMetadata(){return this._clientMetadata}state(){return this._oauthAttemptId=(0,lo.randomUUID)(),this._oauthState=function(e,t,r){const n={id:e,owner:t,...r?{attemptId:r}:{}};return Buffer.from(JSON.stringify(n),"utf8").toString("base64url")}(this._identifier,{workspaceId:this._redirectUrl},this._oauthAttemptId),this._oauthState}clientInformation(){return this._clientInformation}hasClientInformation(){return void 0!==this._clientInformation}async saveClientInformation(e){this._clientInformation=e,await this._saveClientInformation(e)}tokens(){return this.scopeStepUp?.tokensForSdk(this._tokens)??this._tokens}async saveTokens(e){const t=this._refreshInProgress;this._refreshInProgress=!1,this._tokens=e,await this._saveTokens(e),await(this.scopeStepUp?.recordTokens(e,{isRefresh:t}))}async prepareForRefresh(){await(this._prepareForRefresh?.()),this._refreshInProgress=!0}async releaseRefreshLeaseOnError(e){this._refreshInProgress=!1,await(this._releaseRefreshLeaseOnError?.(e))}async invalidateCredentials(e){switch(this._refreshInProgress=!1,e){case"tokens":this._tokens=void 0;break;case"client":this._clientInformation=void 0;break;case"verifier":this._codeVerifier=void 0,this._oauthState=void 0,this._oauthAttemptId=void 0;break;case"all":this._tokens=void 0,this._clientInformation=void 0,this._codeVerifier=void 0,this._oauthState=void 0,this._oauthAttemptId=void 0,this._lastRedirectUrl=void 0,await(this.scopeStepUp?.clear({keepPendingScopes:!0}));break;default:return e}await(this._invalidateCredentials?.(e))}async redirectToAuthorization(e){const t=await(this.scopeStepUp?.prepareAuthorization());(function(e,t,r={}){const n=r.stepUpScopes??[],o=void 0!==t&&t.length>0?t:n.length>0?(e.searchParams.get("scope")??"").split(" ").filter((e=>e.length>0)):void 0;var s;void 0!==o&&e.searchParams.set("scope",(s={scopes:o,stepUpScopes:n},[...new Set([...s.scopes,...s.stepUpScopes])]).join(" "))})(e,function(e,t,r){const n=Jy(e);return!0!==n?.pinsScopesOverConfiguredScopes?void 0!==t&&t.length>0||void 0===r?t:tv(e)?.baseScopes??t:void 0!==n.scopesPinGate&&!0!==r?.(n.scopesPinGate)?t:n.scopes??t}(this._serverUrl??"",this._scopes,this._isScopePinGateEnabled),{stepUpScopes:t?.stepUpScopes}),void 0!==this._serverUrl&&function(e,t){const r=Jy(t)?.authorizationParams;if(void 0!==r)for(const[t,n]of Object.entries(r))e.searchParams.set(t,n)}(e,this._serverUrl);for(const[t,r]of Object.entries(this._restMcpProviderMetadata?.authorizationParams??{}))e.searchParams.set(t,r);(!0===this._restMcpProviderMetadata?.omitConsentPrompt||function(e){return"login.microsoftonline.com"===e.hostname}(e))&&function(e){const t=new Set(e.searchParams.getAll("prompt").flatMap((e=>e.split(" "))).filter((e=>""!==e&&"consent"!==e)));e.searchParams.delete("prompt"),t.size>0&&e.searchParams.set("prompt",[...t].join(" "))}(e),await(t?.recordRequestedScopes(e)),this._lastRedirectUrl=e}get lastRedirectUrl(){return this._lastRedirectUrl}async saveCodeVerifier(e){this._codeVerifier=e}codeVerifier(){if(!this._codeVerifier)throw new Error("No code verifier saved");return this._codeVerifier}}async function eP(e){const{serverName:t,config:n,tokenStorage:o}=e,s=await _C(n.url,e.fetchImpl),i=dv({loopbackIpv4:s?.loopbackIpv4,redirectUrl:e.authRedirectUrl}),a=function(e,t){const r=SC(e?.CLIENT_ID);if(void 0!==r)return{client_id:r,...e?.CLIENT_SECRET?{client_secret:e.CLIENT_SECRET}:{},redirect_uris:hv(t),grant_types:[...Xx],response_types:[...Qx],token_endpoint_auth_method:"none"}}(n.auth,i),c=function({storedClientInformation:e,staticClientInformation:t}){return t?e&&e.client_id===t.client_id?{...t,...e,client_secret:t.client_secret??e.client_secret,redirect_uris:t.redirect_uris,grant_types:e.grant_types??t.grant_types,response_types:e.response_types??t.response_types,token_endpoint_auth_method:e.token_endpoint_auth_method??t.token_endpoint_auth_method}:t:e}({storedClientInformation:await o.loadClientInformation(),staticClientInformation:a});return new Yx({identifier:t,redirectUrl:i,serverUrl:n.url,restMcpProviderMetadata:s,gtmMcpMatch:e.gtmMcpMatch??{gtmApiOrigin:void 0},clientMetadata:{redirect_uris:hv(i),token_endpoint_auth_method:"none",grant_types:[...Xx],response_types:[...Qx],client_name:"Cursor",logo_uri:"https://ptht05hbb1ssoooe.public.blob.vercel-storage.com/assets/uploads/cursorlogomcpv3.svg"},scopes:n.auth?.scopes,isScopePinGateEnabled:e.isScopePinGateEnabled,...!0===e.scopeChallengeStepUp&&void 0!==o.loadScopeStepUpRecord&&void 0!==o.saveScopeStepUpRecord?{scopeStepUp:jC({serverUrl:n.url,accountKey:t,configuredScopes:n.auth?.scopes,readTokenScope:async()=>void 0!==o.loadGrantedScope?o.loadGrantedScope():(await o.loadTokens())?.scope,readRecord:async()=>o.loadScopeStepUpRecord?.(),writeRecord:async e=>o.saveScopeStepUpRecord?.(e),readScopesSupported:t=>async function(e){try{const{discoverAuthorizationServerMetadata:t,discoverOAuthProtectedResourceMetadata:n}=await Promise.resolve().then(r.bind(r,"../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js")),o=await n(e.serverUrl,void 0!==e.resourceMetadataUrl?{resourceMetadataUrl:new URL(e.resourceMetadataUrl)}:void 0,e.fetch),s=await t(o.authorization_servers?.[0]??new URL("/",e.serverUrl),{fetchFn:e.fetch}).catch((()=>{}));if(void 0===s&&!0===e.requireAuthorizationServerMetadata)return;const i=new Set([...o.scopes_supported??[],...s?.scopes_supported??[]]);return i.size>0?[...i]:void 0}catch{return}}({serverUrl:n.url,resourceMetadataUrl:t,fetch:e.fetchImpl})})}:{},tokens:await o.loadTokens(),clientInformation:c,saveTokens:e=>o.saveTokens(e),prepareForRefresh:()=>o.prepareForRefresh?.()??Promise.resolve(),releaseRefreshLeaseOnError:e=>o.releaseRefreshLeaseOnError?.(e)??Promise.resolve(),invalidateCredentials:o.invalidateCredentials?e=>o.invalidateCredentials(e):void 0,saveClientInformation:e=>o.saveClientInformation(e),addClientAuthentication:o.tokenEndpointAuth?.({clientId:c?.client_id})})}const tP=new Set;let rP=!1;function nP(){for(const e of tP)try{process.kill(e,"SIGKILL")}catch{}}function oP(e){return qC(e)?new kx.D_:e}function sP(e,t){return dE(e??globalThis.fetch.bind(globalThis),{serverUrl:t})}function iP(e,t,r){const n=hE(e,t),o=r??(globalThis.fetch?globalThis.fetch.bind(globalThis):void 0),s=void 0!==n.cursorAuthHeaderValue&&void 0!==n.cursorAuthOrigin&&void 0!==o?pE((()=>n.cursorAuthHeaderValue),n.cursorAuthOrigin,o):o;return{transportHeaders:n.headers,baseFetch:s}}class aP{constructor(e,t,r){this._toolListGeneration=0,this._toolListSuccessGeneration=0,this._toolListStateGeneration=0,this._callToolLock=Promise.resolve(),this._callToolQueueDepth=0,this._stateEnteredAtMs=Date.now(),this._terminatingSession=!1,this._closeRequested=!1,this.serverName=e,this.client=t,this.tools=new fE,this.stateValue=r.initialState,this._authProvider=r.authProvider,this._authCodeExchange=r.authCodeExchange,this._sessionId=r.sessionId,this._protocolVersion=r.protocolVersion,this._resumedInstructions=r.resumedInstructions,this._sessionlessInitialize=r.sessionlessInitialize,this.config=r.config,this._oauthLifecycleLogger=r.oauthLifecycleLogger,this._serverSignals=r.serverSignals,this._redactLogText=r.redactLogText,this.setupElicitationHandler(),!0===r.stdioServer&&(t.onclose=()=>{this._closeRequested||(this.updateState({kind:"error",message:"MCP server exited"},"stdio_exited"),this.tools.invalidate())})}_stateKindLabel(e){return"requires_authentication"===e.kind?"needsAuth":e.kind}_logStateTransition(e,t,r,n){if(!this._oauthLifecycleLogger)return;const o=this._stateKindLabel(e),s=this._stateKindLabel(t);if(o===s)return;const i=Date.now()-this._stateEnteredAtMs,a=(()=>{try{const e=this.config&&"url"in this.config?this.config.url:void 0;return e?new URL(e).host:void 0}catch{return}})();jE({logger:this._oauthLifecycleLogger,event:"mcp_oauth_state_transition",metadata:{identifier:this.serverName,from:o,to:s,cause:r,serverUrlHost:a,previousStateDurationMs:i,...n}})}static createClient(e={}){const t={elicitation:{form:{}},...!1===e.mcpAppsUi?{}:{extensions:{"io.modelcontextprotocol/ui":{mimeTypes:["text/html;profile=mcp-app"]}}}};return new xx.K({name:"Cursor",version:"1.0.0"},{capabilities:t,jsonSchemaValidator:Bx})}setupElicitationHandler(){this.client.setRequestHandler(KC.$9,(async e=>{if(!this._currentElicitationProvider)return{action:"decline"};if(!("requestedSchema"in e.params))return{action:"decline"};try{const t=e.params.requestedSchema,r=await this._currentElicitationProvider.elicit({message:e.params.message,requestedSchema:t});return{action:r.action,content:r.content}}catch(e){return{action:"decline"}}}))}static async fromStreamableHttp(e,t,r,n,o,s,i,a,c,l,u,d=!1,h={}){const p=new URL(t.url);o=o??av;const f=await eP({serverName:e,config:t,tokenStorage:r,authRedirectUrl:o,fetchImpl:s,gtmMcpMatch:c,isScopePinGateEnabled:l,scopeChallengeStepUp:u}),m=f.tokens(),g=hE(t.url,n),w=g.headers,y=d&&function(e){return Object.entries(e??{}).some((([e,t])=>"authorization"===e.toLowerCase()&&t.trim().length>0))}(w)?void 0:f,v=s??(globalThis.fetch?globalThis.fetch.bind(globalThis):void 0),b=void 0!==g.cursorAuthHeaderValue&&void 0!==g.cursorAuthOrigin&&void 0!==v?pE((()=>g.cursorAuthHeaderValue),g.cursorAuthOrigin,v):v,S=e=>void 0===b||void 0===i?b:cx({fetch:b,logger:i.logger,metadata:{...i.metadata,transportType:e},redactLogText:i.redactLogText});let k;const _=e=>{const r=f.scopeStepUp,n=e??v;return void 0===r||void 0===n?e:(o={fetch:n,scopeStepUp:r,serverUrl:t.url,startSignIn:async e=>{const t=void 0!==e.resourceMetadataUrl&&URL.canParse(e.resourceMetadataUrl)?new URL(e.resourceMetadataUrl):void 0;await(0,kx.j2)(f,{serverUrl:p.toString(),...void 0!==t?{resourceMetadataUrl:t}:{},...void 0!==b?{fetchFn:b}:{}});const r=f.lastRedirectUrl;k=void 0!==r&&void 0!==t?{redirectUrl:r,resourceMetadataUrl:t}:void 0}},async(e,t)=>{const r=await o.fetch(e,t);if(401!==r.status&&403!==r.status||!function(e){if("string"!=typeof e)return!1;let t;try{t=JSON.parse(e)}catch{return!1}return(Array.isArray(t)?t:[t]).some((e=>"object"==typeof e&&null!==e&&"method"in e&&"tools/call"===e.method))}(t?.body))return r;const n=await o.scopeStepUp.decide({status:r.status,wwwAuthenticate:r.headers.get("www-authenticate"),toolName:HC(t?.body)});if(void 0===n)return r;if(o.onDecision?.(n),await(r.body?.cancel().catch((()=>{}))),"offer"===n.kind)try{await o.scopeStepUp.signIn((()=>o.startSignIn(n)))}catch(e){EC(o.scopeStepUp.accountKey).warn("MCP OAuth scope step-up: could not start the sign-in",{event:"mcp_oauth_scope_step_up_sign_in_failed",errorName:e instanceof Error?e.name:typeof e})}throw new WC(n,o.serverUrl,o.scopeStepUp.connectorName)});var o},C=aP.createClient(h),E=e=>e instanceof kx.D_||function(e){if(null===e||"object"!=typeof e)return!1;const t=e.name;if("string"==typeof t&&zC.has(t))return!0;const r=e.errorCode;return!("string"!=typeof r||!GC.has(r.toLowerCase()))||function(e){if(null===e||"object"!=typeof e)return!1;const t=e.name,r=e.errorCode;if("InvalidRequestError"!==t&&("string"!=typeof r||"invalid_request"!==r.toLowerCase()))return!1;const n=e.message;return"string"==typeof n&&VC.some((e=>e.test(n)))}(e)}(e)||qC(e),x=async t=>{if(!f.hasClientInformation())throw new Error("OAuth client registration has not completed. The MCP server may not support dynamic client registration or the registration failed.");const r=void 0!==k&&k.redirectUrl===f.lastRedirectUrl?k.resourceMetadataUrl:void 0;await(0,kx.j2)(f,{serverUrl:p.toString(),authorizationCode:t,...void 0!==r?{resourceMetadataUrl:r}:{},...void 0!==b?{fetchFn:b}:{}}),a&&jE({logger:a,event:"mcp_oauth_callback_completion",metadata:{identifier:e,...yE(p.toString()),...lx(f.tokens(),{expiresInIsFresh:!0})}})},P=r=>{const n=f.lastRedirectUrl?.toString?.()??"",o=new aP(e,C,{oauthLifecycleLogger:a,redactLogText:i?.redactLogText,initialState:{kind:"requires_authentication",url:n,callback:async e=>{try{await x(e),o.updateState({kind:"ready"})}catch(e){const t=e instanceof Error?e.message:"Authentication failed";throw new Error(`Authentication callback failed: ${t}`)}}},authProvider:f,authCodeExchange:x,sessionId:r,config:t});return o},I=async r=>{const n=new _x.A(p,{authProvider:y,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...w??{}}},fetch:_(S("sse"))});try{return await C.connect(n),new aP(e,C,{initialState:{kind:"ready"},authProvider:f,authCodeExchange:x,config:t,oauthLifecycleLogger:a,redactLogText:i?.redactLogText})}catch(t){if(await n.close().catch((()=>{})),E(t))return a&&jE({logger:a,event:"mcp_oauth_state_transition",metadata:{identifier:e,from:"connecting",to:"needsAuth",cause:"connect_auth_error",transport:"sse",refreshTokenPresent:Boolean(m?.refresh_token),...yE(p.toString()),...NE(t,i?.redactLogText)}}),P();if(void 0!==r&&ux(t)&&t instanceof _x._)throw function(e,t){let r=e;for(let e=0;e<8&&r instanceof Error&&r.cause instanceof Error;e++)r=r.cause;return r instanceof Error&&void 0===r.cause&&Reflect.defineProperty(r,"cause",{value:t,writable:!0,configurable:!0,enumerable:!1}),e}(r,t);throw t}};if("sse"===t.type)return I();const R=new Ex.j(p,{authProvider:y,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...w??{}}},fetch:_(sP(S("streamableHttp"),p))});try{await C.connect(R);const r=function(e,t=Date.now){return sE(oE(e),t)}(t.url)?void 0:function(e,r){const o=r.protocolVersion;if(void 0!==r.sessionId||void 0===o)return;const s=e.getServerCapabilities(),i=e.getServerVersion();if(void 0===s||void 0===i)return;const a=e.getInstructions();return{result:{protocolVersion:o,capabilities:s,serverInfo:i,...void 0===a?{}:{instructions:a}},credentialFingerprint:Rx({url:t.url,headers:n,accessToken:f.tokens()?.access_token})}}(C,R);return new aP(e,C,{initialState:{kind:"ready"},authProvider:f,authCodeExchange:x,sessionId:R.sessionId,protocolVersion:R.protocolVersion,...void 0===r?{}:{sessionlessInitialize:r},config:t,oauthLifecycleLogger:a,redactLogText:i?.redactLogText})}catch(t){if(E(t))return a&&jE({logger:a,event:"mcp_oauth_state_transition",metadata:{identifier:e,from:"connecting",to:"needsAuth",cause:"connect_auth_error",transport:"streamableHttp",refreshTokenPresent:Boolean(m?.refresh_token),...yE(p.toString()),...NE(t,i?.redactLogText)}}),P(R.sessionId);if(ux(t))return I(t);throw t}}static async fromStreamableHttpWithoutOAuth(e,t,r){const n=aP.createClient(),o=new Ex.j(new URL(t.url),{requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...t.headers}},fetch:r});return await n.connect(o),new aP(e,n,{initialState:{kind:"ready"},sessionId:o.sessionId,protocolVersion:o.protocolVersion,config:t})}static async fromCachedSession(e,t,r,n,o,s=av,i,a,c,l,u){const d=new URL(t.url),h=await eP({serverName:e,config:t,tokenStorage:n,authRedirectUrl:s,fetchImpl:i,gtmMcpMatch:l,isScopePinGateEnabled:u}),{transportHeaders:p,baseFetch:f}=iP(t.url,o,i),m=new Ex.j(d,{authProvider:h,sessionId:r.sessionId,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...p??{}}},fetch:void 0!==f&&void 0!==a?cx({fetch:f,logger:a.logger,metadata:{...a.metadata,transportType:"streamableHttp"},redactLogText:a.redactLogText}):f});m.setProtocolVersion(r.protocolVersion);const g=aP.createClient();return await g.connect(m),new aP(e,g,{initialState:{kind:"ready"},authProvider:h,sessionId:m.sessionId,protocolVersion:r.protocolVersion,...void 0===r.instructions?{}:{resumedInstructions:r.instructions},config:t,oauthLifecycleLogger:c,redactLogText:a?.redactLogText})}static async fromSessionlessInitialize(e,t,r,n,o,s=av,i,a,c,l){const u=await eP({serverName:e,config:t,tokenStorage:n,authRedirectUrl:s,fetchImpl:i,gtmMcpMatch:a,isScopePinGateEnabled:c});if(Rx({url:t.url,headers:o,accessToken:u.tokens()?.access_token})!==r.credentialFingerprint)return;const{transportHeaders:d,baseFetch:h}=iP(t.url,o,i),p=new Ex.j(new URL(t.url),{authProvider:u,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...d??{}}},fetch:h}),f=aP.createClient();return await f.connect(new Tx(p,r.result)),new aP(e,f,{initialState:{kind:"ready"},authProvider:u,sessionlessInitialize:r,config:t,redactLogText:l})}get sessionId(){return this._sessionId}get protocolVersion(){return this._protocolVersion}get sessionlessInitialize(){return this._sessionlessInitialize}get holdsOAuthAccessToken(){return Boolean(this._authProvider?.tokens()?.access_token)}async openStandaloneStream(){const e=this.client.transport;e instanceof Ex.j&&await e.resumeStream("")}static async fromCommand(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{qx(s,(0,$.VI)(e.withName("McpSdkClient.fromCommand")),!1);const l=(c=o?.spawn,void 0!==c||"linux"!==process.platform?c:(e,t,r)=>(0,wl.D9)(gl.spawn,e,t,r)),u=r.args??[],d=new Cx.oQ({command:r.command,args:u,env:dx(bx({command:r.command,args:u,env:n})),cwd:r.cwd,stderr:"pipe",...l&&{spawn:l}}),h=function(e){const t=new Wx;let r=null===e;return null!==e&&(e.on("data",(e=>{t.full||t.push(e)})),e.once("end",(()=>{t.end(),r=!0}))),{read:()=>OE(t.text.replace(/\s+/g," ").trim(),{maxLength:yC}),waitForFlush:async()=>{r||null===e||await new Promise((t=>{let r;const n=()=>{void 0!==r&&clearTimeout(r),e.off("end",n),t()};r=setTimeout(n,250),r.unref(),e.once("end",n)}))}}}(d.stderr),p=aP.createClient({mcpAppsUi:o?.mcpAppsUi}),f=o?.connectTimeoutMs??(void 0!==(a=r.startupTimeoutSec)&&Number.isFinite(a)&&a>0?Math.min(1e3*a,3e5):6e4);let m;d.onclose=()=>{var e;void 0!==m&&(e=m,tP.delete(e))};let g=0,w=!0;d.onerror=e=>{w&&function(e){return e instanceof SyntaxError||"ZodError"===e.name}(e)&&(g+=1)};const y=new AbortController,v=p.connect(d,{timeout:f,signal:y.signal});let b;m=d.pid??void 0,void 0!==m&&(i=m,tP.add(i),rP||(rP=!0,process.on("exit",nP)));const S=new Promise(((e,r)=>{b=setTimeout((()=>r(new Error(`MCP server connection timed out after ${f}ms: ${t}`))),f)}));try{await Promise.race([v,S])}catch(e){throw y.abort(),v.catch((()=>{})),await d.close().catch((()=>{})),await h.waitForFlush(),g>0&&e instanceof Error&&(e.message=`${e.message}; non-JSON-RPC output on stdout before initialize (${String(g)} line${1===g?"":"s"})`),function(e,t){if(""===t)return e;const r=e instanceof Error?e:new Error(String(e));return r.message=`${r.message}; stderr: ${t}`,Hx.set(r,t),r}(e,h.read())}finally{w=!1,void 0!==b&&clearTimeout(b)}return new aP(t,p,{initialState:{kind:"ready"},config:r,stdioServer:void 0!==m,serverSignals:Ix(d)})}catch(e){s.error=e,s.hasError=!0}finally{zx(s)}var i,a,c}terminateSessionOnClose(e){this._sessionTermination=e}setToolCallRequestOptions(e){this._toolCallRequestOptions=e}failToolCallInFlight(e){const t=this._toolCallInFlight;return void 0!==t&&!t.signal.aborted&&(t.abort(e),!0)}onServerSignal(e){return this._serverSignals?.subscribe(e)??(()=>{})}setToolCallOutputSchemaPassthrough(e){this._toolCallOutputSchemaPassthrough=e}async close(){if(this._closeRequested=!0,this._terminatingSession)return;const e=this._sessionTermination,t=this.client.transport;if(void 0!==e&&t instanceof Ex.j)return this._terminatingSession=!0,void(async()=>{await async function(e,t){const r=await async function(e,t){if(void 0===e.sessionId)return{outcome:"no_session",durationMs:0};const r=Date.now(),n=e.terminateSession();n.catch((()=>{}));try{await(0,Dr.wj)(n,t.timeoutMs)}catch(e){const t=Date.now()-r;return e instanceof Dr.MU?{outcome:"timeout",durationMs:t}:e instanceof Ex.b&&void 0!==e.code&&e.code>0?{outcome:"rejected",durationMs:t,httpStatus:e.code,error:e.message}:{outcome:"failed",durationMs:t,error:String(e)}}const o=t.deleteObserver?.lastDeleteStatus;return{outcome:405===o?"unsupported":"terminated",durationMs:Date.now()-r,...void 0!==o?{httpStatus:o}:{}}}(e,t);try{t.onResult?.(r)}catch{}return r}(t,e),await this.client.close()})().catch((()=>{}));await this.client.close()}async getTools(e){const t={stack:[],error:void 0,hasError:!1};try{const r=qx(t,(0,$.VI)(e.withName("McpSdkClient.getTools")),!1);if(r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("mcp.transport",Zx(this.config)),"requires_authentication"===this.stateValue.kind)return r.span.setAttribute("mcp.tools.requires_authentication",!0),[];if("error"===this.stateValue.kind)return[];const n=++this._toolListGeneration;let o=0,s=0;try{const e=await this.tools.get((async()=>{const e=await Sx({fetchPage:async e=>{o++;const t=await async function(e,t,r){try{const r=await e.listTools({cursor:t});return{tools:r.tools,nextCursor:r.nextCursor,...$x}}catch(c){if(!(c instanceof Error&&"issues"in c&&Array.isArray(c.issues)))throw c}const n=await e.request({method:"tools/list",params:{cursor:t}},Ax),o=[];let s=0,i=0,a=0;for(const e of n.tools){let t=e;if(jx(e)){const r=e.inputSchema;Nx(r)&&(t=Lx(e,r),s++)}let n=KC.Dn.safeParse(t);if(!n.success&&(c=n.error).issues.some((e=>"outputSchema"===e.path[0]))){const o=KC.Dn.safeParse(Fx(t));o.success&&(a++,r(Mx(e),Dx(n.error),"output_stripped"),n=o)}n.success?o.push(n.data):(i++,r(Mx(e),Ox(n.error.issues),"dropped"))}var c;return{tools:o,nextCursor:"string"==typeof n.nextCursor?n.nextCursor:void 0,typeFilled:s,toolDropped:i,outputStripped:a}}(this.client,e,((e,t,n)=>{(function(e,t,r){const n=JSON.stringify([e,t,r]);if(lP.has(n))return lP.delete(n),lP.add(n),!1;if(lP.add(n),lP.size>256){const e=lP.keys().next().value;void 0!==e&&lP.delete(e)}return!0})(n,this.serverName,e??"")&&Gx.warn(r.ctx,"output_stripped"===n?"Removed an MCP tool output schema the client rejected":"Left out an MCP tool whose definition is invalid",{serverName:this.serverName,..."string"==typeof e?{toolName:e}:{},issues:t})}));return s+=t.typeFilled,uP(r.ctx,"type_filled",t.typeFilled),uP(r.ctx,"tool_dropped",t.toolDropped),uP(r.ctx,"output_stripped",t.outputStripped),t},itemsOf:e=>e.tools,nextCursorOf:e=>e.nextCursor});return e.map((e=>({...e,inputSchema:h_(e.inputSchema),outputSchema:void 0===e.outputSchema?void 0:h_(e.outputSchema)})))}));return this.noteToolListSuccess(),r.span.setAttribute("mcp.tools.fetched",o>0),r.span.setAttribute("mcp.tools.pages",o),o>0&&r.span.setAttribute("mcp.tools.type_filled",s),r.span.setAttribute("mcp.tools.count",e.length),e}catch(e){const t=oP(e);if(r.span.setAttribute("mcp.tools.fetched",o>0),r.span.setAttribute("mcp.tools.pages",o),o>0&&r.span.setAttribute("mcp.tools.type_filled",s),this.noteToolListFailure(r.ctx,t,n),t instanceof kx.D_&&n===this._toolListGeneration&&n>this._toolListStateGeneration&&"ready"===this.stateValue.kind){const e=this.stateValue,r=this._authProvider?.lastRedirectUrl?.toString()??"";this.stateValue={kind:"requires_authentication",url:r,callback:e=>this.completeRuntimeAuthorization(e)},this.discardToolListError(),this._logStateTransition(e,this.stateValue,"runtime_unauthorized",{...NE(t,this._redactLogText)}),this._stateEnteredAtMs=Date.now()}throw t}}catch(e){t.error=e,t.hasError=!0}finally{zx(t)}}toolListAttemptIsCurrent(e){return e>this._toolListSuccessGeneration&&e>this._toolListStateGeneration}noteToolListSuccess(){this._toolListError=void 0,this._toolListSuccessGeneration=this._toolListGeneration}discardToolListError(){this._toolListError=void 0,this._toolListStateGeneration=this._toolListGeneration}noteToolListFailure(e,t,r){const n=KC.O4.MethodNotFound;if(t instanceof KC.Nh&&t.code===n&&void 0===this.client.getServerCapabilities()?.tools)return void this.noteToolListSuccess();if(t instanceof kx.D_||!this.toolListAttemptIsCurrent(r))return;const o=function(e){if(e instanceof KC.Nh)return{descriptor:`McpError ${e.code}`,errorClass:"McpError",jsonRpcCode:e.code};if(e instanceof Ex.b||e instanceof _x._){const t=e instanceof Ex.b?"StreamableHTTPError":"SseError",r="number"==typeof e.code?e.code:void 0;return{descriptor:void 0===r?t:`${t} ${r}`,errorClass:t,...void 0===r?{}:{httpStatus:r}}}return e instanceof Error?{descriptor:"Error",errorClass:"Error"}:{descriptor:"unknown",errorClass:"unknown"}}(t);o.descriptor!==this._toolListError&&Gx.warn(e,"MCP server failed to list its tools",{serverName:this.serverName,errorClass:o.errorClass,...void 0!==o.jsonRpcCode?{jsonRpcCode:o.jsonRpcCode}:{},...void 0!==o.httpStatus?{httpStatus:o.httpStatus}:{}}),this._toolListError=o.descriptor}async callTool(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{const a=qx(s,(0,$.VI)(e.withName("McpSdkClient.callTool")),!1);a.span.setAttribute("toolName",t),a.span.setAttribute("serverName",this.serverName),a.span.setAttribute("mcp.transport",Zx(this.config));const c=this._callToolLock,l=this._callToolQueueDepth;let u;this._callToolQueueDepth++,this._callToolLock=new Promise((e=>{u=e}));try{{const e={stack:[],error:void 0,hasError:!1};try{const t=qx(e,(0,$.VI)(a.ctx.withName("McpSdkClient.callTool.lockWait")),!1);t.span.setAttribute("serverName",this.serverName),t.span.setAttribute("mcp.call_tool.queued_ahead",l);const r=performance.now();await c;const n=performance.now()-r;t.span.setAttribute("mcp.call_tool.lock_wait_ms",n),a.span.setAttribute("mcp.call_tool.lock_wait_ms",n),a.span.setAttribute("mcp.call_tool.queued_ahead",l)}catch(t){e.error=t,e.hasError=!0}finally{zx(e)}}if("requires_authentication"===this.stateValue.kind)throw new kx.D_(`MCP server "${this.serverName}" requires authentication`);this._currentToolCallId=n,this._currentToolName=t,this._currentElicitationProvider=o;const s=new AbortController;this._toolCallInFlight=s;const u=this._authProvider?.lastRedirectUrl;try{const n={stack:[],error:void 0,hasError:!1};try{const o=qx(n,(0,$.VI)(a.ctx.withName("McpSdkClient.callTool.sdk")),!1);o.span.setAttribute("toolName",t),o.span.setAttribute("serverName",this.serverName);const c=await this.sendToolCall({name:t,arguments:r},s.signal);return o.span.setAttribute("mcp.call_tool.is_error",!0===c.isError),Kx(e,this.config,{isError:!0===c.isError}),{content:c.content,isError:!0===c.isError,structuredContent:(i=c.structuredContent,p_(i)),_meta:S_(c._meta)}}catch(e){n.error=e,n.hasError=!0}finally{zx(n)}}catch(t){const r=oP(t);r instanceof WC?(Kx(e,this.config,{error:r,httpStatus:r.decision.status}),function(e,t){try{Jx.increment(e,1,{decision:t.decision.kind,dropped:String(t.decision.dropped.length>0)})}catch{}}(e,r)):Kx(e,this.config,{error:r});const n=r instanceof WC&&"offer"===r.decision.kind&&void 0!==this._authProvider?.lastRedirectUrl&&this._authProvider.lastRedirectUrl!==u;if((r instanceof kx.D_||n)&&"ready"===this.stateValue.kind){const e=this.stateValue,t=this._authProvider?.lastRedirectUrl?.toString()??"";this.stateValue={kind:"requires_authentication",url:t,callback:e=>this.completeRuntimeAuthorization(e)},this.discardToolListError(),this._logStateTransition(e,this.stateValue,n?"scope_step_up":"runtime_unauthorized",{...NE(r,this._redactLogText)}),this._stateEnteredAtMs=Date.now()}throw r}finally{this._toolCallInFlight=void 0,this._currentElicitationProvider=void 0,this._currentToolCallId=void 0,this._currentToolName=void 0}}finally{this._callToolQueueDepth--,c.then(u)}}catch(e){s.error=e,s.hasError=!0}finally{zx(s)}var i}sendToolCall(e,t){const r=this._toolCallRequestOptions?.(e.name),n={...r,signal:void 0===r?.signal?t:AbortSignal.any([r.signal,t])};return!0===this._toolCallOutputSchemaPassthrough?.()?this.client.request({method:"tools/call",params:e},KC.TF,n):this.client.callTool(e,void 0,n)}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{if(qx(t,(0,$.VI)(e.withName("McpSdkClient.getInstructions")),!1).span.setAttribute("serverName",this.serverName),"requires_authentication"===this.stateValue.kind)return;return this.client.getInstructions()??this._resumedInstructions}catch(e){t.error=e,t.hasError=!0}finally{zx(t)}}async listResources(e){const t={stack:[],error:void 0,hasError:!1};try{if(qx(t,(0,$.VI)(e.withName("McpSdkClient.listResources")),!1),"requires_authentication"===this.stateValue.kind||"error"===this.stateValue.kind)return{resources:[]};const r=this.client.getServerCapabilities();return r?.resources?{resources:await Sx({fetchPage:e=>this.client.listResources({cursor:e}),itemsOf:e=>e.resources,nextCursorOf:e=>e.nextCursor})}:{resources:[]}}catch(e){t.error=e,t.hasError=!0}finally{zx(t)}}async readResource(e,t){const r={stack:[],error:void 0,hasError:!1};try{return qx(r,(0,$.VI)(e.withName("McpSdkClient.readResource")),!1),"requires_authentication"===this.stateValue.kind?{contents:[]}:{contents:(await this.client.readResource({uri:t.uri})).contents}}catch(e){r.error=e,r.hasError=!0}finally{zx(r)}}async listPrompts(e){const t={stack:[],error:void 0,hasError:!1};try{return qx(t,(0,$.VI)(e.withName("McpSdkClient.listPrompts")),!1),"requires_authentication"===this.stateValue.kind||"error"===this.stateValue.kind?[]:(this.client.getServerCapabilities()??{prompts:!1}).prompts?(await Sx({fetchPage:e=>this.client.listPrompts({cursor:e}),itemsOf:e=>e.prompts,nextCursorOf:e=>e.nextCursor})).map((e=>({name:e.name,description:e.description,arguments:e.arguments?.map((e=>({name:e.name,description:e.description,required:e.required})))}))):[]}catch(e){t.error=e,t.hasError=!0}finally{zx(t)}}async getPrompt(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{return qx(n,(0,$.VI)(e.withName("McpSdkClient.getPrompt")),!1),"requires_authentication"===this.stateValue.kind?{messages:[]}:{messages:(await this.client.getPrompt({name:t,arguments:r})).messages.map((e=>({role:e.role,content:Array.isArray(e.content)?e.content.map((e=>"text"===e.type?{type:"text",text:e.text}:"image"===e.type?{type:"image",data:e.data,mimeType:e.mimeType}:{type:"text",text:JSON.stringify(e)})):[{type:"text",text:"string"==typeof e.content?e.content:JSON.stringify(e.content)}]})))}}catch(e){n.error=e,n.hasError=!0}finally{zx(n)}}getCurrentToolCallContext(){if(this._currentToolName)return{toolName:this._currentToolName,toolCallId:this._currentToolCallId}}async getState(e){return"ready"===this.stateValue.kind&&void 0!==this._toolListError?{kind:"ready",toolListError:this._toolListError}:this.stateValue}async completeRuntimeAuthorization(e){if(!this._authCodeExchange)throw new Error(`MCP server "${this.serverName}" cannot complete authorization: no code exchange is configured for this client.`);try{await this._authCodeExchange(e)}catch(e){const t=e instanceof Error?e.message:"Authentication failed";throw new Error(`Authentication callback failed: ${t}`)}this.updateState({kind:"ready"},"runtime_authorization_completed")}updateState(e,t){const r=this.stateValue;this.discardToolListError(),this.stateValue=e,this._logStateTransition(r,e,t??"explicit_update"),this._stateEnteredAtMs=Date.now()}}const cP=(0,u.Pu)("mcp_tool.schema",{description:"One MCP tool definition a tools/list repair touched",labelNames:["outcome"]}),lP=new Set;function uP(e,t,r){if(0!==r)try{cP.increment(e,r,{outcome:t})}catch{}}class dP extends Error{constructor(e,t){super(`MCP server ${e} not found, available servers: ${t.join(", ")}`),this.serverName=e,this.availableServers=t,this.name="McpServerNotFoundError"}}Error,Error;class hP{constructor(e){this.tools=e}async execute(e,t,r,n){const o=this.tools[e];if(!o)throw new qk(e,Object.keys(this.tools));return o.execute(t,r,n)}getTools(){return Object.entries(this.tools).map((([e,t])=>({...t.definition,name:e})))}}class pP{async getClients(e){return{}}async getClient(e,t){}async getInstructions(e){return[]}async getToolSet(e){return new hP({})}async getTools(e){return[]}async getToolsForServers(e,t){return[]}}class fP{constructor(e){this.manager=e}async getClients(e){return this.manager.getClients()}async getClient(e,t){return this.manager.getClient(t)}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{const r=qx(t,(0,$.VI)(e.withName("ManagerMcpLease.getInstructions")),!1);return await this.manager.getInstructions(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{zx(t)}}async getToolSet(e){const t={stack:[],error:void 0,hasError:!1};try{const r=qx(t,(0,$.VI)(e.withName("ManagerMcpLease.getToolSet")),!1);return await this.manager.getToolSet(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{zx(t)}}async getTools(e){const t={stack:[],error:void 0,hasError:!1};try{const r=qx(t,(0,$.VI)(e.withName("ManagerMcpLease.getTools")),!1);return(await this.getToolSet(r.ctx)).getTools()}catch(e){t.error=e,t.hasError=!0}finally{zx(t)}}async getToolsForServers(e,t){const r=new Set(t);return(await this.getTools(e)).filter((e=>r.has(e.clientKey)))}onDidChange(e){return{dispose:this.manager.onDidChange((()=>e(void 0)))}}async reconcileSelection(e,t,r){for(const e of t.removed){const t=this.manager.getClient(e);this.manager.deleteClient(e);try{await(t?.close?.())}catch{}}for(const n of t.added){if(this.manager.getClient(n))continue;const t=await r(e,n);this.manager.setClient(n,t)}}}class mP{constructor(e,t){this.clients=e,this.elicitationFactory=t,this.changeListeners=new Set,this.warnedToolNameCollisions=new Set}onDidChange(e){return this.changeListeners.add(e),()=>{this.changeListeners.delete(e)}}fireDidChange(){for(const e of this.changeListeners)try{e()}catch(e){console.error("Error in McpManager change listener:",e)}}getClients(){return this.clients}getClient(e){return this.clients[e]}setClient(e,t){this.clients[e]=t,this.fireDidChange()}deleteClient(e){delete this.clients[e],this.fireDidChange()}setListingDeadline(e){this.listingDeadlineAt=void 0===e?void 0:performance.now()+e}async closeAllClients(){const e=Object.values(this.clients);await Promise.all(e.map((async e=>{try{await(e.close?.())}catch{}})))}async getToolSet(e){const t={stack:[],error:void 0,hasError:!1};try{const r=qx(t,(0,$.VI)(e.withName("McpManager.getToolSet")),!1),n=qx(t,gP(this.listingDeadlineAt),!1),o=await(0,Dr.PH)(Object.entries(this.clients),(([e,t])=>n.within(t,r.ctx,(()=>t.getTools(r.ctx))).then((r=>(r??[]).map((r=>({...r,clientKey:e,clientName:t.serverName,client:t}))))).catch((()=>[]))),{max:n.concurrency}),s=Array.from(o.values()).flat(),i=new Map;for(const e of s){const t=`${e.clientName}-${e.name}`,r=i.get(t);void 0===r?i.set(t,[e]):r.push(e)}const a={};for(const[e,t]of i){const n=t[0];if(void 0===n)continue;if(t.some((e=>e.clientName!==n.clientName||e.name!==n.name))){if(!this.warnedToolNameCollisions.has(e)){this.warnedToolNameCollisions.add(e);const r=t.map((e=>`${e.clientName}/${e.name}`)).join(", ");console.warn("Colliding MCP tool name; exposing neither:",`${e} (${r})`)}continue}const o=t[t.length-1]?.clientKey,s=t.filter((e=>e.clientKey===o)),i=s[0]??n;s.length>1&&!this.warnedToolNameCollisions.has(e)&&(this.warnedToolNameCollisions.add(e),console.warn("MCP server lists a tool name more than once; using the first:",`${i.clientName}/${i.name}`)),a[e]={definition:{...i,clientKey:i.clientKey,providerIdentifier:i.clientName,toolName:i.name},execute:async(e,t,n)=>{const o=n?.createProvider(i.clientName,i.name,t);return await i.client.callTool(r.ctx,i.name,e,t,o)}}}return new hP(a)}catch(e){t.error=e,t.hasError=!0}finally{zx(t)}}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{const r=qx(t,(0,$.VI)(e.withName("McpManager.getInstructions")),!1),n=qx(t,gP(this.listingDeadlineAt),!1),o=await(0,Dr.PH)(Object.entries(this.clients),(([e,t])=>n.within(t,r.ctx,(()=>t.getInstructions(r.ctx))).then((e=>e&&0!==e.trim().length?new fn.I0({serverName:t.serverName,instructions:e.trim()}):null)).catch((()=>null))),{max:n.concurrency});return Array.from(o.values()).filter((e=>null!==e))}catch(e){t.error=e,t.hasError=!0}finally{zx(t)}}}function gP(e){if(void 0===e)return{concurrency:4,within:(e,t,r)=>r(),[Symbol.dispose]:()=>{}};let t;const r=new Promise((r=>{t=setTimeout((()=>r(void 0)),Math.max(0,e-performance.now()))}));return{concurrency:Number.POSITIVE_INFINITY,within:async(e,t,n)=>{const o=await Promise.race([e.getState(t).catch((()=>{})),r]);return"ready"===o?.kind?n():Promise.race([n(),r])},[Symbol.dispose]:()=>clearTimeout(t)}}function wP(e,t){return function(e){const{logger:t,ctx:r}=e;return{debug:(e,n)=>t.debug(r,e,n),info:(e,n)=>t.info(r,e,n),warn:(e,n)=>t.warn(r,e,n),error:(e,n,o)=>t.error(r,e,n,o)}}({ctx:e,logger:t})}Error;class yP{constructor(e){this.options=e,jE({logger:e.logger,event:"mcp_oauth_provider_initialized",metadata:this.baseMetadata})}get baseMetadata(){return{identifier:this.options.identifier,...this.options.serverUrl?{serverUrl:yE(this.options.serverUrl)}:{}}}async loadTokens(){const e=await this.options.inner.loadTokens();return jE({logger:this.options.logger,event:"mcp_oauth_tokens_loaded",level:"debug",metadata:{...this.baseMetadata,...lx(e)}}),e}async saveTokens(e){await this.options.inner.saveTokens(e),jE({logger:this.options.logger,event:"mcp_oauth_tokens_saved",metadata:{...this.baseMetadata,...lx(e,{expiresInIsFresh:!0})}})}async prepareForRefresh(){jE({logger:this.options.logger,event:"mcp_oauth_refresh_prepare",metadata:this.baseMetadata}),await(this.options.inner.prepareForRefresh?.())}async releaseRefreshLeaseOnError(e){jE({logger:this.options.logger,event:"mcp_oauth_refresh_error_release",level:"warn",error:e,metadata:{...this.baseMetadata,...NE(e,this.options.redactLogText)}}),await(this.options.inner.releaseRefreshLeaseOnError?.(e))}async loadClientInformation(){const e=await this.options.inner.loadClientInformation();return jE({logger:this.options.logger,event:"mcp_oauth_client_info_loaded",level:"debug",metadata:{...this.baseMetadata,...SE(e)}}),e}async saveClientInformation(e){await this.options.inner.saveClientInformation(e),jE({logger:this.options.logger,event:"mcp_oauth_client_info_saved",metadata:{...this.baseMetadata,...SE(e)}})}async invalidateCredentials(e){void 0!==this.options.inner.invalidateCredentials&&(jE({logger:this.options.logger,event:"mcp_oauth_credentials_invalidated",level:"warn",metadata:{...this.baseMetadata,scope:e}}),await this.options.inner.invalidateCredentials(e))}tokenEndpointAuth(e){return this.options.inner.tokenEndpointAuth?.(e)}get loadScopeStepUpRecord(){return this.options.inner.loadScopeStepUpRecord?.bind(this.options.inner)}get saveScopeStepUpRecord(){return this.options.inner.saveScopeStepUpRecord?.bind(this.options.inner)}}class vP{constructor(e,t){this.storage=e,this.identifier=t}async loadTokens(){return this.storage.loadTokens(this.identifier)}async saveTokens(e){return this.storage.saveTokens(this.identifier,e)}async loadClientInformation(){return this.storage.loadClientInformation(this.identifier)}async saveClientInformation(e){return this.storage.saveClientInformation(this.identifier,e)}get loadScopeStepUpRecord(){const{storage:e,identifier:t}=this;return void 0===e.loadScopeStepUpRecord?void 0:()=>e.loadScopeStepUpRecord(t)}get saveScopeStepUpRecord(){const{storage:e,identifier:t}=this;return void 0===e.saveScopeStepUpRecord?void 0:r=>e.saveScopeStepUpRecord(t,r)}}class bP{constructor(e){this.inner=e}async loadTokens(){}async loadClientInformation(){}async saveTokens(e){return this.inner.saveTokens(e)}async saveClientInformation(e){return this.inner.saveClientInformation(e)}async invalidateCredentials(e){await(this.inner.invalidateCredentials?.(e))}get loadScopeStepUpRecord(){return this.inner.loadScopeStepUpRecord?.bind(this.inner)}get saveScopeStepUpRecord(){return this.inner.saveScopeStepUpRecord?.bind(this.inner)}async loadGrantedScope(){return void 0!==this.inner.loadGrantedScope?this.inner.loadGrantedScope():(await this.inner.loadTokens())?.scope}}var SP=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},kP=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const _P=(0,l.h)("DefinitionMcpLoader"),CP=(0,u.Pu)("connector_policy.blocked",{description:"MCP servers a team or org policy refused to load, once per loader and server.",labelNames:["surface","stage","reason"]});function EP(e){const{filePath:t,baseDir:r}=e;return"~"===t||t.startsWith("~/")?s.default.join(o.default.homedir(),t.slice(1)):t.startsWith("./")||"."===t?s.default.resolve(r??process.cwd(),t):t}function xP(e){return"getManagedSlackWorkspaceLists"in e&&"function"==typeof e.getManagedSlackWorkspaceLists}function PP(e){return"getMcpNetworkControlsConfig"in e&&"function"==typeof e.getMcpNetworkControlsConfig}function IP(e){return e?.length??0}function RP(e){if(void 0!==e)return(0,lo.createHash)("sha256").update(z_(e)).digest("hex")}function TP(e){if(void 0===e)return;let t;return r=>(void 0===t&&(t=e(),queueMicrotask((()=>{t=void 0}))),t?pC(r):r)}async function AP(e,t,n,o,s={middlewares:[],configPath:""},i,a,c={},l={}){const u={stack:[],error:void 0,hasError:!1};try{const{middlewares:d,configPath:h}=s,p=SP(u,(0,$.VI)(e.withName("mcp-agent-exec.loadServer")),!1);p.span.setAttribute("serverName",t);const f=!1!==l.mcpAppsUi;p.span.setAttribute("mcpAppsUi",f),_P.info(p.ctx,`Loading MCP server "${t}" ${f?"declaring":"without declaring"} the MCP Apps UI extension`,{event:"mcp_apps_ui_capability",serverName:t,mcpAppsUi:f,transport:"command"in n?"stdio":"http"});let m=async(e,n)=>{const s={stack:[],error:void 0,hasError:!1};try{const u=SP(s,(0,$.VI)(e.withName("loadServer.next")),!1);u.span.setAttribute("serverName",t);const h=u.ctx;if("command"in n){u.span.setAttribute("kind","command");const e=d.find(PP);return await async function(e,t,n,o,s={}){const i=n.cwd?EP({filePath:n.cwd}):void 0;let a,c;if(n.args&&n.args.length>0)a=EP({filePath:n.command,baseDir:i}),c=n.args.map((e=>EP({filePath:e,baseDir:i})));else{const e=(0,fC.A)(n.command);a=EP({filePath:e[0],baseDir:i}),c=e.slice(1).map((e=>EP({filePath:e,baseDir:i})))}const l=n.env??{},{startupTimeoutSec:u}=n,d=await(o?.getMcpNetworkControlsConfig?.({command:[n.command,...n.args??[]].join(" ")})),h=(0,mv.$H)(d);if(void 0!==h){const{buildMcpSandboxPolicy:n}=await r.e(449).then(r.bind(r,"../mcp-agent-exec/dist/mcp-sandbox-policy.js")),{SandboxUnsupportedError:o,spawnInSandbox:p}=await Promise.resolve().then(r.bind(r,"../shell-exec/dist/api/index.js")),f=i??process.cwd(),m=await n(h,f);_P.info(e,function(e){return`Sandboxing local MCP server "${e.serverName}" with network controls: networkControlsEnabled=${String(!0===e.networkControlsConfig?.enabled)}, mcpNetworkMode=${e.networkControlsConfig?.mcpNetworkMode??"unset"}, mcpNetworkAllowlistCount=${IP(e.networkControlsConfig?.mcpNetworkAllowlist)}, mcpNetworkDenylistCount=${IP(e.networkControlsConfig?.mcpNetworkDenylist)}, localAgentNetworkAllowlistCount=${IP(e.networkControlsConfig?.localAgentNetworkAllowlist)}, sandboxPolicyHash=${RP(e.sandboxNetworkControlsConfig)??"none"}`}({serverName:t,networkControlsConfig:d,sandboxNetworkControlsConfig:h}),function(e){return{event:"mcp_stdio_sandbox_policy",serverName:e.serverName,networkControlsEnabled:!0===e.networkControlsConfig?.enabled,mcpNetworkMode:e.networkControlsConfig?.mcpNetworkMode,mcpNetworkAllowlistCount:IP(e.networkControlsConfig?.mcpNetworkAllowlist),mcpNetworkDenylistCount:IP(e.networkControlsConfig?.mcpNetworkDenylist),localAgentNetworkAllowlistCount:IP(e.networkControlsConfig?.localAgentNetworkAllowlist),sandboxPolicyHash:RP(e.sandboxNetworkControlsConfig)}}({serverName:t,networkControlsConfig:d,sandboxNetworkControlsConfig:h}));try{return await aP.fromCommand(e,t,{command:a,args:c,cwd:i,startupTimeoutSec:u},l,{...s,spawn:(e,t,r)=>p(e,t,r,m)})}catch(e){if(e instanceof o)throw new G_(t,e);throw e}}return!0===d?.enabled&&"no_sandbox"===d.mcpNetworkMode&&(!0===d.win32UserExtensionUnsandbox?_P.info(e,`Starting local MCP server "${t}" without MCP sandboxing`,{event:"mcp_stdio_win32_user_extension_unsandbox",serverName:t}):_P.info(e,`Starting local MCP server "${t}" without MCP sandboxing`)),aP.fromCommand(e,t,{command:a,args:c,cwd:i,startupTimeoutSec:u},l,s)}(h,t,n,e,l)}if("url"in n){u.span.setAttribute("kind","url");const e=i?.(t);return await async function(e,t,r,n,o,s,i,a,c={}){const l=wP(e,_P),u=function(e,t,r){return{logger:{debug:(t,r)=>_P.debug(e,t,r),info:(t,r)=>_P.info(e,t,r),warn:(t,r)=>_P.warn(e,t,r),error:(t,r,n)=>_P.error(e,t,r,n)},metadata:{identifier:t,source:"mcp-agent-exec"},redactLogText:TP(r)}}(e,t,a),d=void 0!==s&&Z_(r.url)?X_(globalThis.fetch.bind(globalThis),{managedSlackWorkspaceLists:()=>s.getManagedSlackWorkspaceLists()}):void 0;return aP.fromStreamableHttp(t,r,n,r.headers,o,d,u,l,void 0,void 0,i,!1,c)}(h,t,n,o,e,d.find(xP),a,c.isLinkSharedPaymentTokenLogRedactionEnabled,l)}throw new Error(`Invalid server: ${JSON.stringify(n)}`)}catch(e){s.error=e,s.hasError=!0}finally{kP(s)}};for(const e of d){const r=m;m=async(n,o)=>await e.load(n,t,o,h,r)}try{return await m(p.ctx,n)}catch(e){throw function(e,t){if(void 0===t)return e;!function(e,t){if("object"!=typeof e||null===e)return;const r=Hx.get(e);void 0!==r&&Hx.set(e,t(r))}(e,t);const r=function(e,t){if(void 0===t)return e;const r={results:new Map,cycled:new Set},n=Q_(e,t,r),o=new Map([...r.cycled].flatMap((e=>{const t=r.results.get(e);return t===e?[]:[[e,t]]})));return o.size>0&&function(e,t){const r=new Set,n=[e];for(let e=0;n.length>0&&e<iC;e++){const e=n.pop();if(!(e instanceof Error||lC(e))||r.has(e))continue;r.add(e);const o=new Set(Object.keys(e));e instanceof Error&&o.add("cause").add("errors");for(const r of o){const o=tC(e,r),s=Y_(o,t);s!==o&&eC(e,r,s),n.push(s)}}}(n,o),n}(e,t);return function(e,t){if("object"!=typeof e||null===e||"object"!=typeof t||null===t)return;const r=Hx.get(e);void 0!==r&&Hx.set(t,r)}(e,r),r}(e,TP(c.isLinkSharedPaymentTokenLogRedactionEnabled))}}catch(e){u.error=e,u.hasError=!0}finally{kP(u)}}class $P{constructor(e,t=L_){this.configPath=e,this.readConfig=t,this.configPromise=t(e)}clearCache(){this.configPromise=this.readConfig(this.configPath)}async getDefinitions(e,t=!0){const r=await this.configPromise;return Object.entries(r.mcpServers).map((([e,t])=>({identifier:e,serverConfig:t,configPath:this.configPath})))}}class MP{constructor(e,t,r=[],n={}){this.source=e,this.tokenStorage=t,this.middlewares=r,this.options=n,this.clientCache=new Map}async load(e,t=!0){const r={stack:[],error:void 0,hasError:!1};try{SP(r,(0,$.VI)(e.withName("DefinitionMcpLoader.load")),!1),t||(await this.closeAllCachedClients(),this.source.clearCache?.());const n=await this.source.getDefinitions(e,t);await this.evictClientsOnSandboxPolicyChange(e,n);const o={};return await(0,Dr.PH)([...n],(async r=>{try{const n=t?this.clientCache.get(r.identifier):void 0,s=n??await this.loadDefinitionClient(e,r);n||this.clientCache.set(r.identifier,s),o[r.identifier]=s}catch(t){if(this.handleDefinitionLoadError(e,r,t))return;!function(e,t,r,n){const o=TP(n)??(e=>e),s=function(e){if("object"==typeof e&&null!==e)return Hx.get(e)}(r);_P.warn(e,"Failed to load MCP server",{identifier:t.identifier,source:t.source,configPath:t.configPath,metadata:t.metadata,errorMessage:o(r instanceof Error?r.message:String(r)),stderrTail:void 0===s?void 0:o(s)})}(e,r,t,this.options.isLinkSharedPaymentTokenLogRedactionEnabled)}}),{max:this.options.maxConcurrency??Math.max(n.length,1)}),new mP(o,this.options.elicitationFactory)}catch(e){r.error=e,r.hasError=!0}finally{kP(r)}}clearClient(e){this.clientCache.delete(e)}clearAllMcpCaches(){this.clientCache.clear()}async evictClientsOnSandboxPolicyChange(e,t){const r=this.middlewares.find(PP);if(!r)return;let n;try{n=JSON.stringify(await Promise.all([...t].sort(((e,t)=>e.identifier.localeCompare(t.identifier))).map((async e=>{const t=await(r.getMcpNetworkControlsConfig?.((n=e.serverConfig,"url"in n?{url:n.url}:{command:[n.command,...n.args??[]].join(" ")})))??{};var n;return[e.identifier,z_(t)]}))))}catch{return}const o=this.sandboxPolicyFingerprint;this.sandboxPolicyFingerprint=n,void 0!==o&&o!==n&&(_P.info(e,"MCP network-controls policy changed; reloading MCP clients to apply the new egress policy"),await this.closeAllCachedClients())}async closeAllCachedClients(){const e=[...this.clientCache.values()];this.clientCache.clear(),await(0,Dr.PH)(e,(async e=>{try{await(e.close?.())}catch{}}),{max:Math.max(e.length,1)})}async loadClient(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{SP(n,(0,$.VI)(e.withName("DefinitionMcpLoader.loadClient")),!1);const o=await this.source.getDefinitions(e);if(await this.evictClientsOnSandboxPolicyChange(e,o),!r){const e=this.clientCache.get(t);if(e)return e}const s=o.find((e=>e.identifier===t));if(!s)throw new Error(`MCP server "${t}" not found in config`);let i;try{i=await this.loadDefinitionClient(e,s,r)}catch(t){throw this.handleDefinitionLoadError(e,s,t),t}return r||this.clientCache.set(t,i),i}catch(e){n.error=e,n.hasError=!0}finally{kP(n)}}async loadDefinitionClient(e,t,r){const n=t.authStorageKey??t.identifier,o=new vP(this.tokenStorage,n),s=wP(e,_P),i=new yP({inner:o,logger:s,redactLogText:TP(this.options.isLinkSharedPaymentTokenLogRedactionEnabled),identifier:n,serverUrl:"url"in t.serverConfig?t.serverConfig.url:void 0}),a=r?new bP(i):i;return AP(e,t.identifier,t.serverConfig,a,{middlewares:this.middlewares,configPath:t.configPath??""},this.options.authRedirectUrlGenerator,this.options.scopeChallengeStepUp,{isLinkSharedPaymentTokenLogRedactionEnabled:this.options.isLinkSharedPaymentTokenLogRedactionEnabled})}handleDefinitionLoadError(e,t,r){let n=!1;try{n="handled"===this.options.onDefinitionLoadError?.(e,t,r)}catch(r){_P.warn(e,"MCP definition load error hook failed",{identifier:t.identifier,source:t.source,configPath:t.configPath,metadata:t.metadata,errorMessage:r instanceof Error?r.message:String(r)})}return n||function(e){return e instanceof Qk||e instanceof Yk||e instanceof e_||e instanceof DP}(r)}}class DP extends Error{constructor(e,t,r){super(r??("teamNetworkAllowlist"===t?`MCP server "${e}" is not on the team network allowlist`:`MCP server "${e}" is blocked by team policy`)),this.serverName=e,this.reason=t,this.name="McpServerBlockedError"}}const OP=[1e3,3e3];class FP{constructor(e){this.blockingService=e,this.countedPolicyBlocks=new Set}async getMcpNetworkControlsConfig(e){return await(this.blockingService.getMcpNetworkControlsConfig?.(e))??{}}async getManagedSlackWorkspaceLists(){return await(this.blockingService.getManagedSlackWorkspaceLists?.())??[]}async load(e,t,r,n,o){const s={command:"command"in r?[r.command,...r.args??[]].join(" "):void 0,url:"url"in r?r.url:void 0},i=await(this.blockingService.getMcpServerBlockInfo?.(s))??{blocked:await this.blockingService.isServerBlocked(s)};if(i.blocked){const r=i.reason??"teamPolicy";throw"teamPolicy"!==r||this.countedPolicyBlocks.has(t)||(this.countedPolicyBlocks.add(t),CP.increment(e,1,{surface:"desktop",stage:"tool_call",reason:"server_not_allowed"})),new DP(t,r,i.message)}for(let n=0;;n++)try{const t=await o(e,r);return!0===i.hostMcpBridge&&this.blockingService.recordHostMcpBridgeClient?.(t),this.blockingService.recordMcpServerClient?.(t,s),t}catch(e){if(e instanceof K_)throw new DP(t,"teamPolicy",e.message);const r=e instanceof J_?OP[n]:void 0;if(void 0===r)throw e;await(0,Dr.cb)(r)}}}class NP extends MP{constructor(e,t,r=[],n={}){super(new $P(e),t,r,n),this.configPath=e}static init(e,t,r=[]){return new NP(t,e,r)}}function LP(e){return"stdio"===e.type&&e.command?{command:e.command,args:e.args??[],env:e.env,cwd:e.cwd}:"streamableHttp"===e.type&&e.url?{url:e.url,headers:e.headers,auth:e.auth,...void 0!==e.tls?{tls:e.tls}:{},...void 0!==e.placement?{placement:e.placement}:{}}:void 0}var jP=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth.js");function UP(e){const t=jP.VE.safeParse(e);return t.success?t.data:void 0}function BP(e){const t=jP.H5.safeParse(e);return t.success?t.data:void 0}class WP{constructor(e){this.mcpAuthPath=e;const t=WP.mcpAuthPromises.get(e);if(t)this.mcpAuthPromise=t;else{const t=this.loadMcpAuth();this.mcpAuthPromise=t,WP.mcpAuthPromises.set(e,t),t.catch((()=>{WP.mcpAuthPromises.get(e)===t&&WP.mcpAuthPromises.delete(e)}))}WP.saveLocks.has(e)||WP.saveLocks.set(e,Promise.resolve())}async loadMcpAuth(){try{const e=await(0,fo.readFile)(this.mcpAuthPath,"utf8"),t=JSON.parse(e);if(t&&"object"==typeof t){if(Object.values(t).some((e=>e&&"object"==typeof e&&null!==e&&("access_token"in e||"refresh_token"in e)&&!("tokens"in e)&&!("clientInfo"in e)))){const e={};for(const[r,n]of Object.entries(t)){const t=UP(n);void 0!==t&&(e[r]={tokens:t})}return e}const e={};for(const[r,n]of Object.entries(t))n&&"object"==typeof n&&null!==n&&(e[r]={tokens:"tokens"in n?UP(n.tokens):void 0,clientInfo:"clientInfo"in n?BP(n.clientInfo):void 0,..."scopeStepUp"in n?{scopeStepUp:n.scopeStepUp}:{}});return e}return{}}catch(e){if(e instanceof Error&&e.message.includes("ENOENT"))return{};throw e}}async loadTokens(e){const t=await this.mcpAuthPromise;return t[e]?.tokens}async saveTokens(e,t){await this.withSaveLock((async()=>{const r=await this.mcpAuthPromise;r[e]||(r[e]={}),r[e].tokens=t,await this.saveMcpAuth(r)}))}async loadClientInformation(e){const t=await this.mcpAuthPromise;return t[e]?.clientInfo}async withSaveLock(e){const t=WP.saveLocks.get(this.mcpAuthPath)??Promise.resolve();let r;WP.saveLocks.set(this.mcpAuthPath,new Promise((e=>{r=e})));try{return await t,await e()}finally{r()}}async saveClientInformation(e,t){await this.withSaveLock((async()=>{const r=await this.mcpAuthPromise;r[e]||(r[e]={}),r[e].clientInfo=t,await this.saveMcpAuth(r)}))}async loadScopeStepUpRecord(e){const t=await this.mcpAuthPromise;return t[e]?.scopeStepUp}async saveScopeStepUpRecord(e,t){await this.withSaveLock((async()=>{const r=await this.mcpAuthPromise;r[e]||(r[e]={}),void 0===t?delete r[e].scopeStepUp:r[e].scopeStepUp=t,await this.saveMcpAuth(r)}))}async deleteCredentials(e){await this.withSaveLock((async()=>{const t=await this.mcpAuthPromise;e in t&&(delete t[e],await this.saveMcpAuth(t))}))}async saveMcpAuth(e){await(0,fo.mkdir)(s.dirname(this.mcpAuthPath),{recursive:!0}),await(0,fo.writeFile)(this.mcpAuthPath,JSON.stringify(e,null,2))}}WP.mcpAuthPromises=new Map,WP.saveLocks=new Map,(0,y.cF)(Symbol("execHookConversationId"),void 0),(0,y.cF)(Symbol("execHookGenerationId"),void 0),(0,y.cF)(Symbol("execHookModel"),void 0);const HP=(0,y.cF)(Symbol("execHookWorkspaceRoots"),void 0);var qP=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},zP=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const GP=(0,u.Pu)("mcp.filesystem.divergence",{description:"Divergence detected between MCP lease state and filesystem state",labelNames:["divergence_type","mcp_source","configured_servers","mcp_version"]}),VP=(0,u.Pu)("mcp.filesystem.sync_check",{description:"MCP filesystem sync check executed",labelNames:["synced","mcp_source","configured_servers","mcp_version"]}),KP=(0,u.wt)("mcp.filesystem.sync_check.expected_servers",{description:"Number of expected MCP servers at last sync check",labelNames:["mcp_source","mcp_version"]}),JP=(0,u.wt)("mcp.filesystem.sync_check.actual_servers",{description:"Number of actual MCP servers on disk at last sync check",labelNames:["mcp_source","mcp_version"]}),ZP=(0,u.wt)("mcp.filesystem.sync_check.servers_missing",{description:"Number of expected MCP servers missing from disk at last sync check",labelNames:["mcp_source","mcp_version"]}),XP=(0,u.wt)("mcp.filesystem.sync_check.tool_mismatches",{description:"Number of MCP servers with tool count mismatches at last sync check",labelNames:["mcp_source","mcp_version"]}),QP=(0,l.h)("McpFileSystemWriter"),YP="mcpFsStructuredLogOptIn";function eI(e,t){return t?.includeStructuredLogs?{...e??{},[YP]:!0}:e}const tI={debug(e,t,r,n){QP.debug(e,t,eI(r,n))},info(e,t,r,n){QP.info(e,t,eI(r,n))},warn(e,t,r,n){QP.warn(e,t,eI(r,n))},error(e,t,r,n,o){QP.error(e,t,r,eI(n,o))}},rI="mcps",nI="tools",oI="~staging",sI="~prev",iI=[25,50,100,200],aI=new Set(["EPERM","EBUSY","EACCES"]),cI=new Map;function lI(e){return e.slice(0,e.indexOf("~"))}function uI(e,t){return`${e}~${Date.now()}-${process.pid}-${(0,lo.randomBytes)(4).toString("hex")}${t}`}const dI=/~(\d+)-\d+-[0-9a-f]+~(?:staging|prev)$/;async function hI(e,t){const r=dI.exec(t),n=r?Number(r[1]):0;try{const{mtimeMs:r}=await(0,fo.stat)((0,s.join)(e,t));return Date.now()-Math.max(n,r)>6e4}catch{return!1}}const pI="mcp_auth",fI="Authenticate this MCP server so its tools can be used. Call this tool through your MCP tool-calling interface when STATUS.md indicates this server needs authentication.",mI="# >>> CURSOR MANAGED BLOCK >>>",gI="# <<< CURSOR MANAGED BLOCK <<<",wI=["# Ignore everything in .cursor","*","# Un-ignore projects so we can descend to allowlisted subdirs","!projects/","projects/*","!projects/*/","projects/*/*","# MCP tool descriptors, resources, prompts","!projects/*/mcps/","!projects/*/mcps/**","# Agent transcripts for citation","!projects/*/agent-transcripts/","!projects/*/agent-transcripts/**","# Terminal output files","!projects/*/terminals/","!projects/*/terminals/**","# Conversation notes (shared scratchpad)","!projects/*/agent-notes/","!projects/*/agent-notes/**","# Large tool output files","!projects/*/agent-tools/","!projects/*/agent-tools/**","# Plugin cache (rules, skills, agents)","!plugins/","!plugins/**","# Built-in Cursor skills","!skills-cursor/","!skills-cursor/**","# User's personal skills","!skills/","!skills/**","# User's personal slash commands","!commands/","!commands/**","# User's plan files","!plans/","!plans/**","# Subagent state/transcripts","!subagents/","!subagents/**","# User-level cursor rules","!rules/","!rules/**"].join("\n");function yI(e,t,r=15e3){let n;return Promise.race([e.catch((()=>t)),new Promise((e=>{n=setTimeout((()=>e(t)),r)}))]).finally((()=>clearTimeout(n)))}function vI(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_")}function bI(e){if(void 0===e)return;const t=e.trim();return t.length>0?t:void 0}function SI(e){switch(e.kind){case"loading":return"initializing";case"requires_authentication":return"needsAuth";case"ready":return"connected";case"error":return"error";default:return"disconnected"}}function kI(e){if(Array.isArray(e))return e.map((e=>kI(e)));if(function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}(e)){const t=Object.entries(e).filter((([,e])=>void 0!==e)).sort((([e],[t])=>e<t?-1:e>t?1:0)).map((([e,t])=>[e,kI(t)]));return Object.fromEntries(t)}return e}function _I(e){return JSON.stringify(kI(e))}function CI(e){const t=e.map((e=>({value:e,key:_I(e)})));return t.sort(((e,t)=>e.key<t.key?-1:e.key>t.key?1:0)),t.map((e=>e.value))}function EI(e){const t=CI(e.tools.map((e=>({name:e.toolName,description:e.description,inputSchema:e.inputSchema,outputSchema:e.outputSchema})))),r=CI(e.resources.map((e=>({uri:e.uri,name:e.name,description:e.description,mimeType:e.mimeType})))),n=CI(e.prompts.map((e=>({name:e.name,description:e.description,arguments:e.arguments}))));return _I({id:e.serverIdentifier,name:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId,tools:t,resources:r,prompts:n,instructions:e.instructions,status:e.status})}class xI{constructor(e,t,r){this.cachedFingerprints=new Map,this.disposed=!1,this.hasPendingLeaseChangeEvent=!1,this.lastDivergenceCheckMs=0,this.mcpLease=e,this.projectDir=t,this.debounceMs=r?.debounceMs??100,this.mcpAuthCopyOverrides=r?.mcpAuthCopyOverrides,this.exposeVirtualMcpAuthTool=r?.exposeVirtualMcpAuthTool??!0,this.alwaysExposeVirtualMcpAuthTool=r?.alwaysExposeVirtualMcpAuthTool??!1,this.snapshotProvider=r?.snapshotProvider,this.mcpVersion=r?.mcpVersion??(this.snapshotProvider?"snapshots":"v1"),this.onDidWrite=r?.onDidWrite,this.ctx=this.getContext(r?.loggerBackend),this.startupCleanupPromise=this.cleanupStaleStagingDirs(this.ctx),this.leaseChangeDisposable=this.mcpLease.onDidChange((e=>{tI.info(this.ctx,"Lease change event received",{serverIdentifiers:e?.serverIdentifiers,reason:e?.reason}),this.onLeaseChanged(this.ctx,e)})),tI.info(this.ctx,"Constructor: scheduling initial write"),this.scheduleWrite(this.ctx),this.ensureCursorDirGitignore()}ensureCursorDirGitignore(){(async function(e){const t=(0,s.join)(e,".gitignore"),r=`${mI}\n${wI}\n${gI}\n`;let n;await(0,fo.mkdir)(e,{recursive:!0});try{n=await(0,fo.readFile)(t,"utf-8")}catch(e){if("ENOENT"!==Ua(e))throw e}if(void 0===n)return void await(0,fo.writeFile)(t,r);const o=n.indexOf(mI),i=n.indexOf(gI,o+30);if(-1===o||-1===i)await(0,fo.writeFile)(t,r);else{const e=`${n.slice(0,o)}${r}${n.slice(i+30).replace(/^\n/,"")}`;e!==n&&await(0,fo.writeFile)(t,e)}})((0,s.join)((0,o.homedir)(),".cursor")).catch((e=>{tI.warn(this.ctx,"Failed to ensure ~/.cursor/.gitignore",e)}))}async cleanupStaleStagingDirs(e){const t=this.getLogContext(e),r=(0,s.join)(this.projectDir,rI);try{const e=await(0,fo.readdir)(r);await Promise.allSettled(e.filter((e=>e.endsWith(oI))).map((async e=>{await hI(r,e)&&await(0,fo.rm)((0,s.join)(r,e),{recursive:!0,force:!0})})))}catch(e){"ENOENT"!==Ua(e)&&tI.error(t,"Error clearing stale mcps staging dirs",e)}}onLeaseChanged(e,t){if(this.disposed)return;const r=t??{serverIdentifiers:void 0};this.hasPendingLeaseChangeEvent?this.pendingLeaseChangeEvent=function(...e){const[t,r]=e;return e.length<2?t:qn(r)?{serverIdentifiers:void 0,reason:t?.reason??r?.reason}:void 0===t?r:qn(t)?{serverIdentifiers:void 0,reason:t.reason??r?.reason}:{serverIdentifiers:[...new Set([...t.serverIdentifiers??[],...r?.serverIdentifiers??[]])],reason:t.reason??r?.reason}}(this.pendingLeaseChangeEvent??{serverIdentifiers:void 0},r):(this.pendingLeaseChangeEvent=r,this.hasPendingLeaseChangeEvent=!0),void 0!==this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout((()=>{this.debounceTimer=void 0;const t=this.takePendingLeaseChangeEvent();this.scheduleWrite(e,t)}),this.debounceMs)}takePendingLeaseChangeEvent(){if(!this.hasPendingLeaseChangeEvent)return;const e=this.pendingLeaseChangeEvent??{serverIdentifiers:void 0};return this.pendingLeaseChangeEvent=void 0,this.hasPendingLeaseChangeEvent=!1,e}scheduleWrite(e,t){const r=this.getLogContext(e);if(this.disposed)return;const n=this.writePromise;this.writePromise=(async()=>{if(n)try{await n}catch(e){tI.error(r,"Error waiting for previous write",e)}this.disposed||(await this.startupCleanupPromise,this.disposed||await this.fetchAndWrite(e,t))})()}getContext(e){let t=(0,y.q6)();return e&&(t=t.with(l._O,e)),t}getLogContext(e){return e.with(l._O,this.ctx.get(l._O))}getMetricTags(e){return{...e,mcp_version:this.mcpVersion}}getMcpAuthToolDescription(){return bI(this.mcpAuthCopyOverrides?.authToolDescription)??fI}shouldExposeVirtualMcpAuthToolForStatus(e,t){return this.exposeVirtualMcpAuthTool&&jn(e)&&(this.alwaysExposeVirtualMcpAuthTool||"needsAuth"===t)}getErrorStatusMessage(){return bI(this.mcpAuthCopyOverrides?.errorStatusMessage)??"The MCP server errored. If this server is important for completing the task, concisely inform the user and ask them to check the MCP status in Cursor's Customize page > MCPs; otherwise continue with a different approach."}getNeedsAuthStatusMessage(e){return t=bI(this.mcpAuthCopyOverrides?.needsAuthStatusMessageWithAuthTool)??'The MCP server needs authentication. Authenticate it by calling the `{authToolName}` tool for server "{serverIdentifier}" through your MCP tool-calling interface using an empty arguments object. If this server is important for completing the task, authenticate it first; otherwise continue with a different approach.',r={serverIdentifier:e,authToolName:pI},t.replace(/\{serverIdentifier\}/g,r.serverIdentifier).replace(/\{authToolName\}/g,r.authToolName);var t,r}getNeedsAuthStatusMessageForWrite(e){return this.exposeVirtualMcpAuthTool&&jn(e)?this.getNeedsAuthStatusMessage(e):bI(this.mcpAuthCopyOverrides?.needsAuthStatusMessageWithoutVirtualTool)??"This MCP server requires authentication before its tools can be used. Open Cursor's Customize page > MCPs, select this server, and use Authenticate/Reopen, or refresh credentials in your MCP configuration (for example mcp.json), then restart this environment. If this server is not required for the task, continue without it."}async getToolsForServers(e,t){if(0===t.length)return[];const r=this.getLogContext(e);try{return await this.mcpLease.getToolsForServers(e,t)}catch(n){tI.warn(r,`getToolsForServers() threw, falling back to filtered getTools(): ${Ba(n)}`);const o=await this.mcpLease.getTools(e).catch((e=>(tI.warn(r,`getTools() threw during scoped-tool fallback, defaulting to []: ${e}`),[]))),s=new Set(t);return o.filter((e=>s.has(e.clientKey)))}}async fetchClientDataForServer(e,t,r,n){const o=await yI(r.getState(e),{kind:"error"}).then((r=>("error"!==r.kind||"message"in r||tI.warn(e,`getState() timed out for "${t}", defaulting to error`),r))),s="ready"===o.kind||"requires_authentication"===o.kind,[i,a,c]=await Promise.all([s?yI(r.listResources(e),{resources:[]}):Promise.resolve({resources:[]}),s?yI(r.listPrompts(e),[]):Promise.resolve([]),s&&n?.fetchInstructions?yI(r.getInstructions(e),void 0):Promise.resolve(void 0)]);return{clientKey:t,serverName:r.serverName,plugin:r.plugin,marketplace:r.marketplace,pluginId:r.pluginId,marketplaceId:r.marketplaceId,resources:i.resources.map((e=>({...e,serverIdentifier:t,serverName:r.serverName}))),prompts:a.map((e=>({...e,serverIdentifier:t,serverName:r.serverName}))),instructions:c,status:SI(o)}}buildServerDataMap(e,t,r){const n=new Map;for(const e of t){const t=Sw(e.clientKey);n.set(e.clientKey,{serverIdentifier:e.clientKey,serverName:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId,sanitizedId:t,folderPath:(0,s.join)(this.projectDir,rI,t),tools:[],resources:e.resources,prompts:e.prompts,instructions:e.instructions,status:e.status})}for(const t of e){let e=n.get(t.clientKey);if(!e){const r=Sw(t.clientKey);e={serverIdentifier:t.clientKey,serverName:t.providerIdentifier,plugin:t.plugin,marketplace:t.marketplace,pluginId:t.pluginId,marketplaceId:t.marketplaceId,sanitizedId:r,folderPath:(0,s.join)(this.projectDir,rI,r),tools:[],resources:[],prompts:[],instructions:void 0,status:void 0},n.set(t.clientKey,e)}e.tools.push(t)}if(void 0!==r)for(const e of r){const t=e.serverIdentifier?.trim();let r=t?Array.from(n.values()).find((e=>e.serverIdentifier===t)):void 0;if(!r){const t=e.serverName?.trim();r=t?Array.from(n.values()).find((e=>e.serverName===t)):void 0}r&&e.instructions&&(r.instructions=e.instructions)}if(this.exposeVirtualMcpAuthTool)for(const e of n.values())this.shouldExposeVirtualMcpAuthToolForStatus(e.serverIdentifier,e.status)&&(e.tools.some((e=>e.toolName===pI))||e.tools.push({clientKey:(o={serverIdentifier:e.serverIdentifier,serverName:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId,authToolDescription:this.getMcpAuthToolDescription()}).serverIdentifier,providerIdentifier:o.serverName,plugin:o.plugin,marketplace:o.marketplace,pluginId:o.pluginId,marketplaceId:o.marketplaceId,toolName:pI,name:pI,description:o.authToolDescription,inputSchema:{type:"object",properties:{},additionalProperties:!1}}));var o;return n}buildServersToWrite(e,t){const r=[],n=new Set;for(const o of t.values()){const t=o.tools.length>0||o.resources.length>0||o.prompts.length>0||o.instructions,s="error"===o.status||"needsAuth"===o.status||"initializing"===o.status;t||s?n.has(o.sanitizedId)?tI.warn(e,`Skipping server "${o.serverIdentifier}" — sanitizedId "${o.sanitizedId}" collides with another server`):(n.add(o.sanitizedId),r.push(o)):tI.info(e,`Server "${o.serverIdentifier}" excluded from write: tools=${o.tools.length}, resources=${o.resources.length}, prompts=${o.prompts.length}, hasInstructions=${!!o.instructions}, status=${o.status}`)}return r}mergeScopedRefreshWithCachedServerData(e,t){const r=[...t.tools];if(this.shouldExposeVirtualMcpAuthToolForStatus(e.serverIdentifier,e.status)&&!r.some((e=>e.toolName===pI))){const t=e.tools.find((e=>e.toolName===pI));void 0!==t&&r.push(t)}return{...e,...t,tools:r,resources:e.resources,prompts:e.prompts,instructions:e.instructions,status:e.status,plugin:t.plugin??e.plugin,marketplace:t.marketplace??e.marketplace,pluginId:t.pluginId??e.pluginId,marketplaceId:t.marketplaceId??e.marketplaceId}}async refreshServersFromLease(e,t){const r=this.getLogContext(e),n=[...new Set(t.serverIdentifiers??[])];tI.info(r,`fetchAndWrite: refreshing ${n.length} targeted servers`,{serverIdentifiers:n});const o=await this.getToolsForServers(e,n),s=await this.mcpLease.getInstructions(e).catch((e=>(tI.warn(r,`getInstructions() threw during scoped refresh, defaulting to []: ${e}`),[]))),i=await Promise.all(n.map((async t=>{try{const r=await this.mcpLease.getClient(e,t);return void 0===r?{serverIdentifier:t,kind:"missing"}:{serverIdentifier:t,kind:"client",client:r}}catch(e){return tI.warn(r,`getClient("${t}") threw during scoped refresh, preserving cached data: ${Ba(e)}`),{serverIdentifier:t,kind:"error",error:e}}}))),a=i.filter((e=>"missing"===e.kind)).map((e=>e.serverIdentifier));let c=new Set;if(a.length>0){const t=await this.mcpLease.getClients(e).catch((e=>{tI.warn(r,`getClients() threw while confirming targeted server removal, preserving cached data: ${e}`)}));void 0!==t&&(c=new Set(a.filter((e=>void 0===t[e]))))}const l=await Promise.all(i.filter((e=>"client"===e.kind)).map((({serverIdentifier:t,client:r})=>this.fetchClientDataForServer(e,t,r,{fetchInstructions:!0})))),u=new Map((this.cachedServerData??[]).map((e=>[e.serverIdentifier,e]))),d=this.buildServerDataMap(o,l,s),h=new Set(n),p=new Set(i.filter((e=>"error"===e.kind||"missing"===e.kind&&!c.has(e.serverIdentifier))).map((e=>e.serverIdentifier)));for(const e of n){const t=u.get(e),n=d.get(e);if(void 0===n)c.has(e)?u.delete(e):tI.warn(r,`refreshServersFromLease: preserving cached data for "${e}" because targeted refresh returned no replacement`);else{if(p.has(e)&&void 0!==t){u.set(e,this.mergeScopedRefreshWithCachedServerData(t,n)),tI.warn(r,`refreshServersFromLease: preserving cached metadata for "${e}" because the client was unavailable during targeted refresh`);continue}u.set(e,n)}}const f=new Map(Array.from(u.values()).map((e=>[e.sanitizedId,e.serverIdentifier])));for(const[e,t]of this.cachedFingerprints)if(!h.has(e)&&!u.has(e)){const t=Sw(e);f.set(t,e)}const m=this.buildServersToWrite(e,u);await this.writeServerData(e,m,f),this.cachedServerData=m,this.fireOnDidWrite(m)}async fetchAndWrite(e,t){const r={stack:[],error:void 0,hasError:!1};try{qP(r,(0,$.VI)(e.withName("McpFileSystemWriter.fetchAndWrite")),!1);const n=this.getLogContext(e);try{if(void 0!==this.cachedServerData&&void 0!==t&&!qn(t)&&[...new Set(t.serverIdentifiers??[])].length>0)return void await this.refreshServersFromLease(e,t);const[r,o,s]=await Promise.all([this.mcpLease.getTools(e).catch((e=>(tI.warn(n,`getTools() threw, defaulting to []: ${e}`),[]))),this.mcpLease.getInstructions(e).catch((()=>[])),this.mcpLease.getClients(e).catch((e=>(tI.warn(n,`getClients() threw, defaulting to {}: ${e}`),{})))]),i=Object.keys(s);tI.info(n,`fetchAndWrite: lease returned ${r.length} tools across ${i.length} clients`);const a=Object.entries(s).map((([t,r])=>this.fetchClientDataForServer(e,t,r))),c=await Promise.all(a),l=this.buildServerDataMap(r,c,o),u=this.buildServersToWrite(e,l),d=new Map(Array.from(l.values()).map((e=>[e.sanitizedId,e.serverIdentifier])));await this.writeServerData(e,u,d),this.cachedServerData=u,this.fireOnDidWrite(u)}catch(e){tI.error(n,"Error fetching/writing MCP state",e)}}catch(e){r.error=e,r.hasError=!0}finally{zP(r)}}fireOnDidWrite(e){if(this.onDidWrite)try{const t=e.map((e=>({serverIdentifier:e.serverIdentifier,folderPath:e.folderPath,tools:e.tools.map((t=>({toolName:t.toolName,definitionPath:(0,s.join)(e.folderPath,nI,`${vI(t.toolName)}.json`)})))})));this.onDidWrite(t)}catch{}}async writeServerData(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{qP(n,(0,$.VI)(e.withName("McpFileSystemWriter.writeServerData")),!1);const o=this.getLogContext(e),i=(0,s.join)(this.projectDir,rI);await(0,fo.mkdir)(i,{recursive:!0});const a=new Map;for(const e of t)try{a.set(e.serverIdentifier,EI(e))}catch(t){tI.error(o,"Error computing server fingerprint, will force write",t,{serverIdentifier:e.serverIdentifier}),a.set(e.serverIdentifier,`__error_${Date.now()}_${Math.random()}`)}const c=[];for(const e of t){const t=this.cachedFingerprints.get(e.serverIdentifier);t!==a.get(e.serverIdentifier)&&(c.push(e),void 0!==t&&tI.info(o,`Server "${e.serverIdentifier}" fingerprint changed: tools=${e.tools.length}, status=${e.status}`))}for(const e of t)if(!c.includes(e))try{await(0,fo.stat)((0,s.join)(i,e.sanitizedId))}catch{tI.info(o,`Server "${e.serverIdentifier}" directory missing on disk, forcing write`),c.push(e)}const l=new Set;for(const[e]of this.cachedFingerprints)if(!a.has(e)){const t=this.cachedServerData?.find((t=>t.serverIdentifier===e)),n=t?.sanitizedId??Sw(e);r.has(n)?(tI.info(o,`Server "${e}" (sanitized="${n}") still in lease but excluded from write, preserving directory`),a.set(e,this.cachedFingerprints.get(e))):(tI.info(o,`Server "${e}" (sanitized="${n}") left the lease, scheduling directory removal`),l.add(n))}const u=void 0===this.cachedServerData;if(u)try{const e=await(0,fo.readdir)(i),t=new Set(e.filter((e=>!e.endsWith(oI)&&!e.endsWith(sI))));for(const r of e){const e=r.endsWith(oI),n=r.endsWith(sI);if((e||n)&&await hI(i,r))if(e)await(0,fo.rm)((0,s.join)(i,r),{recursive:!0,force:!0});else{const e=lI(r);if(t.has(e))await(0,fo.rm)((0,s.join)(i,r),{recursive:!0,force:!0});else try{await(0,fo.rename)((0,s.join)(i,r),(0,s.join)(i,e)),t.add(e)}catch{await(0,fo.rm)((0,s.join)(i,r),{recursive:!0,force:!0}).catch((()=>{}))}}}for(const e of t)if(r.has(e)){const t=r.get(e);a.has(t)||a.set(t,`__preserved_${e}`)}else l.add(e)}catch(e){tI.error(o,"Error clearing mcps directory",e)}const d=Array.from(l);if(c.length>0||l.size>0){const e=c.map((e=>({serverIdentifier:e.serverIdentifier,sanitizedId:e.sanitizedId,toolCount:e.tools.length})));tI.info(o,`Incremental write: ${c.length} changed, ${l.size} removed, ${t.length-c.length} unchanged`,{changedServerCount:c.length,changedServers:e,removedServerCount:l.size,removedServerSanitizedIds:d,unchangedServerCount:t.length-c.length,totalServerCount:t.length,leaseServerCount:r.size,coldStartReconcile:u,projectDirHash:(0,lo.createHash)("sha256").update(this.projectDir).digest("hex")},{includeStructuredLogs:!0})}const h=await Promise.allSettled(c.map((t=>this.writeServerAtomic(e,t,i))));for(let t=0;t<c.length;t++){const r=h[t];if("rejected"===r.status){const n=c[t],o=this.cachedFingerprints.get(n.serverIdentifier);void 0!==o?a.set(n.serverIdentifier,o):a.delete(n.serverIdentifier),tI.error(e,"Error writing server directory",r.reason,{serverIdentifier:n.serverIdentifier,sanitizedId:n.sanitizedId},{includeStructuredLogs:!0})}}const p=await Promise.allSettled(d.map((e=>(0,fo.rm)((0,s.join)(i,e),{recursive:!0,force:!0}))));for(let r=0;r<p.length;r++){const n=p[r];if("rejected"===n.status){const o=d[r];tI.error(e,"Error removing server directory",n.reason,{sanitizedId:o,removalIndex:r,removalAttemptCount:p.length,removedServerCount:d.length,removedServerSanitizedIds:d,changedServerCount:c.length,unchangedServerCount:t.length-c.length,totalServerCount:t.length},{includeStructuredLogs:!0})}}this.cachedFingerprints=a}catch(e){n.error=e,n.hasError=!0}finally{zP(n)}}async writeServerAtomic(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{qP(n,(0,$.VI)(e.withName("McpFileSystemWriter.writeServerAtomic")),!1);const o=(0,s.join)(r,t.sanitizedId),i=cI.get(o),a=(async()=>{await(i?.catch((()=>{}))),await this.swapServerDirectory(e,t,r)})();cI.set(o,a);try{await a}finally{cI.get(o)===a&&cI.delete(o)}}catch(e){n.error=e,n.hasError=!0}finally{zP(n)}}async swapServerDirectory(e,t,r){const n=uI(t.sanitizedId,oI),o=(0,s.join)(r,n),i=(0,s.join)(r,t.sanitizedId);try{await this.writeServerDirectory(e,t,{basePath:r,dirName:n})}catch(e){throw await(0,fo.rm)(o,{recursive:!0,force:!0}).catch((()=>{})),e}const a=(0,s.join)(r,uI(t.sanitizedId,sI));let c=!1;try{try{await this.renameWithRetry(i,a),c=!0}catch(e){if("ENOENT"!==Ua(e))throw e}await this.renameWithRetry(o,i)}catch(r){if(tI.error(e,"Per-server swap failed",r,{serverIdentifier:t.serverIdentifier,sanitizedId:t.sanitizedId},{includeStructuredLogs:!0}),c)try{await this.renameWithRetry(a,i)}catch{await(0,fo.stat)(i).then((()=>!0),(()=>!1))&&await(0,fo.rm)(a,{recursive:!0,force:!0}).catch((()=>{}))}throw await(0,fo.rm)(o,{recursive:!0,force:!0}).catch((()=>{})),r}await(0,fo.rm)(a,{recursive:!0,force:!0}).catch((()=>{}))}async renameWithRetry(e,t){for(let r=0;;r++)try{return void await(0,fo.rename)(e,t)}catch(e){const t=Ua(e);if(r>=iI.length||void 0===t||!aI.has(t))throw e;await(0,Dr.cb)(iI[r])}}async writeServerDirectory(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{qP(n,(0,$.VI)(e.withName("McpFileSystemWriter.writeServerDirectory")),!1);const o=(0,s.join)(r.basePath,r.dirName??t.sanitizedId);if(await(0,fo.mkdir)(o,{recursive:!0}),t.tools.length>0){const e=(0,s.join)(o,nI);await(0,fo.mkdir)(e,{recursive:!0});for(const r of t.tools){const t=vI(r.toolName),n=(0,s.join)(e,`${t}.json`),o=Wn(r);await(0,fo.writeFile)(n,JSON.stringify(o,null,2))}}if(t.resources.length>0){const e=(0,s.join)(o,"resources");await(0,fo.mkdir)(e,{recursive:!0});for(const r of t.resources){const t=vI(r.name||r.uri.replace(/[^a-zA-Z0-9_-]/g,"_")),n=(0,s.join)(e,`${t}.json`),o={uri:r.uri,name:r.name,description:r.description,mimeType:r.mimeType};await(0,fo.writeFile)(n,JSON.stringify(o,null,2))}}if(t.prompts.length>0){const e=(0,s.join)(o,"prompts");await(0,fo.mkdir)(e,{recursive:!0});for(const r of t.prompts){const t=vI(r.name),n=(0,s.join)(e,`${t}.json`),o={name:r.name,description:r.description,arguments:r.arguments};await(0,fo.writeFile)(n,JSON.stringify(o,null,2))}}if(t.instructions&&t.instructions.trim().length>0){const e=(0,s.join)(o,"INSTRUCTIONS.md");await(0,fo.writeFile)(e,t.instructions.trim())}if("error"===t.status||"needsAuth"===t.status){const e=(0,s.join)(o,"STATUS.md"),r="error"===t.status?this.getErrorStatusMessage():this.getNeedsAuthStatusMessageForWrite(t.serverIdentifier);await(0,fo.writeFile)(e,r)}const i=(0,s.join)(o,"SERVER_METADATA.json"),a={serverIdentifier:t.serverIdentifier,serverName:t.serverName};await(0,fo.writeFile)(i,JSON.stringify(a,null,2))}catch(e){n.error=e,n.hasError=!0}finally{zP(n)}}async getMcpFileSystemOptions(e,t){const r={stack:[],error:void 0,hasError:!1};try{if(this.disposed)return;qP(r,(0,$.VI)(e.withName("McpFileSystemWriter.getMcpFileSystemOptions")),!1);const n=this.getLogContext(e),o=await this.ensureWritesSettled(e,t?.timeoutMs);if(this.snapshotProvider&&!o)return this.buildOptionsFromSnapshots(e);this.snapshotProvider&&o&&tI.warn(n,"Snapshot mode write barrier timed out; falling back to cached descriptors",{timeoutMs:t?.timeoutMs},{includeStructuredLogs:!0});const i=(this.cachedServerData??[]).map((e=>{const t=e.tools.map((t=>{const r=vI(t.toolName),n=(0,s.join)(e.folderPath,nI,`${r}.json`);return new fn.E$({toolName:t.toolName,definitionPath:n,...fv(t.annotations)})}));return new fn.UC({serverIdentifier:e.serverIdentifier,serverName:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginDbId:e.pluginId,marketplaceId:e.marketplaceId,folderPath:e.folderPath,serverUseInstructions:e.instructions,tools:t})}));return this.checkDescriptorsVsFilesystem(e,i,"workbench_lease"),new fn.Is({enabled:!0,workspaceProjectDir:this.projectDir,mcpDescriptors:i})}catch(e){r.error=e,r.hasError=!0}finally{zP(r)}}async ensureWritesSettled(e,t){const r=this.getLogContext(e),n=void 0!==this.debounceTimer;if(void 0!==this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0,this.scheduleWrite(e,this.takePendingLeaseChangeEvent())),n&&tI.info(r,"getMcpFileSystemOptions force-fired pending debounce"),!this.writePromise)return!1;if(void 0!==t){let e,n=!1;try{await Promise.race([this.writePromise,new Promise((r=>{e=setTimeout((()=>{n=!0,r()}),t)}))])}catch(e){tI.error(r,"Error waiting for pending write to complete",e)}finally{clearTimeout(e)}return n&&tI.warn(r,`getMcpFileSystemOptions timed out after ${t}ms waiting for write; returning stale cache`),n}try{await this.writePromise}catch(e){tI.error(r,"Error waiting for pending write to complete",e)}return!1}async buildOptionsFromSnapshots(e){const t={stack:[],error:void 0,hasError:!1};try{qP(t,(0,$.VI)(e.withName("McpFileSystemWriter.buildOptionsFromSnapshots")),!1);const r=this.getLogContext(e),n=Date.now(),o=await this.snapshotProvider.getAllSnapshots(e),i=(0,s.join)(this.projectDir,rI),a=o.filter((e=>e.tools.length>0||e.resources.length>0||e.prompts.length>0||void 0!==e.instructions||this.shouldExposeVirtualMcpAuthToolForStatus(e.serverIdentifier,e.status)||"needsAuth"===e.status||"error"===e.status)).map((e=>{const t=Sw(e.serverIdentifier),r=(0,s.join)(i,t),n=e.tools.map((e=>{const t=vI(e.name);return new fn.E$({toolName:e.name,definitionPath:(0,s.join)(r,nI,`${t}.json`),...fv(e.annotations)})}));if(this.shouldExposeVirtualMcpAuthToolForStatus(e.serverIdentifier,e.status)&&!e.tools.some((e=>e.name===pI))){const e=vI(pI);n.push(new fn.E$({toolName:pI,definitionPath:(0,s.join)(r,nI,`${e}.json`)}))}return new fn.UC({serverIdentifier:e.serverIdentifier,serverName:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginDbId:e.pluginId,marketplaceId:e.marketplaceId,folderPath:r,serverUseInstructions:e.instructions,tools:n})})),c=a.reduce(((e,t)=>e+t.tools.length),0);return tI.info(r,`buildOptionsFromSnapshots completed in ${Date.now()-n}ms: ${o.length} snapshots, ${a.length} descriptors, ${c} tools`),this.checkDescriptorsVsFilesystem(e,a,"snapshot"),new fn.Is({enabled:!0,workspaceProjectDir:this.projectDir,mcpDescriptors:a})}catch(e){t.error=e,t.hasError=!0}finally{zP(t)}}async waitForPendingWrites(){if(void 0!==this.debounceTimer&&await new Promise((e=>{const t=()=>{void 0===this.debounceTimer?e():setTimeout(t,10)};t()})),this.writePromise)try{await this.writePromise}catch{}}getCachedServerData(){return this.cachedServerData}checkDescriptorsVsFilesystem(e,t,r){const n=this.getLogContext(e),o=Date.now();o-this.lastDivergenceCheckMs<xI.DIVERGENCE_CHECK_COOLDOWN_MS||(this.lastDivergenceCheckMs=o,this._checkDescriptorsVsFilesystemAsync(e,t,r).catch((e=>{tI.warn(n,"Divergence check failed",e)})))}async _checkDescriptorsVsFilesystemAsync(e,t,r){const n=this.getLogContext(e),o=(0,s.join)(this.projectDir,rI),i=new Set,a=new Map;for(const e of t){const t=Sw(e.serverIdentifier);i.add(t),a.set(t,e.tools.length)}let c=[];try{c=await(0,fo.readdir)(o),c=c.filter((e=>!e.endsWith(oI)&&!e.endsWith(sI)))}catch(e){if("ENOENT"!==Ua(e))throw e}const l=new Set(c);let u=!0,d=0,h=0,p=0;const f=function(e){return 0===e?"0":e<=3?"1-3":e<=6?"4-6":e<=10?"7-10":"11+"}(i.size);for(const t of i)l.has(t)||(u=!1,d++,GP.increment(e,1,this.getMetricTags({divergence_type:"server_missing",mcp_source:r,configured_servers:f})),tI.warn(n,"Divergence detected: server missing from filesystem",{mcpFileSystemMeta:{divergenceType:"server_missing",serverId:t,source:r,configuredServers:i.size,configuredServersBucket:f}},{includeStructuredLogs:!0}));for(const t of l)i.has(t)||(u=!1,h++,GP.increment(e,1,this.getMetricTags({divergence_type:"server_stale",mcp_source:r,configured_servers:f})));for(const t of i){if(!l.has(t))continue;const c=a.get(t)??0,d=(0,s.join)(o,t,nI);let h=0;try{h=(await(0,fo.readdir)(d)).filter((e=>e.endsWith(".json"))).length}catch{}h!==c&&(u=!1,p++,GP.increment(e,1,this.getMetricTags({divergence_type:"tool_count_mismatch",mcp_source:r,configured_servers:f})),tI.warn(n,"Divergence detected: tool count mismatch",{mcpFileSystemMeta:{divergenceType:"tool_count_mismatch",serverId:t,expected:c,actual:h,source:r,configuredServers:i.size,configuredServersBucket:f}},{includeStructuredLogs:!0}))}VP.increment(e,1,this.getMetricTags({synced:String(u),mcp_source:r,configured_servers:f})),KP.gauge(e,i.size,this.getMetricTags({mcp_source:r})),JP.gauge(e,l.size,this.getMetricTags({mcp_source:r})),ZP.gauge(e,d,this.getMetricTags({mcp_source:r})),XP.gauge(e,p,this.getMetricTags({mcp_source:r})),tI.info(n,"MCP filesystem sync check",{mcpFileSystemMeta:{synced:u,expectedServers:i.size,actualServers:l.size,serversMissing:d,serversStale:h,toolMismatches:p,source:r,configuredServers:i.size,configuredServersBucket:f}},{includeStructuredLogs:!0}),u||tI.warn(n,"MCP filesystem divergence summary",{mcpFileSystemMeta:{synced:u,expectedServers:i.size,actualServers:l.size,serversMissing:d,serversStale:h,toolMismatches:p,source:r,configuredServers:i.size,configuredServersBucket:f}},{includeStructuredLogs:!0})}dispose(){this.disposed||(this.disposed=!0,void 0!==this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0),this.leaseChangeDisposable&&(this.leaseChangeDisposable.dispose(),this.leaseChangeDisposable=void 0),this.cachedServerData=void 0,this.cachedFingerprints.clear())}}xI.DIVERGENCE_CHECK_COOLDOWN_MS=1e4;var PI=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},II=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function RI(e){if("object"!=typeof e||null===e||Array.isArray(e))return;const t={};for(const[r,n]of Object.entries(e))"string"==typeof n&&(t[r]=n);return t}const TI=(0,l.h)("local-exec:mcp");function AI(e,t){const r=s.default.relative(e,t);return""===r||!s.default.isAbsolute(r)&&".."!==r&&!r.startsWith(`..${s.default.sep}`)}function $I(e){return e instanceof Error&&"code"in e&&"string"==typeof e.code?e.code:void 0}function MI(e){return new Za._Z({content:{case:"image",value:new Za.do({data:e.data,mimeType:e.mimeType})}})}function DI(e){return new Za._Z({content:{case:"text",value:new Za.zN({text:e})}})}async function OI(e,t,r){const n=await r.permissionsService.shouldBlockMcp(e,t,r.toolDef,{alreadyApproved:t.skipApproval,...void 0===r.client?{}:{client:r.client},...void 0===r.resolvedTool?{}:{resolvedTool:r.resolvedTool}});if(!n)return;const o=await lu(n,{onNeedsApproval:async(e,n)=>{if("mcp"!==n.type)return new Za.iz({result:{case:"error",value:new Za.Nh({error:"Invalid approval details type for MCP execution"})}});const o=await r.pendingDecisionProvider.requestApproval({type:xg.Mcp,details:{name:n.name,toolName:n.toolName,toolTitle:n.toolTitle,destructiveHint:n.destructiveHint,providerIdentifier:n.providerIdentifier,source:r.toolDef?.source,args:n.args,reason:n.reason??e,canAllowlist:n.canAllowlist,smartModeApprovalReason:n.smartModeApprovalReason,smartModeApprovalRequestId:n.smartModeApprovalRequestId,allowlistEntry:n.allowlistEntry,computerUseApp:n.computerUseApp},toolCallId:t.toolCallId});return o.approved&&void 0!==n.computerUseApp&&!0!==n.computerUseApp.allowOnce&&r.permissionsService.allowComputerUseAppForSession?.({bundleId:n.computerUseApp.bundleId}),o.approved?t.smartModeApprovalOnly?new Za.iz({result:{case:"approved",value:new Za.Ke}}):null:new Za.iz({result:{case:"rejected",value:new Za.xo({reason:`User rejected MCP: ${t.name}${o.reason?` - ${o.reason}`:""}`})}})},onUserRejected:e=>new Za.iz({result:{case:"error",value:new Za.Nh({error:`User rejected MCP: ${t.name}${e?` - ${e}`:""}`})}}),onPermissionDenied:(e,r)=>{const n=`MCP tool execution blocked: ${t.name} - ${e}`;return new Za.iz({result:{case:"permissionDenied",value:new Za.HQ({error:n,isReadonly:r?.isReadonly??!1})}})}});return o??void 0}class FI{constructor(e,t,r,n,o=4e4,s,i){this.toolSet=e,this.permissionsService=t,this.pendingDecisionProvider=r,this.projectDir=n,this.fileOutputThresholdBytes=o,this.elicitationFactory=s,this.ensureMcpServersLoaded=i}async describeDisconnectedServer(e,t){const r=new Set(t.filter((e=>""!==e)));if(0===r.size)return;let n;try{n=await this.toolSet.getClients(e)}catch{return}const o=Object.entries(n).find((([e,t])=>r.has(e)||r.has(t.serverName)));if(void 0===o)return;const[s,i]=o;let a;try{a=await i.getState(e)}catch{return}if("ready"===a.kind&&void 0===a.toolListError)return;const c=function(e){switch(e){case"needsAuth":return"This MCP server requires authentication before its tools can be used.";case"error":return"This MCP server failed during live tool discovery. Its tools are unavailable until the connection is fixed.";case"loading":return"This MCP server is still loading; tools may not be available yet.";default:return}}(zn(a));return void 0!==c?`MCP server "${s}" has no callable tools right now. ${c}${"error"===a.kind&&a.message?` (${a.message})`:""}`:void 0}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const o=PI(r,(0,$.VI)(e.withName("LocalMcpToolExecutor.execute")),!1).ctx,i=t.serverIdentifier||t.providerIdentifier;await(this.ensureMcpServersLoaded?.(o,[i]));const a=await this.toolSet.getTools(o),c=Array.from(new Set(a.map((e=>e.clientKey)))).sort(),l=a.find((e=>e.clientKey===i&&e.toolName===t.toolName)),u=a.find((e=>e.name===t.name));if(void 0!==u&&(void 0!==l?u!==l:u.toolName!==t.toolName||u.clientKey!==i&&u.providerIdentifier!==i))return new Za.iz({result:{case:"error",value:new Za.Nh({error:`MCP tool "${t.name}" is not the tool "${t.toolName}" on server "${i}" that the call names.`})}});const d=void 0===l?void 0:await this.toolSet.getClient(o,l.clientKey).catch((()=>{})),h=l??u,p=void 0===h?void 0:h===l?d:await this.toolSet.getClient(o,h.clientKey).catch((()=>{})),f=await OI(o,t,{permissionsService:this.permissionsService,pendingDecisionProvider:this.pendingDecisionProvider,toolDef:l,...void 0===d?{}:{client:d},...void 0===h?{}:{resolvedTool:void 0===p?"unresolved":{client:p,annotations:h.annotations}}});if(void 0!==f)return f;const m=await this.toolSet.getToolSet(o),g=void 0===h&&!0===await(this.permissionsService.enforcesMcpAdminToolLimits?.());let w;try{if(g)throw new qk(t.name,a.map((e=>e.name)));w=await m.execute(l?.name??t.name,Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t.toJson()]))),t.toolCallId,this.elicitationFactory)}catch(e){let r=e;if(zk(r)&&t.providerIdentifier.length>0&&!a.some((e=>e.clientKey===t.providerIdentifier||e.providerIdentifier===t.providerIdentifier))&&(r=new dP(t.providerIdentifier,c)),r instanceof dP){const e=await this.describeDisconnectedServer(o,[i,t.providerIdentifier]);return void 0!==e?new Za.iz({result:{case:"error",value:new Za.Nh({error:e})}}):new Za.iz({result:{case:"serverNotFound",value:new Za.JL({name:r.serverName,availableServers:r.availableServers})}})}if(zk(r))return new Za.iz({result:{case:"toolNotFound",value:new Za.WV({name:r.toolName,availableTools:r.availableTools})}});throw r}const y=[];for(const e of w.content){const r=e.type;if("text"===r&&"object"==typeof e&&null!==e&&"text"in e&&"string"==typeof e.text)y.push(DI(e.text));else if("resource"===r){const r=v_(e),n=void 0===r?void 0:Buffer.from(r,"base64"),s=void 0===n?void 0:await by(n).then(MI,(e=>{TI.warn(o,"Describing an undecodable MCP resource image",{toolName:t.toolName,bytes:n.byteLength,error:e instanceof Error?e.message:String(e)})}));y.push(s??DI(b_(e)))}else if("image"===r){const r=e,s="string"==typeof r.data?Buffer.from(r.data,"base64"):Buffer.alloc(0);let i;try{i=await by(s)}catch(e){TI.warn(o,"Omitting undecodable MCP tool image",{toolName:t.toolName,mimeType:"string"==typeof r.mimeType?r.mimeType.slice(0,100):typeof r.mimeType,bytes:s.byteLength,error:e instanceof Error?e.message:String(e)}),y.push(DI(`[Image omitted: the tool returned ${n=r.mimeType,"string"==typeof n&&/^image\/[\w.+-]{1,40}$/.test(n)?n:"image"} data (${s.byteLength} bytes) that could not be decoded.]`));continue}y.push(MI(i))}else if("image"!==r){const t=b_(e);y.push(DI(t))}}const v=await async function({contentItems:e,thresholdBytes:t,write:r}){const n=e.filter((e=>"text"===e.content.case&&void 0===e.content.value.outputLocation)).map((e=>"text"===e.content.case?e.content.value.text:"")).join("\n\n");if(t<=0||Buffer.byteLength(n,"utf8")<=t)return e;const o=await r(n);if(void 0===o)return;const s=[];let i=!1;for(const t of e)"text"===t.content.case&&void 0===t.content.value.outputLocation?i||(s.push(new Za._Z({content:{case:"text",value:new Za.zN({text:"",outputLocation:o})}})),i=!0):s.push(t);return s}({contentItems:y,thresholdBytes:this.fileOutputThresholdBytes,write:e=>async function(e,t){const r=s.default.join(t,Xa),n=s.default.join(r,`${(0,lo.randomUUID)()}.txt`);await(0,fo.mkdir)(s.default.dirname(n),{recursive:!0});const o=No(e,Qa),i=Us(o),a=Buffer.byteLength(o,"utf8");return await(0,fo.writeFile)(n,o,"utf8"),new Ya.pV({filePath:n,sizeBytes:BigInt(a),lineCount:BigInt(i)})}(e,this.projectDir)});if(void 0===v)throw new Error("Failed to materialize MCP text output");const b=w.structuredContent&&"object"==typeof w.structuredContent&&!Array.isArray(w.structuredContent)?we.Struct.fromJson(w.structuredContent):void 0,S=new Za.QW({content:v,isError:w.isError,structuredContent:b,resultMeta:void 0===w._meta?void 0:we.Struct.fromJson(w._meta)});return new Za.iz({result:{case:"success",value:S}})}catch(e){r.error=e,r.hasError=!0}finally{II(r)}var n}}class NI{constructor(e,t){this.mcpLease=e,this.ensureMcpServersLoaded=t}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=PI(r,(0,$.VI)(e.withName("LocalListMcpResourcesExecutor.execute")),!1).ctx;try{if(t.server){await(this.ensureMcpServersLoaded?.(n,[t.server]));const e=await this.mcpLease.getClients(n),r=e[t.server]??Object.values(e).find((e=>e.serverName===t.server));if(!r)return new Za.kP({result:{case:"error",value:new Za.w2({error:`Server "${t.server}" not found`})}});const o=await this.listResourcesFromClient(n,r,t.server,!0);return new Za.kP({result:{case:"success",value:new Za.T2({resources:o})}})}const e=await this.mcpLease.getClients(n),r=new Set,o=await this.mcpLease.getTools(n);for(const e of o)r.add(e.providerIdentifier),r.add(`user-${e.providerIdentifier}`);const s=[];for(const[t,o]of Object.entries(e)){if(r.size>0&&!r.has(t))continue;const e=await this.listResourcesFromClient(n,o,t);s.push(...e)}return new Za.kP({result:{case:"success",value:new Za.T2({resources:s})}})}catch(e){const t=e instanceof Error?e.message:String(e);return new Za.kP({result:{case:"error",value:new Za.w2({error:`Failed to list MCP resources: ${t}`})}})}}catch(e){r.error=e,r.hasError=!0}finally{II(r)}}async listResourcesFromClient(e,t,r,n=!1){const o=await t.getState(e);if("ready"!==o.kind&&(!n||"loading"!==o.kind))return[];const s=await t.listResources(e);return s&&s.resources?s.resources.map((e=>new Za.X2({uri:e.uri,name:e.name,description:e.description,mimeType:e.mimeType,server:r,annotations:RI(e.annotations)}))):[]}}class LI{constructor(e,t=".",r,n=[],o,s){this.mcpLease=e,this.projectDir=t,this.permissionsService=r,this.pendingDecisionProvider=o,this.ensureMcpServersLoaded=s,this.workspacePaths=n.filter((e=>e.length>0))}resolveProjectDir(e){const t=e.get(HP),r=t?.find((e=>"string"==typeof e&&e.length>0));return r||(this.workspacePaths.length>0?this.workspacePaths[0]:this.projectDir)}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=PI(r,(0,$.VI)(e.withName("LocalReadMcpResourceExecutor.execute")),!1).ctx,o=t.smartModeApproval?.reason;if(void 0!==o){if(void 0===this.pendingDecisionProvider)return new Za.ZD({result:{case:"error",value:new Za.Jx({uri:t.uri,error:"Auto-review approval provider is not configured"})}});const e=await this.pendingDecisionProvider.requestApproval({type:xg.Mcp,details:{name:"FetchMcpResource",toolName:"FetchMcpResource",providerIdentifier:t.server,args:{server:we.Value.fromJson(t.server),uri:we.Value.fromJson(t.uri),...void 0!==t.downloadPath?{downloadPath:we.Value.fromJson(t.downloadPath)}:{}},reason:"smartMode",canAllowlist:!1,smartModeApprovalReason:o,smartModeApprovalRequestId:t.smartModeApproval?.requestId},toolCallId:t.toolCallId});if(!e.approved)return new Za.ZD({result:{case:"rejected",value:new Za.Dh({reason:"User rejected MCP resource fetch"+(e.reason?` - ${e.reason}`:"")})}})}await(this.ensureMcpServersLoaded?.(n,[t.server]));const i=await this.mcpLease.getClients(n),a=i[t.server]??Object.values(i).find((e=>e.serverName===t.server));if(!a)return new Za.ZD({result:{case:"error",value:new Za.Jx({uri:t.uri,error:`Server "${t.server}" not found`})}});try{if("ready"!==(await a.getState(n)).kind)return new Za.ZD({result:{case:"error",value:new Za.Jx({uri:t.uri,error:`Server "${t.server}" is not ready`})}});const e=await a.readResource(n,{uri:t.uri});if(!e||!e.contents||0===e.contents.length)return new Za.ZD({result:{case:"notFound",value:new Za.ov({uri:t.uri})}});const r=e.contents[0];if(t.downloadPath){const e=await async function(e,t){const r=s.default.resolve(e),n=await(0,fo.realpath)(r),o=s.default.resolve(r,t.replace(/^\/+/,""));if(!AI(r,o))throw new Error("downloadPath must stay within the workspace");let i=s.default.dirname(o);for(;;)try{if(!AI(n,await(0,fo.realpath)(i)))throw new Error("downloadPath must stay within the workspace");break}catch(e){if("ENOENT"!==$I(e))throw e;const t=s.default.dirname(i);if(t===i)throw e;i=t}if(await(0,fo.mkdir)(s.default.dirname(o),{recursive:!0}),!AI(n,await(0,fo.realpath)(s.default.dirname(o))))throw new Error("downloadPath must stay within the workspace");try{if((await(0,fo.lstat)(o)).isSymbolicLink())throw new Error("downloadPath must stay within the workspace")}catch(e){if("ENOENT"!==$I(e))throw e}return o}(this.resolveProjectDir(n),t.downloadPath);if(r.text)await(0,fo.writeFile)(e,r.text,"utf8");else if(r.blob){const t=Buffer.from(r.blob,"base64");await(0,fo.writeFile)(e,t)}return new Za.ZD({result:{case:"success",value:new Za.KZ({uri:t.uri,name:r.name,description:r.description,mimeType:r.mimeType,downloadPath:e})}})}if(r.text)return new Za.ZD({result:{case:"success",value:new Za.KZ({uri:t.uri,name:r.name,description:r.description,mimeType:r.mimeType,annotations:RI(r.annotations),metaJson:Bn(r._meta),content:{case:"text",value:r.text}})}});if(r.blob){const e=Buffer.from(r.blob,"base64");return new Za.ZD({result:{case:"success",value:new Za.KZ({uri:t.uri,name:r.name,description:r.description,mimeType:r.mimeType,annotations:RI(r.annotations),metaJson:Bn(r._meta),content:{case:"blob",value:e}})}})}return new Za.ZD({result:{case:"error",value:new Za.Jx({uri:t.uri,error:"Failed to read resource"})}})}catch(e){const r=e instanceof Error?e.message:String(e);return TI.warn(n,"LocalReadMcpResourceExecutor.execute failed",{server:t.server,hasDownloadPath:Boolean(t.downloadPath),errorName:e instanceof Error?e.name:typeof e,errorMessage:r}),new Za.ZD({result:{case:"error",value:new Za.Jx({uri:t.uri,error:`Failed to read MCP resource: ${r}`})}})}}catch(e){r.error=e,r.hasError=!0}finally{II(r)}}}var jI=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const UI=1e4,BI=5e3,WI={PAGER:"cat",MANPAGER:"cat",LESS:"-R",PIP_PROGRESS_BAR:"off",TQDM_DISABLE:"1"};class HI{constructor(){this.fullOutput="",this.outputHead="",this.outputTail="",this.totalChars=0}append(e){if(0===e.length)return;const t=this.totalChars;if(this.totalChars+=e.length,t<BI&&(this.outputHead=No(this.outputHead+e,BI)),this.outputTail=Lo(this.outputTail+e,BI),t<UI){const r=Math.min(e.length,UI-t);this.fullOutput+=e.slice(0,r)}this.totalChars>UI&&(this.fullOutput="")}getOutput(){return this.totalChars<=UI?this.fullOutput:void 0}getTruncation(){if(!(this.totalChars<=UI))return{outputHead:this.outputHead,outputTail:this.outputTail,elidedChars:this.totalChars-this.outputHead.length-this.outputTail.length}}}class qI{constructor(){this.kept="",this.full=!1}append(e){if(this.full)return;const t=Go-this.kept.length;this.full=e.length>=t,this.kept+=No(e,t)}get text(){return this.kept}}function zI(e,t){return null!==e?e:null===t?-1:-o.constants.signals[t]}class GI{constructor(e,t,r){this.permissionsService=e,this.ignoreService=t,this.defaultCwd=r}buildResult({args:e,workingDirectory:t,processResult:r,sandboxPolicy:n}){const o={command:e.command,workingDirectory:t,exitCode:r.returncode,signal:r.signal,stdout:r.stdout,stderr:r.exceptionInfo||r.stderr,interleavedOutput:r.output,outputHead:r.outputTruncation?.outputHead,outputTail:r.outputTruncation?.outputTail,elidedChars:r.outputTruncation?.elidedChars,executionTime:r.localExecutionTimeMs??0,localExecutionTimeMs:r.localExecutionTimeMs},s=r.exceptionInfo.length>0,i=0!==r.returncode||s?{case:"failure",value:new he.xC({...o,aborted:s,abortReason:r.abortReason})}:{case:"success",value:new he.QR(o)};return new he.W4({result:i,sandboxPolicy:es(n)})}async runProcess({ctx:e,args:t,workingDirectory:r,sandboxPolicy:n,timeoutMs:o}){const s=performance.now(),i=this.defaultCwd,a=(await(0,Eo.resolveSandboxPolicyForWorkspace)(i,n?{perRepo:n}:void 0)).policy,c="insecure_none"!==a.type?{...a,sandboxWorkspaceRoot:i}:a;return await new Promise((n=>{const i=new HI,a=new qI,l=new qI;let u,d,h=!1,p=!1,f="",m=()=>{};const g=(0,Eo.Qw)((0,Eo.ue)((0,Eo.Xw)({...process.env,...WI,CURSOR_AGENT:"1"}))),w={cwd:r,env:g,stdio:["pipe","pipe","pipe"],detached:"win32"!==process.platform,windowsVerbatimArguments:"win32"===process.platform},y="win32"===process.platform?{executable:process.env.ComSpec??"cmd.exe",args:(v=t.command,["/d","/s","/c",`"${v}"`])}:{executable:"/bin/sh",args:["-c",t.command]};var v;const b="insecure_none"===c.type?(0,wl.D9)(gl.spawn,y.executable,y.args,w):(0,Eo.spawnInSandbox)(y.executable,y.args,w,c);b.stdin?.end();const S=e=>{h||(h=!0,clearTimeout(d),m(),n({...e,output:i.getOutput(),outputTruncation:i.getTruncation(),localExecutionTimeMs:bw(performance.now()-s)}))};d=setTimeout((()=>{if(p=!0,void 0===u&&(f=`An error occurred while executing the command: Command timed out after ${o}ms`,u=he.Lv.TIMEOUT,m()),void 0!==b.pid&&"win32"!==process.platform)try{return void process.kill(-b.pid,"SIGKILL")}catch{}b.kill("SIGKILL")}),o);const k=()=>{if(void 0===u){if(f="An error occurred while executing the command: Command aborted",u=he.Lv.USER_ABORT,void 0!==b.pid&&"win32"!==process.platform)try{return void process.kill(-b.pid,"SIGTERM")}catch{}b.kill("SIGTERM")}};e.signal.aborted?k():(e.signal.addEventListener("abort",k,{once:!0}),m=()=>{e.signal.removeEventListener("abort",k)}),b.stdout?.setEncoding("utf8"),b.stdout?.on("data",(e=>{a.append(e),i.append(e)})),b.stderr?.setEncoding("utf8"),b.stderr?.on("data",(e=>{l.append(e),i.append(e)})),b.on("error",(e=>{S({stdout:a.text,stderr:l.text,returncode:-1,signal:"",exceptionInfo:`An error occurred while executing the command: ${e.message}`})})),b.on("close",((e,t)=>{S({stdout:a.text,stderr:l.text,returncode:f.length>0?-1:zI(e,t),signal:t??(p?"SIGKILL":""),exceptionInfo:f,abortReason:u})}))}))}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(r,(0,$.VI)(e.withName("LocalMiniSweAgentBashExecutor.execute")),!1).ctx;(0,$.HF)(n,"LocalMiniSweAgentBashExecutor.execute");const o=t.command,s=(0,Ho.o1)(t.workingDirectory||this.defaultCwd),i=t.timeout>0?t.timeout:3e4;if(!t.parsingResult)return new he.W4({result:{case:"spawnError",value:new he.mJ({command:o,workingDirectory:s,error:"Parsing result is required"})}});let a=t.requestedSandboxPolicy?Yo(t.requestedSandboxPolicy):void 0;const c=await this.permissionsService.shouldBlockShellCommand(n,o,{workingDirectory:s,timeout:i,parsingResult:t.parsingResult,toolCallId:t.toolCallId},a);if("block"===c.kind)return"permissionsConfig"===c.reason.type&&c.reason.isReadonly?new he.W4({result:{case:"permissionDenied",value:new he.jn({command:o,workingDirectory:s,error:"Command blocked by permissions configuration",isReadonly:!0})}}):new he.W4({result:{case:"rejected",value:new he.pZ({command:o,workingDirectory:s,reason:uu(c.reason)})}});a=c.policy,_s()&&(a=Rs(o,t.parsingResult)),a&&"insecure_none"!==a.type&&(a={...a,ignoreMapping:await this.ignoreService.getCursorIgnoreMapping()});const l=await this.runProcess({ctx:n,args:t,workingDirectory:s,sandboxPolicy:a,timeoutMs:i});return this.buildResult({args:t,workingDirectory:s,processResult:l,sandboxPolicy:a})}catch(e){r.error=e,r.hasError=!0}finally{jI(r)}}}const VI=q("shell-executor",(e=>new B(e,Z("shellArgs"),X("shellResult"))),((e,t)=>{t.register(new R(e,Y("shellArgs"),Q("shellResult")))})),KI=q("mini-swe-agent-bash-executor",(e=>new B(e,Z("miniSweAgentBashArgs"),X("miniSweAgentBashResult"))),((e,t)=>{t.register(new R(e,Y("miniSweAgentBashArgs"),Q("miniSweAgentBashResult")))}));function JI(e){return`${e} changed on disk after this tool call read it. Nothing was written. Read the file again and retry.`}function ZI(e){return`${e} changed on disk after you last read or wrote it. Nothing was written. Read the file again and retry.`}(0,y.cF)(Symbol("optionalPendingPodWrite"),!1);const XI=q("write-executor",(e=>new B(e,Z("writeArgs"),X("writeResult"))),((e,t)=>{t.register(new R(e,Y("writeArgs"),Q("writeResult")))})),QI=q("delete-executor",(e=>new B(e,Z("deleteArgs"),X("deleteResult"))),((e,t)=>{t.register(new R(e,Y("deleteArgs"),Q("deleteResult")))})),YI=q("fetch-executor",(e=>new B(e,Z("fetchArgs"),X("fetchResult"))),((e,t)=>{t.register(new R(e,Y("fetchArgs"),Q("fetchResult")))})),eR=q("git-diff-executor",(e=>new B(e,Z("gitDiffRequest"),X("gitDiffResponse"))),((e,t)=>{t.register(new R(e,Y("gitDiffRequest"),Q("gitDiffResponse")))})),tR=q("grep-executor",(e=>new B(e,Z("grepArgs"),X("grepResult"))),((e,t)=>{t.register(new R(e,Y("grepArgs"),Q("grepResult")))})),rR="[REDACTED]",nR=new TextEncoder;async function oR(e){const t=nR.encode(e),r=await crypto.subtle.digest("SHA-256",t);return{sha256:[...new Uint8Array(r)].map((e=>e.toString(16).padStart(2,"0"))).join(""),bytes:t.byteLength}}class sR{constructor(e){this.inner=e}async execute(e,t,r){if(!0!==t.digestOnly)return this.inner.execute(e,t,r);const n=t.clone();return n.digestOnly=void 0,n.maxChars=void 0,async function(e){if("success"!==e.result.case)return e;const t=e.result.value;if("content"!==t.output.case)return e;const{sha256:r,bytes:n}=await oR(t.output.value),o=t.clone();return o.output={case:void 0},o.outputBlobId=void 0,o.sha256=r,o.sizeBytes=BigInt(n),new Fw.sV({result:{case:"success",value:o}})}(await this.inner.execute(e,n,r))}}const iR=q("read-executor",(e=>new B(e,Z("readArgs"),X("readResult"))),((e,t)=>{t.register(new R(e,Y("readArgs"),Q("readResult")))})),aR=q("redacted-read-executor",(e=>new B(e,Z("redactedReadArgs"),X("redactedReadResult"))),((e,t)=>{t.register(new R(e,Y("redactedReadArgs"),Q("redactedReadResult")))})),cR=q("ls-executor",(e=>new B(e,Z("lsArgs"),X("lsResult"))),((e,t)=>{t.register(new R(e,Y("lsArgs"),Q("lsResult")))})),lR=q("diagnostics-executor",(e=>new B(e,Z("diagnosticsArgs"),X("diagnosticsResult"))),((e,t)=>{t.register(new R(e,Y("diagnosticsArgs"),Q("diagnosticsResult")))})),uR=q("canvas-diagnostics-executor",(e=>new B(e,Z("canvasDiagnosticsArgs"),X("canvasDiagnosticsResult"))),((e,t)=>{t.register(new R(e,Y("canvasDiagnosticsArgs"),Q("canvasDiagnosticsResult")))})),dR="$file:";const hR=(0,u.Pu)("mcp.symbolic_args.expansion",{description:"Outcome of late-binding $file:/abs/path MCP argument expansion at the executor boundary. The call is refused rather than carrying a placeholder to the server when the read reports having replaced a saved secret (`redacted`), or, from a read executor too old to report that, when its text still carries the redaction marker (`redacted_marker`)",labelNames:["route","outcome"]}),pR=(0,u.v5)("mcp.symbolic_args.bytes",{description:"Total bytes substituted into one MCP tool call by $file:/abs/path arguments",labelNames:["route"]}),fR=(0,u.Pu)("mcp.symbolic_args.describe",{description:"Per-file $file:/abs/path describe reads: `vm_digest` when the read executor hashed the file where it lives, `outdated_executor` when it returned the text instead (it predates $file: expansion, so the call is refused)",labelNames:["source"]}),mR=(0,u.v5)("mcp.symbolic_args.paths",{description:"Number of distinct $file:/abs/path arguments expanded in one MCP tool call",labelNames:["route"]});function gR(e,t,r){return{kind:e,message:`Could not resolve the symbolic argument "${dR}${t}": ${r} A string argument of the form "${dR}/absolute/path" is replaced with that file's contents before the tool runs; pass the literal text instead if you did not intend that.`}}const wR={redacted:e=>`${e} contains a saved secret, and a saved secret is never sent through a "${dR}/absolute/path" argument, so this call was not made. Do not retry it, and do not read the file to pass the value yourself. Tell the user that this file holds a saved secret and that they have to enter it in the tool's service themselves.`,redacted_marker:e=>`${e} may contain a saved secret: its text includes the placeholder "${rR}", and the computer that read it is too old to say whether a saved secret stood there, so this call was not made. Do not retry it, and do not read the file to pass the value yourself. Tell the user that this file may hold a saved secret and that they have to enter it in the tool's service themselves.`};function yR(e,t){return{kind:e,message:`Could not resolve the symbolic argument "${dR}${t}": ${wR[e](t)}`}}class vR extends Error{constructor(e){super(e.message),this.failure=e}}let bR;async function SR(e,t,r,n,o,{maxFileBytes:s=8388608,maxTotalBytes:i=16777216,refuseSavedSecrets:a=!1}){if(t.length>4)throw new vR(gR("too_many",t[4]??"",`at most 4 symbolic arguments may be used in one call (${t.length} given). Split the call or pass paths to tools that accept them.`));const c=r();if(void 0===c)throw new vR(gR("no_read_executor",t[0]??"","this environment cannot read files on behalf of a tool call."));const l=await(0,Dr.xb)(t,(t=>async function(e,t,r,n,o){const s=await t.execute(e,new Fw.a2({path:r,toolCallId:n,...o.digestOnly?{digestOnly:!0}:{}}));if("success"!==s.result.case)throw new vR(function(e,t,r){switch(e.result.case){case"fileNotFound":return gR("not_found",t,"the file does not exist.");case"permissionDenied":return gR("permission_denied",t,"reading it was not permitted.");case"rejected":return gR("rejected",t,`${e.result.value.reason||"the read was rejected"}. Only files the Read tool can read without approval can be substituted; read it with Read instead.`);case"invalidFile":return gR("not_text",t,"the file cannot be read as text.");case"error":return r?{kind:"read_error",message:`Could not resolve the symbolic argument "${dR}${t}": ${e.result.value.error}`}:gR("read_error",t,e.result.value.error);default:return gR("read_error",t,"the read returned no result.")}}(s,r,o.refuseSavedSecrets));return await async function(e,t,r,{maxFileBytes:n,digestOnly:o,refuseSavedSecrets:s}){const i=function(e,t,r,n){const o=n&&void 0!==t.sha256&&void 0!==t.sizeBytes?{sha256:t.sha256,bytes:Number(t.sizeBytes)}:void 0;if(void 0===o&&"content"!==t.output.case)throw new vR(gR("not_text",r,"the file is not a text file."));if(n){if(fR.increment(e,1,{source:void 0!==o?"vm_digest":"outdated_executor"}),void 0===o)throw new vR(gR("outdated_executor",r,"the computer that would run this tool has an older tool runner that cannot substitute files. Read the file and pass its contents instead."));return o}}(e,t,r,o),a="content"===t.output.case?t.output.value:void 0,{sha256:c,bytes:l}=i??await oR(a??""),u={content:a,bytes:l,sha256:c};if(t.truncated||l>n)throw new vR(gR("too_large",r,`the file is too large to inline (${Number(t.fileSize)||l} bytes; at most ${n} bytes per file may be substituted). Pass the path to a tool that accepts one, or read a range of it.`));return await async function(e,t,r,n){if(n){if(!0===e.redacted)throw new vR(yR("redacted",r));if(void 0===e.redacted&&await async function(e){return void 0!==e.content?e.content.includes(rR):(await(bR??=Promise.all([rR,`${rR}\n`,`${rR}\r\n`].map((async e=>(await oR(e)).sha256))).then((e=>new Set(e))),bR)).has(e.sha256)}(t))throw new vR(yR("redacted_marker",r))}}(t,u,r,s),u}(e,s.result.value,r,o)}(e,c,t,n,{maxFileBytes:s,digestOnly:o,refuseSavedSecrets:a})),{max:4});let u=0;for(const[e,r]of l)if(u+=r.bytes,u>i)throw new vR(gR("over_budget",e,`together the ${t.length} symbolic arguments exceed the ${i} bytes that may be substituted per call. Pass paths to tools that accept them instead.`));return l}async function kR(e,t,{route:r,getReadExecutor:n,...o}){if(0===t.symbolicPathArguments.length)return{kind:"none"};const s=new Map(t.symbolicPathArguments.map((e=>[e.path,e]))),i=[...s.keys()],a=t=>(hR.increment(e,1,{route:r,outcome:t.kind}),{kind:"failed",failure:t,result:new Za.iz({result:{case:"error",value:new Za.Nh({error:t.message})}})});let c;try{c=await SR(e,i,n,t.toolCallId,!1,o)}catch(e){return a(function(e,t){return e instanceof vR?e.failure:gR("read_error",t,e instanceof Error?e.message:String(e))}(e,i[0]??""))}let l=0;for(const[e,t]of c){l+=t.bytes;const r=s.get(e);if(r?.sha256!==t.sha256)return a(gR("content_changed",e,`the file changed after the call was reviewed (${r?.sizeBytes??0} bytes then, ${t.bytes} bytes now), so its new contents were not sent. Re-run the call to review the current contents.`))}const u=new Map([...c].map((([e,t])=>[e,t.content??""]))),d=function(e,t){const r=e=>{const n=function(e){if("string"!=typeof e||!e.startsWith(dR))return;const t=e.slice(6);return(r=t).startsWith("/")||/^[a-zA-Z]:[\\/]/.test(r)||r.startsWith("\\\\")?t:void 0;var r}(e);return void 0!==n?t.get(n)??e:Array.isArray(e)?e.map(r):null!==e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map((([e,t])=>[e,r(t)]))):e};return Object.fromEntries(Object.entries(e).map((([e,t])=>[e,r(t)])))}(Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t.toJson()]))),u),h=t.clone();return h.args=Object.fromEntries(Object.entries(d).map((([e,t])=>[e,we.Value.fromJson(t)]))),h.symbolicPathArguments=[],h.argumentsRepaired=!1,hR.increment(e,1,{route:r,outcome:"expanded"}),pR.record(e,l,{route:r}),mR.record(e,i.length,{route:r}),{kind:"expanded",expansion:{args:h,files:[...c].map((([e,t])=>({path:e,bytes:t.bytes}))),paths:i.length,bytes:l}}}const _R=/\b413\b|payload too large|request entity too large|body.*too large|too large.*body|ECONNRESET|EPIPE|socket hang up|max(?:imum)? (?:body|payload|request|content) (?:size|length)/i;function CR(e,t,r,n){return _R.test(t)?(hR.increment(e,1,{route:n,outcome:"server_rejected_body"}),`${t}\n\nThe request carried ${r.bytes} bytes of file contents substituted from ${r.paths} "${dR}/abs/path" argument(s), and the server appears to have rejected the request body as too large. Do not retry the same call: pass a smaller file or a range of it, or use a tool that accepts a path or upload instead.`):t}function ER(e){return e.files.map((e=>`"${dR}${e.path}" was replaced with the contents of ${e.path} (${e.bytes} bytes) before the call.`)).join("\n")}class xR{constructor(e,t,r={}){this.inner=e,this.getReadExecutor=t,this.options=r}isBackendRouted(e){return this.inner.isBackendRouted?.(e)??!1}async execute(e,t,r){if(0===t.symbolicPathArguments.length)return this.inner.execute(e,t,r);const n=await kR(e,t,{route:"local",getReadExecutor:this.getReadExecutor,refuseSavedSecrets:!0===this.options.refuseSavedSecrets&&t.refuseSavedSecrets});if("none"===n.kind)return this.inner.execute(e,t,r);if("failed"===n.kind)return n.result;let o;try{o=await this.inner.execute(e,n.expansion.args,r)}catch(t){throw t instanceof Error&&(t.message=CR(e,t.message,n.expansion,"local")),t}return function(e,t,r){const n=t.clone();return"success"===n.result.case?n.result.value.content.push(new Za._Z({content:{case:"text",value:new Za.zN({text:ER(r)})}})):"error"===n.result.case&&(n.result.value.error=CR(e,n.result.value.error,r,"local")),n}(e,o,n.expansion)}}const PR=q("background-shell-executor",(e=>new B(e,Z("backgroundShellSpawnArgs"),X("backgroundShellSpawnResult"))),((e,t)=>{t.register(new R(e,Y("backgroundShellSpawnArgs"),Q("backgroundShellSpawnResult")))})),IR=q("write-background-shell-input-executor",(e=>new B(e,Z("writeShellStdinArgs"),X("writeShellStdinResult"))),((e,t)=>{t.register(new R(e,Y("writeShellStdinArgs"),Q("writeShellStdinResult")))})),RR=q("agent-store-conflict-executor",(e=>new B(e,Z("agentStoreConflictArgs"),X("agentStoreConflictResult"))),((e,t)=>{t.register(new R(e,Y("agentStoreConflictArgs"),Q("agentStoreConflictResult")))})),TR=q("shell-allowlist-precheck-executor",(e=>new B(e,Z("shellAllowlistPrecheckArgs"),X("shellAllowlistPrecheckResult"))),((e,t)=>{t.register(new R(e,Y("shellAllowlistPrecheckArgs"),Q("shellAllowlistPrecheckResult")))})),AR=q("mcp-allowlist-precheck-executor",(e=>new B(e,Z("mcpAllowlistPrecheckArgs"),X("mcpAllowlistPrecheckResult"))),((e,t)=>{t.register(new R(e,Y("mcpAllowlistPrecheckArgs"),Q("mcpAllowlistPrecheckResult")))})),$R=q("web-fetch-allowlist-precheck-executor",(e=>new B(e,Z("webFetchAllowlistPrecheckArgs"),X("webFetchAllowlistPrecheckResult"))),((e,t)=>{t.register(new R(e,Y("webFetchAllowlistPrecheckArgs"),Q("webFetchAllowlistPrecheckResult")))})),MR=q("force-background-shell-executor",(e=>new B(e,Z("forceBackgroundShellArgs"),X("forceBackgroundShellResult"))),((e,t)=>{t.register(new R(e,Y("forceBackgroundShellArgs"),Q("forceBackgroundShellResult")))})),DR=q("computer-use-executor",(e=>new B(e,Z("computerUseArgs"),X("computerUseResult"))),((e,t)=>{t.register(new R(e,Y("computerUseArgs"),Q("computerUseResult")))})),OR=q("record-screen-executor",(e=>new B(e,Z("recordScreenArgs"),X("recordScreenResult"))),((e,t)=>{t.register(new R(e,Y("recordScreenArgs"),Q("recordScreenResult")))}));var FR=r("../proto/dist/generated/agent/v1/agent_store_conflict_exec_pb.js");function NR(e){if(void 0!==e)return{journalEpoch:e.journalEpoch,seq:Number(e.seq),lastEventId:e.lastEventId}}class LR{constructor(e){this.drainer=e}async execute(e,t){try{void 0!==t.includeQuotaNotices&&this.drainer.setIncludeQuotaNoticesOverride(t.includeQuotaNotices);const e=await this.drainer.drain({cursor:NR(t.cursor),advance:!1!==t.advance});return new FR.Ev({result:{case:"success",value:new FR.iS({events:e.events.map((e=>new FR.RZ({v:e.v,eventId:e.event_id,journalEpoch:e.journal_epoch,seq:BigInt(e.seq),tsMs:BigInt(e.ts_ms),kind:e.kind,storeId:e.store_id,originalRelPath:e.original_rel_path,conflictRelPath:e.conflict_rel_path,originalAbsPath:e.original_abs_path,conflictAbsPath:e.conflict_abs_path,preservedBytes:void 0===e.preserved_bytes?void 0:BigInt(e.preserved_bytes),scopeKind:e.scope_kind,limitBytes:void 0===e.limit_bytes?void 0:BigInt(e.limit_bytes),usageBytes:void 0===e.usage_bytes?void 0:BigInt(e.usage_bytes)}))),nextCursor:(r=e.nextCursor,new FR.LK({journalEpoch:r.journalEpoch,seq:BigInt(r.seq),lastEventId:r.lastEventId})),gap:e.gap})}})}catch(e){return new FR.Ev({result:{case:"error",value:new FR.h6({error:e instanceof Error?e.message:String(e)})}})}var r}}class jR{constructor(e){this.shellStdinWriter=e}async execute(e,t){const r=t.shellId;try{await this.shellStdinWriter(r,t.chars)}catch(e){return new Co.nt({result:{case:"error",value:new Co.Gv({error:`Failed to write to shell ${r} stdin: ${e instanceof Error?e.message:"Unknown error"}`})}})}return new Co.nt({result:{case:"success",value:new Co.tR({shellId:r,terminalFileLengthBeforeInputWritten:0})}})}}var UR=r("../proto/dist/generated/agent/v1/canvas_diagnostics_exec_pb.js"),BR=r("../proto/dist/generated/agent/v1/diagnostics_exec_pb.js");class WR{constructor(e,t){this.getCanvasDiagnostics=e,this.beginCanvasSave=t}async execute(e,t){let r=()=>{};const n=new Promise((e=>{r=e}));let o;if(void 0===this.beginCanvasSave)o=Promise.resolve(void 0);else try{o=this.beginCanvasSave(t.path,{typecheckOutcome:n}).catch((()=>{}))}catch{o=Promise.resolve(void 0)}try{const e=await this.getCanvasDiagnostics(t.path);return void 0===e?(r("unavailable"),HR(qR(t.path,"diagnostics unavailable"),await o)):(r(e.some((e=>1===e.severity))?"failed":"passed"),HR(new UR.GL({result:{case:"success",value:new UR.uX({path:t.path,diagnostics:e.map(zR)})}}),await o))}catch(e){return r("unavailable"),HR(qR(t.path,e instanceof Error?e.message:String(e)),await o)}}}function HR(e,t){return void 0===t||(e.saveState=t.saveState,e.canvasId=t.canvasId,e.title=t.title,e.saveDetail=t.saveDetail),e}function qR(e,t){return new UR.GL({result:{case:"error",value:new UR.HW({path:e,error:t})}})}function zR(e){return new BR.oQ({severity:GR(e.severity),range:new Ya.Q6({start:new Ya.yX({line:e.range.start.line+1,column:e.range.start.character+1}),end:new Ya.yX({line:e.range.end.line+1,column:e.range.end.character+1})}),message:e.message,source:"ts",code:e.code??""})}function GR(e){switch(e){case 1:return BR.h_.ERROR;case 2:return BR.h_.WARNING;case 3:return BR.h_.INFORMATION;case 4:return BR.h_.HINT;default:return BR.h_.UNSPECIFIED}}class VR{constructor(e){if(e.startsWith("file://")){if(!this.isValidFileUrl(e))throw new Error(`Invalid file URL: ${e}`);this.urlString=e}else{const t=this.resolvePath(e);this.urlString=this.pathToFileUrl(t)}}isValidFileUrl(e){try{return"file:"===new URL(e).protocol}catch{return!1}}resolvePath(e){if(e.includes("\\")&&(e=e.replace(/\\/g,"/")),/^[a-zA-Z]:\//.test(e)||/^\//.test(e))return e;const t=e.split("/"),r=[];for(let e=0;e<t.length;e++){const n=t[e];".."===n?r.pop():"."!==n&&""!==n&&r.push(n)}return 0===r.length?".":`/${r.join("/")}`}pathToFileUrl(e){return/^[a-zA-Z]:\//.test(e)?`file:///${e.charAt(0).toLowerCase()}:${e.substring(2).replace(/\\/g,"/")}`:(e.startsWith("/")||(e=`/${e}`),`file://${encodeURIComponent(e).replace(/%2F/g,"/")}`)}fileUrlToPath(e){try{const t=new URL(e);if(t.pathname.startsWith("/")&&/^\/[a-zA-Z]:\//.test(t.pathname)){return`${t.pathname[1].toUpperCase()}:${t.pathname.substring(3)}`}return decodeURIComponent(t.pathname)}catch{throw new Error(`Invalid file URL format: ${e}`)}}get fsPath(){return this.toPath()}static fromPath(e){return new VR(e)}static fromUrl(e){if(!e.startsWith("file://"))throw new Error(`Expected file:// URL, got: ${e}`);return new VR(e)}static fromString(e){return new VR(e)}toPath(){return this.fileUrlToPath(this.urlString)}toString(){return this.urlString}serialize(){return this.toString()}toURL(){try{return new URL(this.urlString)}catch{throw new Error(`Invalid URL format: ${this.urlString}`)}}getFilename(){const e=this.toPath(),t=e.includes("\\")?"\\":"/";return e.split(t).pop()||""}getDirectory(){const e=this.toPath(),t=e.includes("\\")?"\\":"/",r=e.lastIndexOf(t);return-1===r?e:e.substring(0,r)}equals(e){return this.urlString===e.urlString}toJSON(){return this.toString()}}var KR=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class JR{constructor(e,t){this.workspacePath=e,this.diagnosticsProvider=t}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{let n;!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,$.VI)(e.withName("LocalDiagnosticsExecutor.execute")),!1),[e,n]=e.withTimeoutAndCancel(1e4);try{const r=(0,Ho.o1)(t.path,this.workspacePath);try{const e=await(0,fo.stat)(r);if(!e.isFile()&&!e.isDirectory())return new BR.Ek({result:{case:"fileNotFound",value:new BR.Mu({path:t.path})}})}catch(e){if("ENOENT"===Ua(e))return new BR.Ek({result:{case:"fileNotFound",value:new BR.Mu({path:t.path})}});if("EACCES"===Ua(e))return new BR.Ek({result:{case:"permissionDenied",value:new BR.RP({path:t.path})}});throw e}const n=(0,Ho.o1)(r,this.workspacePath),o=new VR(n);await this.diagnosticsProvider.open(e,o);const s=(await this.diagnosticsProvider.getDiagnostics(e,o)).map((e=>this.convertDiagnostic(e)));return new BR.Ek({result:{case:"success",value:new BR.a1({path:t.path,diagnostics:s,totalDiagnostics:s.length})}})}catch(r){return e.canceled?new BR.Ek({result:{case:"error",value:new BR.Ho({path:t.path,error:"Request timed out after 10 seconds"})}}):new BR.Ek({result:{case:"error",value:new BR.Ho({path:t.path,error:r instanceof Error?r.message:String(r)})}})}finally{n()}}catch(e){r.error=e,r.hasError=!0}finally{KR(r)}}convertDiagnostic(e){const t=e.message,r="string"==typeof t?t:t&&"object"==typeof t&&"value"in t&&"string"==typeof t.value?t.value:"";return new BR.oQ({severity:this.convertSeverity(e.severity),range:e.range?new Ya.Q6({start:new Ya.yX({line:e.range.start.line,column:e.range.start.character}),end:new Ya.yX({line:e.range.end.line,column:e.range.end.character})}):void 0,message:r,source:e.source,code:e.code?String(e.code):void 0})}convertSeverity(e){switch(e){case 1:return BR.h_.ERROR;case 2:return BR.h_.WARNING;case 3:return BR.h_.INFORMATION;case 4:return BR.h_.HINT;default:return BR.h_.UNSPECIFIED}}}async function ZR(e){const{repoRoot:t,filePaths:r,getContent:n}=e,o=new Map;if(0===r.length)return o;const s=await async function(e,t){const r=new Map;if(0===t.length)return r;try{const{stdout:n}=await aw().run(e,["check-attr","linguist-generated","--stdin"],{input:`${t.join("\n")}\n`});for(const e of n.trim().split("\n")){const t=e.match(/^(.+): linguist-generated: (.+)$/);if(t){const e=t[1],n=t[2];"true"===n||"set"===n?r.set(e,!0):"false"!==n&&"unset"!==n||r.set(e,!1)}}}catch{}return r}(t,r);return await Promise.all(r.map((async e=>{const t=s.get(e);if(!0!==t)if(!1!==t)if(function(e){return new XR(e).isGeneratedByPath()}(e))o.set(e,{isGenerated:!0,source:"path-heuristic"});else{if(n){const t=await n(e);if(void 0!==t&&function(e,t){return new XR(e,(()=>t)).isGeneratedByContent()}(e,t))return void o.set(e,{isGenerated:!0,source:"content-heuristic"})}o.set(e,{isGenerated:!1,source:"none"})}else o.set(e,{isGenerated:!1,source:"gitattributes"});else o.set(e,{isGenerated:!0,source:"gitattributes"})}))),o}class XR{constructor(e,t){this.name=e,this.extname=s.extname(e).toLowerCase(),this.getContent=t}get lines(){if(void 0===this.cachedLines){const e=this.getContent?.();this.cachedLines=e?e.split("\n"):[]}return this.cachedLines}get data(){return this.getContent?.()}isGeneratedByPath(){return this.xcodeFile()||this.intellijFile()||this.cocoapods()||this.carthageBuild()||this.generatedGraphqlRelay()||this.generatedNetDesignerFile()||this.generatedNetSpecflowFeatureFile()||this.composerLock()||this.cargoLock()||this.cargoOrig()||this.denoLock()||this.flakeLock()||this.bazelLock()||this.nodeModules()||this.goVendor()||this.goLock()||this.packageResolved()||this.poetryLock()||this.pdmLock()||this.uvLock()||this.pixiLock()||this.esyLock()||this.npmShrinkwrapOrPackageLock()||this.pnpmLock()||this.bunLock()||this.terraformLock()||this.generatedYarnPlugnplay()||this.godeps()||this.generatedByZephir()||this.htmlcov()||this.gradleWrapper()||this.mavenWrapper()||this.pipenvLock()||this.generatedPascalTlb()||this.generatedSqlxQuery()||this.sourceMapByName()}isGeneratedByContent(){return!!this.getContent&&(this.minifiedFiles()||this.hasSourceMap()||this.sourceMap()||this.compiledCoffeescript()||this.generatedParser()||this.generatedNetDocfile()||this.generatedPostscript()||this.compiledCythonFile()||this.generatedGo()||this.generatedProtocolBufferFromGo()||this.generatedProtocolBuffer()||this.generatedJavascriptProtocolBuffer()||this.generatedTypescriptProtocolBuffer()||this.generatedApacheThrift()||this.generatedJniHeader()||this.vcrCassette()||this.generatedAntlr()||this.generatedModule()||this.generatedUnity3dMeta()||this.generatedRacc()||this.generatedJflex()||this.generatedGrammarkit()||this.generatedRoxygen2()||this.generatedHtml()||this.generatedJison()||this.generatedGrpcCpp()||this.generatedDart()||this.generatedPerlPpportHeader()||this.generatedGamemakerstudio()||this.generatedGimp()||this.generatedVisualstudio6()||this.generatedHaxe()||this.generatedJooq()||this.generatedSorbetRbi()||this.generatedMysqlViewDefinitionFormat())}xcodeFile(){return[".nib",".xcworkspacedata",".xcuserstate"].includes(this.extname)}intellijFile(){return/(?:^|\/)\.idea\//.test(this.name)}cocoapods(){return/(^Pods|\/Pods)\//.test(this.name)}carthageBuild(){return/(^|\/)Carthage\/Build\//.test(this.name)}generatedGraphqlRelay(){return/__generated__\//.test(this.name)}generatedNetDesignerFile(){return/\.designer\.(cs|vb)$/i.test(this.name)}generatedNetSpecflowFeatureFile(){return/\.feature\.cs$/i.test(this.name)}composerLock(){return/composer\.lock/.test(this.name)}cargoLock(){return/Cargo\.lock/.test(this.name)}cargoOrig(){return/Cargo\.toml\.orig/.test(this.name)}denoLock(){return/deno\.lock/.test(this.name)}flakeLock(){return/(^|\/)flake\.lock$/.test(this.name)}bazelLock(){return/(^|\/)MODULE\.bazel\.lock$/.test(this.name)}nodeModules(){return/node_modules\//.test(this.name)}goVendor(){return/vendor\/((?!-)[-0-9A-Za-z]+(?<!-)\.)+(com|edu|gov|in|me|net|org|fm|io)/.test(this.name)}goLock(){return/(Gopkg|glide)\.lock/.test(this.name)}packageResolved(){return/Package\.resolved/.test(this.name)}poetryLock(){return/poetry\.lock/.test(this.name)}pdmLock(){return/pdm\.lock/.test(this.name)}uvLock(){return/uv\.lock/.test(this.name)}pixiLock(){return/pixi\.lock/.test(this.name)}esyLock(){return/(^|\/)(\w+\.)?esy\.lock$/.test(this.name)}npmShrinkwrapOrPackageLock(){return/npm-shrinkwrap\.json/.test(this.name)||/package-lock\.json/.test(this.name)}pnpmLock(){return/pnpm-lock\.yaml/.test(this.name)}bunLock(){return/(?:^|\/)bun\.lockb?$/.test(this.name)}terraformLock(){return/(?:^|\/)\.terraform\.lock\.hcl$/.test(this.name)}generatedYarnPlugnplay(){return/(^|\/)\.pnp\..*$/.test(this.name)}godeps(){return/Godeps\//.test(this.name)}generatedByZephir(){return/\.zep\.(c|h|php)$/.test(this.name)}htmlcov(){return/(?:^|\/)htmlcov\//.test(this.name)}gradleWrapper(){return/(?:^|\/)gradlew(?:\.bat)?$/i.test(this.name)}mavenWrapper(){return/(?:^|\/)mvnw(?:\.cmd)?$/i.test(this.name)}pipenvLock(){return/Pipfile\.lock/.test(this.name)}generatedPascalTlb(){return/_tlb\.pas$/i.test(this.name)}generatedSqlxQuery(){return/(?:^|\/)\.sqlx\/query-[a-f\d]{64}\.json$/.test(this.name)}sourceMapByName(){return/\.(css|js)\.map$/i.test(this.name)}maybeMinified(){return[".js",".css"].includes(this.extname)}minifiedFiles(){return!(!this.maybeMinified()||0===this.lines.length)&&this.lines.reduce(((e,t)=>e+t.length),0)/this.lines.length>110}hasSourceMap(){return!!this.maybeMinified()&&this.lines.slice(-2).some((e=>/^\/[*/][#@] source(?:Mapping)?URL|sourceURL=/.test(e)))}sourceMap(){if(".map"!==this.extname)return!1;if(/\.(css|js)\.map$/i.test(this.name))return!0;const e=this.lines[0]||"";return/^{"version":\d+,/.test(e)||/^\/\*\* Begin line maps\. \*\*\/{/.test(e)}compiledCoffeescript(){if(".js"!==this.extname)return!1;const e=this.lines[0]||"";if(/^\/\/ Generated by /.test(e))return!0;if("(function() {"===e&&"}).call(this);"===(this.lines[this.lines.length-2]||"")&&""===(this.lines[this.lines.length-1]||"")){let e=0;for(const t of this.lines)if(/var /.test(t)){const r=t.match(/_fn|_i|_len|_ref|_results/g);e+=1*(r?.length||0);const n=t.match(/__bind|__extends|__hasProp|__indexOf|__slice/g);e+=3*(n?.length||0)}return e>=3}return!1}generatedNetDocfile(){return".xml"===this.extname&&!(this.lines.length<=3)&&(this.lines[1]||"").includes("<doc>")&&(this.lines[2]||"").includes("<assembly>")&&(this.lines[this.lines.length-2]||"").includes("</doc>")}generatedParser(){if(".js"!==this.extname)return!1;const e=this.lines.slice(0,5).join("");return/^(?:[^/]|\/[^*])*\/\*(?:[^*]|\*[^/])*Generated by PEG\.js/.test(e)}generatedPostscript(){if(![".ps",".eps",".pfa"].includes(this.extname))return!1;const e=this.data;if(!e)return!1;if(/^\s*(?:currentfile eexec\s+|\/sfnts\s+\[\s<)/.test(e))return!0;const t=this.lines.slice(0,10).find((e=>/^%%Creator: /.test(e)));return!!t&&(!(!/[0-9]|draw|mpage|ImageMagick|inkscape|MATLAB/.test(t)&&!/PCBNEW|pnmtops|\(Unknown\)|Serif Affinity|Filterimage -tops/.test(t))||!!t.includes("EAGLE")&&this.lines.slice(0,5).some((e=>/^%%Title: EAGLE Drawing /.test(e))))}generatedGo(){return".go"===this.extname&&!(this.lines.length<=1)&&this.lines.slice(0,40).some((e=>/^\/\/ Code generated .*/.test(e)))}generatedProtocolBufferFromGo(){return".proto"===this.extname&&!(this.lines.length<=1)&&this.lines.slice(0,20).some((e=>e.includes("This file was autogenerated by go-to-protobuf")))}generatedProtocolBuffer(){return!![".py",".java",".h",".cc",".cpp",".m",".rb",".php"].includes(this.extname)&&!(this.lines.length<=1)&&this.lines.slice(0,3).some((e=>e.includes("Generated by the protocol buffer compiler. DO NOT EDIT!")))}generatedJavascriptProtocolBuffer(){return".js"===this.extname&&!(this.lines.length<=6)&&(this.lines[5]||"").includes("GENERATED CODE -- DO NOT EDIT!")}generatedTypescriptProtocolBuffer(){return".ts"===this.extname&&!(this.lines.length<=4)&&(this.lines[0]||"").includes("Code generated by protoc-gen-ts_proto. DO NOT EDIT.")}generatedApacheThrift(){return!![".rb",".py",".go",".js",".m",".java",".h",".cc",".cpp",".php"].includes(this.extname)&&this.lines.slice(0,6).some((e=>e.includes("Autogenerated by Thrift Compiler")))}generatedJniHeader(){return".h"===this.extname&&!(this.lines.length<=2)&&(this.lines[0]||"").includes("/* DO NOT EDIT THIS FILE - it is machine generated */")&&(this.lines[1]||"").includes("#include <jni.h>")}vcrCassette(){return".yml"===this.extname&&!(this.lines.length<=2)&&(this.lines[this.lines.length-2]||"").includes("recorded_with: VCR")}generatedAntlr(){return".g"===this.extname&&!(this.lines.length<=2)&&(this.lines[1]||"").includes("generated by Xtest")}compiledCythonFile(){return!![".c",".cpp"].includes(this.extname)&&!(this.lines.length<=1)&&(this.lines[0]||"").includes("Generated by Cython")}generatedModule(){if(".mod"!==this.extname)return!1;if(this.lines.length<=1)return!1;const e=this.lines[0]||"";return e.includes("PCBNEW-LibModule-V")||e.includes("GFORTRAN module version '")}generatedUnity3dMeta(){return".meta"===this.extname&&!(this.lines.length<=1)&&(this.lines[0]||"").includes("fileFormatVersion: ")}generatedRacc(){return".rb"===this.extname&&!(this.lines.length<=2)&&(this.lines[2]||"").startsWith("# This file is automatically generated by Racc")}generatedJflex(){return".java"===this.extname&&!(this.lines.length<=1)&&(this.lines[0]||"").startsWith("/* The following code was generated by JFlex ")}generatedGrammarkit(){return".java"===this.extname&&!(this.lines.length<=1)&&(this.lines[0]||"").startsWith("// This is a generated file. Not intended for manual editing.")}generatedRoxygen2(){return".rd"===this.extname&&!(this.lines.length<=1)&&(this.lines[0]||"").includes("% Generated by roxygen2: do not edit by hand")}generatedHtml(){if(![".html",".htm",".xhtml"].includes(this.extname))return!1;if(this.lines.length<=1)return!1;if(this.lines.slice(0,2).some((e=>/<!-- Generated by pkgdown: do not edit by hand -->/.test(e))))return!0;if(this.lines.length>2&&(this.lines[2]||"").startsWith("\x3c!-- This is an automatically generated file."))return!0;if(this.lines.slice(0,31).some((e=>/<!--\s+Generated by Doxygen\s+[.0-9]+\s*-->/i.test(e))))return!0;const e=this.lines.slice(0,31).join(" ").match(/<meta(\s+[^>]+)>/gi);if(!e)return!1;for(const t of e){const e=this.extractHtmlMeta(t);if("generator"===e.name?.toLowerCase()&&(e.content||e.value)){const t=e.content||e.value||"";if(/^(org\s+mode|j?latex2html|groff|makeinfo|texi2html|ronn)\b/i.test(t))return!0}}return!1}extractHtmlMeta(e){const t={},r=e.matchAll(/(?<=^|\s)(name|content|value)\s*=\s*("[^"]+"|'[^']+'|[^\s"']+)/gi);for(const e of r){const r=e[1].toLowerCase();let n=e[2];(n.startsWith('"')&&n.endsWith('"')||n.startsWith("'")&&n.endsWith("'"))&&(n=n.slice(1,-1)),t[r]=n}return t}generatedJison(){if(".js"!==this.extname)return!1;if(this.lines.length<=1)return!1;const e=this.lines[0]||"";return e.startsWith("/* parser generated by jison ")||e.startsWith("/* generated by jison-lex ")}generatedGrpcCpp(){return!![".cpp",".hpp",".h",".cc"].includes(this.extname)&&!(this.lines.length<=1)&&(this.lines[0]||"").startsWith("// Generated by the gRPC")}generatedDart(){return".dart"===this.extname&&!(this.lines.length<=1)&&this.lines.slice(0,3).some((e=>/generated code\W{2,3}do not modify/i.test(e)))}generatedPerlPpportHeader(){return!!/ppport\.h$/.test(this.name)&&!(this.lines.length<=10)&&(this.lines[8]||"").includes("Automatically created by Devel::PPPort")}generatedGamemakerstudio(){if(![".yy",".yyp"].includes(this.extname))return!1;if(this.lines.length<=3)return!1;const e=this.lines.slice(0,3).join("");return/^\s*[{[]/.test(e)||/^\d\.\d\.\d.+\|\{/.test(this.lines[0]||"")}generatedGimp(){if(![".c",".h"].includes(this.extname))return!1;if(0===this.lines.length)return!1;const e=this.lines[0]||"";return/^\/\* GIMP [a-zA-Z0-9- ]+ C-Source image dump \(.+?\.c\) \*\//.test(e)||/^\/\* {2}GIMP header image file format \([a-zA-Z0-9- ]+\): .+?\.h {2}\*\//.test(e)}generatedVisualstudio6(){return".dsp"===this.extname&&this.lines.slice(0,3).some((e=>e.includes("# Microsoft Developer Studio Generated Build File")))}generatedHaxe(){return!![".js",".py",".lua",".cpp",".h",".java",".cs",".php"].includes(this.extname)&&this.lines.slice(0,3).some((e=>e.includes("Generated by Haxe")))}generatedJooq(){return".java"===this.extname&&this.lines.slice(0,2).some((e=>e.includes("This file is generated by jOOQ.")))}generatedSorbetRbi(){return".rbi"===this.extname&&!(this.lines.length<5)&&/^# typed:/.test(this.lines[0]||"")&&(this.lines[2]||"").includes("DO NOT EDIT MANUALLY")&&/^# Please (run|instead update this file by running) `bin\/tapioca/.test(this.lines[4]||"")}generatedMysqlViewDefinitionFormat(){return".frm"===this.extname&&(this.lines[0]||"").includes("TYPE=VIEW")}}const QR=e=>{if(!e)return[];if("string"!=typeof e||e.match(/^\s+$/))return[];const t=e.split("\n");if(0===t.length)return[];const r=[];let n=null,o=null,s=0,i=0,a=null;const c=e=>{o?.changes.push({type:"normal",normal:!0,ln1:s++,ln2:i++,content:e}),a.oldLines--,a.newLines--},l=e=>{const[t,o]=tT(e)??[];n={chunks:[],deletions:0,additions:0,from:t,to:o},r.push(n)},u=()=>{n&&!n.chunks.length||l()},d=e=>+(e||1),h=e=>{o&&(o.changes.push({type:"del",del:!0,ln:s++,content:e}),n.deletions++,a.oldLines--)},p=e=>{o&&(o.changes.push({type:"add",add:!0,ln:i++,content:e}),n.additions++,a.newLines--)},f=e=>{if(!o)return;const[t]=o.changes.slice(-1);o.changes.push({type:t.type,[t.type]:!0,ln1:t.ln1,ln2:t.ln2,ln:t.ln,content:e})},m=[[/^diff\s/,l],[/^new file mode (\d+)$/,(e,t)=>{u(),n.new=!0,n.newMode=t[1],n.from="/dev/null"}],[/^deleted file mode (\d+)$/,(e,t)=>{u(),n.deleted=!0,n.oldMode=t[1],n.to="/dev/null"}],[/^old mode (\d+)$/,(e,t)=>{u(),n.oldMode=t[1]}],[/^new mode (\d+)$/,(e,t)=>{u(),n.newMode=t[1]}],[/^index\s[\da-zA-Z]+\.\.[\da-zA-Z]+(\s(\d+))?$/,(e,t)=>{u(),n.index=e.split(" ").slice(1),t[1]&&(n.oldMode=n.newMode=t[1].trim())}],[/^---\s/,e=>{u(),n.from=nT(e)}],[/^\+\+\+\s/,e=>{u(),n.to=nT(e)}],[/^@@\s+-(\d+),?(\d+)?\s+\+(\d+),?(\d+)?\s@@/,(e,t)=>{n||l(e);const[r,c,u,h]=t.slice(1);s=+r,i=+u,o={content:e,changes:[],oldStart:+r,oldLines:d(c),newStart:+u,newLines:d(h)},a={oldLines:d(c),newLines:d(h)},n.chunks.push(o)}],[/^\$/,f]],g=[[/^\$/,f],[/^-/,h],[/^\+/,p],[/^\s+/,c]],w=e=>{a?(e=>{const t=e.charCodeAt(0);if(43===t)p(e);else if(45===t)h(e);else if(32===t)c(e);else if(92===t&&/^\$/.test(e))f(e);else for(const[t,r]of g){const n=e.match(t);if(n){r(e,n);break}}0===a.oldLines&&0===a.newLines&&(a=null)})(e):(e=>{for(const[t,r]of m){const n=e.match(t);if(n){r(e,n);break}}})(e)};for(const e of t)w(e);return r},YR=/(a|i|w|c|o|1|2)\/.*(?=["']? ["']?(b|i|w|c|o|1|2)\/)|(b|i|w|c|o|1|2)\/.*$/g,eT=/^(a|b|i|w|c|o|1|2)\//,tT=e=>{const t=e?.match(YR);return t?.map((e=>e.replace(eT,"").replace(/("|')$/,"")))},rT=/^\\?['"]|\\?['"]$/g,nT=e=>{let t=oT(e,"-+").trim();return t=iT(t),t.replace(rT,"").replace(eT,"")},oT=(e,t)=>{if(e=cT(e),!t&&String.prototype.trimLeft)return e.trimLeft();const r=aT(t);return e.replace(new RegExp(`^${r}+`),"")},sT=/\t.*|\d{4}-\d\d-\d\d\s\d\d:\d\d:\d\d(.\d+)?\s(\+|-)\d\d\d\d/,iT=e=>{const t=sT.exec(e);return t&&(e=e.substring(0,t.index).trim()),e},aT=e=>null==e?"\\s":e instanceof RegExp?e.source:`[${cT(e).replace(/([.*+?^=!:${}()|[\]/\\])/g,"\\$1")}]`,cT=e=>`${e??""}`,lT=(0,l.h)("local-mercurial-diff"),uT=5242880,dT="0000000000000000000000000000000000000000";let hT,pT;async function fT(e,t,r={}){const n=await async function(){if(void 0===hT&&(hT=await async function(e){const t="win32"===process.platform?["hg.com","hg.exe"]:["hg"];for(const r of e.split(s.default.delimiter))if(s.default.isAbsolute(r))for(const e of t){const t=s.default.join(r,e);try{if(!(await fo.stat(t)).isFile())continue;return"win32"!==process.platform&&await fo.access(t,go.constants.X_OK),t}catch{}}}(process.env.PATH??"")??null),null===hT){const e=new Error("hg executable not found");throw e.code="ENOENT",e}return hT}();return await new Promise(((o,s)=>{const i=(0,gl.spawn)(n,t,{cwd:e,env:{...process.env,HGPLAIN:"+strictflags",HGRCPATH:"",HGRCSKIPREPO:"1"},shell:!1}),a=new Xi.StringDecoder("utf8");let c="";i.stdout.on("data",(e=>{c+=a.write(e)})),i.stderr.on("data",(()=>{})),i.on("error",(e=>{!0===r.allowFailure?o(""):s(e)})),i.on("close",(e=>{if(0===e||!0===r.allowFailure)o(c+a.end());else{const r=t.find((e=>!e.startsWith("-")))??"hg";s(new Error(`MercurialDiffFailed: hg ${r} exited ${e??"unknown"}`))}}))}))}async function mT(e){const t=await async function(e){let t=s.default.resolve(e);for(;;){try{if((await fo.stat(s.default.join(t,".hg"))).isDirectory())return!0}catch{}const e=s.default.dirname(t);if(e===t)return!1;t=e}}(e);if(!t)return;const r=function(e,t){return e&&"absent"!==t?"skips-repo-config"!==t?"unsafe":"proceed":"not-mercurial"}(t,await async function(){if(void 0!==pT)return pT;const e=await fo.mkdtemp(s.default.join((0,o.tmpdir)(),"hg-probe-"));try{const t=await fT(e,["help","environment"]);pT=/\bHGRCSKIPREPO\b/.test(t)?"skips-repo-config":"reads-repo-config"}catch(e){pT=function(e){return"object"==typeof e&&null!==e&&"code"in e&&"ENOENT"===e.code}(e)?"absent":"reads-repo-config"}finally{await fo.rm(e,{recursive:!0,force:!0})}return pT}());if("not-mercurial"===r)return;if("unsafe"===r)throw new Error("MercurialClientUnsafe: hg would read repository config");let n;try{n=(await fT(e,["root"])).trim()}catch{return}if(0!==n.length)try{return(await fo.stat(s.default.join(n,".hg"))).isDirectory()?n:void 0}catch{return}}function gT(e,t){return"win32"===process.platform?s.default.win32.normalize(e).toLowerCase()===s.default.win32.normalize(t).toLowerCase():s.default.resolve(e)===s.default.resolve(t)}function wT(e,t){const r=s.default.relative(s.default.resolve(t),s.default.resolve(e));return 0===r.length||!s.default.isAbsolute(r)&&!r.split(s.default.sep).includes("..")}async function yT(e){const t=s.default.resolve(e);try{return await fo.realpath(t)}catch{return t}}function vT(e){if(0===e.length)return[];const t=e.replace(/\r\n/g,"\n").replace(/\r/g,"\n"),r=t.split("\n");return t.endsWith("\n")&&r.pop(),r}function bT(e){if(e.includes("\0")||/[\r\n]/.test(e))throw new Error("MercurialDiffFailed: base ref contains a newline")}async function ST({repositoryRoot:e,rev:t,filePath:r}){const n=await async function({repositoryRoot:e,rev:t,filePath:r}){let n;try{n=await fT(e,["files","-r",t,"-T","{size}","--",r])}catch{return}const o=n.trim();if(!/^\d+$/.test(o))return;const s=Number(o);return Number.isFinite(s)?s:void 0}({repositoryRoot:e,rev:t,filePath:r});return void 0===n||n>uT?"":fT(e,["cat","-r",t,"--",r])}async function kT(e,t,r){const n=function(e){switch(e){case Le.ek.NAME_STATUS:return Le.ek.NAME_STATUS;case Le.ek.NAME_STATUS_AND_NUMSTAT:return Le.ek.NAME_STATUS_AND_NUMSTAT;case Le.ek.FILE_DIFFS:return Le.ek.FILE_DIFFS;case Le.ek.DIFFS_WITH_BEFORE_AND_AFTER:return Le.ek.DIFFS_WITH_BEFORE_AND_AFTER;default:return Le.ek.FILE_DIFFS}}(r.outputFormat),o=["root"],i=(await fT(t,["root"])).trim();if(0===i.length)throw new Error("MercurialDiffFailed: hg root did not resolve");let a,c;if(0!==r.ref.length||"HEAD"!==r.baseRef&&(r.mergeBase||0!==r.baseRef.length)){if(r.mergeBase||0===r.baseRef.length)a=await async function({cwd:e,baseRef:t,commands:r}){if(t.length>0&&"HEAD"!==t){bT(t),r.push("log");const n=(await fT(e,["log","-r",`ancestor(., (${t}))`,"-T","{node}"])).trim();if(0===n.length||n===dT)throw new Error("MercurialDiffFailed: base ref did not resolve");return n}r.push("log");const n=(await fT(e,["log","-r","max(::. and public())","-T","{node}"],{allowFailure:!0})).trim();if(n.length>0&&n!==dT)return n;const o=(await fT(e,["log","-r","ancestor(., default)","-T","{node}"],{allowFailure:!0})).trim();if(o.length>0&&o!==dT)return o;const s=(await fT(e,["log","-r",".","-T","{node}"],{allowFailure:!0})).trim();return s.length>0?s:dT}({cwd:t,baseRef:r.baseRef,commands:o});else if(bT(r.baseRef),o.push("log"),a=(await fT(t,["log","-r",r.baseRef,"-T","{node}"])).trim(),0===a.length)throw new Error("MercurialDiffFailed: base ref did not resolve");r.ref.length>0&&(bT(r.ref),o.push("log"),c=(await fT(t,["log","-r",r.ref,"-T","{node}"])).trim())}const l=["diff","--git"];r.includeSpaceChanges||l.push("-b"),void 0!==r.unifiedContextLines&&l.push(`-U${r.unifiedContextLines}`),void 0!==a&&l.push("-r",a),void 0!==c&&l.push("-r",c),r.targetPaths.length>0&&l.push("--",...r.targetPaths),o.push("diff");const u=await fT(t,l),d=function(e){const t=e.replace(/\r\n/g,"\n");return new Le.o$({diffs:QR(t).map((e=>function(e){const t=new Le.QP({from:e.from,to:e.to,chunks:e.chunks.map((e=>new Le.Ei({content:e.content,lines:e.changes.map((e=>e.content)),oldStart:e.oldStart,oldLines:e.oldLines,newStart:e.newStart,newLines:e.newLines})))});return t.added=e.additions,t.removed=e.deletions,t}(e))),diffType:Le.Wf.UNSPECIFIED})}(u);let h=[];if(r.maxUntrackedFiles>0&&(o.push("status"),h=await async function({cwd:e,repositoryRoot:t,maxUnknownFiles:r}){let n=(await fT(e,["status","-un0"])).split("\0").filter((e=>e.length>0));return n.length>r&&(n=n.slice(0,r)),(await Promise.all(n.map((async e=>{try{const r=s.default.join(t,e),n=await fo.stat(r);if(n.size>uT){const t=await async function(e){const t=(0,lo.createHash)("sha256"),r=await fo.open(e,"r");try{const e=Buffer.alloc(65536);let n=0;for(;;){const{bytesRead:o}=await r.read(e,0,e.length,n);if(0===o)break;t.update(e.subarray(0,o)),n+=o}}finally{await r.close()}return t.digest("hex")}(r);return{contents:"",path:e,omittedDueToSize:!0,byteSize:n.size,contentHash:t}}return{contents:await fo.readFile(r,"utf8"),path:e}}catch{return}})))).filter((e=>void 0!==e))}({cwd:t,repositoryRoot:i,maxUnknownFiles:r.maxUntrackedFiles}),d.diffs.push(...h.map((e=>function(e){if(!0===e.omittedDueToSize)return new Le.QP({from:"/dev/null",to:e.path,chunks:[],added:0,removed:0});const t=vT(e.contents);if(0===t.length)return new Le.QP({from:"/dev/null",to:e.path,chunks:[],added:0,removed:0});const r=t.length;return new Le.QP({from:"/dev/null",to:e.path,chunks:[new Le.Ei({content:`@@ -0,0 +1${1===r?"":`,${r}`} @@`,lines:t.map((e=>`+${e}`)),oldStart:0,oldLines:0,newStart:1,newLines:r})],added:r,removed:0})}(e))))),n!==Le.ek.FILE_DIFFS)for(const e of d.diffs)e.chunks=[];if(n===Le.ek.DIFFS_WITH_BEFORE_AND_AFTER){const e=a??".";await Promise.all(d.diffs.map((async t=>{if("/dev/null"!==t.from)try{t.beforeFileContents=await ST({repositoryRoot:i,rev:e,filePath:t.from})}catch{t.beforeFileContents=""}else t.beforeFileContents="";if("/dev/null"!==t.to)if(void 0===c)try{const e=s.default.join(i,t.to),r=await fo.stat(e);t.afterFileContents=r.size>uT?"":await fo.readFile(e,"utf8")}catch{t.afterFileContents=""}else try{t.afterFileContents=await ST({repositoryRoot:i,rev:c,filePath:t.to})}catch{t.afterFileContents=""}else t.afterFileContents=""})))}const p=[u,function(e){const t=[];for(const r of e){const e=vT(r.contents);if(t.push(`diff --git a/${r.path} b/${r.path}`),t.push("new file mode 100644"),t.push("--- /dev/null"),t.push(`+++ b/${r.path}`),0===e.length)continue;const n=e.length;t.push(`@@ -0,0 +1${1===n?"":`,${n}`} @@`),t.push(...e.map((e=>`+${e}`)))}return t.join("\n")}(h.filter((e=>!0!==e.omittedDueToSize))),h.filter((e=>!0===e.omittedDueToSize)).map((e=>`omitted-untracked ${e.byteSize??0} ${e.contentHash??""} ${JSON.stringify(e.path)}`)).join("\n")].filter((e=>e.length>0)).join("\n"),f=r.computePatchId?function(e){if(0!==e.length)return`hg:${(0,lo.createHash)("sha256").update(e).digest("hex")}`}(p.length>0?`${p}\n`:""):void 0;let m,g;if(!0===r.returnHeadSha){o.push("log","status");const e=(await fT(t,["log","-r",".","-T","{node}"],{allowFailure:!0})).trim();m=e.length>0?e:dT,g=(await fT(t,["status","-0"])).length>0}lT.info(e,"Local mercurial diff commands",{sourceControl:"mercurial",commands:o});const w=new Le.df({diff:d,submoduleDiffs:[],patchId:f,headSha:m,hasUncommittedChanges:g}),y=r.maxResponseBytes??0;if(y>0){const t=w.toBinary().byteLength;if(t>y)throw lT.info(e,"Local diff outcome",{sourceControl:"mercurial",outcome:"too_large"}),new Error(`GetDiffResponseTooLarge: ${t} bytes exceeds the ${y} byte limit`)}return lT.info(e,"Local diff outcome",{sourceControl:"mercurial",outcome:"ok",fileCount:d.diffs.length,patchIdPrefixed:!0===f?.startsWith("hg:")}),w}const _T=(0,l.h)("local-git-diff");function CT({exitCode:e,stderr:t}){return new Error(`Git command failed with code ${e}: ${t}`)}async function ET(e,t,r={}){let n;try{n=await e(t)}catch(e){if(!0===r.ignoreErrors)return"";throw e}if(0!==n.exitCode&&!0!==r.ignoreErrors)throw CT(n);return!0===r.shouldNotTrimOutput?n.stdout:n.stdout.trim()}function xT(e){const t=QR(e);return new Le.o$({diffs:t.map((e=>function(e){const t=new Le.QP({from:e.from,to:e.to,chunks:e.chunks.map((e=>new Le.Ei({content:e.content,lines:e.changes.map((e=>e.content)),oldStart:e.oldStart,oldLines:e.oldLines,newStart:e.newStart,newLines:e.newLines})))});return t.added=e.additions,t.removed=e.deletions,t}(e))),diffType:Le.Wf.UNSPECIFIED})}function PT(e){const t=[];for(const n of e){const e={body:`+${(r=n.contents).replaceAll("\n","\n+")}`,numLines:Us(r)},o=1===e.numLines?"@@ -0,0 +1 @@":`@@ -0,0 +1,${e.numLines} @@`;t.push(`diff --git a/${n.path} b/${n.path}\n--- /dev/null\n+++ b/${n.path}\n${o}\n${e.body}`)}var r;return t.join("\n")}const IT=["main","master","develop"];async function RT(e,t){const r=s.default.join(e,t),n=await fo.lstat(r);if(n.isSymbolicLink())return{contents:await fo.readlink(r),path:t,isSymlink:!0};if(!n.isFile())throw new Error("Not a regular file or symlink");return{contents:await fo.readFile(r,"utf8"),path:t,isSymlink:!1}}async function TT(e,t,r){const n=aw(),o=(e,r)=>n.run(t,e,r),i=await async function(e,t){let r;try{const e=(await ET(t,["rev-parse","--show-toplevel"])).trim();e.length>0&&(r=e)}catch{}if(void 0!==r){const t=await async function({cwd:e,gitRoot:t}){const r=await yT(t);let n=await yT(e);if(gT(n,r))return;let o=!1;for(;wT(n,r)&&!gT(n,r);){try{if((await fo.stat(s.default.join(n,".hg"))).isDirectory()){o=!0;break}}catch{}const e=s.default.dirname(n);if(e===n)break;n=e}return o?mT(e):void 0}({cwd:e,gitRoot:r});return void 0!==t?"mercurial":"git"}return void 0===await mT(e)?"none":"mercurial"}(t,o);if(_T.info(e,"Local diff source control",{sourceControl:i}),"none"===i)throw _T.info(e,"Local diff outcome",{sourceControl:i,outcome:"no_version_control"}),new Error("NoVersionControl: no git or mercurial repository");if("mercurial"===i)return kT(e,t,r);const a=function(e){switch(e){case Le.ek.NAME_STATUS:return Le.ek.NAME_STATUS;case Le.ek.NAME_STATUS_AND_NUMSTAT:return Le.ek.NAME_STATUS_AND_NUMSTAT;case Le.ek.FILE_DIFFS:return Le.ek.FILE_DIFFS;case Le.ek.DIFFS_WITH_BEFORE_AND_AFTER:return Le.ek.DIFFS_WITH_BEFORE_AND_AFTER;default:return Le.ek.FILE_DIFFS}}(r.outputFormat),c=await(async()=>{let e=r.baseRef.length>0?r.baseRef:await async function(e){try{const t=await ET(e,["symbolic-ref","--short","refs/remotes/origin/HEAD"]);if(t)return t.trim()}catch{}for(const t of IT){const r=`origin/${t}`;try{return await ET(e,["rev-parse","--verify",r]),r}catch{}}try{const t=(await ET(e,["branch","-r"])).split("\n").map((e=>e.trim())).find((e=>e.startsWith("origin/")));if(t)return t}catch{}try{const t=await ET(e,["config","--get","init.defaultBranch"]);if(t)return t.trim()}catch{}throw new Error("Could not determine default branch")}(o);if(r.mergeBase){const t=r.ref.length>0?r.ref:"HEAD";e=(await ET(o,["merge-base","--end-of-options",e,t])).trim()}return e})(),l=["diff","--no-color"];r.includeSpaceChanges||l.push("--ignore-space-change"),void 0!==r.unifiedContextLines&&l.push(`-U${r.unifiedContextLines}`);const u=["--end-of-options",c];r.ref.length>0&&u.push(r.ref),r.targetPaths.length>0&&u.push("--",...r.targetPaths);const d=await o([...l,...u]);let h,p;if(0===d.exitCode)h=d.stdout,p=xT(h);else{const t=CT(d);if(r.computePatchId||!await async function(e){return(await ET(e,["config","--get-regexp","^(extensions\\.partialclone|remote\\..+\\.promisor)$"],{ignoreErrors:!0})).split("\n").some((e=>/^(extensions\.partialclone \S|remote\..+\.promisor( (true|yes|on|1))?$)/i.test(e)))}(o))throw t;p=await async function(e,t){const r=(await ET(e,["diff","--name-status","--no-renames","-z",...t])).split("\0"),n=[];for(let e=1;e<r.length;e+=2){const t=r[e-1],o=r[e];n.push(new Le.QP({from:"A"===t?"/dev/null":o,to:"D"===t?"/dev/null":o}))}return new Le.o$({diffs:n,diffType:Le.Wf.UNSPECIFIED,fileContentsOmitted:!0})}(o,u).catch((()=>{throw t})),_T.info(e,"Local diff outcome",{sourceControl:i,outcome:"partial_clone_names_only"})}let f=[];if(r.maxUntrackedFiles>0){f=await async function(e,t,r){let n=(await ET(t,["ls-files","--others","--exclude-standard"])).split("\n").map((e=>e.trim())).filter((e=>e.length>0));return n.length>r&&(n=n.slice(0,r)),(await Promise.all(n.map((async t=>{try{return await RT(e,t)}catch{return}})))).filter((e=>void 0!==e))}(t,o,r.maxUntrackedFiles);for(const e of f){const t=e.isSymlink?`${PT([e])}\n\`:await ET(o,["diff","--no-color","--no-index","--","/dev/null",e.path],{ignoreErrors:!0,shouldNotTrimOutput:!0});p.diffs.push(...xT(t).diffs)}}if(a!==Le.ek.FILE_DIFFS||!0===p.fileContentsOmitted)for(const e of p.diffs)e.chunks=[];if(a===Le.ek.DIFFS_WITH_BEFORE_AND_AFTER&&!0!==p.fileContentsOmitted){const n=r.ref.length>0?r.ref:"HEAD";await Promise.all(p.diffs.map((async s=>{try{if("/dev/null"!==s.from)try{s.beforeFileContents=await ET(o,["show","--end-of-options",`${c}:${s.from}`],{shouldNotTrimOutput:!0})}catch{s.beforeFileContents=""}else s.beforeFileContents="";if("/dev/null"!==s.to)if(r.ref.length>0)try{s.afterFileContents=await ET(o,["show","--end-of-options",`${n}:${s.to}`],{shouldNotTrimOutput:!0})}catch{s.afterFileContents=""}else try{s.afterFileContents=(await RT(t,s.to)).contents}catch{try{s.afterFileContents=await ET(o,["show","--end-of-options",`${n}:${s.to}`],{shouldNotTrimOutput:!0})}catch{s.afterFileContents=""}}else s.afterFileContents=""}catch(t){_T.error(e,"Error fetching file contents for diff",t)}})))}const m=new Map;for(const e of p.diffs){const t="/dev/null"!==e.to?e.to:e.from;t&&m.set(t,e)}const g=[...m.keys()],w=r.ref.length>0?r.ref:"HEAD";try{const e=await ZR({repoRoot:t,filePaths:g,getContent:async e=>{const t=m.get(e);if(t){if(void 0!==t.afterFileContents)return t.afterFileContents;try{if(t.to&&"/dev/null"!==t.to)return await ET(o,["show","--end-of-options",`${w}:${t.to}`],{shouldNotTrimOutput:!0})}catch{}}}});for(const[t,r]of e){const e=m.get(t);e&&(e.isGenerated=r.isGenerated)}}catch(t){_T.warn(e,"Generated-file detection failed; continuing without it",{error:t instanceof Error?t.message:String(t)})}const y=r.computePatchId&&void 0!==h?await async function(e,t){if(0===t.length)return;const{exitCode:r,stdout:n,stderr:o}=await e(["patch-id","--stable"],{input:t});if(0!==r)throw new Error(`git patch-id failed with code ${r}: ${o}`);return n.trim().split(/\s+/)[0]||void 0}(o,function(...e){const t=e.filter((e=>e.length>0));return 0===t.length?"":`${t.join("\n")}\n`}(h,PT(f))):void 0,v=!0===r.returnHeadSha?(await ET(o,["rev-parse","HEAD"])).trim():void 0,b=!0===r.returnHeadSha?(await ET(o,["status","--porcelain=v1","--untracked-files=all"])).trim().length>0:void 0,S=new Le.df({diff:p,submoduleDiffs:[],patchId:y,headSha:v,hasUncommittedChanges:b}),k=r.maxResponseBytes??0;if(k>0){const e=S.toBinary().byteLength;if(e>k)throw new Error(`GetDiffResponseTooLarge: ${e} bytes exceeds the ${k} byte limit`)}return S}class AT{async execute(e,t){return TT(e,t.cwd,t)}}var $T=r("../proto/dist/generated/agent/v1/mcp_allowlist_precheck_exec_pb.js");class MT{constructor(e){this.permissionsService=e}async execute(e,t){const r=await this.permissionsService.isMcpFullyAllowlisted(e,{providerIdentifier:t.providerIdentifier,toolName:t.toolName,annotationsJson:t.annotationsJson});return new $T.M({allowlisted:r})}}var DT=r("../proto/dist/generated/agent/v1/record_screen_exec_pb.js"),OT=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function FT(e){return null!==e.exitCode||null!==e.signalCode||e.killed}function NT(e,t){return"object"==typeof e&&null!==e&&"code"in e&&e.code===t}function LT(e){return e instanceof Error?e.message:String(e)}function jT(e,t,r,n){const o=[],s=function(e,t){const r=e.ffmpegExitCode??e.childProcess.exitCode,n=e.ffmpegExitSignal??e.childProcess.signalCode;if(e.ffmpegDiedEarly||null!==e.ffmpegDiedTime||null!==r||null!==n)return`ffmpeg exited code=${r} signal=${n}${null!==e.ffmpegDiedTime?` ${Math.max(0,Math.round((t-e.ffmpegDiedTime)/1e3))}s before SAVE`:""}`}(t,n);return void 0!==s&&o.push(s),void 0!==r&&o.push(`stop failed: ${LT(r)}`),o.length>0?`${e} (${o.join("; ")})`:e}const UT=(0,Fs.promisify)(gl.execFile);class BT{constructor(e){if(this.activeRecording=null,this.inFlightSaves=[],this.onRecordingStartedCallback=null,this.onRecordingStoppedCallback=null,this.recordingStoppedCallbackInvoked=!1,this.artifactsDir=e.artifactsDir,this.stagingDir=e.stagingDir??"/opt/cursor/recording-staging/",this.display=e.display,this.disablePolishedRendering=e.disablePolishedRendering??!1,this.polishedRenderer=e.polishedRenderer,!this.disablePolishedRendering){if(!this.polishedRenderer)throw new Error("record_screen requires a polished recording renderer when polished rendering is enabled. This tool should run via exec-daemon where that dependency is bundled.");this.polishedRenderer.assertAvailable()}}setOnRecordingStarted(e){this.onRecordingStartedCallback=e}setOnRecordingStopped(e){this.onRecordingStoppedCallback=e}invokeStoppedCallbackOnce(){!this.recordingStoppedCallbackInvoked&&this.onRecordingStoppedCallback&&(this.recordingStoppedCallbackInvoked=!0,this.onRecordingStoppedCallback())}async cleanupRecording(e){try{await e.inputEventLogger.stop()}catch{}if(!FT(e.childProcess)&&e.childProcess.pid)try{await this.stopFfmpegRecording(e)}catch{try{process.kill(e.childProcess.pid,"SIGKILL")}catch{}}}getActiveInputEventLogger(){return this.activeRecording?.inputEventLogger??null}async dispose(){const e=this.inFlightSaves.map((e=>e.promise));if(e.length>0)try{await(0,Dr.wj)(Promise.all(e),BT.IN_FLIGHT_SAVE_DISPOSE_TIMEOUT_MS,"Timed out waiting for in-flight recording save")}catch{}if(this.activeRecording){await this.cleanupRecording(this.activeRecording),this.invokeStoppedCallbackOnce();try{await fo.rm(this.activeRecording.sessionDir,{force:!0,recursive:!0})}catch{}this.activeRecording=null}}findInFlightSave(e){return this.inFlightSaves.find((t=>t.state===e))}clearActiveRecordingIfCurrent(e){this.activeRecording===e&&(this.activeRecording=null)}invokeStoppedCallbackIfCurrent(e){this.activeRecording===e&&this.invokeStoppedCallbackOnce()}sanitizeToolCallId(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_")}async ensureRecordingDirectoryExists(){await fo.mkdir(this.stagingDir,{recursive:!0}),await fo.mkdir(this.artifactsDir,{recursive:!0})}buildSessionDir(e){const t=this.sanitizeToolCallId(e),r=`session-${(new Date).toISOString().replace(/[:.]/g,"-")}-${t}`;return s.join(this.stagingDir,r)}validateAndNormalizeSaveAsFilename(e){let t=e.trim();return t.startsWith(this.artifactsDir)&&(t=t.slice(this.artifactsDir.length),t.startsWith("/")&&(t=t.slice(1))),t=t.trim(),0===t.length?{success:!1,reason:DT.y.UNSPECIFIED}:t.includes("/")||t.includes("\\")?{success:!1,reason:DT.y.SLASHES_NOT_ALLOWED}:(t=t.replace(/[^a-zA-Z0-9 ._-]/g,"_"),t=t.trim(),0===t.length?{success:!1,reason:DT.y.UNSPECIFIED}:(t.length>128&&(t=t.slice(0,128).trim()),t.toLowerCase().endsWith(".mp4")||(t=`${t}.mp4`),{success:!0,filename:t}))}async movePolishedVideo(e,t){try{return void await fo.rename(e,t)}catch(e){if(!NT(e,"EXDEV"))throw e}try{await fo.copyFile(e,t)}catch(e){throw await fo.rm(t,{force:!0}).catch((()=>{})),e}try{await fo.unlink(e)}catch(e){throw await fo.rm(t,{force:!0}).catch((()=>{})),e}}async getUniqueArtifactVideoPath(e){const t=s.parse(e),r=t.name||"recording",n=t.ext||".mp4";let o=`${r}${n}`,i=2;for(;;){const e=s.join(this.artifactsDir,o);try{const t=await fo.open(e,"wx");return await t.close(),e}catch(e){if(!NT(e,"EEXIST"))throw e;o=`${r}-${i}${n}`,i++}}}async resolveArtifactVideoPath(e){const{saveAsFilename:t,stagingSessionDir:r}=e;let n,o;if(t){const e=this.validateAndNormalizeSaveAsFilename(t);e.success?o=e.filename:(n=e.reason,o=`${s.basename(r)}.mp4`)}else o=`${s.basename(r)}.mp4`;return{finalVideoPath:await this.getUniqueArtifactVideoPath(o),requestedFilePathRejectedReason:n}}async getVideoDurationMs(e){const{stdout:t}=await(0,wl.D9)(UT,"ffprobe",["-v","error","-show_entries","format=duration","-of","default=noprint_wrappers=1:nokey=1",e],{encoding:"utf8"}),r=parseFloat(t.trim());if(!Number.isFinite(r)||r<0)throw new Error(`Invalid video duration from ffprobe: ${t.trim()}`);return Math.floor(1e3*r)}async getVideoDimensions(e){const{stdout:t}=await(0,wl.D9)(UT,"ffprobe",["-v","error","-select_streams","v:0","-show_entries","stream=width,height","-of","csv=p=0:s=x",e],{encoding:"utf8"}),[r,n]=t.trim().split("x"),o=Number.parseInt(r,10),s=Number.parseInt(n,10);if(!Number.isFinite(o)||!Number.isFinite(s))throw new Error(`Invalid video dimensions from ffprobe: ${t.trim()}`);if(o<=0||s<=0)throw new Error(`Invalid non-positive video dimensions from ffprobe: ${t.trim()}`);return{width:o,height:s}}async renderPolished(e,t){const r=s.join(t,"recording"),n=s.join(r,"recording_full.mp4");try{await this.polishedRenderer.renderRecordingSession({stagingSessionDir:t,outputVideoPath:n,fps:BT.PROXY_TARGET_FPS,includeBrandTag:!0}),await fo.access(n,fo.constants.R_OK)}catch(t){const r=(0,$.fU)(e);throw r?.setAttribute("error.type",function(e){return e instanceof Error?e.message.startsWith("Failed to load polished-renderer native binding")?"binding_load_failed":"code"in e&&"string"==typeof e.code?e.code:e.name:typeof e}(t)),r?.setStatus({code:2}),t}return n}async getVideoFramerate(e){try{const{stdout:t}=await(0,wl.D9)(UT,"ffprobe",["-v","error","-select_streams","v:0","-show_entries","stream=r_frame_rate","-of","default=noprint_wrappers=1:nokey=1",e],{encoding:"utf8"}),r=t.trim();if(r.includes("/")){const[e,t]=r.split("/"),n=Number.parseFloat(e),o=Number.parseFloat(t);if(Number.isFinite(n)&&Number.isFinite(o)&&0!==o){const e=n/o;if(e>0&&e<500)return Math.round(e)}}else{const e=Number.parseFloat(r);if(Number.isFinite(e)&&e>0&&e<500)return Math.round(e)}console.warn(`[record-screen] Unexpected ffprobe r_frame_rate output "${r}", defaulting to ${BT.PROXY_TARGET_FPS}fps`)}catch(e){console.warn(`[record-screen] Failed to read video framerate: ${e instanceof Error?e.message:String(e)}, defaulting to ${BT.PROXY_TARGET_FPS}fps`)}return BT.PROXY_TARGET_FPS}async startFfmpegRecording(e,t){const r=s.join(t,"recording");await fo.mkdir(r,{recursive:!0});const n=s.join(r,"recording_render_proxy_1080p.mp4");let o;try{o=(await Tm(this.display)).display.refreshRate}catch(e){console.warn(`[record-screen] Failed to detect refresh rate: ${e instanceof Error?e.message:String(e)}, using default ${BT.DEFAULT_REFRESH_RATE}Hz`),o=BT.DEFAULT_REFRESH_RATE}const i=["-video_size",e,"-framerate",String(o),"-draw_mouse","0","-f","x11grab","-i",this.display,"-vf",`scale=${BT.PROXY_TARGET_WIDTH}:-2:flags=lanczos,fps=${BT.PROXY_TARGET_FPS}`,"-c:v","libx264","-preset",BT.PROXY_PRESET,"-crf",String(BT.PROXY_CRF),"-pix_fmt","yuv420p","-profile:v","high","-x264-params","keyint=1:min-keyint=1:scenecut=0:bframes=0","-movflags","+faststart","-tune","fastdecode","-y",n],a=(0,wl.D9)(gl.spawn,"ffmpeg",i,{stdio:["ignore","pipe","pipe"],detached:!0}),c=new Promise(((e,t)=>{let r="",n=!1;a.stderr?.on("data",(t=>{r+=t.toString(),!n&&r.includes("frame=")&&(n=!0,e(Date.now()))}));const o=setTimeout((()=>{n||t(new Error("ffmpeg did not start encoding within 5 seconds"))}),5e3);a.once("exit",((e,r)=>{clearTimeout(o),n||t(new Error(`ffmpeg exited before starting: code=${e} signal=${r}`))})),a.once("error",(e=>{clearTimeout(o),n||t(new Error(`ffmpeg failed to start: ${e.message}`))}))}));return await new Promise(((e,t)=>{const r=setTimeout(e,300);a.once("error",(e=>{clearTimeout(r),t(new Error(`Failed to start ffmpeg: ${e.message}`))})),a.once("exit",((e,n)=>{clearTimeout(r),t(null!==e&&0!==e?new Error(`ffmpeg exited with code ${e}`):null!==n?new Error(`ffmpeg killed by signal ${n}`):new Error("ffmpeg exited unexpectedly during startup"))}))})),{process:a,videoStartedPromise:c}}async runFfmpegCommand(e,t){return await new Promise(((r,n)=>{const o=(0,wl.D9)(gl.spawn,"ffmpeg",t,{stdio:["ignore","ignore","pipe"]});let s="";o.stderr?.on("data",(e=>{s.length<2e4&&(s+=e.toString())})),o.once("error",(t=>{n(new Error(`ffmpeg ${e} failed to start: ${t instanceof Error?t.message:String(t)}`))})),o.once("close",(t=>{0===t?r():n(new Error(`ffmpeg ${e} exited with code ${t}: ${s.trim()}`))}))}))}async saveRecordingDataPackage(e){const{sessionDir:t,durationMs:r,recordingStartEpochMs:n,ffmpegStartedEpochMs:o,inputEvents:i,resolution:a,renderProxies:c}=e,l=s.join(t,"recording"),u=s.join(l,"recording-data.json"),d=o-n,h=i.map((e=>({executionTimestampMs:e.executionTimestampMs,commandDurationMs:e.commandDurationMs,positionBefore:e.positionBefore,positionAfter:e.positionAfter,cursorTypeAfter:e.cursorTypeAfter,action:{action:this.serializeAction(e.action)}}))),p={version:3,durationMs:r,recordingStartEpochMs:n,ffmpegStartedEpochMs:o,eventToVideoOffsetMs:d,displayWidth:a.display.width,displayHeight:a.display.height,apiWidth:a.api.width,apiHeight:a.api.height,inputEvents:h,renderProxies:c??null};await fo.writeFile(u,JSON.stringify(p,null,2))}serializeAction(e){const{action:t}=e,r={case:t.case};switch(t.case){case"click":r.value={coordinate:t.value.coordinate?{x:t.value.coordinate.x,y:t.value.coordinate.y}:null,button:t.value.button,count:t.value.count,modifierKeys:t.value.modifierKeys};break;case"mouseMove":r.value={coordinate:t.value.coordinate?{x:t.value.coordinate.x,y:t.value.coordinate.y}:null};break;case"type":r.value={text:t.value.text};break;case"key":r.value={key:t.value.key,holdDurationMs:t.value.holdDurationMs};break;case"scroll":r.value={coordinate:t.value.coordinate?{x:t.value.coordinate.x,y:t.value.coordinate.y}:null,direction:t.value.direction,amount:t.value.amount,modifierKeys:t.value.modifierKeys};break;case"drag":r.value={path:t.value.path.map((e=>({x:e.x,y:e.y}))),button:t.value.button};break;case"wait":r.value={durationMs:t.value.durationMs};break;case"screenshot":case"cursorPosition":case"mouseDown":case"mouseUp":r.value=t.value;break;default:r.value={}}return r}async stopFfmpegRecording(e){const{childProcess:t}=e;if(FT(t)||!t.pid)return;const r=t.pid;return new Promise(((e,n)=>{const o=setTimeout((()=>{try{try{process.kill(-r,"SIGKILL")}catch{process.kill(r,"SIGKILL")}}catch{}n(new Error("Timeout waiting for ffmpeg to stop"))}),2e4);t.once("exit",(()=>{clearTimeout(o),e()})),t.once("error",(e=>{clearTimeout(o),n(new Error(`Error stopping ffmpeg: ${e.message}`))}));try{try{process.kill(-r,"SIGTERM")}catch{process.kill(r,"SIGTERM")}}catch(t){if(clearTimeout(o),NT(t,"ESRCH"))return void e();n(new Error(`Failed to send SIGTERM: ${t instanceof Error?t.message:String(t)}`))}}))}async performSave(e,t,r){const n=Date.now();try{const o=await r.inputEventLogger.stop(),i=r.inputEventLogger.getRecordingStartTime();let a;this.invokeStoppedCallbackIfCurrent(r);try{!FT(r.childProcess)&&r.childProcess.pid&&await this.stopFfmpegRecording(r)}catch(e){a=e,console.warn(`[record-screen] Failed to stop ffmpeg: ${LT(e)}`)}const c=r.ffmpegStartedEpochMs??i,l=r.sessionDir,u=s.join(l,"recording"),d=s.join(u,"recording_render_proxy_1080p.mp4");let h,p,f;try{await fo.access(d,fo.constants.R_OK)}catch(e){await this.cleanupRecording(r),this.clearActiveRecordingIfCurrent(r);const t=NT(e,"ENOENT")?`Recording proxy not found at ${d}`:`Recording proxy at ${d} could not be validated: ${LT(e)}`;return new DT.Tj({result:{case:"failure",value:new DT.yH({error:jT(t,r,a,n)})}})}try{if([h,p,f]=await Promise.all([this.getVideoDurationMs(d),this.getVideoDimensions(d),this.getVideoFramerate(d)]),h<=0)throw new Error(`Recording proxy has zero duration at ${d}`)}catch(e){await this.cleanupRecording(r);const t=LT(e),o=t.includes(d)?t:`Recording proxy at ${d} could not be validated: ${t}`;return new DT.Tj({result:{case:"failure",value:new DT.yH({error:jT(o,r,a,n)})}})}const m={profileVersion:BT.PROXY_PROFILE_VERSION,generatedAtEpochMs:Date.now(),source:{width:p.width,height:p.height,durationMs:h,fps:f},artifacts:[{name:"render_proxy_1080p",path:"recording_render_proxy_1080p.mp4",width:p.width,height:p.height,fps:BT.PROXY_TARGET_FPS,codec:"h264",profile:BT.PROXY_PROFILE_VERSION,keyint:1,status:"success",elapsedMs:0}]};await this.saveRecordingDataPackage({sessionDir:l,durationMs:h,recordingStartEpochMs:i,ffmpegStartedEpochMs:c,inputEvents:o,resolution:r.resolution,renderProxies:m});const{finalVideoPath:g,requestedFilePathRejectedReason:w}=await this.resolveArtifactVideoPath({saveAsFilename:t.saveAsFilename,stagingSessionDir:l});try{if(this.disablePolishedRendering)await fo.copyFile(d,g);else{const t=await this.renderPolished(e,l);await this.movePolishedVideo(t,g)}}catch(e){throw await fo.rm(g,{force:!0}).catch((()=>{})),e}try{await fo.rm(l,{force:!0,recursive:!0})}catch(e){console.warn(`[record-screen] Failed to remove staging session ${l}: ${LT(e)}`)}return this.clearActiveRecordingIfCurrent(r),new DT.Tj({result:{case:"saveSuccess",value:new DT.ol({path:g,recordingDurationMs:we.protoInt64.parse(h.toString()),requestedFilePathRejectedReason:w})}})}catch(e){return await this.cleanupRecording(r),this.invokeStoppedCallbackIfCurrent(r),new DT.Tj({result:{case:"failure",value:new DT.yH({error:LT(e)})}})}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(r,(0,$.VI)(e.withName("LocalRecordScreenExecutor.execute")),!1);try{await this.ensureRecordingDirectoryExists()}catch(e){return new DT.Tj({result:{case:"failure",value:new DT.yH({error:`Failed to create recording directory: ${e instanceof Error?e.message:String(e)}. Ensure the parent directory exists and has write permissions, or run: sudo mkdir -p ${this.stagingDir} ${this.artifactsDir} && sudo chmod 777 ${this.stagingDir} ${this.artifactsDir}`})}})}if(t.mode===DT.$u.UNSPECIFIED)return new DT.Tj({result:{case:"failure",value:new DT.yH({error:"Mode must be one of START_RECORDING, SAVE_RECORDING, DISCARD_RECORDING"})}});switch(t.mode){case DT.$u.START_RECORDING:{this.recordingStoppedCallbackInvoked=!1;let e=!1;if(this.activeRecording){const t=this.activeRecording;if(!this.inFlightSaves.some((e=>e.state===t))){e=!0;try{await this.cleanupRecording(t),await fo.rm(t.sessionDir,{force:!0,recursive:!0}).catch((()=>{}))}catch{}}this.activeRecording=null}let r=null,n=null,o=null;try{o=this.buildSessionDir(t.toolCallId||"recording"),await fo.mkdir(o,{recursive:!0});const{resolutionString:s,resolution:i}=await Tm(this.display),{process:a,videoStartedPromise:c}=await this.startFfmpegRecording(s,o);r=a;const l=function(e){const t=e.lastIndexOf(":");if(-1===t)throw new Error(`Invalid X11 display string: ${e} (missing ':')`);const r=e.slice(t+1).split(".")[0],n=parseInt(r,10);if(!Number.isFinite(n)||n<0)throw new Error(`Invalid X11 display number in: ${e} (parsed: ${r})`);return n}(this.display);n=new jm({displayNum:l,resolution:i}),await n.start();const u=n.getRecordingStartTime();let d;try{d=await c}catch(e){throw new Error(`ffmpeg failed to start encoding: ${e instanceof Error?e.message:String(e)}`)}const h={childProcess:r,sessionDir:o,startTime:u,inputEventLogger:n,resolution:i,ffmpegStartedEpochMs:d,ffmpegDiedEarly:!1,ffmpegDiedTime:null,ffmpegExitCode:null,ffmpegExitSignal:null};this.activeRecording=h,this.onRecordingStartedCallback&&this.onRecordingStartedCallback(n),r.once("exit",((e,t)=>{h.ffmpegDiedEarly=!0,h.ffmpegDiedTime=Date.now(),h.ffmpegExitCode=e,h.ffmpegExitSignal=t}));const p=!!t.saveAsFilename;return new DT.Tj({result:{case:"startSuccess",value:new DT.T4({wasPriorRecordingCancelled:e,wasSaveAsFilenameIgnored:p})}})}catch(e){if(n)try{await n.stop()}catch{}if(r&&!r.killed&&r.pid)try{process.kill(r.pid,"SIGKILL")}catch{}return o&&await fo.rm(o,{force:!0,recursive:!0}).catch((()=>{})),this.activeRecording=null,new DT.Tj({result:{case:"failure",value:new DT.yH({error:e instanceof Error?e.message:String(e)})}})}}case DT.$u.SAVE_RECORDING:{if(!this.activeRecording)return 1===this.inFlightSaves.length?await this.inFlightSaves[0].promise:new DT.Tj({result:{case:"failure",value:new DT.yH({error:"No active recording to save"})}});const e=this.activeRecording,r=this.findInFlightSave(e);if(r)return await r.promise;const o=Promise.resolve().then((()=>this.performSave(n.ctx,t,e))),s={state:e,promise:o};this.inFlightSaves.push(s);try{return await o}finally{this.inFlightSaves=this.inFlightSaves.filter((e=>e!==s))}}case DT.$u.DISCARD_RECORDING:{if(!this.activeRecording)return new DT.Tj({result:{case:"failure",value:new DT.yH({error:"No active recording to discard"})}});const e=this.activeRecording;if(this.findInFlightSave(e))return new DT.Tj({result:{case:"failure",value:new DT.yH({error:"Save in progress for this recording; wait for it or start a new recording"})}});try{return await e.inputEventLogger.stop(),this.invokeStoppedCallbackOnce(),!FT(e.childProcess)&&e.childProcess.pid&&await this.stopFfmpegRecording(e),await fo.rm(e.sessionDir,{force:!0,recursive:!0}),this.activeRecording=null,new DT.Tj({result:{case:"discardSuccess",value:new DT.N8}})}catch(t){await this.cleanupRecording(e),this.invokeStoppedCallbackOnce();const r=e.sessionDir;let n=!1;try{await fo.rm(r,{force:!0,recursive:!0}),n=!0}catch{}this.activeRecording=null;const o=t instanceof Error?t.message:String(t),s=n?"":`. Session may remain at: ${r}`;return new DT.Tj({result:{case:"failure",value:new DT.yH({error:`Failed to discard recording: ${o}${s}`})}})}}default:{const e=t.mode;return new DT.Tj({result:{case:"failure",value:new DT.yH({error:`Unhandled recording mode: ${String(e)}`})}})}}}catch(e){r.error=e,r.hasError=!0}finally{OT(r)}}}async function WT(e){const t=await(0,fo.readdir)(e,{withFileTypes:!0}).catch((()=>[])),r=[];for(const n of t){const t=s.join(e,n.name),o={name:n.name,path:t,isDirectory:n.isDirectory()};n.isDirectory()&&(o.children=await WT(t)),r.push(o)}return r.sort(((e,t)=>e.isDirectory&&!t.isDirectory?-1:!e.isDirectory&&t.isDirectory?1:e.name.localeCompare(t.name)))}function HT(e,t="",r=!0){const n=[`${t}${r?"└── ":"├── "}${e.isDirectory?`${e.name}/`:e.name}`],o=e.children;if(o?.length){const e=t+(r?" ":"│ ");o.forEach(((t,r)=>{const s=r===o.length-1;n.push(...HT(t,e,s))}))}return n}async function qT(e){if(!await(0,fo.access)(e,fo.constants.R_OK).then((()=>!0),(()=>!1)))return"(No notes directory yet - will be created when you write your first note)";const t=await WT(e);return 0===t.length?"(Notes directory is empty)":t.flatMap(((e,r)=>HT(e,"",r===t.length-1))).join("\n")}async function zT(e,t){return qT(s.join(e,"agent-notes",t))}async function GT(e){return qT(s.join(e,"agent-notes","shared"))}BT.IN_FLIGHT_SAVE_DISPOSE_TIMEOUT_MS=3e4,BT.PROXY_TARGET_WIDTH=1920,BT.PROXY_TARGET_FPS=60,BT.PROXY_CRF=17,BT.PROXY_PRESET="veryfast",BT.PROXY_PROFILE_VERSION="render-proxy-h264-all-i-v1",BT.DEFAULT_REFRESH_RATE=60;var VT=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},KT=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const JT=3e3,ZT=(0,l.h)("local-exec:request-context"),XT=Symbol("sectionLoadTimedOut");function QT(e,t){if(void 0===t)return e;let r;const n=new Promise((e=>{r=setTimeout((()=>e(XT)),t)}));return e.catch((()=>{})),Promise.race([e,n]).finally((()=>{clearTimeout(r)}))}class YT{async read(e,t){const r=this.inFlight??this.begin(e),n=this.last;if(void 0===n)return r;const o=await QT(r,t).catch((()=>XT));return o===XT?n.value:o}prefetch(e){void 0===this.inFlight&&this.begin(e).catch((()=>{}))}begin(e){const t=e();this.inFlight=t;const r=()=>{this.inFlight===t&&(this.inFlight=void 0)};return t.then((e=>{this.last={value:e},r()}),r),t}}async function eA(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{VT(o,(0,$.VI)(e.withName("LocalRequestContextExecutor.getGitStatusForRepoPath")),!1);try{return(await t.exec(e,r,["--no-optional-locks","status","--short","--branch"],{timeout:n,caller:"getGitStatusForRepoPath"})).stdout}catch{return}}catch(e){o.error=e,o.hasError=!0}finally{KT(o)}}async function tA(e,t,r,n){try{const o=(await t.exec(e,r,["rev-parse","--abbrev-ref","HEAD"],{timeout:n,caller:"getGitBranchForRepoPath"})).stdout.trim();if("HEAD"===o||0===o.length)return;return o}catch{return}}async function rA(e,t,r,n){const o=e=>{let t;const r=new Promise((e=>{t=setTimeout((()=>{e(void 0)}),n)}));return Promise.race([e.catch((()=>{})),r]).finally((()=>{void 0!==t&&clearTimeout(t)}))},[s,i]=await Promise.all([o(eA(e,t,r,n)),o(tA(e,t,r,n))]);return{status:s,branchName:i}}async function nA(e,t,r={}){const{projectDir:n,notesSessionId:s,agentNotesEnabled:i,reportProcessWorkingDirectory:a,getSmartModeClassifierAutoModeEnabled:c,devForceNextSmartModeClassifierBlockToken:l,isWorkingDirHomeDir:u,getSandboxEnabled:d,getSandboxSupported:h,getNetworkAllowlistInfo:p,userTerminalHint:f,artifactsFolder:m,secretRedactionEnabled:g,getComputerUseSupported:w,getComputerUseDesktop:y,getMockPromptTime:v}=r,b=y?.(),S=`${o.default.platform()} ${o.default.release()}`,k=(0,Eo.G6)(f),_=v?.(),C=(()=>{try{return(new Intl.DateTimeFormat).resolvedOptions().timeZone??void 0}catch{return}})(),E=n,x=n?`${n}/terminals`:void 0,P=n&&!1!==i?`${n}/agent-notes/shared`:void 0,I=n&&s&&!1!==i?`${n}/agent-notes/${s}`:void 0,R=n?`${n}/agent-transcripts`:void 0,T=!!d&&d(),A=h?.(),$=c?.();let M;if(p)try{M=await p()}catch{M=void 0}return new Mr.GE({osVersion:S,workspacePaths:t,shell:k,sandboxEnabled:T,projectFolder:E,terminalsFolder:x,agentSharedNotesFolder:P,agentConversationNotesFolder:I,agentTranscriptsFolder:R,timeZone:C,...!1!==a&&{processWorkingDirectory:process.cwd()},artifactsFolder:m,...void 0!==$&&{smartModeClassifierAutoModeEnabled:$},...void 0!==l&&{devForceNextSmartModeClassifierBlockToken:l},...void 0!==_&&{devMockPromptTime:we.Timestamp.fromDate(_)},...void 0!==g&&{secretRedactionEnabled:g},...void 0!==A&&{sandboxSupported:A},...void 0!==M?.hasDefaults&&{sandboxNetworkHasDefaults:M.hasDefaults},...M?.explicitEntries&&M.explicitEntries.length>0&&{sandboxNetworkExplicitAllowlist:M.explicitEntries},...void 0!==w&&{computerUseSupported:w()},...void 0!==b&&{computerUseDesktop:b},...void 0!==u&&{isWorkingDirHomeDir:u}})}const oA={type:"object",properties:{},additionalProperties:!1};function sA(e,t){return{tools:(!0===t?.internalBrowserProvidersOnly?e.servers.filter((e=>Un.has(e.serverIdentifier))):e.servers).flatMap((e=>e.tools)).map((e=>new fn.gd({name:e.name,providerIdentifier:e.providerIdentifier,toolName:e.toolName,description:e.description,...!0===t?.inputSchemaJson?{inputSchemaJson:void 0===e.inputSchema?void 0:JSON.stringify(e.inputSchema)}:{inputSchema:e.inputSchema?we.Value.fromJson(e.inputSchema):void 0}}))),mcpInstructions:e.servers.flatMap((e=>e.instructions))}}function iA(e,t){const r=!0===t?.slimDescriptors,n=e.servers.map((e=>{const n=e.instructions.map((e=>e.instructions)).filter(Boolean).join("\n"),o=e.tools.map((e=>new fn.E$({toolName:e.toolName,...fv(e.annotations),...r?{}:{description:e.description,...!0===t?.inputSchemaJson?{inputSchemaJson:void 0===e.inputSchema?void 0:JSON.stringify(e.inputSchema)}:{inputSchema:void 0!==e.inputSchema?we.Value.fromJson(e.inputSchema):void 0}}})));return!jn(e.serverIdentifier)||!0!==t?.alwaysExposeVirtualMcpAuthTool&&"needsAuth"!==e.status||o.some((e=>e.toolName===pI))||o.push(new fn.E$({toolName:pI,...r?{}:{description:fI,...!0===t?.inputSchemaJson?{inputSchemaJson:JSON.stringify(oA)}:{inputSchema:we.Value.fromJson(oA)}}})),new fn.UC({serverIdentifier:e.serverIdentifier,serverName:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginDbId:e.pluginId,marketplaceId:e.marketplaceId,serverUseInstructions:n||void 0,tools:o})}));return new fn.U_({enabled:!0,mcpDescriptors:n})}function aA(e){const t=e?.trim();return t||void 0}function cA(e,t){const r=function(e){return aA(e.serverIdentifier)}(e);if(r)return r;const n=aA(e.serverName);return n?t.get(n)??n:void 0}class lA{constructor(e){this.mcpLease=e}async getState(e){const[t,r]=await Promise.all([this.mcpLease.getTools(e).catch((t=>(ZT.warn(e,"Error fetching MCP tools",{error:t}),[]))),this.mcpLease.getInstructions(e).catch((t=>(ZT.warn(e,"Error fetching MCP instructions",{error:t}),[])))]);return function(e,t,r,n=!1){const o=new Map;for(const t of e)o.has(t.providerIdentifier)||o.set(t.providerIdentifier,t.clientKey);const s=t.map((e=>cA(e,o))).filter((e=>Boolean(e))),i=[...new Set([...e.map((e=>e.clientKey)),...s,...Array.from(r?.entries()??[]).filter((([,e])=>"connected"!==e.status)).map((([e])=>e))])];if(n&&void 0!==r){const e=new Map(Array.from(r.keys(),((e,t)=>[e,t])));i.sort(((t,r)=>(e.get(t)??e.size)-(e.get(r)??e.size)))}return{servers:i.map((n=>{const s=e.filter((e=>e.clientKey===n));return{serverName:s[0]?.providerIdentifier??n,serverIdentifier:n,plugin:s[0]?.plugin,marketplace:s[0]?.marketplace,tools:s,instructions:t.filter((e=>cA(e,o)===n)),status:r?.get(n)?.status,errorMessage:r?.get(n)?.errorMessage}}))}}(t,r,await async function(e,t){const r=await t.getClients(e).catch((t=>(ZT.warn(e,"Error fetching MCP clients",{error:t}),{}))),n=await Promise.all(Object.entries(r).map((async([t,r])=>{const n=await r.getState(e).catch((()=>({kind:"error",message:"Failed to fetch MCP client state"})));return[t,{status:zn(n),errorMessage:"error"===n.kind&&void 0!==n.message?n.message:void 0}]})));return new Map(n)}(e,this.mcpLease))}}function uA(e){return new Za._W({result:{case:"success",value:new Za.pv({servers:e.servers.map((e=>new Za.XE({serverName:e.serverName,serverIdentifier:e.serverIdentifier,plugin:e.plugin,marketplace:e.marketplace,tools:e.tools.map((e=>new fn.gd({name:e.name,providerIdentifier:e.providerIdentifier,toolName:e.toolName,description:e.description,inputSchema:e.inputSchema?we.Value.fromJson(e.inputSchema):void 0,metaJson:Bn(e._meta),...fv(e.annotations)}))),instructions:e.instructions,status:e.status,errorMessage:e.errorMessage})))})}})}class dA{constructor(e,t,r){this.mcpStateAccessor=e,this.ensureMcpServersLoaded=t,this.options=r}async execute(e,t){try{await(this.ensureMcpServersLoaded?.(e,t.serverIdentifiers,{wait:!t.kickOnly}))}catch{}t.refreshPolicy!==Za.ew.FORCE_IF_MISSING&&t.refreshPolicy!==Za.ew.FORCE||await(this.mcpStateAccessor.refreshNow?.(e));const r=await this.mcpStateAccessor.getState(e);if(!0===this.options?.filterToRequestedServers&&t.serverIdentifiers.length>0){const e=new Set(t.serverIdentifiers),n=r.servers.filter((t=>e.has(t.serverIdentifier)));if(n.length>0)return uA({...r,servers:n})}return uA(r)}}class hA{constructor(e,t,r,n,o,s,i,a,c={}){this.cursorRulesService=e,this.cloudRulesService=t,this.subagentsService=r,this.repositoryProvider=n,this.grepProvider=o,this.mcpStateAccessor=s,this.gitExecutor=i,this.workspacePaths=a,this.reusedGitInfo=new Map,this.reusedMcpState=new YT,this.reusedAgentSkills=new YT,this.reusedAdminCommandDenylist=new YT,this.cachedWorkspaces=new Map,this.inFlightWorkspaceWarms=new Map;const{projectDir:l,getSmartModeClassifierAutoModeEnabled:u,getAdminCommandDenylist:d,devForceNextSmartModeClassifierBlockToken:h,isWorkingDirHomeDir:p,agentNotesEnabled:f,reportProcessWorkingDirectory:m,createFileWatcher:g,getSandboxEnabled:w,getSandboxSupported:y,getNetworkAllowlistInfo:v,userTerminalHint:b,getMcpFileSystemOptions:S,mcpMetaToolEnabled:k,mcpMetaToolSlimDescriptors:_,mcpInputSchemaJson:C,alwaysExposeVirtualMcpAuthTool:E,getArtifactsFolder:x,secretRedactionEnabled:P,attributionConfigProvider:I,isAttributionDisabledByAdmin:R,getAgentSkills:T,additionalRules:A,getComputerUseSupported:$,getComputerUseDesktop:M,getMockPromptTime:D}=c;this.projectDir=l,this.isWorkingDirHomeDir=p,this.agentNotesEnabled=f??!0,this.reportProcessWorkingDirectory=m??!0,this.getSandboxEnabled=w,this.getSandboxSupported=y,this.getNetworkAllowlistInfo=v,this.getSmartModeClassifierAutoModeEnabled=u,this.getAdminCommandDenylist=d,this.devForceNextSmartModeClassifierBlockToken=h,this.getMockPromptTime=D,this.userTerminalHint=b,this.getMcpFileSystemOptions=S,this.mcpMetaToolEnabled=k??!1,this.mcpMetaToolSlimDescriptors=_??!1,this.mcpInputSchemaJson=C??!1,this.alwaysExposeVirtualMcpAuthTool=E??!1,this.getArtifactsFolder=x,this.secretRedactionEnabled=P,this.attributionConfigProvider=I,this.isAttributionDisabledByAdmin=R,this.getAgentSkills=T,this.additionalRules=A??[],this.getComputerUseSupported=$,this.getComputerUseDesktop=M,this.reduceContextHotPath=c.reduceContextHotPath??!1,this.sectionLoadTimeoutMs=c.sectionLoadTimeoutMs,this.reportSectionCompleteness=c.reportSectionCompleteness??!1,this.freshSectionWaitMs=c.freshSectionWaitMs,this.onRequestContext=c.onRequestContext,!0!==c.deferWarmup&&this.warm(),void 0!==g&&(this.fileWatcher=g(),this.fileWatcher.onDidChange((e=>{this.onWorkspacePathChanged(e)})),this.fileWatcher.onDidCreate((e=>{this.onWorkspacePathChanged(e)})),this.fileWatcher.onDidDelete((e=>{this.onWorkspacePathChanged(e)})))}warm(){this.warmWorkspaceCaches(),void 0===this.globalCache&&this.rebuildGlobalCache()}onWorkspacePathChanged(e){this.rebuildAllCaches()}getWorkspaceCache(e){return this.cachedWorkspaces.get(e)}warmWorkspaceCaches(){const e=(0,y.q6)();Promise.all(this.workspacePaths.map((t=>this.ensureWorkspaceCacheWarm(e,t))))}ensureWorkspaceCacheWarm(e,t){if(this.cachedWorkspaces.has(t))return Promise.resolve();const r=this.inFlightWorkspaceWarms.get(t);if(void 0!==r)return r;const n=this.warmWorkspaceCache(e,t).finally((()=>{this.inFlightWorkspaceWarms.delete(t)}));return this.inFlightWorkspaceWarms.set(t,n),n}async warmWorkspaceCache(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=VT(r,(0,$.VI)(e.withName("LocalRequestContextExecutor.warmWorkspaceCache")),!1),o=await _a(n.ctx,this.gitExecutor,t),s=o?await Ca(n.ctx,this.gitExecutor,o):void 0,i={repoPath:o??void 0,remoteUrl:void 0!==s?Ea(s):void 0};if(this.cachedWorkspaces.set(t,i),void 0!==this.freshSectionWaitMs&&void 0!==i.repoPath){const e=i.repoPath;this.gitInfoSection(e).prefetch((()=>rA((0,y.q6)(),this.gitExecutor,e,JT)))}}catch(e){r.error=e,r.hasError=!0}finally{KT(r)}}gitInfoSection(e){let t=this.reusedGitInfo.get(e);return void 0===t&&(t=new YT,this.reusedGitInfo.set(e,t)),t}rebuildAllCaches(){this.cacheDebounceTimeout&&clearTimeout(this.cacheDebounceTimeout),this.cacheDebounceTimeout=setTimeout((()=>{this.cacheDebounceTimeout=void 0,this.rebuildGlobalCache()}),5e3)}invalidateGlobalCache(){this.globalCache=void 0,this.lastGoodGlobalCache=void 0,this.globalCacheTraceId=void 0}refreshGlobalCache(){this.cacheDebounceTimeout&&(clearTimeout(this.cacheDebounceTimeout),this.cacheDebounceTimeout=void 0),this.rebuildGlobalCache()}rebuildGlobalCache(){const e={stack:[],error:void 0,hasError:!1};try{const t=(0,y.q6)(),r=VT(e,(0,$.VI)(t.withName("LocalRequestContextExecutor.rebuildGlobalCache")),!1);this.globalCacheTraceId=r.span.spanContext().traceId;const n=this.computeGlobalCache(r.ctx);return this.globalCache=n,(this.reduceContextHotPath||void 0!==this.sectionLoadTimeoutMs||void 0!==this.freshSectionWaitMs)&&n.then((e=>{this.globalCache===n&&(this.lastGoodGlobalCache=e)}),(()=>{this.globalCache===n&&(this.globalCache=void 0)})),n}catch(t){e.error=t,e.hasError=!0}finally{KT(e)}}async computeGlobalCache(e){const t={stack:[],error:void 0,hasError:!1};try{const r=VT(t,(0,$.VI)(e.withName("LocalRequestContextExecutor.computeGlobalCache")),!1),n=AbortSignal.timeout(1e3),o=performance.now(),s={},i=(e,t)=>{const r=performance.now();return t.finally((()=>{s[e]=Math.round(performance.now()-r)}))},[a,c,l,u]=await Promise.all([i("cursorRules",this.cursorRulesService.getAllCursorRules(r.ctx)),i("cloudRule",this.cloudRulesService?this.cloudRulesService.getCloudRule(r.ctx):Promise.resolve(null)),i("codebaseRef",this.repositoryProvider.getCodebaseReference(r.ctx,n).catch((()=>{}))),i("subagents",this.subagentsService?this.subagentsService.getAllSubagents().catch((()=>[])):Promise.resolve([]))]),d=Math.round(performance.now()-o);return d>1e3&&ZT.warn(r.ctx,"computeGlobalCache: slow",{totalMs:d,...s,ruleCount:a.length}),{rules:[...this.additionalRules,...a],cloudRule:c,codebaseReference:l,customSubagents:u}}catch(e){t.error=e,t.hasError=!0}finally{KT(t)}}dispose(){this.cacheDebounceTimeout&&(clearTimeout(this.cacheDebounceTimeout),this.cacheDebounceTimeout=void 0),this.fileWatcher&&(this.fileWatcher.dispose(),this.fileWatcher=void 0),this.globalCache=void 0,this.lastGoodGlobalCache=void 0}async collectWorkspaceCaches(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=VT(r,(0,$.VI)(e.withName("LocalRequestContextExecutor.collectWorkspaceCaches")),!1);let o;if(this.grepProvider.getTrackedState)try{o=await this.grepProvider.getTrackedState(this.workspacePaths)}catch{o=void 0}let s=!0,i=!0;return{gitRepos:(await Promise.all(this.workspacePaths.map((async e=>{let r=this.getWorkspaceCache(e);if(void 0===r){if(!t.waitForWorkspaceCache)return s=!1,void this.ensureWorkspaceCacheWarm(n.ctx,e);if(await this.ensureWorkspaceCacheWarm(n.ctx,e),r=this.getWorkspaceCache(e),void 0===r)return void(s=!1)}const a=o?.[e];if(void 0!==a)return void 0!==r.repoPath&&void 0===a.gitStatus&&(i=!1),new Mr.DS({path:r.repoPath,status:a.gitStatus,branchName:a.gitBranchName,remoteUrl:r.remoteUrl,isOriginBacked:Sa(r.remoteUrl)});if(void 0===r.repoPath)return;const c=r.repoPath,{status:l,branchName:u}=void 0===this.freshSectionWaitMs?await rA(n.ctx,t.gitExecutor,c,JT):await this.gitInfoSection(c).read((()=>rA((0,y.q6)(),t.gitExecutor,c,JT)),this.freshSectionWaitMs);return void 0===l&&(i=!1),new Mr.DS({path:r.repoPath,status:l,branchName:u,remoteUrl:r.remoteUrl,isOriginBacked:Sa(r.remoteUrl)})})))).filter((e=>void 0!==e)),gitRepoInfoComplete:s,gitStatusInfoComplete:s&&i}}catch(e){r.error=e,r.hasError=!0}finally{KT(r)}}shareBoundedSectionLoad(e,t,r){if(void 0===this.sectionLoadTimeoutMs)return r();const n=e();if(void 0!==n)return n;const o=r();t(o);const s=()=>{e()===o&&t(void 0)};return o.then(s,s),o}async computeCachedRequestContext(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=VT(n,(0,$.VI)(e.withName("LocalRequestContextExecutor.computeCachedRequestContext")),!1),s=this.projectDir,i=async()=>{const e={stack:[],error:void 0,hasError:!1};try{const t=VT(e,(0,$.VI)(o.ctx.withName("LocalRequestContextExecutor.computeCachedRequestContext.getGlobalData")),!1);if(this.globalCacheTraceId&&t.span.setAttribute("cacheTraceId",this.globalCacheTraceId),!this.reduceContextHotPath&&void 0===this.freshSectionWaitMs){if(void 0===this.globalCache){const e=this.computeGlobalCache(o.ctx);this.globalCache=e,e.catch((()=>{this.globalCache===e&&(this.globalCache=void 0)})),void 0!==this.sectionLoadTimeoutMs&&e.then((t=>{this.globalCache===e&&(this.lastGoodGlobalCache=t)}),(()=>{}))}return this.globalCache}return void 0!==this.lastGoodGlobalCache?this.lastGoodGlobalCache:this.globalCache??this.rebuildGlobalCache()}catch(t){e.error=t,e.hasError=!0}finally{KT(e)}},a=performance.now(),c={},l=(e,t)=>{const r=performance.now();return t.finally((()=>{c[e]=Math.round(performance.now()-r)}))},u=e=>QT(e,this.sectionLoadTimeoutMs),d=(e,t,r)=>this.shareBoundedSectionLoad(e,t,r),h=this.freshSectionWaitMs,p=(e,t)=>void 0===h?t():e.read(t,h),f=void 0===h?o.ctx:(0,y.q6)(),[m,g,w,{gitRepos:v,gitRepoInfoComplete:b,gitStatusInfoComplete:S},k,_,C,E,x,P]=await Promise.all([l("globalCache",u(i())),l("mcpState",u(p(this.reusedMcpState,(()=>d((()=>this.inFlightMcpState),(e=>{this.inFlightMcpState=e}),(()=>this.mcpStateAccessor.getState(f))))))),l("env",nA(o.ctx,this.workspacePaths,{projectDir:s,notesSessionId:t.notesSessionId,agentNotesEnabled:this.agentNotesEnabled,reportProcessWorkingDirectory:this.reportProcessWorkingDirectory,getSmartModeClassifierAutoModeEnabled:this.getSmartModeClassifierAutoModeEnabled,devForceNextSmartModeClassifierBlockToken:this.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:this.getMockPromptTime,isWorkingDirHomeDir:this.isWorkingDirHomeDir,getSandboxEnabled:this.getSandboxEnabled,getSandboxSupported:this.getSandboxSupported,getNetworkAllowlistInfo:this.getNetworkAllowlistInfo,userTerminalHint:this.userTerminalHint,artifactsFolder:this.getArtifactsFolder?.(o.ctx),secretRedactionEnabled:this.secretRedactionEnabled,getComputerUseSupported:this.getComputerUseSupported,getComputerUseDesktop:this.getComputerUseDesktop})),l("git",this.collectWorkspaceCaches(o.ctx,{waitForWorkspaceCache:!0===t.waitForWorkspaceCache,gitExecutor:r})),l("conversationNotes",this.agentNotesEnabled&&s&&t.notesSessionId?zT(s,t.notesSessionId):Promise.resolve(void 0)),l("sharedNotes",this.agentNotesEnabled&&s?GT(s):Promise.resolve(void 0)),l("mcpFileSystemOptions",this.getMcpFileSystemOptions?this.getMcpFileSystemOptions(o.ctx,{timeoutMs:3e3}):Promise.resolve(void 0)),l("attribution",this.isAttributionDisabledByAdmin?this.isAttributionDisabledByAdmin().catch((()=>!0)):Promise.resolve(!1)),l("agentSkills",u(p(this.reusedAgentSkills,(()=>d((()=>this.inFlightAgentSkills),(e=>{this.inFlightAgentSkills=e}),(()=>this.getAgentSkills?this.getAgentSkills(f):Promise.resolve([]))))))),l("adminCommandDenylist",u(p(this.reusedAdminCommandDenylist,(()=>d((()=>this.inFlightAdminCommandDenylist),(e=>{this.inFlightAdminCommandDenylist=e}),(()=>this.getAdminCommandDenylist?this.getAdminCommandDenylist():Promise.resolve(void 0)))))))]),I=m===XT,R=g===XT,T=x===XT,A=P===XT,M=I?this.lastGoodGlobalCache??{rules:[...this.additionalRules],cloudRule:null,codebaseReference:void 0,customSubagents:[]}:m,D=R?{servers:[]}:g,O=T?[]:x,F=A?void 0:P;(I||R||T||A)&&ZT.warn(o.ctx,"computeCachedRequestContext: section load timed out",{timeoutMs:this.sectionLoadTimeoutMs,rulesAndSubagents:I,mcpState:R,agentSkills:T,adminCommandDenylist:A});const N=performance.now()-a;for(const[e,t]of Object.entries(c))o.span.setAttribute(`requestContext.timing.${e}Ms`,t);o.span.setAttribute("requestContext.timing.totalMs",Math.round(N)),N>1e3&&ZT.warn(o.ctx,"computeCachedRequestContext: slow parallel data collection",{durationMs:Math.round(N),...c});const L=this.mcpMetaToolEnabled?iA(D,{alwaysExposeVirtualMcpAuthTool:this.alwaysExposeVirtualMcpAuthTool,slimDescriptors:this.mcpMetaToolSlimDescriptors,inputSchemaJson:this.mcpInputSchemaJson}):void 0,j=this.attributionConfigProvider?.get(),U=!E&&(j?.attribution?.attributeCommitsToAgent??!0),B=!E&&(j?.attribution?.attributePRsToAgent??!0),W=new Mr.bb({rules:M.rules,env:w,gitRepos:v,gitRepoInfoComplete:b,repositoryInfo:M.codebaseReference?[{relativeWorkspacePath:M.codebaseReference.relativeWorkspacePath,repoName:M.codebaseReference.repoName,repoOwner:M.codebaseReference.repoOwner,isTracked:M.codebaseReference.isTracked,isLocal:M.codebaseReference.isLocal,orthogonalTransformSeed:M.codebaseReference.orthogonalTransformSeed,pathEncryptionKey:M.codebaseReference.pathEncryptionKey}]:[],...sA(D,{internalBrowserProvidersOnly:this.mcpMetaToolEnabled&&this.mcpMetaToolSlimDescriptors,inputSchemaJson:this.mcpInputSchemaJson}),conversationNotesListing:k,sharedNotesListing:_,customSubagents:M.customSubagents,mcpFileSystemOptions:C,mcpMetaToolOptions:L,supportsMcpAuth:!0,commitAttributionMessage:U?"enabled":void 0,prAttributionMessage:B?"enabled":void 0,agentSkills:O,adminCommandDenylist:F?.rules??[]});return null!==M.cloudRule&&void 0!==M.cloudRule&&(W.cloudRule=M.cloudRule),this.reportSectionCompleteness&&(W.rulesInfoComplete=!I,W.customSubagentsInfoComplete=!I,W.agentSkillsInfoComplete=!T,W.mcpInfoComplete=!R,W.mcpFileSystemInfoComplete=this.mcpMetaToolEnabled||void 0!==C,W.envInfoComplete=!0,W.gitStatusInfoComplete=S),W}catch(e){n.error=e,n.hasError=!0}finally{KT(n)}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{this.onRequestContext?.();const n=VT(r,(0,$.VI)(e.withName("LocalRequestContextExecutor.execute")),!1);n.span.setAttribute("enableCaching",void 0!==this.fileWatcher),n.span.setAttribute("hasGlobalCache",!!this.globalCache);try{const e=this.gitExecutor.forRequest?.()??this.gitExecutor,r=await this.computeCachedRequestContext(n.ctx,t,e);return new Mr._G({result:{case:"success",value:new Mr.yW({requestContext:r})}})}catch(e){return e instanceof Error||"string"==typeof e?n.span.recordException(e):n.span.recordException(Ba(e)),new Mr._G({result:{case:"error",value:new Mr.nf({error:e instanceof Error?e.message:String(e)})}})}}catch(e){r.error=e,r.hasError=!0}finally{KT(r)}}}function pA(e){return 0!==e.timeout?e.timeout:e.isBackground||e.timeoutBehavior===he._d.BACKGROUND||void 0!==e.hardTimeout&&e.hardTimeout>0?0:3e4}var fA=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class mA{constructor(e,t,r,n){this.permissionsService=e,this.coreExecutor=t,this.ignoreService=r}buildResultFromExit(e){return 0===(e.exitCode??-1)?new he.W4({result:{case:"success",value:new he.QR({...e,stdout:e.outputLocation?"":e.stdout,stderr:e.outputLocation?"":e.stderr})},sandboxPolicy:es(e.sandboxPolicy)}):new he.W4({result:{case:"failure",value:new he.xC({...e,aborted:void 0!==e.abortReason,stdout:e.outputLocation?"":e.stdout,stderr:e.outputLocation?"":e.stderr})},sandboxPolicy:es(e.sandboxPolicy)})}async executeWithPolicy(e,t,r,n,o){const s=Date.now(),i=new AbortController,a=e.signal?AbortSignal.any([e.signal,i.signal]):i.signal,c=setTimeout((()=>{i.abort()}),n);try{let n,l,u,d="",h="",p=null;const f=o?{perRepo:o}:void 0;for await(const o of this.coreExecutor.execute(e,{command:t.command,workingDirectory:r,signal:a,toolCallId:t.toolCallId,conversationId:t.conversationId,requestId:t.requestId,secretScopeId:t.secretScopeId,sandboxPolicy:f,fileOutputThresholdBytes:t.fileOutputThresholdBytes,pipeStdin:!1}))"stdout"===o.type?d+=o.data:"stderr"===o.type?h+=o.data:"exit"===o.type&&(p=null!=o.code?0|o.code:null,l=o.outputLocation,n=o.aborted?a.aborted?i.signal.aborted&&a.reason===i.signal.reason?he.Lv.TIMEOUT:he.Lv.USER_ABORT:he.Lv.UNSPECIFIED:void 0,u=bw(o.localExecutionTimeMs));clearTimeout(c);const m=Date.now()-s,g={command:t.command,workingDirectory:r,exitCode:void 0!==n?-1:p??-1,signal:void 0!==n?"SIGTERM":"",abortReason:n,stdout:d,stderr:h,executionTime:m,localExecutionTimeMs:u,sandboxPolicy:o,outputLocation:l};return this.buildResultFromExit(g)}catch(s){return clearTimeout(c),i.signal.aborted&&!e.signal.aborted?new he.W4({result:{case:"timeout",value:new he.eG({command:t.command,workingDirectory:r,timeoutMs:n})},sandboxPolicy:es(o)}):e.signal.aborted?new he.W4({result:{case:"rejected",value:new he.pZ({command:t.command,workingDirectory:r,reason:"Command aborted"})},sandboxPolicy:es(o)}):new he.W4({result:{case:"spawnError",value:new he.mJ({command:t.command,workingDirectory:r,error:s instanceof Error?s.message:"Unknown error"})},sandboxPolicy:es(o)})}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(r,(0,$.VI)(e.withName("LocalShellExecutor.execute")),!1).ctx;(0,$.HF)(n,"LocalShellExecutor.execute");const o=t.command,s=t.requestedSandboxPolicy?Yo(t.requestedSandboxPolicy):void 0,i=t.workingDirectory||await this.coreExecutor.getCwd(t.conversationId),a=pA(t),c=(0,Ho.o1)(i);if(!t.parsingResult)return new he.W4({result:{case:"spawnError",value:new he.mJ({command:o,workingDirectory:c,error:"Parsing result is required"})}});let l;if(_o(t)){const e=await this.permissionsService.shouldEnforceShellInvariantBlocks(n,{workingDirectory:c,skipUnsafeWorkingDirectoryBlock:!0,command:o,parsingResult:t.parsingResult,toolCallId:t.toolCallId,resolveSkippedApprovalPolicy:!0},s);if("block"===e.kind)return new he.W4({result:du(o,c,e.reason)});l=e.policy??s}else{const e=await this.permissionsService.shouldBlockShellCommand(n,o,{workingDirectory:c,timeout:a,parsingResult:t.parsingResult,toolCallId:t.toolCallId,smartModeApprovalReason:t.smartModeApproval?.reason,smartModeApprovalRequestId:t.smartModeApproval?.requestId,hookApprovalRequirement:So(t)},s);if("block"===e.kind)return new he.W4({result:du(o,c,e.reason)});l=e.policy}return l=await Ja(l,{command:o,workingDirectory:c,parsingResult:t.parsingResult,permissionsService:this.permissionsService,ignoreService:this.ignoreService}),this.executeWithPolicy(n,t,i,a,l)}catch(e){r.error=e,r.hasError=!0}finally{fA(r)}}}var gA=r("../proto/dist/generated/agent/v1/shell_allowlist_precheck_exec_pb.js");class wA{constructor(e){this.permissionsService=e}async execute(e,t){const r=t.parsingResult??new he.HO,n=await this.permissionsService.isShellCommandFullyAllowlisted(e,t.command,{workingDirectory:t.workingDirectory,parsingResult:r,classifierResult:t.classifierResult,toolCallId:t.toolCallId});return new gA.e({allowlisted:n})}}class yA{constructor(e){this.shellStreamExecutor=e}async execute(e,t,r){return""===t.toolCallId.trim()?new he.jK({status:he.iA.NOT_FOUND}):this.shellStreamExecutor.forceBackgroundByToolCallId(e,t.toolCallId)}}var vA=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const bA=(0,l.h)("local-exec:shell-stream");class SA{constructor(e,t){this.iterator=e,this.timeoutMs=t,this.pendingPromise=null,this.stopPromise=new Promise((e=>{this.stopResolve=e}))}stop(e){return void 0===this.stopReason&&(this.stopReason=e,this.stopResolve?.(),!0)}get timedOut(){return"background"===this.stopReason?.kind&&this.stopReason.reason===he.Jg.TIMEOUT}get backgroundRequested(){return"background"===this.stopReason?.kind}get backgroundReasonValue(){return"background"===this.stopReason?.kind?this.stopReason.reason:void 0}get stopReasonValue(){return this.stopReason}async*iterate(){this.timer=setTimeout((()=>{this.stop({kind:"background",reason:he.Jg.TIMEOUT})}),this.timeoutMs);try{for(;;){if(void 0!==this.stopReason)return;this.pendingPromise=this.iterator.next();const e=await Promise.race([this.pendingPromise.then((e=>({kind:"result",result:e}))),this.stopPromise.then((()=>({kind:"stopped"})))]);if("stopped"===e.kind)return;if(this.pendingPromise=null,e.result.done)return;yield e.result.value}}finally{clearTimeout(this.timer)}}requestBackground(){return this.stop({kind:"background",reason:he.Jg.USER_REQUEST})}abort(){this.stop({kind:"abort"})}getHandoffIterator(){if(this.pendingPromise){const e=this.pendingPromise;this.pendingPromise=null;let t=!1;return{next:async()=>t?this.iterator.next():(t=!0,e)}}return this.iterator}}function kA(){let e=()=>{};return{promise:new Promise((t=>{e=t})),resolve:e}}class _A{constructor(e,t,r,n){this.permissionsService=e,this.coreExecutor=t,this.ignoreService=r,this.backgroundShellManager=n,this.activeForegroundExecutions=new Map,this.pendingShells=new Map}hasForegroundWork(){return this.activeForegroundExecutions.size>0||this.pendingShells.size>0}async forceBackgroundByToolCallId(e,t){const r=this.pendingShells.get(t),n=void 0===r||r.awaitingApproval?this.activeForegroundExecutions.get(t):await async function(e,t){const[r,n]=e.withCancel();try{return await Promise.race([t.registered.promise,(0,y.uk)(r).then((()=>{}))])}finally{n()}}(e,r),o=n?.requestBackground();return o?new he.jK({status:he.iA.ACCEPTED,shellResult:o}):new he.jK({status:he.iA.NOT_FOUND})}pendingFrom(e){return{execute:(t,r,n)=>this.whilePending(r,(()=>e.get(ee).execute(t,r,n)))}}execute(e,t){return this.whilePending(t,(r=>this.run(e,t,r)))}async*whilePending(e,t){let r=this.pendingShells.get(e.toolCallId);void 0===r&&(r={awaitingApproval:!1,registered:kA()},""!==e.toolCallId&&e.timeoutBehavior===he._d.BACKGROUND&&this.pendingShells.set(e.toolCallId,r));try{yield*t(r)}finally{this.settle(e.toolCallId,r,void 0)}}settle(e,t,r){this.pendingShells.get(e)===t&&this.pendingShells.delete(e),t.registered.resolve(r)}async*run(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{e.signal?.throwIfAborted(),function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(n,(0,$.VI)(e.withName("LocalShellStreamExecutor.execute")),!1);const o=t.command;let s=t.requestedSandboxPolicy?Yo(t.requestedSandboxPolicy):void 0;const i=t.workingDirectory||await this.coreExecutor.getCwd(t.conversationId),a=pA(t),c=(0,Ho.o1)(i),l=Date.now(),u=performance.now(),d=new he.HO($o(o).structured),h=ps({command:o,parsingResult:d,blockedCommands:t.adminCommandDenylist});if(void 0!==h)return void(yield new he.FI({event:{case:"rejected",value:new he.pZ({command:o,workingDirectory:c,reason:h})}}));const p=await this.permissionsService.shouldEnforceShellInvariantBlocks(e,{workingDirectory:c,skipUnsafeWorkingDirectoryBlock:!0,command:o,parsingResult:d,toolCallId:t.toolCallId,resolveSkippedApprovalPolicy:_o(t)},s);if("block"===p.kind)return"permissionsConfig"===p.reason.type?void(yield new he.FI({event:{case:"permissionDenied",value:new he.jn({command:o,workingDirectory:c,error:"Command blocked by permissions configuration",isReadonly:p.reason.isReadonly??!1})}})):void(yield new he.FI({event:{case:"rejected",value:new he.pZ({command:o,workingDirectory:c,reason:uu(p.reason)})}}));if(bA.info(e,"Shell stream: approval gate reached",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,hasSmartModeApproval:void 0!==t.smartModeApproval,hasSmartModeApprovalReason:void 0!==t.smartModeApproval?.reason,hasSmartModeApprovalRequestId:void 0!==t.smartModeApproval?.requestId,requestedPolicyType:s?.type??"undefined",parserCommandCount:d.executableCommands.length,classifierCommandCount:t.classifierResult?.commands.length??0,commandLength:o.length}),_o(t)){const r=p.policy??s;bA.info(e,"Shell stream: skipped local approval",{toolCallId:t.toolCallId,requestedPolicyType:s?.type??"undefined",effectivePolicyType:r?.type??"undefined"}),s=r}else{r.awaitingApproval=!0;const n=await this.permissionsService.shouldBlockShellCommand(e,o,{workingDirectory:c,timeout:a,parsingResult:d,toolCallId:t.toolCallId,classifierResult:t.classifierResult,smartModeApprovalReason:t.smartModeApproval?.reason,smartModeApprovalRequestId:t.smartModeApproval?.requestId,hookApprovalRequirement:So(t),onApprovalRequested:()=>{r.registered.resolve(void 0),r.registered=kA()}},s);if(r.awaitingApproval=!1,"block"===n.kind){if(bA.info(e,"Shell stream: approval gate blocked command",{toolCallId:t.toolCallId,blockReasonType:n.reason.type,hasSmartModeApproval:void 0!==t.smartModeApproval,skipApproval:t.skipApproval}),"permissionsConfig"===n.reason.type)return void(yield new he.FI({event:{case:"permissionDenied",value:new he.jn({command:o,workingDirectory:c,error:"Command blocked by permissions configuration",isReadonly:n.reason.isReadonly??!1})}}));const r=uu(n.reason);return void(yield new he.FI({event:{case:"rejected",value:new he.pZ({command:o,workingDirectory:c,reason:r})}}))}s=n.policy,bA.info(e,"Shell stream: approval gate allowed command",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,effectivePolicyType:s.type})}s=await Ja(s,{command:o,workingDirectory:c,parsingResult:d,permissionsService:this.permissionsService,ignoreService:this.ignoreService}),yield new he.FI({event:{case:"start",value:new he.tD({sandboxPolicy:es(s)})}});const f=t.timeoutBehavior===he._d.BACKGROUND,m=f&&!t.closeStdin&&void 0===t.smartModeApproval,g=new AbortController,w=f?g.signal:e.signal?AbortSignal.any([e.signal,g.signal]):g.signal,y=!0,v=s?{perRepo:s}:void 0,b=this.coreExecutor.execute(e,{command:o,workingDirectory:i,signal:w,toolCallId:t.toolCallId,conversationId:t.conversationId,requestId:t.requestId,secretScopeId:t.secretScopeId,sandboxPolicy:v,fileOutputThresholdBytes:t.fileOutputThresholdBytes,pipeStdin:m,showElapsedTime:y});let S;f||(S=setTimeout((()=>g.abort()),a));const k=f?new SA(b[Symbol.asyncIterator](),a):null;let _,C,E,x="",P=!1,I=!1;const R=t.toolCallId&&k?{requestBackground:()=>{if(k.requestBackground())return E=E??this.backgroundShellManager.generateShellId(),new he.W4({result:{case:"success",value:new he.QR({shellId:E,pid:C,command:o,workingDirectory:c,msToWait:bw(performance.now()-u),backgroundReason:he.Jg.USER_REQUEST,interleavedOutput:x})}})}}:void 0;t.toolCallId&&R&&this.activeForegroundExecutions.set(t.toolCallId,R),this.settle(t.toolCallId,r,R);const T=()=>{t.toolCallId&&this.activeForegroundExecutions.get(t.toolCallId)===R&&this.activeForegroundExecutions.delete(t.toolCallId)},A=()=>{k&&!k.backgroundRequested&&(g.abort(),k.abort())};let M;k&&e.signal&&(e.signal.aborted?A():e.signal.addEventListener("abort",A,{once:!0}));const D=t.hardTimeout;void 0!==D&&D>0&&(M=setTimeout((()=>{void 0!==E?this.backgroundShellManager.abort(E)||g.abort():(P=!0,g.abort(),k?.abort())}),D));const O=k?.iterate()??b;try{for await(const r of O)if("stdout"===r.type)x+=r.data,yield new he.FI({event:{case:"stdout",value:new he.o0({data:r.data})}});else if("stderr"===r.type)x+=r.data,yield new he.FI({event:{case:"stderr",value:new he.Db({data:r.data})}});else if("stdin_ready"===r.type)_=r.stdin,C=r.pid;else if("exit"===r.type){let n;I=!0,r.aborted&&(n=e.signal?.aborted?he.Lv.USER_ABORT:k?.timedOut||g.signal.aborted?he.Lv.TIMEOUT:he.Lv.USER_ABORT),yield new he.FI({event:{case:"exit",value:new he.vb({code:(r.code??-1)>>>0,cwd:await this.coreExecutor.getCwd(t.conversationId),outputLocation:r.outputLocation,aborted:r.aborted,abortReason:n,localExecutionTimeMs:bw(r.localExecutionTimeMs)})}})}}catch(r){if(!(r instanceof Eo.SandboxUnsupportedError))throw r;const n=s?.type??"unknown";return bA.debug(e,"Shell stream: sandbox policy unsupported on this host",{toolCallId:t.toolCallId,policyType:n,reason:r.reason}),void(yield new he.FI({event:{case:"sandboxUnsupported",value:new he.rI({command:o,workingDirectory:c,sandboxPolicyType:n,reason:r.reason??r.message,isReadonly:"workspace_readonly"===n})}}))}finally{clearTimeout(S),k?.backgroundRequested||clearTimeout(M),T(),!k||k.backgroundRequested||I||g.abort(),e.signal?.removeEventListener("abort",A)}if(k?.backgroundRequested&&!P){const r=E??this.backgroundShellManager.generateShellId();E=r;const n=k.backgroundReasonValue===he.Jg.USER_REQUEST?he.Jg.USER_REQUEST:he.Jg.TIMEOUT,s=n===he.Jg.USER_REQUEST?Math.round(performance.now()-u):a;await this.backgroundShellManager.adopt({ctx:e,shellId:r,command:o,workingDirectory:c,toolCallId:t.toolCallId,sandboxPolicy:v,initialOutput:x,stdin:_,pid:C,abortController:g,eventIterator:k.getHandoffIterator(),startTime:l,monotonicStartMs:u,showElapsedTime:y,description:t.description,outputNotification:t.outputNotification,onCleanup:()=>clearTimeout(M)}),yield new he.FI({event:{case:"backgrounded",value:new he.Y9({shellId:r,command:o,workingDirectory:c,pid:C,msToWait:y?s:void 0,reason:n})}})}else e.signal?.aborted&&void 0!==k?.stopReasonValue?(clearTimeout(M),yield new he.FI({event:{case:"exit",value:new he.vb({code:4294967295,cwd:await this.coreExecutor.getCwd(t.conversationId),aborted:!0,abortReason:he.Lv.USER_ABORT})}})):clearTimeout(M)}catch(e){n.error=e,n.hasError=!0}finally{vA(n)}}}const CA={kind:"absent"};class EA{constructor(e){this.cells=new Map,this.takenCells=new WeakMap,this.collectedCells=new FinalizationRegistry((e=>{void 0===this.cells.get(e)?.deref()&&this.cells.delete(e)})),this.claims=new Map,this.nextGeneration=0,this.entries=new mo.q({max:1e3,ttl:6e4,ttlResolution:0,perf:e})}begin(e){this.entries.purgeStale();const t=++this.nextGeneration;return this.claims.set($A(e),t),t}record(e,t,r){if(!this.claim(e,r))return;const n=$A(e);this.entries.set(n,{recorded:t,generation:r}),this.commitGeneration(n,r)}forget(e,t){if(!this.claim(e,t))return;const r=$A(e);this.entries.delete(r),this.commitGeneration(r,t)}end(e,t){this.claim(e,t)}take(e){const t=$A(e),r=this.entries.get(t);if(void 0===r)return;const n=this.entries.getRemainingTTL(t);this.entries.delete(t);let o=this.cells.get(t)?.deref();void 0===o&&(o={committed:r.generation},this.cells.set(t,new WeakRef(o)),this.collectedCells.register(o,t));const s={read:e,recorded:r.recorded,remainingTtlMs:n,generation:r.generation};return this.takenCells.set(s,o),s}restore(e){const t=this.takenCells.get(e);if(void 0===t||t.committed!==e.generation)return;const r=$A(e.read);this.entries.has(r)||!Number.isFinite(e.remainingTtlMs)||e.remainingTtlMs<=0||this.entries.set(r,{recorded:e.recorded,generation:e.generation},{ttl:e.remainingTtlMs})}commitGeneration(e,t){const r=this.cells.get(e)?.deref();void 0!==r&&(r.committed=t)}claim(e,t){const r=$A(e);return this.claims.get(r)===t&&(this.claims.delete(r),!0)}}class xA{constructor(){this.views=new mo.q({max:1e3})}get(e){return this.views.get(e)}set(e,t){this.views.set(e,t)}forget(e){this.views.delete(e)}recordWrite(e,t){if(t.length>Ns)return void this.views.delete(e);const r=(0,lo.createHash)("sha256").update(t).digest("hex");this.views.set(e,{kind:"fingerprint",byteLength:t.length,sha256:r})}recordDelete(e){this.views.set(e,CA)}}async function PA(e,t){if(void 0===e)return!1;try{if("absent"===e.kind)return await AA(t);const r=await TA(t);return void 0===r||r.byteLength!==e.byteLength||r.sha256!==e.sha256}catch{return!1}}async function IA(e,t){if("fingerprint"!==e?.kind)return!1;try{return!await AA(t)}catch{return!1}}class RA{constructor(e,t,r,n,o){this.inner=e,this.reads=t,this.permissionsService=r,this.workspacePath=n,this.views=o}async execute(e,t,r){const n=!0===r?.recordAgentView?(0,Ho.o1)(t.path,this.workspacePath):void 0,o=function(e,t){if(""!==e.toolCallId&&void 0===e.offset&&void 0===e.limit)return{toolCallId:e.toolCallId,resolvedPath:(0,Ho.o1)(e.path,t)}}(t,this.workspacePath);if(void 0===o){const o=await this.inner.execute(e,t,r);return this.forgetViewReadPast(n,o),o}const s=this.reads.begin(o);try{let i,a;try{i=await SS(this.permissionsService,o.resolvedPath)}catch{return await this.readAndForget(e,t,r,o,s,n)}if(!1!==i&&"needsApproval"!==i.type)return await this.readAndForget(e,t,r,o,s,n);if(!1!==i){const i=await this.inner.execute(e,t,r),a=await async function(e,t){if("success"===e.result.case&&"content"===e.result.value.output.case)try{return await TA(t)}catch{return}}(i,o.resolvedPath);return this.commit(o,s,i,a,n),i}try{a=await TA(o.resolvedPath)}catch{return await this.readAndForget(e,t,r,o,s,n)}const c=await this.inner.execute(e,t,r);return this.commit(o,s,c,a,n),c}finally{this.reads.end(o,s)}}commit(e,t,r,n,o){let s;if("fileNotFound"===r.result.case?s=CA:void 0!==n&&"success"===r.result.case&&"content"===r.result.value.output.case&&(s={kind:"fingerprint",...n}),void 0===s)return this.reads.forget(e,t),void this.forgetViewReadPast(o,r);this.reads.record(e,s,t),void 0!==o&&this.views?.set(o,s)}async readAndForget(e,t,r,n,o,s){const i=await this.inner.execute(e,t,r);return this.reads.forget(n,o),this.forgetViewReadPast(s,i),i}forgetViewReadPast(e,t){void 0===e||"success"!==t.result.case&&"fileNotFound"!==t.result.case||this.views?.forget(e)}}async function TA(e){try{const t=await(0,fo.stat)(e);if(!t.isFile()||t.size>Ns)return}catch(e){return MA(e)}let t;try{t=await(0,fo.open)(e,function(){const e=go.constants;return e.O_RDONLY|(e.O_NONBLOCK??0)}());const r=await t.stat();if(!r.isFile()||r.size>Ns)return;const n=(0,lo.createHash)("sha256");let o=0;const s=Buffer.alloc(65536);for(;o<=Ns;){const{bytesRead:e}=await t.read(s,0,s.length,o);if(0===e)break;o+=e,n.update(s.subarray(0,e))}if(o>Ns)return;return{byteLength:o,sha256:n.digest("hex")}}catch(e){return MA(e)}finally{await(t?.close())}}async function AA(e){try{return await(0,fo.stat)(e),!0}catch(e){if(DA(e))return!1;throw e}}function $A({toolCallId:e,resolvedPath:t}){return`${e}\0${t}`}function MA(e){if(!DA(e))throw e}function DA(e){const t=Ua(e);return"ENOENT"===t||"ENOTDIR"===t}var OA=r("../proto/dist/generated/agent/v1/web_fetch_allowlist_precheck_exec_pb.js");class FA{constructor(e){this.permissionsService=e}async execute(e,t){const r=await this.permissionsService.isWebFetchFullyAllowlisted(e,{url:t.url});return new OA.M({allowlisted:r})}}var NA=r("node:constants");const LA=[".md",".markdown",".mdown",".mkd",".mkdn",".mdx"],jA=/(?:^|\/)\.cursor\/projects\/[^/]+\/canvases\/[^/]+\.canvas\.tsx$/i;function UA(e){const t=e.trim().toLowerCase();return LA.some((e=>t.endsWith(e)))}function BA(e){return jA.test(e.trim().replace(/\\/g,"/"))}const WA="win32"===process.platform;process.platform;var HA=r("../proto/dist/generated/agent/v1/write_exec_pb.js");class qA extends Error{constructor(e,t){super(t),this.name="SymlinkRefusedError",this.path=e}}function zA(e,{nonBlocking:t}){const r=go.constants;let n=e;return"number"==typeof r.O_NOFOLLOW&&(n|=r.O_NOFOLLOW),t&&"number"==typeof r.O_NONBLOCK&&(n|=r.O_NONBLOCK),"number"==typeof r.O_CLOEXEC&&(n|=r.O_CLOEXEC),n}async function GA(e,t,r){const{fd:n}=await async function(e,t,r){let n;try{n=await async function(e,t){try{return await(0,fo.open)(e,zA(t,{nonBlocking:!0}),438)}catch(r){const n=Ua(r);if(("EAGAIN"===n||"EWOULDBLOCK"===n)&&await async function(e){try{return(await(0,fo.lstat)(e)).isFile()}catch{return!1}}(e))return await(0,fo.open)(e,zA(t,{nonBlocking:!1}),438);throw r}}(e,t)}catch(t){if(function(e){const t=Ua(e);return"ELOOP"===t||"EMLINK"===t||"EPERM"===t&&"number"==typeof go.constants.O_NOFOLLOW}(t))throw new qA(e,`Refusing to ${r} through a symlink at ${e}`);throw t}try{let t;try{t=(0,go.realpathSync)(e)}catch{throw new qA(e,`Cannot verify canonical path before ${r}: ${e}`)}if(t!==e)throw new qA(e,`Refusing ${r}: ${e} now resolves through a symlinked parent to ${t}`);const o=await n.stat();if(!o.isFile())throw new qA(e,`Refusing to ${r} non-regular file at ${e}`);return{fd:n,stats:o}}catch(e){throw await n.close(),e}}(e,go.constants.O_WRONLY|go.constants.O_CREAT,"write");try{await n.truncate(0);const e=function(e){return Buffer.isBuffer(e)?e:Buffer.from(e)}(t);let o=0;for(;o<e.length;){const{bytesWritten:t}=await n.write(e,o,e.length-o,o);if(0===t)break;o+=t}r?.flush&&await n.sync()}finally{await n.close()}}var VA=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const KA=(0,l.h)("LocalWriteExecutor"),JA=(0,u.Pu)("local_exec.write.encoding_check",{description:"Text writes that landed, per encoding detector (mojibake, U+FFFD): whether the written text holds the pattern and holds more of it than the file did, and for a detection what the file held, its extension family, encoding and the machine's Windows code page",labelNames:["detector","outcome","file","ext","encoding","code_page","run_count","delta","before_count","pattern"]}),ZA=async(e,t,r,n)=>{const o=setTimeout((()=>{KA.warn(e,`[watchdog, LocalWriteExecutor] ${t} still not completed after ${r}ms`)}),r);try{return await n()}finally{clearTimeout(o)}};function XA(e){return new Error(`Could not create ${e}: directory creation exceeded the path depth and was stopped.`)}async function QA(e){try{return(await(0,fo.stat)(e)).isDirectory()?"directory":"present"}catch(e){if("ENOENT"===Ua(e))return"missing";throw e}}async function YA(e,t){const r=[];let n=e;for(let o=0;o<=t;o+=1){const t=await QA(n);if("directory"===t)return r.reverse(),r;if("present"===t)return await(0,fo.mkdir)(n,{recursive:!1}),r.reverse(),r;r.push(n);const o=(0,s.dirname)(n);if(o===n){const t=new Error(`ENOENT: no such file or directory, mkdir '${e}'`);throw t.code="ENOENT",t.syscall="mkdir",t.path=e,t}n=o}throw XA(e)}class e${constructor(e,t,r,{workspacePaths:n,workspacePath:o,worktreeMainPath:s,projectDir:i,onWriteForAiTracking:a,writeFileMutationGuard:c,toolCallReads:l,agentFileViews:u}){this.fileChangeTracker=e,this.permissionsService=t,this.pendingDecisionProvider=r,this.workspacePaths=n,this.workspacePath=o,this.worktreeMainPath=s,this.projectDir=i,this.onWriteForAiTracking=a,this.writeFileMutationGuard=c,this.toolCallReads=l,this.agentFileViews=u}async execute(e,t,r){if(function(e){if(!e.startsWith("file://"))return!1;try{return(0,Fu.fileURLToPath)(e),!1}catch{return!0}}(t.path))return new HA.v3({result:{case:"error",value:new HA.QM({path:t.path,error:`${t.path} is not a valid file URL. Use an absolute path instead.`})}});const n=(0,Ho.o1)(t.path,this.workspacePath),o=this.toolCallReads,s=void 0!==o&&""!==t.toolCallId?o.take({toolCallId:t.toolCallId,resolvedPath:n}):void 0,i=!0===r?.refuseUnreadChanges?this.agentFileViews?.get(n):void 0,a={writeStarted:!1},c=()=>{void 0===s||a.writeStarted||o?.restore(s)};try{const r=await this.executeWithRecord(e,t,n,s?.recorded,i,a);return n$(r)&&c(),r}catch(e){throw c(),e}}async executeWithRecord(e,t,r,n,o,i){const a={stack:[],error:void 0,hasError:!1};try{const c=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(a,(0,$.VI)(e.withName("LocalWriteExecutor.execute")),!1).ctx,l=(t.path,t.fileText),u=t.fileBytes.length>0?t.fileBytes:void 0,d=["assets","agent-tools","swarm-agents"],h=Qv(r,d)||void 0!==this.projectDir&&!this.workspacePaths.some((e=>{return t=e,n=r,WA&&(t=t.toLowerCase(),n=n.toLowerCase()),t===n||(t.charAt(t.length-1)!==s.sep&&(t+=s.sep),n.startsWith(t));var t,n}))&&Yv(this.projectDir,r,d);if((0,Ho.fl)({targetPath:r,workspacePaths:this.workspacePaths,mainWorktreePath:this.worktreeMainPath}))return new HA.v3({result:{case:"error",value:new HA.QM({path:r,error:Ho.PS})}});let p,f,m,g,w=!1;try{const e=await(0,fo.stat)(r);if(g=511&e.mode,e.size<=Vo){const e=await ZA(c,"readText before write",3e3,(()=>Ai(r,t.encodingHint)));p=e.text,f=e.encoding,m=Ig(e)}else w=!0}catch(e){w="ENOENT"!==Ua(e)}const y=await fb(r),v=y.resolvedPath,b=async()=>{return await PA(n,v)?JI(r):(t=n,void 0!==(e=o)&&void 0!==t&&e.kind===t.kind&&("absent"===e.kind||"fingerprint"===t.kind&&e.byteLength===t.byteLength&&e.sha256===t.sha256)||!await PA(o,v)?void 0:ZI(r));var e,t};if(t.planMode&&!await ZA(c,"isPlanModeAllowedWriteTarget",3e3,(()=>async function(e,t){switch(t.resolution.status){case"resolved":case"newFile":return UA(t.resolvedPath)||BA(t.resolvedPath)||await async function(e,t){if(!BA(e))return!1;const r=await fb((0,s.dirname)(e));return t===(0,s.join)(r.resolvedPath,(0,s.basename)(e))}(e,t.resolvedPath);case"danglingSymlink":{const e=await async function(e){let t=e;for(let e=0;e<40;e++){let e;try{e=await(0,fo.readlink)(t)}catch(e){const r=Ua(e);return"ENOENT"===r||"EINVAL"===r?t:void 0}t=(0,s.resolve)((0,s.dirname)(t),e)}}(t.resolvedPath);return void 0!==e&&UA(e)}case"permissionDenied":case"symlinkLoop":case"unknownError":return!1;default:return t.resolution,!1}}(r,y))))return new HA.v3({result:{case:"rejected",value:new HA.en({path:r,reason:"Cannot edit non markdown files in plan mode"})}});const S=(".cursorignore"===(r.split(s.sep).pop()?.toLowerCase()??"")?{type:"permissionsConfig"}:void 0)??await ZA(c,"permissionsService.shouldBlockWrite",3e3,(()=>this.permissionsService.shouldBlockWrite(c,v,l)));if(S){const e=await ZA(c,"handleBlockReason",3e3,(()=>lu(S,{onNeedsApproval:async(e,n)=>{const o="fileEdit"!==n?.type||n.isNewFile,s="fileEdit"===n?.type?n.diffString:l,i="fileEdit"===n?.type?n.blockReason:void 0,a=await b();if(void 0!==a)return t$(r,a);const c=await this.pendingDecisionProvider.requestApproval({type:xg.Write,details:{path:r,reason:e,isNewFile:o,diffString:s,before:p,after:l,blockReason:i},toolCallId:t.toolCallId});return c.approved?null:new HA.v3({result:{case:"rejected",value:new HA.en({path:r,reason:c.reason||""})}})},onUserRejected:e=>new HA.v3({result:{case:"rejected",value:new HA.en({path:r,reason:e||""})}}),onPermissionDenied:(e,t)=>new HA.v3({result:{case:"permissionDenied",value:new HA.U7({path:r,error:e,isReadonly:t?.isReadonly??!1})}})})));if(null!==e)return e}const k=await ZA(c,"anotherSpellingRefusal",3e3,(()=>async function(e){const t=(0,s.basename)(e);let r;try{if(!(await(0,fo.stat)(e)).isFile())return;const n=await(0,fo.readdir)((0,s.dirname)(e));if(n.includes(t))return;const o=t.normalize("NFC");if(n.some((e=>e.normalize("NFC")===o)))return;const i=t.toLowerCase(),a=n.filter((e=>e.toLowerCase()===i)),c=o.toLowerCase();r=a.length>0?a:n.filter((e=>e.normalize("NFC").toLowerCase()===c))}catch{return}const n=1===r.length?r[0]:void 0;return void 0===n?`${t} names an existing file that this folder lists under another name, so writing it would replace that file. Nothing was written. List the folder and write the file by its listed name to change it; for a new file, choose a different name.`:`${t} names the existing file ${n}: this volume does not tell names apart by case, so writing it would replace ${n}. Nothing was written. To change that file, write ${n}; for a new file, choose a name no file in this folder has in any case.`}(r)));if(void 0!==k)return new HA.v3({result:{case:"error",value:new HA.QM({path:r,error:k})}});const _=(0,s.dirname)(v);if(await IA(n,_))return t$(r,JI(r));if(await IA(o,_))return t$(r,ZI(r));let C,E,x,P;try{C=await ZA(c,"mkdir",3e3,(()=>async function(e){const t=function(e){let t=0,r=e;for(;;){const e=(0,s.dirname)(r);if(e===r)return t;t+=1,r=e}}(e),r=t+4;let n=0,o=0,i=await YA(e,t),a=0;for(;a<i.length;){const c=i[a];if(n+=1,n>r)throw XA(e);try{await(0,fo.mkdir)(c,{recursive:!1})}catch(r){const n=Ua(r);if("EEXIST"===n){if("directory"!==await QA(c))throw r;a+=1;continue}if("ENOENT"===n){const n=(0,s.dirname)(c);if(n===c||"missing"!==await QA(n))throw r;i=await YA(e,t),a=0,o=0;continue}throw r}o+=1,a+=1}return o}(_)))}catch(e){const t=Ua(e);return"EACCES"===t||"EPERM"===t?new HA.v3({result:{case:"permissionDenied",value:new HA.U7({path:r,directory:_,operation:"create_directory",error:"Permission denied"})}}):new HA.v3({result:{case:"error",value:new HA.QM({path:r,error:Ba(e)})}})}if(void 0!==u)E=u,x=0;else{const e=await ZA(c,"getBufferForWrite",3e3,(()=>Mi(r,l,this.workspacePath,t.encodingHint)));E=e.buffer,x=e.lines,P=e.format.encoding}const I=()=>ZA(c,"writeFile",3e3,(async()=>{const e=await b();if(void 0!==e)throw new Error(e);let t;c.signal.throwIfAborted(),i.writeStarted=!0,await GA(v,E,{flush:!0}),this.agentFileViews?.recordWrite(r,E),void 0!==P&&await $i(r,{buffer:E,encoding:P});try{t=await(0,fo.open)((0,s.dirname)(v),NA.default.O_RDONLY),await t.sync()}catch{}finally{await(t?.close())}}));let R,T=!1;const A=async()=>{try{await I()}catch(e){throw R=e,T=!0,e}};try{void 0===this.writeFileMutationGuard?await I():await this.writeFileMutationGuard.runExclusive(v,A)}catch(e){if(void 0!==this.writeFileMutationGuard&&(!T||e!==R))return new HA.v3({result:{case:"error",value:new HA.QM({path:r,error:e instanceof Error?e.message:String(e)})}});if(e instanceof qA)return new HA.v3({result:{case:"permissionDenied",value:new HA.U7({path:r,directory:"",operation:"create_file",error:e.message})}});const t=Ua(e);return"EACCES"===t||"EPERM"===t?new HA.v3({result:{case:"permissionDenied",value:new HA.U7({path:r,directory:"",operation:"create_file",error:"Permission denied"})}}):"ENOSPC"===Ua(e)?new HA.v3({result:{case:"noSpace",value:new HA.bM({path:r})}}):"EDQUOT"===t?new HA.v3({result:{case:"error",value:new HA.QM({path:r,error:"Agent-store quota exceeded: this write was rejected because the storage quota is full. Nothing was written; your local copy is intact. Delete or truncate files to free space (including resolved *.conflict* files), then retry. Do not retry the same write without freeing space first."})}}):new HA.v3({result:{case:"error",value:new HA.QM({path:r,error:Ba(e)})}})}if(this.fileChangeTracker&&void 0===u&&!h&&!w){const e={...t.toolCallId?{toolCallId:t.toolCallId}:{},...v===r?{}:{writtenPath:v},...void 0===g?{}:{beforeMode:g},...C>0?{createdDirectories:C}:{}};await this.fileChangeTracker.trackChange(r,p,l,e,m)}if(this.onWriteForAiTracking&&void 0===u&&!h){const e=t.toolCallId?{toolCallId:t.toolCallId}:{};try{await this.onWriteForAiTracking({path:r,beforeContent:p,afterContent:l,metadata:e})}catch(e){KA.warn(c,"onWriteForAiTracking failed (write succeeded)",{path:r,error:e instanceof Error?e.message:String(e)})}}const M=E.byteLength;let D;if(void 0!==u||w||h||this.recordEncodingChecks(c,r,p,f,l),t.returnFileContentAfterWrite)try{D=await ZA(c,"readText after write",3e3,(()=>Ti(r,t.encodingHint)))}catch{}return new HA.v3({result:{case:"success",value:new HA.j6({path:r,linesCreated:x,fileSize:M,...void 0!==D&&{fileContentAfterWrite:D}})}})}catch(e){a.error=e,a.hasError=!0}finally{VA(a)}}recordEncodingChecks(e,t,r,n,o){try{const i={path:t,encoding:n,pages:(s=Il.pages(),"failed"===s?"none":s)};for(const t of function(e,t,r){return[Cc(e,t,r),Ec(e,t,r)]}(r,n,o))JA.increment(e,1,Ac(t,i))}catch(t){for(const t of wc)JA.increment(e,1,{detector:t,outcome:"error",file:"unclassified"});KA.warn(e,"encoding check failed (write succeeded)",{error:t instanceof Error?t.message:String(t)})}var s}}function t$(e,t){return new HA.v3({result:{case:"error",value:new HA.QM({path:e,error:t})}})}class r$ extends Error{constructor(e){super("stale write refusal"),this.result=e,this.name="StaleWriteRefusal"}}function n$(e){if("error"!==e.result.case)return!1;const{error:t,path:r}=e.result.value;return t===JI(r)||t===ZI(r)}const o$=(0,l.h)("local-exec:provider"),s$=new Set,i$=new Ru.AsyncLocalStorage;class a$ extends K{getMcpExecutionPolicyDeps(){return{permissionsService:this.permissionsService,pendingDecisionProvider:this.pendingDecisionStore}}static dropOwnedRequestContextCaches(){for(const e of s$)e.ownedRequestContextExecutor?.invalidateGlobalCache()}static rebuildRequestContextCachesFor(e){for(const t of s$)t.cursorRulesService===e&&t.ownedRequestContextExecutor?.refreshGlobalCache()}constructor(e){super(),this.pendingDecisionStore=e.pendingDecisionStore,this.fileChangeTracker=e.fileChangeTracker,this.gitExecutor=e.gitExecutor,this.ignoreService=e.ignoreService,this.grepProvider=e.grepProvider,this.permissionsService=e.permissionsService,this.workspacePaths=e.workspacePaths,this.worktreeMainPath=e.worktreeMainPath,this.diagnosticsProvider=e.diagnosticsProvider,this.mcpLease=e.mcpLease,this.mcpStateAccessor=e.mcpStateAccessor,this.cursorRulesService=e.cursorRulesService,this.cloudRulesService=e.cloudRulesService,this.subagentsService=e.subagentsService,this.repositoryProvider=e.repositoryProvider,this.projectDir=e.projectDir,this.shellManager=e.shellManager,this._sandboxPolicyResolver=e._sandboxPolicyResolver,this._defaultSandboxPolicy=e._defaultSandboxPolicy??{type:"insecure_none"};const t=e.workspacePaths[0],r=t?function(e){const t=(0,s.join)(e,".cursor/sandbox.json");try{const r=(0,go.readFileSync)(t,"utf-8"),n=JSON.parse(r),o=(0,Eo.$6)(n);return(0,Eo.l7)(o,e)}catch{return}}(t):void 0,n=e._defaultSandboxPolicySources;this._defaultSandboxPolicySources=r||n?{perUser:n?.perUser,perRepo:r??n?.perRepo,teamAdmin:n?.teamAdmin}:void 0,this.mcpFileOutputThresholdBytes=e.mcpFileOutputThresholdBytes,this.backgroundShellFactory=e.backgroundShellFactory,this.backgroundWorkRegistry=e.backgroundWorkRegistry,this.wakeupOwnerConversationId=e.wakeupOwnerConversationId,this.mcpElicitationFactory=e.mcpElicitationFactory,this.createFileWatcher=e.createFileWatcher,this.sharedRequestContextExecutor=e.sharedRequestContextExecutor,this.terminalExecutor=e.terminalExecutor,this.mcpMetaToolEnabled=e.mcpMetaToolEnabled??!1,this.mcpMetaToolSlimDescriptors=e.mcpMetaToolSlimDescriptors??!1,this.mcpInputSchemaJson=e.mcpInputSchemaJson??!1,this.alwaysExposeVirtualMcpAuthTool=e.alwaysExposeVirtualMcpAuthTool??!1,this.enableRecordScreen=e.enableRecordScreen??!1,this.recordScreenArtifactsDir=e.recordScreenArtifactsDir,this.recordScreenDisplay=e.recordScreenDisplay,this.disableRecordScreenRendering=e.disableRecordScreenRendering??!1,this.userTerminalHint=e.userTerminalHint,this.attributionConfigProvider=e.attributionConfigProvider,this.isAttributionDisabledByAdmin=e.isAttributionDisabledByAdmin,this.getAgentSkills=e.getAgentSkills,this.getSmartModeClassifierAutoModeEnabled=e.getSmartModeClassifierAutoModeEnabled,this.getAdminCommandDenylist=e.getAdminCommandDenylist,this.devForceNextSmartModeClassifierBlockToken=e.devForceNextSmartModeClassifierBlockToken,this.getMockPromptTime=e.getMockPromptTime,this.additionalRules=e.additionalRules??[],this.askpassConfig=e.askpassConfig,this.rebuildRequestContextOnRulesChange=!0===e.rebuildRequestContextOnRulesChange;const i=this.terminalExecutor??(0,Eo.Fn)({env:{CURSOR_AGENT:"1"},userTerminalHint:this.userTerminalHint,isLoginShellEnabled:e.isLoginShellEnabled});let a;if(this.workspacePaths.length>1){const e=this.workspacePaths.map((e=>(0,s.dirname)(e)));a=e.every((t=>t===e[0]))?e[0]:void 0}else a=t;let c=new iu(i,t??(0,o.homedir)(),this.projectDir,{shellOutputBackpressureOptions:e.shellOutputBackpressureOptions,extraEnvProvider:e.shellExtraEnvProvider,powershellUtf8Console:e.powershellUtf8Console,powershellUtf8ChildEnv:e.powershellUtf8ChildEnv,powershellParseAfterUtf8Switch:e.powershellParseAfterUtf8Switch,powershellWebRequestUtf8:e.powershellWebRequestUtf8,powershellPerLineStateDump:e.powershellPerLineStateDump,encodingSlices:e.encodingSlices,keepBackgroundJobs:e.keepShellBackgroundJobs});e.shellCoreWrapper&&(c=e.shellCoreWrapper(c)),this.askpassConfig&&(c=new cu(c,this.askpassConfig)),this.shellManager&&(c=new au(c,this.shellManager));const l=e.overrideShellExecutor??(!0===e.suppressDefaultShellExecutor?void 0:new mA(this.permissionsService,c,this.ignoreService,this.pendingDecisionStore));void 0!==l&&this.register(VI,Cm(l)),this.register(KI,Cm(new GI(this.permissionsService,this.ignoreService,a??t??this.projectDir)));const u=new EA,d=new xA,h=e.overrideWriteExecutor??new e$(this.fileChangeTracker,this.permissionsService,this.pendingDecisionStore,{workspacePaths:this.workspacePaths,workspacePath:a,worktreeMainPath:this.worktreeMainPath,projectDir:this.projectDir,onWriteForAiTracking:e.onWriteForAiTracking,writeFileMutationGuard:e.writeFileMutationGuard,toolCallReads:u,agentFileViews:d});this.register(XI,function(e){const t=(r={execute:(t,r,n)=>e.execute(t,r,n).then((e=>{if(n$(e))throw new r$(e);return e}))},Cm(r));var r;return{async execute(e,r,n){try{return await t.execute(e,r,n)}catch(e){if(e instanceof r$)return e.result;throw e}}}}(h));const p=e.overrideDeleteExecutor??new Ag(this.pendingDecisionStore,this.fileChangeTracker,this.permissionsService,a,e.onDeleteForAiTracking,d);this.register(QI,Cm(p)),this.register(YI,Cm(new Ng({encodingSlices:e.encodingSlices}))),this.register(eR,new AT);const f=this.mcpStateAccessor??new lA(this.mcpLease),m=e.overrideGrepExecutor??new Fk(this.ignoreService,this.grepProvider,this.workspacePaths,{mcpStateAccessor:f,permissionsService:this.permissionsService,useStreamingGrep:e.useStreamingGrep,encodingSlices:e.encodingSlices});this.register(tR,Cm(m));const g=e.overrideReadExecutor??new RA(new lk(this.permissionsService,a,{mcpStateAccessor:f,useStreamingRead:e.useStreamingRead,pendingDecisionProvider:this.pendingDecisionStore,encodingSlices:e.encodingSlices}),u,this.permissionsService,a,d),w=new sR(g);this.register(iR,w),e.registerRedactedReadExecutor&&this.register(aR,w);const y=e.overrideLsExecutor??new Hk(this.permissionsService,this.ignoreService,a);this.register(cR,Cm(y)),this.register(lR,Cm(new JR(a,this.diagnosticsProvider))),e.getCanvasDiagnostics&&this.register(uR,Cm(new WR(e.getCanvasDiagnostics,e.beginCanvasSave))),this.register(Gn,Cm(new xR(fl(new FI(this.mcpLease,this.permissionsService,this.pendingDecisionStore,this.projectDir,this.mcpFileOutputThresholdBytes,this.mcpElicitationFactory,e.ensureMcpServersLoaded),e.encodingSlices,"exec_mcp",(e=>"success"===e.result.case)),(()=>this.get(iR))))),this.register(Vn,Cm(new NI(this.mcpLease,e.ensureMcpServersLoaded))),this.register(Kn,Cm(fl(new LI(this.mcpLease,a||this.projectDir,this.permissionsService,this.workspacePaths,this.pendingDecisionStore,e.ensureMcpServersLoaded),e.encodingSlices,"exec_mcp",(e=>"success"===e.result.case)))),this.register(Jn,Cm(new dA(f,e.ensureMcpServersLoaded,{filterToRequestedServers:this.mcpMetaToolEnabled&&this.mcpMetaToolSlimDescriptors})));const v=this.sharedRequestContextExecutor??this.createOwnedRequestContextExecutor(f,t,e),b=Cm({execute:(e,t,r)=>{const n=i$.getStore();return void 0!==n&&(n.ran=!0),v.execute(e,t,r)}});this.register(Ar,{execute:async(t,r,n)=>{const o={ran:!1},s=await i$.run(o,(()=>b.execute(t,r,n)));if("success"!==s.result.case||void 0===s.result.value.requestContext)return s;const i=s.clone();if("success"!==i.result.case)return s;const a=i.result.value.requestContext;if(void 0===a)return i;const c=await f.getState(t),l=sA(c,{internalBrowserProvidersOnly:this.mcpMetaToolEnabled&&this.mcpMetaToolSlimDescriptors,inputSchemaJson:this.mcpInputSchemaJson});if(a.tools=l.tools,a.mcpInstructions=l.mcpInstructions,a.mcpMetaToolOptions=this.mcpMetaToolEnabled?iA(c,{alwaysExposeVirtualMcpAuthTool:this.alwaysExposeVirtualMcpAuthTool,slimDescriptors:this.mcpMetaToolSlimDescriptors,inputSchemaJson:this.mcpInputSchemaJson}):void 0,o.ran&&void 0!==e.getMcpFileSystemOptions||(a.mcpFileSystemOptions=await(e.getMcpFileSystemOptions?.(t))),void 0!==a.env&&(a.env.artifactsFolder=e.getArtifactsFolder?.(t),void 0!==e.getSandboxEnabled&&(a.env.sandboxEnabled=e.getSandboxEnabled()),void 0!==e.getSessionSandboxSupported&&(a.env.sandboxSupported=e.getSessionSandboxSupported())),void 0!==e.getMountedAgentStores&&void 0!==a.env)try{const r=await e.getMountedAgentStores(t);a.env.mountedAgentStores=r.map((e=>e.clone()))}catch{a.env.mountedAgentStores=[],o$.warn(t,"Failed to get mounted agent stores; continuing without prompt inventory")}return i}}),this.backgroundShellExecutor=new Iu(this.permissionsService,c,this.ignoreService,this.projectDir,this.backgroundShellFactory,this.backgroundWorkRegistry,this.wakeupOwnerConversationId,e.backgroundShellManager),this.shellRedeliveryCaches=e.shellRedeliveryCaches??{backgroundShell:_m(),shellStream:_m(),writeStdin:_m()},this.register(PR,Cm(this.backgroundShellExecutor,void 0,this.shellRedeliveryCaches.backgroundShell)),this.shellStreamExecutor=new _A(this.permissionsService,c,this.ignoreService,this.backgroundShellExecutor.getManager()),this.register(ee,function(e,t,r=_m(t)){return{async*execute(t,n,o){if(!o?.execId)return void(yield*e.execute(t,n,o));const s=km(o.execId,n),i=r.get(s);if(i)return void(yield*i.fork());const a=e.execute(t,n,o),c=new Sm(a);r.set(s,c),yield*c.fork()}}}(this.shellStreamExecutor,void 0,this.shellRedeliveryCaches.shellStream)),void 0!==e.agentStoreConflictDrainer&&this.register(RR,new LR(e.agentStoreConflictDrainer)),this.register(TR,new wA(this.permissionsService)),this.register(AR,new MT(this.permissionsService)),this.register($R,new FA(this.permissionsService));const S=new yA(this.shellStreamExecutor);this.register(MR,Cm(S));const k=!1===e.enableWriteBackgroundShellStdin?new jR((async()=>{throw new Error(e.writeBackgroundShellStdinDisabledReason??"write_shell_stdin is disabled for this session")})):new jR(((e,t)=>this.backgroundShellExecutor.writeStdin(e,t)));if(this.register(IR,Cm(k,void 0,this.shellRedeliveryCaches.writeStdin)),e.computerUseExecutor&&(this.computerUseExecutor=e.computerUseExecutor,this.register(DR,Cm(this.computerUseExecutor))),this.enableRecordScreen){if(!this.recordScreenArtifactsDir||!this.recordScreenDisplay)throw new Error("recordScreenArtifactsDir and recordScreenDisplay are required when enableRecordScreen is true");this.recordScreenExecutor=new BT({artifactsDir:this.recordScreenArtifactsDir,display:this.recordScreenDisplay,disablePolishedRendering:this.disableRecordScreenRendering,polishedRenderer:e.polishedRecordingRenderer}),this.register(OR,Cm(this.recordScreenExecutor))}}createOwnedRequestContextExecutor(e,t,r){const n=new hA(this.cursorRulesService,this.cloudRulesService,this.subagentsService,this.repositoryProvider,this.grepProvider,e,this.gitExecutor,void 0===r.requestContextWorkspacePaths?this.workspacePaths:[...r.requestContextWorkspacePaths],{projectDir:this.projectDir,isWorkingDirHomeDir:r.requestContextIsWorkingDirHomeDir??(0,Ho.yn)(t,(0,o.homedir)()),agentNotesEnabled:r.agentNotesEnabled,reportProcessWorkingDirectory:r.reportProcessWorkingDirectory,sectionLoadTimeoutMs:r.requestContextSectionLoadTimeoutMs,reportSectionCompleteness:r.reportRequestContextSectionCompleteness,freshSectionWaitMs:r.requestContextFreshSectionWaitMs,createFileWatcher:this.createFileWatcher,getSandboxEnabled:r.getSandboxEnabled,getSandboxSupported:r.getSandboxSupported,getNetworkAllowlistInfo:r.getNetworkAllowlistInfo,getSmartModeClassifierAutoModeEnabled:this.getSmartModeClassifierAutoModeEnabled,getAdminCommandDenylist:this.getAdminCommandDenylist,devForceNextSmartModeClassifierBlockToken:this.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:this.getMockPromptTime,userTerminalHint:this.userTerminalHint,getMcpFileSystemOptions:r.getMcpFileSystemOptions,mcpMetaToolEnabled:this.mcpMetaToolEnabled,mcpMetaToolSlimDescriptors:this.mcpMetaToolSlimDescriptors,mcpInputSchemaJson:this.mcpInputSchemaJson,alwaysExposeVirtualMcpAuthTool:this.alwaysExposeVirtualMcpAuthTool,getArtifactsFolder:r.getArtifactsFolder,secretRedactionEnabled:r.secretRedactionEnabled,attributionConfigProvider:this.attributionConfigProvider,isAttributionDisabledByAdmin:this.isAttributionDisabledByAdmin,getAgentSkills:this.getAgentSkills,additionalRules:this.additionalRules,getComputerUseSupported:()=>void 0!==this.computerUseExecutor,getComputerUseDesktop:r.getComputerUseDesktop,onRequestContext:r.onRequestContext,deferWarmup:!0===r.deferRequestContextWarmup});return!0===r.deferRequestContextWarmup&&(this.requestContextExecutorAwaitingWarmup=n),this.rebuildRequestContextOnRulesChange&&(this.ownedRequestContextExecutor=n,s$.add(this),this.disposeRulesChangeListener=this.cursorRulesService.onDidChangeRules?.((()=>{n.rebuildAllCaches()}))),n}warmRequestContext(){const e=this.requestContextExecutorAwaitingWarmup;this.requestContextExecutorAwaitingWarmup=void 0,e?.warm()}getRecordScreenExecutor(){return this.recordScreenExecutor}getBackgroundShellManager(){return this.backgroundShellExecutor.getManager()}getShellRedeliveryCaches(){return this.shellRedeliveryCaches}hasForegroundShells(){return this.shellStreamExecutor.hasForegroundWork()}withPendingShells(e){return new J(e,[G(ee,this.shellStreamExecutor.pendingFrom(e))])}async dispose(){this.requestContextExecutorAwaitingWarmup=void 0,this.rebuildRequestContextOnRulesChange&&(s$.delete(this),this.disposeRulesChangeListener?.(),this.disposeRulesChangeListener=void 0,this.ownedRequestContextExecutor?.dispose(),this.ownedRequestContextExecutor=void 0),this.backgroundShellExecutor.dispose(),this.recordScreenExecutor&&await this.recordScreenExecutor.dispose()}}function c$(e){return e.replace(/\\/g,"/")}function l$(e,t){for(const r of t){const t=c$(r);if(e===t||e.startsWith(`${t}/`))return!0}return!1}var u$;function d$(e,t,r){if(function(e){return Boolean(e.plugin?.trim()||e.pluginId?.trim()||e.marketplaceId?.trim())}(e))return u$.Plugin;const n=c$(e.fullPath);return l$(n,r.builtinDirs)?u$.Builtin:If(e.fullPath,t).inAgentStore?u$.UserStore:l$(n,r.userDirs)?u$.UserHome:(l$(n,r.workspaceDirs),u$.Workspace)}"function"==typeof SuppressedError&&SuppressedError,function(e){e[e.Builtin=0]="Builtin",e[e.UserStore=1]="UserStore",e[e.UserHome=2]="UserHome",e[e.Workspace=3]="Workspace",e[e.Plugin=4]="Plugin"}(u$||(u$={}));var h$=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const p$=(0,Fs.debuglog)("merged-agent-skills"),f$=(0,l.h)("merged-agent-skills");class m${constructor(e,t=()=>[],r){this.services=e,this.getDisabledManagedSkillPaths=t,this.getPromptSortContext=r,this.onChangeCallbacks=new Set}async getAllAgentSkills(e){const t={stack:[],error:void 0,hasError:!1};try{const r=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(t,(0,$.VI)(e.withName("MergedAgentSkillsService.getAllAgentSkills")),!1),n=this.services.map((e=>e.getAllAgentSkills(r.ctx).catch((e=>(p$("Failed to load agent skills from service: %s",e instanceof Error?e.message:String(e)),[]))))),o=async()=>{try{return{ok:!0,paths:await this.getDisabledManagedSkillPaths()}}catch(e){return f$.warn(r.ctx,"getDisabledManagedSkillPaths failed; failing closed by dropping all managed skills for this call",{error:e instanceof Error?e.message:String(e)}),{ok:!1}}},[i,a]=await Promise.all([Promise.all(n),o()]),c=i.flat(),l=this.getPromptSortContext?.(),u=Tf(c,l??xf);let d=u;return a.ok?a.paths.length>0&&(d=u.filter((e=>!function(e,t){if(!e)return!1;const r=e.replace(/\\/g,"/");return t.some((e=>r.endsWith(e)))}(e.fullPath,a.paths)))):d=u.filter((e=>{return!((t=e.fullPath)&&t.replace(/\\/g,"/").includes(g$));var t})),void 0!==l?function(e,t){if(e.length<=1)return e;const r=function(e){const t=[cf(e.userHomeDirectory).dirPath],r=mf(e.userHomeDirectory,!0).map((e=>e.dirPath)),n=[];for(const t of e.workspacePaths){n.push((0,s.join)(t,".cursor","rules"));for(const e of ff(t,!0))n.push(e.dirPath)}return{builtinDirs:t,userDirs:r,workspaceDirs:n}}(t),n=e.map(((e,n)=>({skill:e,index:n,tier:d$(e,t,r)})));return n.sort(((e,t)=>e.tier-t.tier||e.index-t.index)),n.map((e=>e.skill))}(d,l):d}catch(e){t.error=e,t.hasError=!0}finally{h$(t)}}reload(e){for(const t of this.services)t.reload(e)}scheduleDidChangeSkills(){void 0===this.changeTimer&&(this.changeTimer=setTimeout((()=>{this.changeTimer=void 0;for(const e of Array.from(this.onChangeCallbacks))e()}),m$.CHANGE_COALESCE_MS))}ensureChangeListenersRegistered(){void 0===this.disposeChangeListeners&&(this.disposeChangeListeners=this.services.map((e=>e.onDidChangeSkills((()=>this.scheduleDidChangeSkills())))))}disposeChangeListenersIfUnused(){if(!(this.onChangeCallbacks.size>0||void 0===this.disposeChangeListeners)){for(const e of this.disposeChangeListeners)e();this.disposeChangeListeners=void 0,void 0!==this.changeTimer&&(clearTimeout(this.changeTimer),this.changeTimer=void 0)}}onDidChangeSkills(e){return this.onChangeCallbacks.add(e),this.ensureChangeListenersRegistered(),()=>{this.onChangeCallbacks.delete(e),this.disposeChangeListenersIfUnused()}}dispose(){if(void 0!==this.changeTimer&&(clearTimeout(this.changeTimer),this.changeTimer=void 0),this.onChangeCallbacks.clear(),void 0!==this.disposeChangeListeners){for(const e of this.disposeChangeListeners)e();this.disposeChangeListeners=void 0}for(const e of this.services)e.dispose()}}m$.CHANGE_COALESCE_MS=1500;const g$=`/${rf.configDir}/${rf.subdir}/`;function w$(e,t){if((e.disabledEnvironments??[]).includes(t))return!1;const r=e.environments??[];return 0===r.length||r.includes(t)}const y$=(0,l.h)("skill-sync-manifest"),v$=".sync-manifest.json",b$=new Set(["EPERM","EBUSY"]),S$=[20,50,100],k$=new Map;async function _$(e,t){try{const r=await(0,fo.readFile)((0,s.join)(e,v$),"utf-8"),n=JSON.parse(r);return function(e){if(!function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}(e))return!1;const t=e;return"number"==typeof t.version&&"object"==typeof t.skills&&null!==t.skills&&!Array.isArray(t.skills)&&(void 0===t.lastInventoryAt||"number"==typeof t.lastInventoryAt)}(n)?n:(y$.warn(t,"Manifest failed schema validation, resetting",{skillDir:e}),{version:1,skills:{}})}catch(r){return r instanceof Error&&"ENOENT"===Ua(r)||y$.debug(t,"Failed to read sync manifest, resetting",{skillDir:e,error:String(r)}),{version:1,skills:{}}}}function C$(e,t,r){e.skills[t]={lastSyncedAt:r}}function E$(e,t){delete e.skills[t]}var x$=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const P$=(0,l.h)("builtin-skills-sync");function I$(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function R$(e){for(const t of Object.keys(e.resources??{}))if(0===t.length||t.includes("\\")||t.includes("\0")||s.posix.isAbsolute(t)||s.posix.normalize(t)!==t||t.split("/").includes("..")||"SKILL.md"===s.posix.basename(t)||!t.endsWith(".md"))throw new Error(`Unsafe managed skill resource path: ${JSON.stringify(t)}`)}function T$(e){const t=dd(e.content),r=I$(t.data)?t.data:{};return hd(`${t.content.trim()}\n`,function(e,t){const r={...t??{},name:e.id,description:e.description};delete r.disabledEnvironments,e.disableModelInvocation?r["disable-model-invocation"]=!0:delete r["disable-model-invocation"],e.environments&&e.environments.length>0?r.environments=e.environments:delete r.environments,e.disabledEnvironments&&e.disabledEnvironments.length>0?r["disabled-environments"]=e.disabledEnvironments:delete r["disabled-environments"];const n={...I$(r.metadata)?r.metadata:{}};return delete n.environments,delete n.disabledEnvironments,delete n["disabled-environments"],Object.keys(n).length>0?r.metadata=n:delete r.metadata,r}(e,r))}async function A$(e,t,r){const n=(0,s.join)(t,r.id),o=(0,s.join)(n,"SKILL.md"),i=r.fileContent,a=Object.keys(r.resources),c=await $$(n);if(a.length>0||c.length>0){const e=new Map([["SKILL.md",i],...Object.entries(r.resources)]),o=new Set(["SKILL.md",...c]);if(o.size===e.size&&[...e.keys()].every((e=>o.has(e)))){let t=!0;for(const[r,o]of e)try{if(await(0,fo.readFile)((0,s.join)(n,...r.split("/")),"utf-8")!==o){t=!1;break}}catch{t=!1;break}if(t)return!1}return await async function(e,t){const r=(0,s.join)(e,t.id),n=await(0,fo.mkdtemp)((0,s.join)(e,`.${t.id}-staging-`)),o=`${n}-backup`;let i=!1;try{await(0,fo.writeFile)((0,s.join)(n,"SKILL.md"),t.fileContent,"utf-8");for(const[e,r]of Object.entries(t.resources)){const t=(0,s.join)(n,...e.split("/"));await(0,fo.mkdir)((0,s.dirname)(t),{recursive:!0}),await(0,fo.writeFile)(t,r,"utf-8")}try{await(0,fo.rename)(r,o),i=!0}catch(e){if(!(e instanceof Error)||"ENOENT"!==Ua(e))throw e}try{await(0,fo.rename)(n,r)}catch(e){throw i&&(await(0,fo.rename)(o,r),i=!1),e}i&&(await(0,fo.rm)(o,{recursive:!0,force:!0}),i=!1)}finally{await(0,fo.rm)(n,{recursive:!0,force:!0})}}(t,r),!0}try{if(await(0,fo.readFile)(o,"utf-8")===i)return!1}catch(t){t instanceof Error&&"ENOENT"===Ua(t)||P$.warn(e,"Unexpected error reading skill file",{skillId:r.id,error:String(t)})}return await(0,fo.mkdir)(n,{recursive:!0}),await(0,fo.writeFile)(o,i,"utf-8"),!0}async function $$(e,t=""){const r=t?(0,s.join)(e,...t.split("/")):e;let n;try{n=await(0,fo.readdir)(r,{withFileTypes:!0})}catch(e){if(e instanceof Error&&"ENOENT"===Ua(e))return[];throw e}const o=[];for(const r of n){const n=t?`${t}/${r.name}`:r.name;r.isDirectory()?o.push(...await $$(e,n)):r.isFile()&&r.name.endsWith(".md")&&"SKILL.md"!==n&&o.push(n)}return o}async function M$(e,t){try{return(await(0,fo.readdir)(t,{withFileTypes:!0})).filter((e=>e.isDirectory()&&!e.name.startsWith("."))).map((e=>e.name))}catch(r){return r instanceof Error&&"ENOENT"===Ua(r)||P$.warn(e,"Failed to list skills directory, skipping cleanup",{skillDir:t,error:String(r)}),[]}}async function D$(e,t={}){const r={stack:[],error:void 0,hasError:!1};try{const i=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(r,(0,$.VI)(e.withName("syncBuiltinSkills")),!1).ctx,a=Date.now(),c=t.userHome??(0,o.homedir)(),l=t.skillDir??cf(c).dirPath;await(0,fo.mkdir)(l,{recursive:!0});const[u,d]=await Promise.all([_$(l,i),M$(i,l)]),h=u.lastInventoryAt;(void 0===h||a-h>=864e5)&&(await async function(e,t,r,n){try{const o=await Promise.all(r.map((async e=>{const r=(0,s.join)(t,e),[o,i]=await Promise.all([O$((0,s.join)(r,"SKILL.md")),"canvas"===e?O$((0,s.join)(r,"sdk")):Promise.resolve(!1)]);return{skill_id:e,has_skill_md:o,has_sdk_dir:i,last_synced_at:n.skills[e]?.lastSyncedAt??null}})));P$.info(e,"managed_skills.startup_inventory",{skills_on_disk:o,manifest_present:Object.keys(n.skills).length>0})}catch(t){P$.warn(e,"Failed to emit managed skills startup inventory",{error:String(t)})}}(i,l,d,u),u.lastInventoryAt=a);const p=new Map;for(const e of t.managedSkills??[])(n=e.id)&&n===n.trim()&&!(n.includes("..")||n.includes("/")||n.includes("\\"))?p.set(e.id,e):P$.warn(i,"Skipping managed skill with unsafe id",{skillId:e.id});const f=void 0===t.canvasKit?void 0:uf(c,t.canvasKit).dirPath,m=void 0!==f&&await O$((0,s.join)(f,lf)),g=new Set([...p.keys(),...d,...m?[lf]:[]]),w=e=>void 0!==f&&e===lf?f:l,y=e=>void 0!==f&&e===lf?m:d.includes(e);let v=0,b=0;const S=[];for(const e of g)try{const t=p.get(e),r=u.skills[e],n=r?a-r.lastSyncedAt:0,o=void 0!==r&&n>2592e5,c=void 0!==t&&w$(t,"local"),d=void 0!==t&&!c,h=void 0!==r||y(e),f=w(e);if(t&&!1!==t.enabled&&c)R$(t),f!==l&&await(0,fo.mkdir)(f,{recursive:!0}),await A$(i,f,{id:e,fileContent:T$(t),resources:t.resources??{}})?v++:b++,C$(u,e,a);else if(!1===t?.enabled||d||o){const n=!1===t?.enabled?"enabled_false":d?"environment_ineligible":"grace_expired";await(0,fo.rm)((0,s.join)(f,e),{recursive:!0,force:!0}),E$(u,e),h&&(S.push(e),P$.info(i,"managed_skills.removed",{skill_id:e,reason:n,server_enabled:t?.enabled??null,had_manifest_entry:void 0!==r,last_synced_ms_ago:r?a-r.lastSyncedAt:null}))}else r||C$(u,e,a)}catch(t){P$.warn(i,"Failed to apply skill, will retry next sync",{skillId:e,error:String(t)})}try{await function(e,t){const r=(k$.get(e)??Promise.resolve()).then((()=>async function(e,t){const r=(0,s.join)(e,`${v$}.${process.pid}.${(0,lo.randomBytes)(6).toString("hex")}.tmp`);await(0,fo.mkdir)(e,{recursive:!0});try{await(0,fo.writeFile)(r,JSON.stringify(t,null,2),"utf-8"),await async function(e,t){for(let r=0;;r++)try{return void await(0,fo.rename)(e,t)}catch(e){const t=Ua(e),n=S$[r];if(void 0===n||void 0===t||!b$.has(t))throw e;await(0,Dr.cb)(n)}}(r,(0,s.join)(e,v$))}catch(e){throw await(0,fo.rm)(r,{force:!0}).catch((()=>{})),e}}(e,t))),n=r.catch((()=>{}));return k$.set(e,n),n.then((()=>{k$.get(e)===n&&k$.delete(e)})),r}(l,u)}catch(e){!function(e){if(e instanceof Error&&"ENOENT"===Ua(e))return!0;const t=String(e);return t.includes("ENOENT")||t.includes("no such file or directory")}(e)?P$.warn(i,"Failed to persist sync manifest",{skillDir:l,error:String(e)}):P$.debug(i,"Skipped persisting sync manifest, path removed concurrently",{skillDir:l,error:String(e)})}return{synced:v,upToDate:b,removed:S}}catch(e){r.error=e,r.hasError=!0}finally{x$(r)}var n}async function O$(e){try{return await(0,fo.stat)(e),!0}catch(e){const t=Ua(e);if("ENOENT"===t||"ENOTDIR"===t)return!1;throw e}}const F$=(0,l.h)("managed-skills-sync");function N$(e,t,r,n,o,s){const i=[],a=e.mcpServers;if(!a)return i;for(const[e,c]of Object.entries(a)){const a=c,l=`plugin-${n}-${e}`,u=e;a.url?i.push({identifier:l,name:u,marketplace:t,marketplaceId:r,pluginName:n,pluginId:o,pluginSource:s,type:"streamableHttp",url:a.url,headers:a.headers,auth:a.auth,tls:a.tls,enabledTools:a.enabledTools,placement:a.placement,projectManaged:!1,pluginManaged:!0}):a.command&&i.push({identifier:l,name:u,marketplace:t,marketplaceId:r,pluginName:n,pluginId:o,pluginSource:s,type:"stdio",command:a.command,args:a.args??[],env:a.env??{},cwd:a.cwd,envFile:a.envFile,enabledTools:a.enabledTools,projectManaged:!1,pluginManaged:!0})}return i}function L$(e){try{const t=new URL(e),r=new URL(t.pathname,t.origin);return r.search=t.search,r.pathname.endsWith("/")&&r.pathname.length>1&&(r.pathname=r.pathname.slice(0,-1)),"/"===r.pathname?r.origin+r.search:r.toString()}catch{return e.toLowerCase().trim()}}class j${constructor(e){this.pluginsService=e}async getPluginMcpServers(){const e=await this.pluginsService.reload(),t=[];for(const r of e){const e="marketplace"in r.identifier.sourceInfo?r.identifier.sourceInfo.marketplace:void 0,n="marketplaceDbId"in r.identifier.sourceInfo?r.identifier.sourceInfo.marketplaceDbId:void 0,o=r.identifier.sourceInfo.name,s="pluginDbId"in r.identifier.sourceInfo?r.identifier.sourceInfo.pluginDbId:void 0,i=r.mcpConfig;i&&t.push(...N$(i,e,n,o,s,r.identifier.source))}return function(e){const t=[],r=new Set;for(const n of e){if("streamableHttp"!==n.type||!n.url){t.push(n);continue}const e=L$(n.url);r.has(e)||(r.add(e),t.push(n))}return t}(t)}}var U$=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function B$(e,t){return void 0===e?[]:(Array.isArray(e)?e:[e]).map((e=>({...e,userHomeDir:t})))}class W${constructor(e,t,r,n,o,s){this.workspacePaths=e,this.userHomeDirectory=t,this.getSettings=r,this.marketplaceOptions=n,this.localPluginVariablesLookup=s,this.plugins=[],this._loadFailures=[],this._pluginSetIncomplete=!0,this._retainedFromPreviousLoad=0,this._wasFirstLoad=!0,this.loadedOnce=!1,this._extensionPlugins=new Map,this._extensionPluginOriginalPaths=new Map,this.pluginLogger=o??ph,this.reload()}async getAllEnabledPlugins(){return await this.ensureLoaded(),[...this.plugins]}getLoadFailures(){return[...this._loadFailures]}isPluginSetIncomplete(){return this._pluginSetIncomplete}getLoadDiagnostics(){return{userHomeDirectory:this.userHomeDirectory,pluginsLoaded:this.plugins.length,retainedFromPreviousLoad:this._retainedFromPreviousLoad,wasFirstLoad:this._wasFirstLoad,sourceUnavailable:this._pluginSetIncomplete}}async reload(){return this.loadPromise||(this.loadPromise=this.load().then((async e=>{const t=!this.loadedOnce;let r=[];try{r=await this._reloadExtensionPlugins()}catch(e){this.pluginLogger.log("error",`Failed to reload extension plugins after base load success: ${Ba(e)}`)}const n=e.sourceUnavailable?this._retainPluginsMissingFromPartialLoad(e.plugins):[],o=[...e.plugins,...n],s=new Set(o.map((e=>e.installPath))),i=r.filter((e=>!s.has(e.installPath)));return this.plugins=[...o,...i],e.sourceUnavailable||(this._loadFailures=e.failures),this._pluginSetIncomplete=e.sourceUnavailable,this._retainedFromPreviousLoad=n.length,this._wasFirstLoad=t,this.loadedOnce=!0,this.pluginLogger.log("info",`Plugins reload completed: ${this.plugins.length} plugins loaded (${i.length} extension, ${n.length} retained), ${e.failures.length} failures`),this.plugins})).catch((async e=>{const t=!this.loadedOnce;this.pluginLogger.log("error",`Failed to load plugins: ${e}`),this._pluginSetIncomplete=!0,this._retainedFromPreviousLoad=0,this._wasFirstLoad=t;try{const e=await this._reloadExtensionPlugins(),t=new Set(this.plugins.map((e=>e.installPath)));this.plugins=[...this.plugins,...e.filter((e=>!t.has(e.installPath)))]}catch(e){this.pluginLogger.log("error",`Failed to reload extension plugins after base load failure: ${Ba(e)}`)}return this.loadedOnce=!0,this.plugins})).finally((()=>{this.loadPromise=void 0}))),this.loadPromise}_retainPluginsMissingFromPartialLoad(e){if(!this.loadedOnce)return[];const t=new Set(e.map(Vp));return this.plugins.filter((e=>"extension"!==e.identifier.source&&void 0===e.loadError&&e.installPath.length>0&&!t.has(Vp(e))))}async reloadPlugin(e){this.loadPromise&&await this.loadPromise;const t=B$(this.marketplaceOptions,this.userHomeDirectory);if(0===t.length)return;if(!(this.getSettings().loadCursorFirstParty??t.length>0))return;const r=t=>t.pluginDbId===e.pluginDbId,n=e=>"cursor-first-party"===e.identifier.source||"cursor-third-party"===e.identifier.source?e.identifier.sourceInfo:void 0,o=t=>n(t)?.pluginDbId===e.pluginDbId,s=(t,r)=>void 0!==t.pluginDbId?t.pluginDbId===e.pluginDbId:t.pluginName===r?.name&&t.marketplaceName===r?.marketplace;let i,a,c;for(const l of t){let t;try{t=await zp({...l,log:l.log??this.pluginLogger,pluginFilter:r})}catch(t){this.pluginLogger.log("error",`reloadPlugin: source load failed for ${e.name}: ${Ba(t)}`);continue}const u=t.plugins.find((e=>o(e)&&void 0===e.loadError));if(void 0!==u){i=u;break}const d=t.plugins.find(o);if(void 0!==d&&void 0===a){const e=n(d);a=d,c=t.failures.find((t=>s(t,e)))}}if(void 0===i){if(void 0!==a){const t=n(a),r={...c??{pluginName:t?.name??e.name,errorMessage:a.loadError??"Plugin load failed",errorType:"unknown",...void 0!==t?.marketplace&&{marketplaceName:t.marketplace}},pluginDbId:e.pluginDbId};this._loadFailures=[...this._loadFailures.filter((e=>!s(e,t))),r]}return}const l=this.plugins.findIndex(o);if(-1===l)this.plugins=[...this.plugins,i];else{const e=[...this.plugins];e[l]=i,this.plugins=e}this.loadedOnce=!0;const u=n(i);return this._loadFailures=this._loadFailures.filter((e=>!s(e,u))),i}async registerExtensionPlugin({path:e,extensionId:t}){const r=(0,s.resolve)(e),n=await(0,fo.realpath)(r);if(!(await(0,fo.stat)(n)).isDirectory())throw new Error(`Extension plugin path is not a directory: ${n}`);const i=o.homedir();if(n.split(s.sep).filter(Boolean).length<3||n===i||"/"===n)throw new Error(`Extension plugin path is too broad (must be a specific subdirectory, not root or home): ${n}`);for(const[e,r]of this._extensionPlugins)if(e!==t&&r.has(n))throw new Error(`Plugin path ${n} is already registered by extension ${e}`);let a=this._extensionPlugins.get(t);if(a||(a=new Map,this._extensionPlugins.set(t,a)),a.has(n))return void this._rememberExtensionPluginOriginalPath({extensionId:t,originalPath:r,canonicalPath:n});const c=(0,s.basename)(n),l=await this._loadExtensionPluginContent(n,t);a.set(n,l),this._rememberExtensionPluginOriginalPath({extensionId:t,originalPath:r,canonicalPath:n}),this.pluginLogger.log("info",`Registered extension plugin: ${c} from ${n} (extension: ${t})`)}async unregisterExtensionPlugin({path:e,extensionId:t}){const r=this._extensionPlugins.get(t);if(!r)return!1;const n=(0,s.resolve)(e);let o;try{o=await(0,fo.realpath)(n)}catch{const e=this._extensionPluginOriginalPaths.get(t);o=e?.get(n)??n}const i=r.delete(o);return 0===r.size?(this._extensionPlugins.delete(t),this._extensionPluginOriginalPaths.delete(t)):i&&this._forgetExtensionPluginOriginalPath(t,o),i&&this.pluginLogger.log("info",`Unregistered extension plugin: ${o} (extension: ${t})`),i}async _loadExtensionPluginContent(e,t){const r=(0,s.basename)(e),n={name:r,localPath:e,extensionId:t},o=await Bp(e,r,{name:r,version:"0.0.0"});return o.displayName&&(n.name=o.displayName),{identifier:{source:"extension",sourceInfo:n},installPath:e,...void 0!==o.displayName&&{displayName:o.displayName},...void 0!==o.description&&{description:o.description},...void 0!==o.authorName&&{authorName:o.authorName},...void 0!==o.logoUrl&&{logoUrl:o.logoUrl},...void 0!==o.version&&{version:o.version},...void 0!==o.homepage&&{homepage:o.homepage},...void 0!==o.repository&&{repository:o.repository},skills:o.skills,rules:o.rules,agents:o.agents,commands:o.commands,mcpConfig:o.mcpConfig??void 0,capabilities:o.capabilities,hooks:o.hooks}}_rememberExtensionPluginOriginalPath(e){let t=this._extensionPluginOriginalPaths.get(e.extensionId);t||(t=new Map,this._extensionPluginOriginalPaths.set(e.extensionId,t)),t.set(e.originalPath,e.canonicalPath)}_forgetExtensionPluginOriginalPath(e,t){const r=this._extensionPluginOriginalPaths.get(e);if(r){for(const[e,n]of r)n===t&&r.delete(e);0===r.size&&this._extensionPluginOriginalPaths.delete(e)}}_getExtensionPluginPaths(){const e=[];for(const[t,r]of this._extensionPlugins)for(const n of r.keys())e.push({canonicalPath:n,extensionId:t});return e}async _reloadExtensionPlugins(){const e=this._getExtensionPluginPaths(),t=[];for(const{canonicalPath:r,extensionId:n}of e)try{const e=await this._loadExtensionPluginContent(r,n),o=this._extensionPlugins.get(n);o&&o.set(r,e),t.push(e)}catch(e){this.pluginLogger.log("error",`Failed to reload extension plugin ${r}: ${Ba(e)}`);const o=this._extensionPlugins.get(n),s=o?.get(r);s&&t.push(s)}return t}async ensureLoaded(){this.loadPromise?await this.loadPromise:this.loadedOnce||await this.reload()}async load(){const e={stack:[],error:void 0,hasError:!1};try{const t=(0,y.q6)().withName("LocalPluginsService.load"),r=(function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(e,(0,$.VI)(t),!1),performance.now()),n=e=>{this.pluginLogger.increment(`local_plugins_service.load.${e}`,1),this.pluginLogger.distribution("local_plugins_service.load.duration",performance.now()-r,{outcome:e})},o=this.getSettings(),i=B$(this.marketplaceOptions,this.userHomeDirectory),a=o.importThirdPartyPlugins,c=o.loadUserLocalPlugins??!0,l=o.loadCursorFirstParty??i.length>0;if(!a&&!l&&!c)return this.pluginLogger.log("info","Skipping plugin loading, cursor 1p, 3p, and user-local plugins are disabled"),{plugins:[],failures:[],sourceUnavailable:!1};this.pluginLogger.increment("local_plugins_service.load.start",1);const u=(e,t)=>{this.pluginLogger.increment("local_plugins_service.load_plugin.error",1),this.pluginLogger.log("error",`Cursor plugin load error ${e.name}@${e.version}: ${t?.message??String(t)}`)};try{const e=await async function(e,t={}){const r=t.log??ph,n=performance.now(),o=t.loadClaude??!0,i=t.loadUserLocal??!0,a=t.marketplaceSources??[],c=t.loadCursorFirstParty??a.length>0,l=[],u=[];let d;o&&l.push(qp(e,0,{userHomeDir:t.userHomeDir,onError:t.onError,log:r})),c&&a.length>0&&(d=Promise.allSettled(a.map((e=>zp({...e,userHomeDir:e.userHomeDir??t.userHomeDir,log:e.log??r}))))),i&&l.push(async function(e={}){const t=e.log??ph,r=performance.now(),n=e.userHomeDir??process.env.HOME;if(!n)return t.log("info","loadUserLocalPlugins: no home directory available, skipping"),[];const o=(0,s.join)(n,".cursor","plugins","local");let i;try{i=await(0,fo.readdir)(o,{withFileTypes:!0})}catch{return t.log("info",`loadUserLocalPlugins: ${o} not found or not readable (${(performance.now()-r).toFixed(1)}ms)`),[]}const a=await(0,fo.realpath)(o).catch((()=>(0,s.resolve)(o))),c=[];for(const r of i){if(!r.isDirectory()&&!r.isSymbolicLink())continue;if(r.name.startsWith("."))continue;const n=(0,s.join)(o,r.name);try{if(r.isSymbolicLink()){let e;try{e=await(0,fo.realpath)(n)}catch(e){t.log("warn",`loadUserLocalPlugin ${r.name} rejected: failed to resolve symlink (${e instanceof Error?e.message:String(e)})`);continue}try{hp(a,e)}catch{t.log("warn",`loadUserLocalPlugin ${r.name} rejected: symlink target ${e} is outside ${o}`);continue}}if(!(await(0,fo.stat)(n)).isDirectory()){r.isSymbolicLink()&&t.log("warn",`loadUserLocalPlugin ${r.name} rejected: symlink target is not a directory`);continue}const s=performance.now(),i=await(e.localPluginVariablesLookup?.(r.name)),{displayName:l,description:u,authorName:d,logoUrl:h,version:p,homepage:f,repository:m,variablesSchema:g,skills:w,rules:y,agents:v,commands:b,mcpConfig:S,capabilities:k,hooks:_}=await Bp(n,r.name,void 0,{configuredVariables:i,log:t}),C={source:"user-local",sourceInfo:{name:r.name,localPath:n}};c.push({identifier:C,installPath:n,...void 0!==l&&{displayName:l},...void 0!==u&&{description:u},...void 0!==d&&{authorName:d},...void 0!==h&&{logoUrl:h},...void 0!==p&&{version:p},...void 0!==f&&{homepage:f},...void 0!==m&&{repository:m},variablesSchema:g,skills:w,rules:y,agents:v,commands:b,mcpConfig:S??void 0,capabilities:k,hooks:_}),t.log("info",`loadUserLocalPlugin ${r.name} loaded in ${(performance.now()-s).toFixed(1)}ms`)}catch(e){t.log("error",`loadUserLocalPlugin ${r.name} failed: ${e instanceof Error?e.message:String(e)}`)}}return t.log("info",`loadUserLocalPlugins completed in ${(performance.now()-r).toFixed(1)}ms (${c.length} plugins loaded)`),c}({userHomeDir:t.userHomeDir,log:r,localPluginVariablesLookup:t.localPluginVariablesLookup}));const[h,p]=await Promise.all([Promise.allSettled(l),d??Promise.resolve([])]);let f=!1;const m=[];for(const e of p)"rejected"!==e.status?(e.value.sourceUnavailable&&(f=!0),m.push(...e.value.plugins),u.push(...e.value.failures)):(f=!0,r.log("error",`marketplace source threw while loading; treating it as unavailable: ${String(e.reason)}`));for(const e of h)"rejected"!==e.status?m.push(...e.value):(f=!0,r.log("error",`plugin source threw while loading; treating it as unavailable: ${String(e.reason)}`));const g=new Set,w=[];for(const e of m){if(!e.installPath){w.push(e);continue}const t=await(0,fo.realpath)(e.installPath).catch((()=>e.installPath));g.has(t)||(g.add(t),w.push(e))}const y=new Map,v=[];for(const e of w){const t=Gp(e);if(void 0!==t){const r=y.get(t),n=!e.loadError;if(!0===r)continue;if(!1===r&&n){const r=v.findIndex((e=>Gp(e)===t&&e.loadError));-1!==r&&v.splice(r,1),y.set(t,!0),v.push(e);continue}y.set(t,n)}v.push(e)}const b=performance.now()-n;return r.log("info",`loadAllPlugins completed in ${b.toFixed(1)}ms (claude=${o}, userLocal=${i}, marketplace=${a.length} sources, total=${v.length} plugins, failures=${u.length}, sourceUnavailable=${f})`),{plugins:v,failures:u,sourceUnavailable:f}}(this.workspacePaths,{userHomeDir:this.userHomeDirectory,loadClaude:a,loadUserLocal:c,loadCursorFirstParty:l&&i.length>0,marketplaceSources:i.length>0?i.map((e=>({...e,onCursorError:u}))):void 0,onError:(e,t)=>{this.pluginLogger.log("error",`Claude plugin load error ${e.raw}: ${t?.message??String(t)}`)},log:this.pluginLogger,localPluginVariablesLookup:this.localPluginVariablesLookup});return n("success"),this.pluginLogger.log("info",`Plugins loaded in ${(performance.now()-r).toFixed(1)}ms`),e}catch(e){return n("error"),this.pluginLogger.log("error",`Failed to load all plugins: ${Ba(e)}`),{plugins:[],failures:[],sourceUnavailable:!0}}}catch(t){e.error=t,e.hasError=!0}finally{U$(e)}}}var H$=r("../proto/dist/generated/aiserver/v1/dashboard_pb.js");const q$=BigInt(0),z$=BigInt(8),G$=BigInt(16),V$=BigInt(65535);function K$(e){const t=e.trim();if(0===t.length)return;const r=t.includes("://")?t:`https://${t}`;try{return new URL(r)}catch{return}}function J$(e){let t=e.trim().replace(/\.+$/,"").toLowerCase();if(t.startsWith("[")){const e=t.indexOf("]");-1!==e&&(t=t.slice(1,e))}else if(t.split(":").length-1==1){const e=t.lastIndexOf(":"),r=t.slice(e+1);Array.from(r).every((e=>/\d/.test(e)))&&(t=t.slice(0,e))}return t}function Z$(e){const t=e.split(".");if(4!==t.length)return;let r=q$;for(const e of t){if(!/^\d{1,3}$/.test(e))return;const t=Number(e);if(!Number.isInteger(t)||t<0||t>255)return;r=r<<z$|BigInt(t)}return{version:4,value:r}}function X$(e){if(0===e.length)return[];const t=[],r=e.split(":");for(let e=0;e<r.length;e++){const n=r[e];if(0===n.length)return;if(n.includes(".")){if(e!==r.length-1)return;const o=Z$(n);if(!o)return;t.push(Number(o.value>>G$&V$)),t.push(Number(o.value&V$))}else{if(!/^[0-9a-f]{1,4}$/i.test(n))return;t.push(Number.parseInt(n,16))}}return t}function Q$(e){return Z$(e)??function(e){const t=J$(e);if(0===t.length||t.includes(":::"))return;const r=t.indexOf("::");if(-1===r){const e=X$(t);if(!e||8!==e.length)return;return{version:6,value:e.reduce(((e,t)=>e<<G$|BigInt(t)),q$)}}if(-1!==t.indexOf("::",r+1))return;const n=X$(t.slice(0,r)),o=X$(t.slice(r+2));if(!n||!o)return;const s=n.length+o.length;return s>7?void 0:{version:6,value:[...n,...new Array(8-s).fill(0),...o].reduce(((e,t)=>e<<G$|BigInt(t)),q$)}}(e)}function Y$(e,t){const r=J$(e),n=J$(t);if("*"===n)return!0;if(n.includes("/"))return function(e,t){const r=t.lastIndexOf("/");if(r<=0||r===t.length-1)return!1;const n=Q$(t.slice(0,r)),o=Q$(e);if(!n||!o||n.version!==o.version)return!1;const s=Number(t.slice(r+1)),i=4===n.version?32:128;if(!Number.isInteger(s)||s<0||s>i)return!1;const a=BigInt(i-s);return o.value>>a==n.value>>a}(r,n);if(n.startsWith("*.")){const e=n.slice(2);return r===e||r.endsWith(`.${e}`)}return r===n}function eM(e,t){if(!e.includes("*"))return e===t;const r=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${r}$`).test(t)}function tM(e,t){if(eM(e,t))return!0;if(e.includes("://")){let r,n;try{r=new URL(e),n=new URL(t)}catch{return!1}if(""!==r.username||""!==r.password||""!==n.username||""!==n.password||r.protocol!==n.protocol||r.port!==n.port)return!1;const o=J$(r.hostname);return!!Y$(J$(n.hostname),o)&&eM(`${r.pathname}${r.search}`,`${n.pathname}${n.search}`)}const r=function(e){const t=function(e){const t=e.trim(),r=t.indexOf("["),n=t.indexOf("]");if(-1!==r&&n>r){const e=t.slice(r+1,n);if(t.slice(n+1).startsWith("("))return`${t.slice(0,r)}${e}`}return t}(e).trim();if(0===t.length)return;const r=t.lastIndexOf("/");if(!t.includes("://")&&r>0&&/^\d+$/.test(t.slice(r+1).trim())){const e=J$(t.slice(0,r));if(e.length>0)return`${e}/${t.slice(r+1).trim()}`}const n=K$(t);if(n)return J$(n.hostname);let o=t;const s=o.indexOf("://");-1!==s&&(o=o.slice(s+3));const i=o.indexOf("/");-1!==i&&(o=o.slice(0,i));const a=J$(function(e){if(e.startsWith("[")){const t=e.indexOf("]");return-1!==t?e.slice(1,t):e}const t=e.split(":");return 2===t.length&&Array.from(t[1]??"").every((e=>/\d/.test(e)))?t[0]:e}(o));if(0!==a.length){if(a.startsWith("*.")){const e=a.slice(2);if(0===e.length||e.includes("*")||e.includes("?"))return;return a}if(!a.includes("*")&&!a.includes("?"))return a}}(e),n=function(e){const t=K$(e);if(t)return J$(t.hostname);const r=J$(e);return r.length>0?r:void 0}(t);return!(!r||!n)&&Y$(n,r)}async function rM(e){try{return await e.current()}catch{return}}function nM(e){try{const t=new URL(e);return`${t.protocol}//${t.host}${t.pathname}`}catch{return}}function oM({failOpenWhenEmpty:e,server:t,settings:r}){if(!0!==r?.allowedMcpConfiguration?.requireMcpServersInTeamNetworkAllowlist||void 0===t.url)return{blocked:!1};const n=function(e){return!0===e.cloudAgentMcpAllowlistApplied&&!1===e.mirrorSandboxAllowlistForEgress?e.cloudAgentEgressAllowlist??[]:e.networkAllowlist??[]}(r).map((e=>e.trim())).filter((e=>e.length>0));return 0===n.length&&e||Ay(t.url,n)?{blocked:!1}:{blocked:!0,reason:"teamNetworkAllowlist",message:"Not on the team network allowlist"}}function sM(e){const t=e?.trim();return t&&t.length>0?t:void 0}function iM(e,t,r){if(!0===r?.useCorePolicy)return!function(e,t){if(void 0===t)return!0;if(!0===t.disableAll)return!1;if(Gk(e))return!0;if(Zk(e,t.offMcpServerRules))return!1;const r=t.allowedMcpServers??[];return 0===r.length&&!0!==t.allowUserOverrideMcpServers||!!function(e,t){return t.length>0&&function(e,t){return t.some((t=>{const r=Vk(t.command),n=Kk(t.serverUrl);if(void 0===r&&void 0===n)return!1;const o=void 0===r||void 0!==e.command&&(0,mv.mD)(r,e.command),s=void 0===n||void 0!==e.url&&(0,mv.vc)(n,e.url);return o&&s}))}(e,t)}(e,r)||!0===t.allowUserOverrideMcpServers&&!Jk(e,t.deniedMcpServers)}(e,t);if(void 0===t)return!1;if(!0===t.disableAll)return!0;const n=t.allowedMcpServers;return 0!==n.length&&!n.some((t=>function(e,t){const r=sM(e.command),n=sM(e.serverUrl);if(void 0===r&&void 0===n)return!1;const o=void 0===r||void 0!==t.command&&function(e,t){if(!e.includes("*"))return e===t;const r=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${r}$`).test(t)}(r,t.command),s=void 0===n||void 0!==t.url&&tM(n,t.url);return o&&s}(t,e)))}class aM{constructor(e,t={}){this.dashboardClient=e,this.options=t}getTeamAdminSettings(){return this.dashboardClient.getTeamAdminSettingsOrEmptyIfNotInTeam(new H$.Byz(!0===this.options.supportsHostMcpBridgeExemption?{supportsHostMcpBridgeExemption:!0}:{}))}getTeamRepos(){return this.dashboardClient.getTeamReposOrEmptyIfNotInTeam(new H$.aYW({}))}}function cM(e,t){if("workspace"!==e)return[];const r=[],n=new Set;for(const e of t??[]){const t=e.trim();0===t.length||n.has(t)||(n.add(t),r.push(t))}return r}class lM{constructor(e){this.fetch=e}get(){const e=this.cached,t=void 0===e?1/0:Date.now()-e.fetchedAt;return void 0===e||t>6e5?(this.cached=void 0,this.refresh()):(t>3e5&&this.refresh().catch((()=>{})),Promise.resolve(e.value))}invalidate(){this.cached=void 0,this.inFlight=void 0}refresh(){if(void 0===this.inFlight){const e=this.fetch().then((t=>(this.inFlight!==e||void 0===t&&void 0!==this.cached||(this.cached={value:t,fetchedAt:Date.now()}),t))).finally((()=>{this.inFlight===e&&(this.inFlight=void 0)}));this.inFlight=e}return this.inFlight}}class uM{constructor(e,t,r={}){this.teamAdminSettingsProvider=e,this.defaultAllowlistProvider=t,this.options=r,this.lastFetchSucceeded=!0,this.settingsGeneration=0,this.lastFetchedGeneration=0,this.settings=new lM((()=>this.fetchSettings())),this.droppedReplies=new WeakSet,this.hostMcpBridgeClients=new WeakSet,this.mcpServerByClient=new WeakMap,this.teamRepos=new lM((()=>this.teamAdminSettingsProvider.getTeamRepos())),this.defaultAllowlist=new lM((()=>this.fetchDefaultAllowlist())),this.getTeamAdminSettings(),this.prefetchTeamRepos()}async prefetchTeamRepos(){try{await this.teamRepos.get()}catch{}}invalidateCache(){this.settingsGeneration+=1,this.settings.invalidate(),!0!==this.options.preserveTeamReposOnInvalidate&&this.teamRepos.invalidate(),this.defaultAllowlist.invalidate()}invalidateTeamRepos(){this.teamRepos.invalidate()}async fetchSettings(){const{fetchIdentity:e}=this.options;if(void 0!==e)return this.fetchSettingsFor(e);const t=this.settingsGeneration;try{const e=await this.teamAdminSettingsProvider.getTeamAdminSettings();return this.lastFetchSucceeded=!0,t>=this.lastFetchedGeneration&&(this.lastFetchedSettings=e,this.lastFetchedGeneration=t),e}catch(e){throw this.lastFetchSucceeded=!1,e}}async fetchSettingsFor(e){const t=await rM(e),r=this.settingsGeneration;if(void 0===t)throw this.lastFetchSucceeded=!1,new Error("No one is named whose team settings a fetch would read");try{const e=await this.teamAdminSettingsProvider.getTeamAdminSettings();return void 0!==e&&this.droppedReplies.delete(e),this.isSentFor(e,t)?(this.lastFetchSucceeded=!0,r>=this.lastFetchedGeneration&&(this.lastFetchedSettings=e,this.lastFetchedGeneration=r),e):e}catch(e){throw this.lastFetchSucceeded=!1,e}}getTeamAdminSettings(){const{fetchIdentity:e}=this.options;return void 0!==e?this.getTeamAdminSettingsFor(e):this.settings.get().catch((()=>{}))}async getTeamAdminSettingsFor(e){const t=await this.settings.get().catch((()=>{})),r=await rM(e);if(void 0===t)return void(this.isSentFor(this.lastFetchedSettings,r)||(this.settingsGeneration+=1));if(void 0===r)return this.answerAsFailedRead();if(this.isSentFor(t,r))return t;let n=t,o=r;const s=await this.settings.get().catch((()=>{}));if(s!==t){if(void 0===s)return this.answerAsFailedRead();if(this.isSentFor(s,r))return s;if(o=await rM(e),void 0===o)return this.answerAsFailedRead();if(this.isSentFor(s,o))return s;n=s}this.droppedReplies.has(n)||(this.droppedReplies.add(n),this.settingsGeneration+=1,this.settings.invalidate());const i=await this.settings.get().catch((()=>{}));return void 0!==i?this.isSentFor(i,r)||this.isSentFor(i,o)||this.isSentFor(i,await rM(e))?i:this.answerAsFailedRead():void 0}answerAsFailedRead(){this.settingsGeneration+=1,this.lastFetchSucceeded=!1}isSentFor(e,t){return void 0!==e&&void 0!==t&&this.options.fetchIdentity?.sentFor(e)===t}async getDotCursorProtection(){const e=await this.getTeamAdminSettings();return e?.dotCursorProtection??!0}async getShouldBlockMcp(){const e=await this.getTeamAdminSettings();return!(!e?.autoRunControls?.enabled||!e?.autoRunControls?.disableMcpAutoRun)}async getDeleteFileProtection(){const e=await this.getTeamAdminSettings();return!(!e?.autoRunControls?.enabled||!e?.autoRunControls?.deleteFileProtection)}async getIsHeadlessDisabled(){return"disabled"===(await this.getHeadlessCliPolicy()).kind}async getHeadlessCliPolicy(){const e=await this.getTeamAdminSettings();return void 0!==e||this.lastFetchSucceeded?!0===e?.cliSettings?.disableHeadless?{kind:"disabled"}:{kind:"enabled"}:{kind:"unavailable"}}async getMcpServerBlockInfo(e){const t=await this.getTeamAdminSettings(),r=t?.allowedMcpConfiguration,n=await this.isMcpSettingsOverhaulEnabled({disableExposureLog:!0});if(!0===r?.disableAll)return{blocked:!0,reason:"teamPolicy",message:"Blocked by team policy"};if(this.isHostMcpBridge(t,e))return{blocked:!1,hostMcpBridge:!0};if(Zk(e,r?.offMcpServerRules))return{blocked:!0,reason:"teamPolicy",message:"Blocked by team policy"};if(n){if(iM(e,r,{useCorePolicy:!0}))return{blocked:!0,reason:"teamPolicy",message:"Blocked by team policy"};const n=await this.getMcpNetworkControlsConfig(e),o=void 0===e.url?{allowed:!0}:(0,mv.ME)(e.url,n);if(!o.allowed)return{blocked:!0,reason:"teamNetworkAllowlist",message:o.message};const s=oM({failOpenWhenEmpty:!1,server:e,settings:t});if(s.blocked)return s}if(!n){const r=function({isMcpAccessNetworkAllowlistEnabled:e,server:t,settings:r}){return e&&!0===r?.allowedMcpConfiguration?.requireMcpServersInTeamNetworkAllowlist?oM({failOpenWhenEmpty:!0,server:t,settings:r}):{blocked:!1}}({isMcpAccessNetworkAllowlistEnabled:await this.isMcpAccessNetworkAllowlistEnabled(),server:e,settings:t});if(r.blocked)return r}return{blocked:!1}}async getManagedSlackWorkspaceLists(){const e=await this.getTeamAdminSettings()??this.lastFetchedSettings;return void 0===e?[]:function(e){return e.memberSlackManagedWorkspacesUnreadable?"unconfirmed":e.memberSlackManagedWorkspaces.map((e=>e.slackTeamIds)).filter((e=>e.length>0))}(e)}async getMcpNetworkControlsConfig(e){const t=await this.getTeamAdminSettings(),r=t?.allowedMcpConfiguration;if(await this.isMcpSettingsOverhaulEnabled()&&(void 0===e||!this.isHostMcpBridge(t,e))){const n="win32"===process.platform&&await this.isWin32UserExtensionStdioUnsandboxEnabled();return(0,mv._N)({allowedMcpConfiguration:r,server:e,localAgentNetworkAllowlist:t?.networkAllowlist,blockMessage:"Not on the team network allowlist",aggregateManagedServerNetworkAllowlists:!1,stdioPlatform:process.platform,unsandboxUserExtensionStdio:n})}return{enabled:!1,localAgentNetworkAllowlist:t?.networkAllowlist,blockMessage:"Not on the team network allowlist"}}isHostMcpBridge(e,t){const r=this.options.hostMcpBridgeUrls;if(!0!==e?.cloudAgentMcpAllowlistApplied||void 0===r||void 0!==t.command||void 0===t.url)return!1;const n=nM(t.url);return void 0!==n&&r.some((e=>nM(e)===n))}recordHostMcpBridgeClient(e){this.hostMcpBridgeClients.add(e)}async isHostMcpBridgeClient(e){if(!this.hostMcpBridgeClients.has(e))return!1;const t=await this.getTeamAdminSettings();return!0===t?.cloudAgentMcpAllowlistApplied&&!0!==t.allowedMcpConfiguration?.disableAll}recordMcpServerClient(e,t){this.mcpServerByClient.set(e,t)}async getMcpAdminToolLimit(e){if(await this.isHostMcpBridgeClient(e))return{kind:"none"};const t=this.mcpServerByClient.get(e);if(void 0===t)return{kind:"unknown_server"};const r=await this.getTeamAdminSettings();if(void 0===r)return this.lastFetchSucceeded?{kind:"none"}:{kind:"settings_unavailable"};const n=function(e,t){const r=e?.find((e=>(0,mv.rM)(e,t)));if(void 0!==r)return yv({mode:r.toolAllowlistMode,tools:r.toolAllowlist})}(r.allowedMcpConfiguration?.allowedMcpServers,t);return void 0===n?{kind:"none"}:{kind:"limit",policy:n}}async isServerBlocked(e){return(await this.getMcpServerBlockInfo(e)).blocked}async getAutoRunControls(){const e=await this.getTeamAdminSettings();if(e?.autoRunControls?.enabled)return{enabled:e.autoRunControls.enabled,allowed:e.autoRunControls.allowed??[],blocked:e.autoRunControls.blocked??[],enableAllowlistMode:e.autoRunControls.enableAllowlistMode??!0,enableRunEverything:e.autoRunControls.enableRunEverything??!1,enableSmartAuto:e.autoRunControls.enableSmartAuto??!0,mcpToolAllowlist:e.autoRunControls.mcpToolAllowlist??[]}}async isReadControlEnabled(){try{return await(this.options.isReadControlEnabled?.())??!0}catch{return!1}}async isDenylistEnforcementKilled(){try{return!0===await(this.options.isAdminCommandDenylistEnforcementKilled?.())}catch{return!1}}async getAdminCommandDenylist(){if(await this.isDenylistEnforcementKilled())return{rules:[]};const e=await this.getTeamAdminSettings();return{rules:e?.autoRunControls?.adminCommandDenylist?.rules??[]}}async isMcpSettingsOverhaulEnabled(e){const t=this.options.isMcpSettingsOverhaulEnabled?.(e);return void 0!==t&&await t}async isWin32UserExtensionStdioUnsandboxEnabled(){try{const e=this.options.isWin32UserExtensionStdioUnsandboxEnabled?.();return void 0!==e&&await e}catch{return!1}}async getMcpToolControls(){const e=await this.getTeamAdminSettings(),t=e?.allowedMcpConfiguration;if(void 0===t)return;const r=function({autoRunControls:e,allowedMcpServers:t}){const r=!0===e?.enabled?e.mcpToolAllowlist??[]:[],n=function(e){return(e??[]).flatMap((e=>{const t=void 0===e.name?"":gv(e.name);if(0===t.length)return[];const r=yv({mode:e.toolAllowlistMode,tools:e.toolAllowlist});return[{name:t,policy:r,flattened:bv(t,r)}]}))}(t);return{tools:(o=[...n.flatMap((e=>[...e.flattened])),...r],[...new Set(o)]),policies:n.map((e=>({name:e.name,policy:e.policy})))};var o}({autoRunControls:e?.autoRunControls,allowedMcpServers:t?.allowedMcpServers});return r.policies.length>0||r.tools.length>0?{enabled:!0,mcpToolAllowlist:r.tools,allowUserOverride:t?.allowUserOverrideMcpServers??!1,serverPolicies:r.policies}:void 0}async getNetworkAccessControls(){const e=await this.getTeamAdminSettings();return void 0!==e||this.lastFetchSucceeded?{allowlist:e?.networkAllowlist??[],denylist:e?.networkDenylist??[],available:!0}:{allowlist:[],denylist:[],available:!1}}async getSandboxingControls(){const e=await this.getTeamAdminSettings(),t=e?.autoRunControls?.sandboxingControls,r=(n=t?.sandboxReadBoundary,n===H$.h0i.WORKSPACE?"workspace":"system");var n;return{sandboxingDisabled:t?.sandboxing===H$.faf.DISABLED,networkingDisabled:t?.sandboxNetworking===H$._mX.ALWAYS_DISABLED,gitDisabled:t?.sandboxGit===H$.i24.ALWAYS_DISABLED,readBoundary:r,readAllowlistPaths:cM(r,t?.sandboxReadAllowlistPaths),allowUserOverrideReadAllowlist:!1!==t?.allowUserOverrideSandboxReadAllowlist}}async isAttributionDisabledByAdmin(){const e=await this.getTeamAdminSettings();return void 0===e&&!this.lastFetchSucceeded||(e?.attributionControls?.disableAttribution??!1)}async isComputerUseDisabledByAdmin(){const e=await this.getTeamAdminSettings();return void 0!==e?!1===e.computerUse:this.lastFetchedGeneration!==this.settingsGeneration||void 0===this.lastFetchedSettings&&!this.lastFetchSucceeded||!1===this.lastFetchedSettings?.computerUse}getDefaultNetworkAllowlist(){return this.defaultAllowlist.get().catch((()=>({allowlist:[],available:!1})))}async fetchDefaultAllowlist(){return this.defaultAllowlistProvider?{allowlist:await this.defaultAllowlistProvider.getDefaultNetworkAllowlist(),available:!0}:{allowlist:[],available:!0}}getTeamRepos(){return this.teamRepos.get()}async isMcpAccessNetworkAllowlistEnabled(){return await(this.options.isMcpAccessNetworkAllowlistEnabled?.())??!1}}const dM=new dw,hM={async resolveWorkspaceState(e){const t=e.workingDirectory??e.projectRoot??e.workspaceRoots?.[0],r=e.projectRoot??(void 0!==t?await _a((0,y.q6)(),dM,t)??t:void 0),n=e.workspaceRoots??(void 0!==r?[r]:void 0!==t?[t]:[]);return{workingDirectory:t,projectRoot:r,projectDirectory:e.projectDirectory??(void 0!==r?po(r):void 0),workspaceRoots:n,createdAt:new Date}}},pM=(0,l.h)("ControlledConversationActionManager");class fM{get signal(){return this.abortController.signal}get abortRequested(){return this.abortCalled}constructor(){this.abortCallbacks=[],this.abortController=new AbortController,this.acceptsActions=!0,this.disposed=!1,this.abortStarted=!1,this.abortCalled=!1,this.runActive=!1,this.unprocessedUserMessages=[],this.clientStream=(0,h.Jt)()}addAbortCallback(e){this.abortCallbacks.push(e)}abort(e,t){if(this.abortCalled=!0,this.abortController.signal.aborted||this.abortStarted)return;const r=t?.interruptedPendingToolCallResolutions;if(this.abortStarted=!0,!this.runActive){this.abortController.abort(e);for(const e of this.abortCallbacks)e();return void(this.abortCallbacks.length=0)}const n=this.abortController,o=[...this.abortCallbacks];this.abortCallbacks.length=0,this.submitConversationAction(new i.QFf({action:{case:"cancelAction",value:new i.TTG({reason:e,interruptedPendingToolCallResolutions:r})}})).catch((()=>{})).finally((()=>{n.abort(e);for(const e of o)e();if(this.abortController===n){const e=[...this.abortCallbacks];this.abortCallbacks.length=0;for(const t of e)t()}}))}async submitConversationAction(e){if(!this.acceptsActions)throw new h.W2("ControlledConversationActionManager is not accepting actions");if("userMessageAction"===e.action.case){const t=e.action.value.userMessage;t&&this.unprocessedUserMessages.push(t)}await this.clientStream.write(e)}queueFollowUpUserMessage(e){if(this.disposed||this.abortStarted)throw new h.W2("ControlledConversationActionManager run was aborted or disposed");this.unprocessedUserMessages.push(e)}async enqueueReplayableConversationAction(e){if("asyncAskQuestionCompletionAction"!==e.action.case)throw new TypeError("Only asyncAskQuestionCompletionAction can use enqueue acknowledgement");if(!this.acceptsActions)throw new h.W2("ControlledConversationActionManager is not accepting actions");this.clientStream.write(e).catch((()=>{}))}markMessageAsProcessed(e){this.unprocessedUserMessages=this.unprocessedUserMessages.filter((t=>t.messageId!==e.messageId))}requeueMessage(e){this.unprocessedUserMessages.some((t=>t.messageId===e.messageId))||this.unprocessedUserMessages.unshift(e)}getUnprocessedUserMessages(){return[...this.unprocessedUserMessages]}hasUnprocessedMessages(){return this.unprocessedUserMessages.length>0}close(){this.acceptsActions=!1,this.clientStream.close()}reopen(){this.disposed||this.acceptsActions||this.resetStream()}resetStream(){if(this.disposed)throw new h.W2("ControlledConversationActionManager disposed");this.acceptsActions=!1,this.clientStream.close(),this.clientStream=(0,h.Jt)(),this.acceptsActions=!0,this.abortController=new AbortController,this.abortStarted=!1;for(const e of this.unprocessedUserMessages)this.clientStream.write(new i.QFf({action:{case:"userMessageAction",value:new i.Vtf({userMessage:e})}})).catch((()=>{}))}async run(e,t){const r=this.clientStream;this.runActive=!0;try{for await(const n of r)try{await t.write(n)}catch(t){pM.error(e,"Error writing conversation action",t)}}catch(e){if(!(e instanceof h.W2))throw e}finally{this.clientStream===r&&(this.runActive=!1)}}dispose(){this.disposed||(this.disposed=!0,this.abortCallbacks.length=0,this.acceptsActions=!1,this.clientStream.throw(new h.W2("ControlledConversationActionManager disposed")))}}var mM=r("../cursor-sdk-local-runtime/dist/utils/logger.js"),gM=r("../agent-kv/dist/agent-store.js");const wM="x-blob-encryption-key";function yM(e,t){const r={...t};return void 0!==r[wM]||(0,gM.TU)(e)&&(r[wM]=e),r}const vM=new Map;function bM(e){if("userMessageAction"===e.action.case)return e.action.value.userMessage?.text}function SM(e,t,r){const n=e.runOptions?.requestedModel;return{conversationId:e.conversationId,generationId:e.conversationId,model:n?.modelId??"unknown",modelId:n?.modelId,modelParams:n?.parameters.map((e=>({id:e.id,value:e.value}))),loopCount:t,promptText:r}}function kM(e){return new i.QFf({action:{case:"userMessageAction",value:new i.Vtf({userMessage:new i.RGk({text:e})})}})}function _M(e){return e instanceof DOMException&&"AbortError"===e.name||e instanceof Error&&("AbortError"===e.name||"The operation was aborted"===e.message)}function CM(e){e?.catch((e=>{mM.Jz.warn("[agent-session-runner] fire-and-forget hook failed:",e)}))}const EM=new Set(["mcp.slack.com","setup.shopify.com"]);async function xM(e,t){if(!("url"in e)||!e.url)return e;const r=await async function(e,t,r,n=fetch){let o;try{o=new URL(e).hostname}catch{return t}const s=void 0!==(i=e,a=r.restMcpHost,function({serverUrl:e,restMcpHost:t}){if(void 0===e)return;let r;try{r=new URL(e)}catch{return}return"https:"===r.protocol&&r.hostname.toLowerCase()===t.toLowerCase()&&""===r.port?Uy(e):void 0}({serverUrl:i,restMcpHost:a}));var i,a;if(!EM.has(o)&&!s)return t;let c=await r.resolve(e);if(!c&&s){const t=(await _C(e,n))?.clientId;void 0!==t&&(c={CLIENT_ID:t})}return c?t?void 0===SC(t.CLIENT_ID)?{...c,...t,CLIENT_ID:c.CLIENT_ID}:{...c,...t}:c:t}(e.url,e.auth,t);return r===e.auth?e:{...e,auth:r}}class PM{constructor(e,t){this.inner=e,this.resolver=t}async getDefinitions(e,t=!0){const r=await this.inner.getDefinitions(e,t);return Promise.all(r.map((async e=>{const t=await xM(e.serverConfig,this.resolver);return t===e.serverConfig?e:{...e,serverConfig:t}})))}clearCache(){this.inner.clearCache?.()}}class IM{constructor(e,t){this.storage=e,this.prefix=t}async loadTokens(e){return this.storage.loadTokens(this.prefix+e)}async saveTokens(e,t){return this.storage.saveTokens(this.prefix+e,t)}async loadClientInformation(e){return this.storage.loadClientInformation(this.prefix+e)}async saveClientInformation(e,t){return this.storage.saveClientInformation(this.prefix+e,t)}}class RM{constructor(e,t){this.storage=e,this.prefix=t}async isServerApproved(e,t,r){return this.storage.isServerApproved(this.prefix+e,t,r)}}class TM{constructor(e){this.higherPrecedenceSources=e}async load(e,t,r,n,o){for(const r of this.higherPrecedenceSources){const n=(await r.getDefinitions(e)).find((e=>e.identifier===t));if(void 0!==n)throw new e_(t,n.configPath??"another config")}return await o(e,r)}}class AM{constructor(e){this.loaders=e}async load(e,t=!0){const r=await Promise.allSettled(this.loaders.map((({loader:r})=>r.load(e,t)))),n=r.find((e=>"rejected"===e.status));if(n)throw await Promise.allSettled(r.flatMap((e=>"fulfilled"===e.status?[e.value.closeAllClients()]:[]))),n.reason;const o=r.filter((e=>"fulfilled"===e.status)).map((e=>e.value)),s={};for(let e=0;e<o.length;e++){const t=o[e],r=this.loaders[e].prefix,n=t.getClients();for(const[e,t]of Object.entries(n)){const n=r+e;n in s||(s[n]=t)}}return new mP(s)}async loadClient(e,t,r=!1){for(const{loader:n,prefix:o}of this.loaders)if(t.startsWith(o)){t=t.slice(o.length);try{return await n.loadClient(e,t,r)}catch(e){if(e instanceof Error&&e.message.includes("not found in config"))continue;throw e}}throw new Error(`MCP client "${t}" not found in config`)}clearClient(e){for(const{loader:t,prefix:r}of this.loaders){if(!e.startsWith(r))continue;const n=e.slice(r.length);t.clearClient?.(n)}}clearAllMcpCaches(){for(const{loader:e}of this.loaders)e.clearAllMcpCaches?.()}}class $M{constructor(e,t,r,n,i=!1,a,c,l=s.join((0,o.homedir)(),".cursor","mcp.json"),u,d,h){const p=Array.isArray(e)?e:[e],f={}.location,m=[];"enterprise"===f?.source&&m.push({path:f.path,prefix:"enterprise-",scope:"enterprise"});for(let e=0;e<p.length;e++){const t=p[e],r=s.basename(t);m.push({path:s.join(t,".cursor","mcp.json"),prefix:`project-${e}-${r}-`,scope:"project"})}m.push({path:l,prefix:"user-",scope:"user"}),"env"===f?.source&&m.push({path:f.path,prefix:"env-",scope:"env"});const g=new Map;for(const e of m)g.has(e.path)&&"user"!==e.scope||g.set(e.path,e);const w=[...g.values()].map((({path:e,prefix:t,scope:r})=>({prefix:t,scope:r,fileSource:new $P(e,"enterprise"===r||"env"===r?U_:void 0)}))),y=[];for(const{prefix:e,scope:o,fileSource:s}of w){const l=i?"":e,d=new IM(t,l),p=new RM(n,l),f=w.flatMap((e=>{return t=e.scope,r=o,B_.indexOf(t)<B_.indexOf(r)&&("enterprise"===t||"env"===r)?[e.fileSource]:[];var t,r})),m=[new i_,...W_(o)?[new r_(p)]:[],new FP(r),...c?[new t_(c)]:[],...f.length>0?[new TM(f)]:[]],g=new MP(u?new PM(s,u):s,d,m,{authRedirectUrlGenerator:a,isLinkSharedPaymentTokenLogRedactionEnabled:h});y.push({prefix:l,loader:g})}this.loader=new AM(y)}static init(e,t,r,n=!1,o,i={}){const a=new WP(s.join(r,"mcp-auth.json"));(async function(e){await(0,fo.rm)(s.join(e,"mcp-cache.json"),{force:!0})})(r).catch((()=>{}));const c=n?{isServerApproved:()=>Promise.resolve(!0)}:new n_(s.join(r,"mcp-approvals.json"),t);return new $M(t,a,e,c,!0,void 0,o,void 0,i.defaultAuthResolver,void 0,i.isLinkSharedPaymentTokenLogRedactionEnabled)}async load(e,t=!0){return this.loader.load(e,t)}async loadClient(e,t,r=!1){return this.loader.loadClient(e,t,r)}clearClient(e){this.loader.clearClient(e)}clearAllMcpCaches(){this.loader.clearAllMcpCaches()}}const MM="cursor-plugins/local";function DM(e){var t;if(e)for(const r of e)if("object"==typeof(t=r)&&null!==t&&t.kind===MM)return r}class OM extends fP{constructor(e){super(e),this.runtimeManager=e,this.disposed=!1}async dispose(){this.disposed||(this.disposed=!0,await this.runtimeManager.closeAllClients())}}class FM{constructor(e){this.storagePath=e}async isServerDisabled(e){try{const t=await(0,fo.readFile)(this.storagePath,"utf8"),r=JSON.parse(t);return Array.isArray(r)?r.includes(e):(await this.writeDisabledServers([]),!1)}catch(e){if("object"==typeof e&&null!==e&&"code"in e&&"ENOENT"===e.code)return!1;throw e}}async writeDisabledServers(e){await(0,fo.mkdir)((0,s.dirname)(this.storagePath),{recursive:!0}),await(0,fo.writeFile)(this.storagePath,JSON.stringify(e,null,2))}}class NM{constructor(e,t){this.pluginMcpService=e,this.importThirdPartyPlugins=t}async getDefinitions(){let e;try{e=await this.pluginMcpService.getPluginMcpServers()}catch(e){return mM.Jz.warn("[cursor-config-mcp] Failed to enumerate plugin MCP servers:",e),[]}const t=[];for(const r of e){if(!this.importThirdPartyPlugins&&WM(r))continue;const e=LP(r);e?t.push({identifier:r.identifier,authStorageKey:r.identifier,serverConfig:e,configPath:"",source:"plugin",metadata:{identifier:r.identifier,pluginName:r.pluginName,pluginSource:r.pluginSource}}):mM.Jz.warn("[cursor-config-mcp] Failed to initialize plugin MCP client:",{identifier:r.identifier,pluginName:r.pluginName,pluginSource:r.pluginSource,result:"invalid-config",errorMessage:"pluginMcpDescriptorToServerConfig returned undefined"})}return t}}class LM{constructor(e){this.servers=e}async getDefinitions(){return Object.entries(this.servers).map((([e,t])=>({identifier:e,authStorageKey:`inline:${e}`,serverConfig:BM(e,t),source:"inline",metadata:{source:"cursor-sdk"}})))}}function jM(e={}){const t=e.teamSettingsService??{getDotCursorProtection:async()=>!1,getShouldBlockMcp:async()=>!1,getDeleteFileProtection:async()=>!1,getIsHeadlessDisabled:async()=>!1,isServerBlocked:async()=>!1,getTeamRepos:async()=>{},getAutoRunControls:async()=>({enabled:!1,allowed:[],blocked:[],enableAllowlistMode:!0,enableRunEverything:!1,enableSmartAuto:!0,mcpToolAllowlist:[]}),getAdminCommandDenylist:async()=>({rules:[]}),getMcpToolControls:async()=>{},getNetworkAccessControls:async()=>({allowlist:[],denylist:[],available:!0}),getMcpNetworkControlsConfig:async()=>({enabled:!1}),getDefaultNetworkAllowlist:async()=>({allowlist:[],available:!0}),getSandboxingControls:async()=>({sandboxingDisabled:!1,networkingDisabled:!1,gitDisabled:!1}),isAttributionDisabledByAdmin:async()=>!1,invalidateCache:()=>{}},r=e.ignoreApprovals??!1,n=e.importThirdPartyPlugins??!1,i=void 0===e.isLinkSharedPaymentTokenLogRedactionEnabled?{}:{isLinkSharedPaymentTokenLogRedactionEnabled:e.isLinkSharedPaymentTokenLogRedactionEnabled};return{async createLease(a){const c=a.workspaceState,l=c.projectRoot??c.workingDirectory,u=c.projectDirectory;if(!l||!u)return new pP;const d=new FM((0,s.join)(u,"mcp-disabled.json")),h=function(e){const{teamSettingsService:t,projectRoot:r,projectDirectory:n,ignoreApprovals:i,disabledStore:a,includeProjectMcp:c,includeUserMcp:l,isLinkSharedPaymentTokenLogRedactionEnabled:u}=e;if(c&&l)return $M.init(t,r,n,i,a,{isLinkSharedPaymentTokenLogRedactionEnabled:u});if(!c&&!l)return;const d=new WP((0,s.join)(n,"mcp-auth.json")),h=i?{isServerApproved:()=>Promise.resolve(!0)}:new n_((0,s.join)(n,"mcp-approvals.json"),r),p=[new i_,new r_(h),new FP(t),new t_(a)],f=[];return c&&f.push({prefix:"",loader:new NP((0,s.join)(r,".cursor","mcp.json"),d,p,{isLinkSharedPaymentTokenLogRedactionEnabled:u})}),l&&f.push({prefix:"",loader:new NP((0,s.join)((0,o.homedir)(),".cursor","mcp.json"),d,p,{isLinkSharedPaymentTokenLogRedactionEnabled:u})}),UM(f)}({teamSettingsService:t,projectRoot:l,projectDirectory:u,ignoreApprovals:r,disabledStore:d,includeProjectMcp:e.includeProjectMcp??!0,includeUserMcp:e.includeUserMcp??!0,isLinkSharedPaymentTokenLogRedactionEnabled:e.isLinkSharedPaymentTokenLogRedactionEnabled}),p=[],f=e.inlineMcpServers??{};if(Object.keys(f).length>0){const e=new WP((0,s.join)(u,"mcp-auth.json")),r=[new i_,new FP(t)];p.push({prefix:"",loader:new MP(new LM(f),e,r,i)})}const m=DM(a.services.pluginBootstrapOutputs);if(m&&(e.includePluginMcp??1)){const e=new n_((0,s.join)(u,"mcp-approvals.json"),l),o=new WP((0,s.join)(u,"mcp-auth.json")),a=[new i_];r||a.push(new r_(e)),a.push(new FP(t),new t_(d));const c=new j$(m.pluginsService),h=new MP(new NM(c,n),o,a,i);p.push({prefix:"",loader:h})}if(h&&p.push({prefix:"",loader:h}),0===p.length)return new pP;const g=UM(p),w=await g.load(e.initializationCtx??(0,y.q6)(),e.cache);return new OM(w)}}}function UM(e){return 1===e.length?e[0].loader:new AM(e)}function BM(e,t){if("command"in t){if(void 0!==t.type&&"stdio"!==t.type)throw new Error(`Unsupported MCP server type "${String(t.type)}" for "${e}"`);return{command:t.command,args:t.args?[...t.args]:void 0,env:t.env,cwd:t.cwd,startupTimeoutSec:t.startupTimeoutSec}}if("url"in t){if(void 0!==t.type&&"http"!==t.type&&"sse"!==t.type)throw new Error(`Unsupported MCP server type "${String(t.type)}" for "${e}"`);const r={url:t.url,headers:t.headers,auth:t.auth?{CLIENT_ID:t.auth.CLIENT_ID,CLIENT_SECRET:t.auth.CLIENT_SECRET,scopes:t.auth.scopes?[...t.auth.scopes]:void 0}:void 0};return"sse"===t.type?{...r,type:"sse"}:r}throw new Error(`Invalid inline MCP server config for "${e}"`)}function WM(e){return"claude-plugin"===e.pluginSource}const HM=["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass"];function qM(e){let t=e.trim();t.startsWith("&")&&(t=t.slice(1).trim());const r=t.charAt(0);if("'"!==r&&'"'!==r)return t.split(/\s/)[0]??"";let n="";for(let e=1;e<t.length;e++){const o=t.charAt(e);if("'"!==r||"'"!==o||"'"!==t.charAt(e+1)){if(o===r)return n;n+=o}else n+="'",e+=1}return n}function zM(e){return e.slice(Math.max(e.lastIndexOf("\\"),e.lastIndexOf("/"))+1)}const GM=new Set(["cat","cd","chdir","clc","clear","cli","cls","clv","compare","copy","cp","curl","del","diff","dir","echo","erase","fc","fl","foreach","ft","fw","gal","gc","gci","gcm","gi","gl","gm","gp","gps","group","gsv","gu","gv","h","history","icm","iex","ii","kill","lp","ls","man","md","mi","mount","move","mp","mv","ni","nv","ogv","oh","popd","ps","pushd","pwd","r","rd","ren","ri","rm","rmdir","rni","rv","sal","sc","select","set","si","sl","sleep","sls","sort","sp","start","sv","tee","type","wget","where","write"]);function VM(e){const t=qM(e),r=zM(t);return!GM.has(r.toLowerCase())&&(!!/\.(exe|bat|cmd|com)$/i.test(r)||t===r&&/^[A-Za-z0-9_]+$/.test(r))}function KM(e){if(VM(e))return"; if ($null -ne $LASTEXITCODE -and $LASTEXITCODE -ne 0) { exit $LASTEXITCODE } elseif ($null -eq $LASTEXITCODE -and @($Error | Where-Object { $_.Exception -is [System.Management.Automation.CommandNotFoundException] }).Count -gt 0) { exit 127 }";const t=qM(e),r=zM(t);return/\.ps1$/i.test(r)?`; $literalHookCommand = '${t.replace(/'/g,"''")}'; $expectedHookCommand = $ExecutionContext.InvokeCommand.ExpandString($literalHookCommand); if ($null -eq $LASTEXITCODE -and @($Error | Where-Object { $_.Exception -is [System.Management.Automation.CommandNotFoundException] -and ($_.Exception.CommandName -eq $expectedHookCommand -or $_.Exception.CommandName -eq $literalHookCommand -or $_.Exception.CommandName -eq $expectedHookCommand.Replace('\\','/') -or $_.Exception.CommandName -eq $expectedHookCommand.Replace('/','\\') -or $_.Exception.CommandName -eq $literalHookCommand.Replace('\\','/') -or $_.Exception.CommandName -eq $literalHookCommand.Replace('/','\\')) }).Count -gt 0) { exit 127 }`:function(e){const t=qM(e);if(0===t.length||VM(e))return!1;const r=zM(t);return!/\.ps1$/i.test(r)&&(!(t!==r||!/^[a-z0-9]+(?:-[a-z0-9]+)+$/.test(r))||t.includes("/")||t.includes("\\")||r.includes("."))}(e)?"; if ($null -eq $LASTEXITCODE -and @($Error | Where-Object { $_.Exception -is [System.Management.Automation.CommandNotFoundException] }).Count -gt 0) { exit 127 }":""}const JM=[".ps1",".exe",".bat",".cmd"];function ZM(e){const t=e.trimStart();if(0===t.length)return e;if(t.startsWith("&"))return e;const r=t.charAt(0);return"'"===r||'"'===r?`& ${e}`:e}function XM(e){return e?.enableClaudeNestedHookSpecificOutputCompatibility??!1}function QM(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function YM(e){if(!QM(e))return;const t=e.hookSpecificOutput;return QM(t)?t:void 0}function eD(e,t){if(!e)return!1;const r=e.hookEventName;return void 0===r||""===r||r===t}function tD(e,t,r){if(!QM(e))return e;const n=e;if(void 0!==n.followup_message)return n;if("block"===n.decision&&"string"==typeof n.reason&&n.reason.trim().length>0)return{...n,followup_message:n.reason.trim()};if(!XM(t))return n;const o=YM(e),s=eD(o,r)?o:void 0,i=void 0!==s?{...n,...s}:n;return"block"===i.decision&&"string"==typeof i.reason&&i.reason.trim().length>0?{...i,followup_message:i.reason.trim()}:n}const rD=e=>{const t=[];return ju(e)?Bu(!0):(t.push("Expected an object"),Bu(!1,t))},nD=e=>{const t=[],r=rD(e);if(!r.isValid)return r;if(void 0!==e.permission){const r=["allow","deny","ask"];r.includes(e.permission)||t.push(`Invalid permission value. Expected one of: ${r.join(", ")}, or undefined`)}return void 0!==e.user_message&&"string"!=typeof e.user_message&&t.push("Invalid user_message value. Expected a string if provided"),void 0!==e.agent_message&&"string"!=typeof e.agent_message&&t.push("Invalid agent_message value. Expected a string if provided"),Bu(0===t.length,t)};function oD(e){const t=e.modelId,r=e.modelParams;return{...void 0!==t&&{model_id:t},...void 0!==r&&r.length>0?{model_params:r.map((e=>({id:e.id,value:e.value})))}:{}}}const sD=new Set([Nu.sessionStart,Nu.beforeSubmitPrompt,Nu.preToolUse,Nu.postToolUse,Nu.postToolUseFailure]);function iD(e){return"prompt"===e.type}function aD(e){return"command"===e.type||void 0===e.type}const cD={[Nu.beforeShellExecution]:nD,[Nu.beforeMCPExecution]:nD,[Nu.afterShellExecution]:e=>{const t=rD(e);return t.isValid,t},[Nu.afterMCPExecution]:e=>{const t=rD(e);return t.isValid,t},[Nu.beforeReadFile]:e=>{const t=[],r=rD(e);if(!r.isValid)return r;if(void 0!==e.permission){const r=["allow","deny"];r.includes(e.permission)||t.push(`Invalid permission value. Expected one of: ${r.join(", ")}, or undefined`)}return void 0!==e.user_message&&"string"!=typeof e.user_message&&t.push("user_message must be a string if provided"),Bu(0===t.length,t)},[Nu.afterFileEdit]:e=>{const t=rD(e);return t.isValid,t},[Nu.beforeTabFileRead]:e=>{const t=[],r=rD(e);if(!r.isValid)return r;if(void 0!==e.permission){const r=["allow","deny"];r.includes(e.permission)||t.push(`Invalid permission value. Expected one of: ${r.join(", ")}, or undefined`)}return void 0!==e.user_message&&"string"!=typeof e.user_message&&t.push("user_message must be a string if provided"),Bu(0===t.length,t)},[Nu.afterTabFileEdit]:e=>rD(e),[Nu.beforeSubmitPrompt]:e=>{const t=rD(e);if(!t.isValid)return t;const r=[];return void 0!==e.continue&&"boolean"!=typeof e.continue&&r.push("continue must be a boolean if provided"),void 0!==e.user_message&&"string"!=typeof e.user_message&&r.push("user_message must be a string if provided"),void 0===e.additional_context||Lu(e.additional_context)||r.push("additional_context must be a string if provided"),Bu(0===r.length,r)},[Nu.stop]:e=>{const t=rD(e);if(!t.isValid)return t;const r=[];return void 0!==e.followup_message&&"string"!=typeof e.followup_message&&r.push("followup_message must be a string if provided"),Bu(0===r.length,r)},[Nu.afterAgentResponse]:e=>{const t=rD(e);return t.isValid,t},[Nu.afterAgentThought]:e=>{const t=rD(e);return t.isValid,t},[Nu.sessionStart]:e=>{const t=rD(e);if(!t.isValid)return t;const r=[];if(void 0!==e.env)if(ju(e.env))for(const[t,n]of Object.entries(e.env))Lu(t)||r.push(`env key "${t}" must be a string`),Lu(n)||r.push(`env value for "${t}" must be a string`);else r.push("env must be an object if provided");return void 0===e.additional_context||Lu(e.additional_context)||r.push("additional_context must be a string if provided"),void 0!==e.continue&&"boolean"!=typeof e.continue&&r.push("continue must be a boolean if provided"),void 0===e.user_message||Lu(e.user_message)||r.push("user_message must be a string if provided"),Bu(0===r.length,r)},[Nu.sessionEnd]:e=>{const t=rD(e);return t.isValid?Bu(!0,[]):t},[Nu.preCompact]:e=>{const t=rD(e);if(!t.isValid)return t;if(null==e||0===Object.keys(e).length)return Bu(!0,[]);const r=[];if(!Uu(e))return r.push("PreCompact response must be an object"),Bu(!1,r);const n=e;return void 0===n.user_message||(e=>"string"==typeof e)(n.user_message)||r.push("user_message must be a string"),Bu(0===r.length,r)},[Nu.subagentStart]:e=>{const t=rD(e);if(!t.isValid)return t;if(!Uu(e))return Bu(!1,["Expected an object"]);const r=[],n=e;if(void 0!==n.permission){const e=["allow","deny","ask"];"string"==typeof n.permission&&e.includes(n.permission)||r.push(`Invalid permission value. Expected one of: ${e.join(", ")}, or undefined`)}return void 0===n.user_message||Lu(n.user_message)||r.push("user_message must be a string if provided"),Bu(0===r.length,r)},[Nu.subagentStop]:e=>{const t=rD(e);if(!t.isValid)return t;const r=[];return Uu(e)&&void 0!==e.followup_message&&"string"!=typeof e.followup_message&&r.push("followup_message must be a string if provided"),Bu(0===r.length,r)},[Nu.preToolUse]:e=>{const t=[],r=rD(e);if(!r.isValid)return r;if(void 0!==e.permission){const r=["allow","deny","ask"];r.includes(e.permission)||t.push(`Invalid permission value. Expected one of: ${r.join(", ")}, or undefined`)}return void 0!==e.user_message&&"string"!=typeof e.user_message&&t.push("Invalid user_message value. Expected a string if provided"),void 0!==e.agent_message&&"string"!=typeof e.agent_message&&t.push("Invalid agent_message value. Expected a string if provided"),void 0!==e.updated_input&&("object"!=typeof e.updated_input||null===e.updated_input||Array.isArray(e.updated_input))&&t.push("Invalid updated_input value. Expected a plain object if provided"),Wu(e.additional_context,"additional_context",t),Bu(0===t.length,t)},[Nu.postToolUse]:e=>{const t=[],r=rD(e);return r.isValid?(Wu(e.additional_context,"additional_context",t),Bu(0===t.length,t)):r},[Nu.postToolUseFailure]:e=>{const t=rD(e);if(!t.isValid)return t;const r=[];return Wu(e.additional_context,"additional_context",r),Bu(0===r.length,r)},[Nu.workspaceOpen]:e=>{const t=rD(e);if(!t.isValid)return t;const r=[];return void 0!==e.pluginPaths&&(Array.isArray(e.pluginPaths)?e.pluginPaths.forEach(((e,t)=>{"string"==typeof e?0===e.trim().length&&r.push(`pluginPaths[${t}] must be a non-empty string`):r.push(`pluginPaths[${t}] must be a string`)})):r.push("pluginPaths must be an array of strings if provided")),Bu(0===r.length,r)}},lD=(e,t,r)=>{const n=function(e,t,r){let n;return n=e===Nu.preToolUse?function(e,t){if(!QM(e))return e;const r=e;if(void 0!==r.permission||void 0!==r.user_message||void 0!==r.agent_message||void 0!==r.updated_input)return r;if(!XM(t))return r;const n=YM(e);if(!eD(n,"PreToolUse"))return r;const o={...r};let s=!1;return void 0!==n.permissionDecision&&(o.permission=n.permissionDecision,s=!0),"string"==typeof n.permissionDecisionReason&&(o.user_message=n.permissionDecisionReason,s=!0),QM(n.updatedInput)&&(o.updated_input=n.updatedInput,s=!0),s?o:r}(t,r):e===Nu.stop?tD(t,r,"Stop"):e===Nu.subagentStop?tD(t,r,"SubagentStop"):t,function(e,t,r,n){if(!sD.has(e)||!QM(r)||void 0!==r.additional_context)return r;const o=QM(t)?function(e){return"string"==typeof e.additionalContext?e.additionalContext:void 0}(t)??function(e,t,r){if(!XM(r))return;const n=Vu[e];if(void 0===n)return;const o=YM(t);return eD(o,n)&&"string"==typeof o.additionalContext?o.additionalContext:void 0}(e,t,n):void 0;return void 0===o?r:{...r,additional_context:o}}(e,t,n,r)}(e,t,r),o=(0,cD[e])(n);return o.isValid?{success:!0,data:n}:{success:!1,errors:o.errors}},uD=[Nu.beforeShellExecution,Nu.beforeMCPExecution,Nu.beforeReadFile,Nu.beforeTabFileRead,Nu.subagentStart,Nu.preToolUse],dD=[Nu.workspaceOpen];function hD(e,t){const r=[];return"string"==typeof e&&e.trim()&&r.push(e.trim()),"string"==typeof t&&t.trim()&&r.push(t.trim()),r.length>0?r.join("\n\n---\n\n"):void 0}function pD(e,t){return{..."object"==typeof e&&null!==e?e:{},...t}}function fD(e){return uD.includes(e)}function mD({step:e,command:t,failClosed:r,kind:n}){const o=fD(e);if(!r&&!o)return{shouldNotifyUser:!1};const s=r?"Tool blocked because this hook is configured to fail closed (block when it fails). "+("invalid_json"===n?`Hook "${t}" returned invalid JSON.`:`Hook "${t}" returned invalid response.`):"invalid_json"===n?`Hook "${t}" returned invalid JSON. The command was blocked for safety.`:`Hook "${t}" returned an invalid response for this hook step. The command was blocked for safety.`;return{blockResponse:wD(e,s),cause:r?"script_fail_closed":"permission_hook_invalid_output",reason:s,shouldNotifyUser:o&&!r}}function gD(e,t){return t}function wD(e,t){return fD(e)?gD(0,{permission:"deny",user_message:t}):e===Nu.beforeSubmitPrompt||e===Nu.sessionStart?gD(0,{continue:!1,user_message:t}):e===Nu.stop?gD(0,{}):void 0}function yD(e){try{return{value:JSON.parse(e)}}catch{return}}function vD(e){if("object"!=typeof e||null===e)return!1;const t=e.event;return"backgrounded"===t?.case}function bD(e){if("object"!=typeof e||null===e)return;const t=e.path;return"string"==typeof t&&t.length>0?t:void 0}class SD{cacheCarriersForExecId(e,t){const r=this.carriersByExecId.get(e);if(!(void 0!==r&&r.length>0&&0===t.length))for(this.carriersByExecId.has(e)&&this.carriersByExecId.delete(e),this.carriersByExecId.set(e,t);this.carriersByExecId.size>SD.CARRIERS_BY_EXEC_ID_MAX;){const e=this.carriersByExecId.keys().next().value;if(void 0===e)break;this.carriersByExecId.delete(e)}}constructor(e,t,r,n){this.inner=e,this.wake=r,this.carriersByExecId=new Map,this.inFlightByExecId=new Map,this.resolveDrain="function"==typeof t?t:e=>t,this.skipPathWriteDrain=n?.skipPathWriteDrain,this.onWakeWrittenPath=n?.onWakeWrittenPath,this.forceWrittenPathBeforeDrain=n?.forceWrittenPathBeforeDrain,this.writeBarrierTimeoutMs=n?.writeBarrierTimeoutMs??2e3,this.resolveWriteBarrierTimeoutMs=n?.resolveWriteBarrierTimeoutMs,this.onWriteBarrier=n?.onWriteBarrier}resolveTimeoutMs(){if(void 0!==this.resolveWriteBarrierTimeoutMs)try{const e=this.resolveWriteBarrierTimeoutMs();if("number"==typeof e&&Number.isFinite(e))return e}catch{}return this.writeBarrierTimeoutMs}get(e){return this.wrapImpl(e.symbol,this.inner.get(e))}*entries(){for(const[e,t]of this.inner.entries())yield[e,this.wrapImpl(e.symbol,t)]}wrapImpl(e,t){if(!function(e){return"object"==typeof e&&null!==e&&"execute"in e&&"function"==typeof e.execute}(t))return t;const r=function(e){return e===XI.symbol||e===QI.symbol?{kind:"path"}:e===VI.symbol||e===ee.symbol||e===PR.symbol?{kind:"exposed"}:void 0}(e),n=this.resolveDrain,o=this.wake,s=this.skipPathWriteDrain,i=this.forceWrittenPathBeforeDrain,a=()=>this.resolveTimeoutMs(),c=this.onWriteBarrier,l=this.onWakeWrittenPath,u=(e,t)=>{if(void 0!==r&&void 0!==o)try{if("path"===r.kind){const r=bD(e);void 0!==r&&(o.wakeForWrittenPath(r),l?.(r,t))}else o.wakeExposedMounts()}catch{}},d=this.cacheCarriersForExecId.bind(this),h=this.carriersByExecId,p=this.inFlightByExecId,f=async(e,t)=>{const r=t?.hookContextCollector;if(void 0===r)return[];if(!1===t?.deliverAgentStoreConflictNotices)return[];const o=void 0!==t?.execId&&t.execId.length>0?t.execId:void 0;if(void 0!==o){const e=h.get(o);if(void 0!==e)return e.length>0&&r.push(...e),e;const t=p.get(o);if(void 0!==t){const e=await t;return e.length>0&&r.push(...e),e}}const s=async t=>{const r=n(e);let s=[];try{const e=await r.peek();if(s=e.eventIds,e.carriers.length>0)return t.push(...e.carriers),r.ack(e.eventIds),void 0!==o&&d(o,e.carriers),e.carriers;s.length>0&&r.ack(s);const n=[];return void 0!==o&&d(o,n),n}catch{return s.length>0&&r.release(s),[]}};if(void 0===o)return await s(r);const i=s(r);p.set(o,i);try{return await i}finally{p.get(o)===i&&p.delete(o)}};return new Proxy(t,{get:(t,n,o)=>"execute"!==n?Reflect.get(t,n,o):(n,o,l)=>{const d=t.execute.call(t,n,o,l);return"object"==typeof(h=d)&&null!==h&&Symbol.asyncIterator in h&&"function"==typeof h[Symbol.asyncIterator]?async function*(){let t=!1,r=!1,s=!1;try{for await(const r of d)if(e===ee.symbol&&vD(r)){if(!t){u(o,n);const e=await f(n,l);t=!0,e.length>0&&(yield new he.FI({event:{case:"hookContext",value:new he.Ng({hookAdditionalContexts:[...e]})}}))}yield r}else yield r;s=!0}catch(e){throw r=!0,e}finally{u(o,n),t||r||!s||await f(n,l)}}():function(e){return"object"==typeof e&&null!==e&&"then"in e&&"function"==typeof e.then}(d)?(async()=>{try{const t=await d;return u(o,n),e===XI.symbol&&!0===s?.()&&!0===l?.enableAgentStoreConflictNotices||(await async function(e,t,r,n){const o=e=>{try{n.onWriteBarrier?.(e)}catch{}};if(void 0===e||"path"!==r?.kind)return;const s=bD(t);if(void 0===s)return;if(!(n.timeoutMs>0))return void o({durationMs:0,outcome:"skipped"});const i=Date.now(),a=e(s).then((e=>e),(()=>"error")),c=await Promise.race([a,(0,Dr.cb)(n.timeoutMs).then((()=>"timeout"))]);"not_store_path"!==c&&o({durationMs:Date.now()-i,outcome:c})}(i,o,r,{timeoutMs:a(),onWriteBarrier:c}),await f(n,l)),t}catch(e){throw u(o,n),e}})():(u(o,n),d);var h}})}}function kD(e){return new RegExp(`<${e}(?:\\s[^>]*)?>[\\s\\S]*?</${e}>`,"gi")}SD.CARRIERS_BY_EXEC_ID_MAX=32,Error,gl.execFileSync,new Map,go.constants.O_NOFOLLOW,new Set(["write_conflict","create_conflict","truncate_conflict_failed","conflict_fallback_failed","quota_exceeded","gap"]),new Set(["write_conflict","create_conflict","truncate_conflict_failed","conflict_fallback_failed","quota_exceeded"]),Math.max(1,Math.floor(8192));const _D=["user_info","project_layout","rules","always_applied_workspace_rules","agent_requestable_workspace_rules","user_rules","agent_skills","available_skills","cloud_instructions","cloud_task_instructions","open_and_recently_viewed_files","system_reminder","system-reminder","instructions_update","mcp_instructions","mcp_file_system","mcp_file_system_servers","git_status","agent_transcripts","cursor_rules_context","attached_files","system_notification","task_notification","agent_notification"].map(kD);function CD(e){return function(e,t){let r=e;if(r.includes("<"))for(const e of t)r=r.replace(e,"");return(r.includes("\n\n\n")?r.replace(ED,"\n\n"):r).trim()}(e,_D)}["system_reminder","system-reminder"].map(kD);const ED=/\n{3,}/g;function xD(e){const t=(0,uo.sh)(e.conversationId);if("subagent"===e.kind&&e.parentConversationId){const r=(0,uo.sh)(e.parentConversationId);return`${uo.O2}/${r}/subagents/${t}.${e.ext}`}return`${uo.O2}/${t}/${t}.${e.ext}`}function PD(e){const t=(0,uo.sh)(e.conversationId);return`${uo.O2}/${t}.${e.ext}`}function ID(e){const t=e.exts??["jsonl","txt"],r=e.includeLegacy??!0,n=[],o=e=>{n.includes(e)||n.push(e)};for(const n of t)o(xD({conversationId:e.conversationId,ext:n,kind:e.kind,parentConversationId:e.parentConversationId})),"subagent"===e.kind&&e.parentConversationId&&o(xD({conversationId:e.conversationId,ext:n,kind:"primary"})),r&&o(PD({conversationId:e.conversationId,ext:n}));return n}var RD;!function(e){e.INTERNAL="INTERNAL",e.EXTERNAL="EXTERNAL",e.NO_PREAMBLE="NO_PREAMBLE"}(RD||(RD={}));var TD=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},AD=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function $D(e){switch(e){case i.xyI.AGENT:return"agent";case i.xyI.ASK:return"ask";case i.xyI.PLAN:return"plan";case i.xyI.DEBUG:return"debug";case i.xyI.TRIAGE:return"triage";case i.xyI.MULTITASK:return"multitask";case i.xyI.CUSTOM:return"custom";case i.xyI.UNSPECIFIED:default:return"agent"}}function MD(e,t){return t instanceof Uint8Array?{__type:"Uint8Array",hex:(r=t,Array.from(r).map((e=>e.toString(16).padStart(2,"0"))).join(""))}:"bigint"==typeof t?t.toString():t;var r}function DD(e,t){return function(e){return"object"==typeof e&&null!==e&&"__type"in e&&"Uint8Array"===e.__type&&"hex"in e&&"string"==typeof e.hex}(t)?`[Binary data omitted from transcript: ${t.hex.length/2} bytes]`:t}const OD=new TextEncoder,FD=new TextDecoder,ND=new class{serialize(e){const t=JSON.stringify(e,MD);return OD.encode(t)}deserialize(e){const t=FD.decode(e);return t.includes('"__type":"Uint8Array"')?JSON.parse(t,DD):JSON.parse(t)}};function LD(e){const t=e.providerOptions;return!0===t?.cursor?.isSummary}function jD(e){return"system"!==e.role&&!LD(e)}function UD(e,t){return"user"===e.role&&"user"===t.role}async function BD(e,t,r){const n=await t.getBlob(e,r);return n?i.Anz.fromBinary(n).summarizedMessages:[]}async function WD(e,t,r,n){const o=await t.getBlob(e,r);if(o){if(o.length>5e6)return n.omittedOversizeBlobCount++,n.omittedOversizeBlobBytes+=o.length,n.largestOmittedOversizeBlobBytes=Math.max(n.largestOmittedOversizeBlobBytes,o.length),{role:"assistant",content:`[Oversize transcript blob omitted: ${s=o.length,`${(s/1e6).toFixed(1)} MB`}]`};var s;try{const e=performance.now(),t=ND.deserialize(o);return n.totalDeserializeDurationMs+=performance.now()-e,n.hydratedBlobCount++,n.hydratedBlobBytes+=o.length,n.largestHydratedBlobBytes=Math.max(n.largestHydratedBlobBytes,o.length),t}catch{return}}}async function HD(e,t,r){const n={messages:[],hydratedBlobCount:0,hydratedBlobBytes:0,largestHydratedBlobBytes:0,totalDeserializeDurationMs:0,omittedOversizeBlobCount:0,omittedOversizeBlobBytes:0,largestOmittedOversizeBlobBytes:0};for(const o of r){const r=await WD(e,t,o,n);r&&n.messages.push(r)}return n}async function qD(e,t,r,n,o){const s=[];let i=0;const a=()=>{const o=WD(e,t,r[i++],n);o.catch((()=>{})),s.push(o)};for(;i<r.length&&s.length<8;)a();for(let e=s.shift();e;e=s.shift()){let t;try{t=await e}catch(e){if(!o.skipFailedReads)throw e}i<r.length&&a(),t&&await o.visit(t)}}function zD(e,t){switch(e.type){case"text":return t?GD(e.text):e.text;case"image":return"[Image]";case"file":return e.filename?`[File: ${e.filename}]`:"[File]";case"reasoning":return`[Thinking] ${e.text}`;case"redacted-reasoning":return"[Thinking]";case"tool-call":return`[Tool call] ${e.toolName}${function(e){if(null==e)return"";switch(typeof e){case"string":return e;case"number":case"boolean":case"bigint":case"symbol":case"function":return e.toString()}const t=Object.entries(e);return 0===t.length?"":`\n${t.map((([e,t])=>{let r;return r="string"==typeof t?t:"object"==typeof t&&null!==t?JSON.stringify(t):String(t),` ${e}: ${r}`})).join("\n")}`}(e.args)}`;case"tool-result":return`[Tool result] ${e.toolName}`;default:return""}}function GD(e){return CD(e)}const VD=/<think>[\s\S]*?<\/think>/gi,KD=/<thinking>[\s\S]*?<\/thinking>/gi,JD=/\n{3,}/g;function ZD(e){let t=e;return t.includes("<")&&(t=t.replace(VD,"").replace(KD,"")),(t.includes("\n\n\n")?t.replace(JD,"\n\n"):t).trim()}function XD(e,t,r){if(void 0===e)return"";if("string"==typeof e){const n=t?GD(e):e;return r?ZD(n):n}return e.map((e=>{if(r&&"text"===e.type){const r=ZD(t?GD(e.text):e.text);return zD({...e,text:r},!1)}return zD(e,t)})).filter(Boolean).join("\n")}function QD(e,t){const r={role:e.role},n=e.content;if("string"==typeof n){const o=t?GD(n):n,s="assistant"===e.role?ZD(o):o;s.trim()&&(r.text=s)}else if(Array.isArray(n)){const o=[],s=[],i=[];let a;for(const r of n)switch(r.type){case"text":{const n=t?GD(r.text):r.text,s="assistant"===e.role?ZD(n):n;s.trim()&&o.push(s);break}case"reasoning":r.text.trim()&&s.push(r.text);break;case"redacted-reasoning":s.push("[REDACTED]");break;case"image":o.push("[Image]");break;case"file":o.push(r.filename?`[File: ${r.filename}]`:"[File]");break;case"tool-call":i.push({toolName:r.toolName,args:r.args});break;case"tool-result":a={toolName:r.toolName}}o.length>0&&(r.text=o.join("\n")),s.length>0&&(r.thinking=s.join("\n")),i.length>0&&(r.toolCalls=i),a&&(r.toolResult=a)}return r}function YD(e){return e.endsWith("\n")?e:`${e}\n`}function eO(e){const{turnEnded:t}=e,r=[],n={},o=[];return void 0!==t&&(r.push(function(e){switch(e.status){case"success":return"Turn ended: success.";case"error":return`Turn ended: error: ${e.error}`;case"aborted":return e.error?`Turn ended: aborted: ${e.error}`:"Turn ended: aborted.";default:return e}}(t)),n.turnEnded=t,o.push(JSON.stringify({type:"turn_ended",...t}))),{textSuffixes:r,jsonFields:n,jsonlLines:o}}function tO(e){if("system"===e.role||LD(e))return;const t=QD(e,"user"===e.role),r=[],n=[];if(t.text&&n.push(t.text),t.thinking&&n.push(t.thinking),n.length>0&&r.push({type:"text",text:n.join("\n\n")}),t.toolCalls)for(const e of t.toolCalls)r.push({type:"tool_use",name:e.toolName,input:e.args});if(0===r.length)return;const o={role:e.role,message:{content:r}};return JSON.stringify(o)}class rO{constructor(e,t,r,n={}){this.projectDir=e,this.blobStore=t,this.writeFile=r,this.options={writeText:n.writeText??!0,writeJson:n.writeJson??!1,writeJsonl:n.writeJsonl??!1,pathResolver:n.pathResolver,appendFile:n.appendFile,streamFullJsonlWrites:n.streamFullJsonlWrites??!1,fallbackToFullWriteOnIncrementalFailure:n.fallbackToFullWriteOnIncrementalFailure??!0}}resolveFilePath(e,t){if(this.options.pathResolver)return this.options.pathResolver(e,t);const r=xD({conversationId:e,ext:t,kind:"primary"});return`${this.projectDir}/${r}`}async writeFromStateFull(e,t,r,n={}){const o={stack:[],error:void 0,hasError:!1};try{const s=TD(o,(0,$.VI)(e.withName("writeFromState")),!1);try{const{overviewFactory:e}=n,o=eO(n),{appendFile:i,streamFullJsonlWrites:a,writeJsonl:c,writeText:l,writeJson:u}=this.options;if(i&&a&&c&&!l&&!u&&!e)try{return await this.writeJsonlStreamed(s,{state:t,filePath:this.resolveFilePath(r,"jsonl"),appendFile:i,terminalLines:o.jsonlLines}),!0}catch(e){console.error("[TranscriptStore] Streamed transcript write failed, retrying as a single write:",e)}const d=await async function(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=TD(n,(0,$.VI)(e.withName("hydrateSummaryArchives")),!1);let s=0;const i=(0,$.OA)(o.ctx),a=[];let c=0,l=0,u=0,d=0,h=0,p=0,f=0;const m=await Promise.all(r.summaryArchives.map((async e=>{s++;try{const r=await BD(i,t,e);return s+=r.length,await HD(i,t,r)}catch{return{messages:[],hydratedBlobCount:0,hydratedBlobBytes:0,largestHydratedBlobBytes:0,totalDeserializeDurationMs:0,omittedOversizeBlobCount:0,omittedOversizeBlobBytes:0,largestOmittedOversizeBlobBytes:0}}})));for(const e of m)a.push(...e.messages),c+=e.hydratedBlobCount,l+=e.hydratedBlobBytes,u=Math.max(u,e.largestHydratedBlobBytes),d+=e.totalDeserializeDurationMs,h+=e.omittedOversizeBlobCount,p+=e.omittedOversizeBlobBytes,f=Math.max(f,e.largestOmittedOversizeBlobBytes);o.span.setAttribute("getBlobCount",s),o.span.setAttribute("hydratedBlobCount",c),o.span.setAttribute("hydratedBlobBytes",l),o.span.setAttribute("largestHydratedBlobBytes",u),o.span.setAttribute("totalDeserializeDurationMs",d),o.span.setAttribute("omittedOversizeBlobCount",h),o.span.setAttribute("omittedOversizeBlobBytes",p),o.span.setAttribute("largestOmittedOversizeBlobBytes",f);const g=TD(n,(0,$.VI)(e.withName("hydratePromptMessages")),!1),w=await HD(i,t,r.rootPromptMessagesJson);g.span.setAttribute("getBlobCount",r.rootPromptMessagesJson.length),g.span.setAttribute("hydratedBlobCount",w.hydratedBlobCount),g.span.setAttribute("hydratedBlobBytes",w.hydratedBlobBytes),g.span.setAttribute("largestHydratedBlobBytes",w.largestHydratedBlobBytes),g.span.setAttribute("totalDeserializeDurationMs",w.totalDeserializeDurationMs),g.span.setAttribute("omittedOversizeBlobCount",w.omittedOversizeBlobCount),g.span.setAttribute("omittedOversizeBlobBytes",w.omittedOversizeBlobBytes),g.span.setAttribute("largestOmittedOversizeBlobBytes",w.largestOmittedOversizeBlobBytes);const y=w.messages.filter(jD);return a.push(...y),a}catch(e){n.error=e,n.hasError=!0}finally{AD(n)}}(s.ctx,this.blobStore,t);if(0===d.length&&0===o.jsonlLines.length)return!0;let h;if((this.options.writeText||e)&&(h=function(e){let t=e.filter((e=>"system"!==e.role));t.length>=2&&"user"===t[0].role&&"user"===t[1].role&&(t=t.slice(1));const r=[];for(const e of t){const t="user"===e.role,n="assistant"===e.role,o=XD(e.content,t,n);o.trim()&&("tool"===e.role?r.push(o):r.push(`${e.role}:\n${o}`))}return r.join("\n\n")}(d)),this.options.writeText){const e=h??"",t=o.textSuffixes.length>0?e.trim().length>0?`${e}\n\n${o.textSuffixes.join("\n")}`:o.textSuffixes.join("\n"):e;t.trim()&&await this.writeFile(this.resolveFilePath(r,"txt"),t)}if(this.options.writeJson){const e=function(e){let t=e.filter((e=>"system"!==e.role));t.length>=2&&"user"===t[0].role&&"user"===t[1].role&&(t=t.slice(1));const r=[];for(const e of t){const t=QD(e,"user"===e.role);(t.text||t.thinking||t.toolCalls||t.toolResult)&&r.push(t)}return 0===r.length?"":JSON.stringify(r,null,2)}(d);if(e||o.jsonlLines.length>0){const n={mode:$D(t.mode),messages:e?JSON.parse(e):[],...o.jsonFields};await this.writeFile(this.resolveFilePath(r,"json"),JSON.stringify(n,null,2))}}if(this.options.writeJsonl){const t=function(e){let t=e.filter((e=>"system"!==e.role));t.length>=2&&UD(t[0],t[1])&&(t=t.slice(1));const r=[];for(const e of t){const t=tO(e);t&&r.push(t)}return r.join("\n")}(d);let n=[t,...o.jsonlLines].filter((e=>e.length>0)).join("\n");if(n&&e&&h?.trim())try{const t=(await e(h)).trim();t&&(n=function(e,t){const r={type:"metadata",metadata:{overview:t}};return`${JSON.stringify(r)}\n${e}`}(n,t))}catch(e){console.error("[TranscriptStore] Failed to generate transcript overview:",e)}n&&await this.writeFile(this.resolveFilePath(r,"jsonl"),YD(n))}return!0}catch(e){return console.error("[TranscriptStore] Failed to write transcript:",e),!1}}catch(e){o.error=e,o.hasError=!0}finally{AD(o)}}async writeJsonlStreamed(e,t){const{filePath:r,appendFile:n}=t;let o=[],s=0,i=0,a=0;const c=async()=>{if(0===o.length)return;const e=`${o.join("\n")}\n`;o=[],s=0,0===i?await this.writeFile(r,e):await n(r,e),i++,a+=e.length},l=async e=>{e&&(o.push(e),s+=e.length+1,s>=1e6&&await c())};let u,d=0;const h=await async function(e,t,r,n){const o={hydratedBlobCount:0,hydratedBlobBytes:0,largestHydratedBlobBytes:0,totalDeserializeDurationMs:0,omittedOversizeBlobCount:0,omittedOversizeBlobBytes:0,largestOmittedOversizeBlobBytes:0};for(const s of r.summaryArchives){let r;try{r=await BD(e,t,s)}catch{continue}await qD(e,t,r,o,{skipFailedReads:!0,visit:n})}return await qD(e,t,r.rootPromptMessagesJson,o,{skipFailedReads:!1,visit:async e=>{jD(e)&&await n(e)}}),o}((0,$.OA)(e.ctx),this.blobStore,t.state,(async e=>{"system"!==e.role&&(d++,1!==d?(2===d&&u&&(UD(u,e)||await l(tO(u)),u=void 0),await l(tO(e))):u=e)}));u&&await l(tO(u));for(const e of t.terminalLines)await l(e);await c(),e.span.setAttribute("streamed",!0),e.span.setAttribute("chunkCount",i),e.span.setAttribute("writtenChars",a),e.span.setAttribute("hydratedBlobCount",h.hydratedBlobCount),e.span.setAttribute("hydratedBlobBytes",h.hydratedBlobBytes),e.span.setAttribute("largestHydratedBlobBytes",h.largestHydratedBlobBytes),e.span.setAttribute("totalDeserializeDurationMs",h.totalDeserializeDurationMs),e.span.setAttribute("omittedOversizeBlobCount",h.omittedOversizeBlobCount),e.span.setAttribute("omittedOversizeBlobBytes",h.omittedOversizeBlobBytes),e.span.setAttribute("largestOmittedOversizeBlobBytes",h.largestOmittedOversizeBlobBytes)}async writeFromStateIncremental(e,t,r,n,o={}){const s={stack:[],error:void 0,hasError:!1};try{const i=t.rootPromptMessagesJson.length,a=eO(o),c=a.jsonlLines.length>0;if(i===n&&!c&&!o.overviewFactory)return i;const l=this.options.appendFile;if(!(l&&this.options.writeJsonl&&!this.options.writeText&&!this.options.writeJson&&n>0&&i>=n&&(i>n||c))||o.overviewFactory)return await this.writeFromStateFull(e,t,r,o)?i:0;const u=TD(s,(0,$.VI)(e.withName("writeFromStateIncremental")),!1);if(i===n&&c)try{return await l(this.resolveFilePath(r,"jsonl"),YD(a.jsonlLines.join("\n"))),i}catch(n){return console.error(this.options.fallbackToFullWriteOnIncrementalFailure?"[TranscriptStore] Failed to append transcript, falling back to full write:":"[TranscriptStore] Failed to append transcript:",n),this.options.fallbackToFullWriteOnIncrementalFailure?await this.writeFromStateFull(e,t,r,o)?i:0:0}try{const e=t.rootPromptMessagesJson.slice(n),o=await HD(u.ctx,this.blobStore,e);u.span.setAttribute("hydratedBlobCount",o.hydratedBlobCount),u.span.setAttribute("hydratedBlobBytes",o.hydratedBlobBytes),u.span.setAttribute("largestHydratedBlobBytes",o.largestHydratedBlobBytes),u.span.setAttribute("totalDeserializeDurationMs",o.totalDeserializeDurationMs),u.span.setAttribute("omittedOversizeBlobCount",o.omittedOversizeBlobCount),u.span.setAttribute("omittedOversizeBlobBytes",o.omittedOversizeBlobBytes),u.span.setAttribute("largestOmittedOversizeBlobBytes",o.largestOmittedOversizeBlobBytes);const s=[];for(const e of o.messages){const t=tO(e);t&&s.push(t)}if(s.push(...a.jsonlLines),s.length>0){const e=YD(s.join("\n"));await l(this.resolveFilePath(r,"jsonl"),e)}return i}catch(n){return console.error(this.options.fallbackToFullWriteOnIncrementalFailure?"[TranscriptStore] Failed to append transcript, falling back to full write:":"[TranscriptStore] Failed to append transcript:",n),this.options.fallbackToFullWriteOnIncrementalFailure?await this.writeFromStateFull(e,t,r,o)?i:0:0}}catch(e){s.error=e,s.hasError=!0}finally{AD(s)}}}function nO(e,t){const r=function(e){return"object"==typeof e&&null!==e}(e)&&t in e?e[t]:void 0;return"string"==typeof r&&""!==r?r:void 0}function oO(e,t){return e.filter((e=>function(e,t){if(!e.matcher||""===e.matcher||"*"===e.matcher)return!0;if(void 0===t)return!0;try{return new RegExp(e.matcher).test(t)}catch{return!0}}(e,t)))}function sO(e){return`Tool blocked because this hook is configured to fail closed (block when it fails). ${e}`}function iO(e){return Object.values(Nu).some((t=>t===e))}function aO(e){switch(e??(0,o.platform)()){case"darwin":return s.default.join("/Library","Application Support","Cursor","hooks.json");case"win32":return s.default.join("C:\\","ProgramData","Cursor","hooks.json");default:return s.default.join("/etc","cursor","hooks.json")}}function cO(e){return iD(e)?`prompt:${e.prompt}`:`command:${e.command}`}function lO(e){return(e.repoHooks??[]).flatMap((e=>[e.projectHooks,e.claudeProjectHooks,e.claudeProjectLocalHooks]))}class uO{constructor(e,t,r){this.fileReader=e,this.paths=t,this.logger=r||{warn:e=>console.warn(`[hooks] ${e}`),info:e=>{}}}async load(e={}){const{loadProjectHooks:t=!0}=e,r={errors:[],configDirs:{}},n=this.paths.projectConfigPath??this.paths.claudeProjectConfigPath??this.paths.claudeProjectLocalConfigPath,o=n?s.default.dirname(s.default.dirname(n)):void 0,i=(e,t)=>{if(!e||!o)return;if(t)return o;const r=s.default.relative(s.default.resolve(o),s.default.resolve(e));return".."===r||r.startsWith(`..${s.default.sep}`)||s.default.isAbsolute(r)?void 0:o},a=async(e,t,n,o,i,a,c,l)=>{if(e)try{if(!await this.fileReader.exists(e))return;if(c&&this.fileReader.pathContainsSymlink&&await this.fileReader.pathContainsSymlink(e,c))return r.errors.push({source:t,message:`${i} at ${e}: refusing to load config path that contains a symlink`}),void this.logger.warn(`Refusing to load ${a} config via symlink path: ${e}`);const u=await this.fileReader.readFile(e);if(!u)return;const{config:d,error:h}=l(u);if(d){switch(n){case"enterpriseHooks":r.enterpriseHooks=d;break;case"teamHooks":r.teamHooks=d;break;case"userHooks":r.userHooks=d;break;case"projectHooks":r.projectHooks=d;break;case"claudeUserHooks":r.claudeUserHooks=d;break;case"claudeProjectHooks":r.claudeProjectHooks=d;break;case"claudeProjectLocalHooks":r.claudeProjectLocalHooks=d;break;default:return}((e,t)=>{r.configDirs[e]=s.default.dirname(t)})(o,e)}else h&&r.errors.push({source:t,message:`${i} at ${e}: ${h}`})}catch(e){r.errors.push({source:t,message:`Error accessing ${a} config file: ${String(e)}`})}},c=[{path:this.paths.enterpriseConfigPath,source:"enterprise",resultKey:"enterpriseHooks",configDirKey:"enterprise",parsePrefix:"Enterprise hooks.json",accessLabel:"enterprise",symlinkCheckRoot:i(this.paths.enterpriseConfigPath,!1)},{path:this.paths.teamConfigPath,source:"team",resultKey:"teamHooks",configDirKey:"team",parsePrefix:"Team hooks.json",accessLabel:"team",symlinkCheckRoot:i(this.paths.teamConfigPath,!1)},{path:this.paths.userConfigPath,source:"user",resultKey:"userHooks",configDirKey:"user",parsePrefix:"User hooks.json",accessLabel:"user",symlinkCheckRoot:i(this.paths.userConfigPath,!1)},{path:t?this.paths.projectConfigPath:void 0,source:"project",resultKey:"projectHooks",configDirKey:"project",parsePrefix:"Project hooks.json",accessLabel:"project",symlinkCheckRoot:i(this.paths.projectConfigPath,!0)}];for(const e of c)await a(e.path,e.source,e.resultKey,e.configDirKey,e.parsePrefix,e.accessLabel,e.symlinkCheckRoot,(t=>this.parseAndValidate(t,e.source)));const l=[{path:this.paths.claudeUserConfigPath,source:"claude-user",resultKey:"claudeUserHooks",configDirKey:"claudeUser",label:"user",symlinkCheckRoot:i(this.paths.claudeUserConfigPath,!1)},{path:t?this.paths.claudeProjectConfigPath:void 0,source:"claude-project",resultKey:"claudeProjectHooks",configDirKey:"claudeProject",label:"project",symlinkCheckRoot:i(this.paths.claudeProjectConfigPath,!0)},{path:t?this.paths.claudeProjectLocalConfigPath:void 0,source:"claude-project-local",resultKey:"claudeProjectLocalHooks",configDirKey:"claudeProjectLocal",label:"project local",symlinkCheckRoot:i(this.paths.claudeProjectLocalConfigPath,!0)}];for(const e of l)await a(e.path,e.source,e.resultKey,e.configDirKey,`Claude ${e.label} settings.json`,`Claude ${e.label}`,e.symlinkCheckRoot,(t=>this.parseClaudeConfig(t,e.source)));return function(e){const{cursorConfigs:t,claudeConfigs:r,logger:n}=e,o=new Map;for(const e of t)if(e?.hooks)for(const[t,r]of Object.entries(e.hooks)){if(!r)continue;let e=o.get(t);e||(e=new Set,o.set(t,e));for(const t of r)e.add(cO(t))}for(const{config:e,source:t}of r)if(e?.hooks)for(const[r,s]of Object.entries(e.hooks)){if(!s)continue;const i=o.get(r);if(!i||0===i.size)continue;const a=s.filter((e=>{const o=cO(e);return!i.has(o)||(n?.info(`Removed duplicate ${t} hook for ${r}: ${o}`),!1)}));a.length!==s.length&&(e.hooks[r]=a)}}({cursorConfigs:[r.enterpriseHooks,r.teamHooks,r.userHooks,r.projectHooks],claudeConfigs:[{config:r.claudeUserHooks,source:"claude-user"},{config:r.claudeProjectHooks,source:"claude-project"},{config:r.claudeProjectLocalHooks,source:"claude-project-local"}],logger:this.logger}),r}parseClaudeConfig(e,t){try{const t=JSON.parse(e);if(!function(e,t={}){if(!Uu(e))return!1;if(!("hooks"in e))return!1;const r=e.hooks;if(!Uu(r))return!1;const n=r;for(const[e,r]of Object.entries(n))if(e in Gu&&Array.isArray(r)){const n=!0===t.allowMatcherlessStop&&"Stop"===e;for(const e of r)if(Uu(e)&&"hooks"in e&&Array.isArray(e.hooks)&&("matcher"in e||n))return!0}return!1}(t))return{};const r=t.hooks;if(!r||0===Object.keys(r).length)return{};const n=cd(r,this.logger),o=zu(n);return o.isValid?{config:n}:{error:`Invalid transformed config: ${o.errors.join("; ")}`}}catch(e){return{error:`Failed to parse JSON: ${String(e)}`}}}parseAndValidate(e,t){try{const n=this.parseJSONC(e),o=zu(n);return o.isValid?"object"==typeof(r=n)&&null!==r&&"version"in r&&"number"==typeof r.version&&"hooks"in r&&"object"==typeof r.hooks&&null!==r.hooks&&!Array.isArray(r.hooks)?{config:n}:{error:`Invalid ${t} config: missing 'hooks' property`}:{error:`Invalid ${t} config: ${o.errors.join("; ")}`}}catch(e){return{error:`Failed to parse ${t} config JSON: ${String(e)}`}}var r}parseJSONC(e){let t=e.replace(/\/\/.*$/gm,"");return t=t.replace(/\/\*[\s\S]*?\*\//g,""),JSON.parse(t)}static getConfiguredSteps(e){const t=new Set,r=[e.enterpriseHooks,e.teamHooks,e.userHooks,e.projectHooks,e.claudeUserHooks,e.claudeProjectHooks,e.claudeProjectLocalHooks,...lO(e)];for(const e of r)if(e?.hooks)for(const r of Object.keys(e.hooks))iO(r)&&t.add(r);for(const r of e.pluginHooks??[])for(const e of Object.keys(r.config.hooks))iO(e)&&t.add(e);return t}}const dO="Read",hO="Write",pO="Delete",fO="List",mO="Grep",gO="Shell",wO="ReadLints";function yO(e,t){if("object"==typeof e&&null!==e)return Object.getOwnPropertyDescriptor(e,t)?.value}const vO=new Set([dO,hO,pO,fO,mO,wO]);function bO(e){const t=yO(e,"tool_name"),r=[yO(e,"file_path"),"string"==typeof t&&vO.has(t)?yO(yO(e,"tool_input"),"file_path"):void 0];for(const e of r)if("string"==typeof e&&e.length>0)return e}const SO=(0,l.h)("cli-hooks-executor");function kO(e){try{return(0,go.statSync)(e).isFile()}catch{return!1}}const _O="\nJSON Parse Error: Error: Failed to parse hook stdout as JSON";function CO(e,t){for(const[r,n]of Object.entries(e))if(r===t)return n}function EO(e,t){const r=CO(e,t);if("string"==typeof r||null===r)return r}class xO{constructor(e,t,r,n,o,s,i,a){this.workspacePath=t,this.globalContext=r,this.shellExecutor=n,this.promptHookClient=o,this.onHookExecution=i,this.options=a,this.sessionEnvById=new Map,this.sessionUserEmailById=new Map,this.activeSessionIdsByConversationId=new Map,this.transcriptParentConversationIdById=new Map,this.configReadyPromises=[],this.config=e,s&&this.addConfigReadyPromise(s)}addConfigReadyPromise(e){this.configReadyPromises.push(e.catch((()=>{})))}reportCommandFailure(e,t){if(void 0!==e)try{e(t)}catch{}}finishHookRun(e,t,r,n){const o=e.transportMode??("prompt"===e.hookType?"prompt":this.getCommandHookPayloadTransportMode());try{this.onHookExecution?.({...e,transportMode:o})}catch{}const s=this.options?.onHookRun;if(void 0===s)return;const i=n.exitCode??e.exitCode,a="spawn_error"===(c=e.errorClass)?"shell_exec_transport_error":"prompt_error"===c?"prompt_execution_error":void 0;var c;try{s({step:e.hookStep,script:t,source:e.hookSource,...void 0===e.pluginId?{}:{pluginId:e.pluginId},request:r,response:n.response??null,durationMs:e.latencyMs,...void 0===i?{}:{exitCode:i},stderr:n.stderr,transportMode:o,configuredTimeoutSec:t.timeout??60,timedOut:!0===e.timedOut,...void 0===a?{}:{failureType:a}})}catch{}}getCommandHookPayloadTransportMode(){return"stdin"===this.options?.commandHookPayloadTransport?"win32"===process.platform?"windows_temp_file":"stdin":"argv_heredoc"}shouldUseCommandHookDirectStdinTransport(){return"stdin"===this.getCommandHookPayloadTransportMode()}async writeCommandHookStdinPayload(e,t){if(!e)throw new Error("Hook stdin transport was requested, but the executor did not provide stdin");try{e.end(Buffer.from(t,"utf8"))}catch(e){const t=e instanceof Error&&"code"in e?e.code:void 0;if("EPIPE"===t||"ERR_STREAM_DESTROYED"===t||"ERR_STREAM_PREMATURE_CLOSE"===t)return;throw e}try{await(0,qh.finished)(e)}catch(e){const t=e instanceof Error&&"code"in e?e.code:void 0;if("EPIPE"===t||"ERR_STREAM_DESTROYED"===t||"ERR_STREAM_PREMATURE_CLOSE"===t)return;throw e}}updateConfig(e){this.config=e}beginSessionEnvironment(e,t){this.sessionEnvById.delete(e.sessionId),this.sessionUserEmailById.delete(e.sessionId);const r=this.activeSessionIdsByConversationId.get(e.conversationId)??[];this.activeSessionIdsByConversationId.set(e.conversationId,r.filter((t=>t!==e.sessionId)).concat(e.sessionId));const n=t?.userEmail?.trim()??"";n.length>0&&this.sessionUserEmailById.set(e.sessionId,n)}setSessionUserEmail(e,t){const r=t?.trim()??"";0!==r.length&&this.sessionUserEmailById.set(e.sessionId,r)}setSessionEnvironment(e,t){void 0===t?this.sessionEnv={...this.sessionEnv,...e}:this.sessionEnvById.set(t.sessionId,{...this.sessionEnvById.get(t.sessionId),...e})}clearSessionEnvironment(e){if(void 0===e)this.sessionEnv=void 0;else{this.sessionEnvById.delete(e.sessionId),this.sessionUserEmailById.delete(e.sessionId);const t=(this.activeSessionIdsByConversationId.get(e.conversationId)??[]).filter((t=>t!==e.sessionId));0===t.length?this.activeSessionIdsByConversationId.delete(e.conversationId):this.activeSessionIdsByConversationId.set(e.conversationId,t)}}resolveUserEmail(e){const{conversation_id:t,session_id:r}=e;if(void 0!==r&&this.sessionUserEmailById.has(r))return this.sessionUserEmailById.get(r)??null;if(void 0!==t){const e=this.activeSessionIdsByConversationId.get(t)?.at(-1);if(void 0!==e){const t=this.sessionUserEmailById.get(e);if(void 0!==t)return t}}return this.globalContext.user_email}setTranscriptParentConversationId(e,t){this.transcriptParentConversationIdById.set(e,t)}async getTranscriptPathIfExists(e){try{const t=(0,uo.Rv)((0,o.homedir)(),this.workspacePath),r=this.transcriptParentConversationIdById.get(e),n=ID(r?{conversationId:e,kind:"subagent",parentConversationId:r}:{conversationId:e,kind:"primary"}).map((e=>(0,s.join)(t,e)));for(const e of n)try{return await(0,fo.access)(e),e}catch{}return null}catch{return null}}async getSubagentTranscriptPathIfExists(e){const{subagentId:t,parentConversationId:r}=e;try{const e=(0,uo.Rv)((0,o.homedir)(),this.workspacePath),n=ID({conversationId:t,kind:"subagent",parentConversationId:r}).map((t=>(0,s.join)(e,t)));for(const e of n)try{return await(0,fo.access)(e),e}catch{}return null}catch{return null}}hasHooksForStep(e){return[this.config.enterpriseHooks,this.config.teamHooks,this.config.userHooks,this.config.projectHooks,this.options?.runtimeHooks,this.config.claudeUserHooks,this.config.claudeProjectHooks,this.config.claudeProjectLocalHooks,...lO(this.config),...(this.config.pluginHooks??[]).map((e=>e.config))].some((t=>{const r=t?.hooks[e];return void 0!==r&&r.length>0}))}hasFailClosedHooksForStep(e,t){const r=[this.config.enterpriseHooks,this.config.teamHooks,this.config.projectHooks,...(this.config.repoHooks??[]).map((e=>e.projectHooks)),this.config.userHooks,this.options?.runtimeHooks];for(const n of r){const r=n?.hooks[e];if(r&&(t?oO(r,t):r).some((e=>!0===e.failClosed)))return!0}for(const r of this.config.pluginHooks??[]){const n=r.config.hooks[e];if(n&&(t?oO(n,t):n).some((e=>aD(e)&&!0===e.failClosed)))return!0}return!1}configuredHookDirectory(e){const t=this.config.configDirs;switch(e){case"enterprise":return t?.enterprise;case"team":return t?.team;case"user":return t?.user;case"claude-user":return t?.claudeUser;default:return}}cwdForHookSource(e,t){if(void 0!==e?.cwd&&e.cwd.length>0)return e.cwd;const r=this.configuredHookDirectory(t.source);if(void 0!==r&&r.length>0)return r;const n=e?.cwdForSource?.(t.source);return void 0!==n&&n.length>0?n:t.fallback}getCwdForSource(e){const t=this.config.configDirs;switch(e){case"enterprise":return t?.enterprise??this.workspacePath;case"team":return t?.team??this.workspacePath;case"project":case"claude-project":case"claude-project-local":case"claude-plugin":case"runtime":default:return this.workspacePath;case"user":return t?.user??this.workspacePath;case"claude-user":return t?.claudeUser??this.workspacePath}}buildHookEnvironment(e){const{transcriptPath:t,sessionId:r,conversationId:n,executionEnv:o}=e,s=this.resolveUserEmail({conversation_id:n,session_id:r});return{CURSOR_PROJECT_DIR:this.workspacePath,CURSOR_VERSION:this.globalContext.cursor_version,...s&&{CURSOR_USER_EMAIL:s},...t&&{CURSOR_TRANSCRIPT_PATH:t},CLAUDE_PROJECT_DIR:this.workspacePath,...this.sessionEnv,...void 0!==r?this.sessionEnvById.get(r):void 0,...o}}shouldSkipHookDueToLoopLimit(e,t,r){if("stop"!==e&&"subagentStop"!==e)return!1;const n=CO(r,"loop_count");if("number"!=typeof n)return!1;const o=n,s=t.loop_limit;return null!==s&&(void 0===s?o>=5:o>=s)}async executeHookForStep(e,t,r){this.configReadyPromises.length>0&&await this.whenConfigReady();const n=function(e){return dD.includes(e)}(e),o=t,i=n?null:o.conversation_id?await this.getTranscriptPathIfExists(o.conversation_id):null;let a;if(e===Nu.subagentStop){const e=EO(t,"subagent_id"),r=EO(t,"parent_conversation_id");a=e?await this.getSubagentTranscriptPathIfExists({subagentId:e,parentConversationId:r??void 0}):null}const c=n?void 0:o.session_id??o.conversation_id,l={...t,...void 0!==c&&{session_id:c},hook_event_name:e,cursor_version:this.globalContext.cursor_version,workspace_roots:[...new Set([this.workspacePath,...(this.config.repoHooks??[]).map((e=>e.repoPath))])],user_email:this.resolveUserEmail(o),...!n&&{transcript_path:i},...e===Nu.subagentStop&&{agent_transcript_path:a??null}},u=function(e,t){switch(e){case"beforeShellExecution":case"afterShellExecution":return nO(t,"command");case"beforeMCPExecution":case"afterMCPExecution":{const e=nO(t,"tool_name");return e?`MCP:${e}`:void 0}case"beforeReadFile":return"Read";case"afterFileEdit":return"Write";case"beforeTabFileRead":return"TabRead";case"afterTabFileEdit":return"TabWrite";case"beforeSubmitPrompt":return"UserPromptSubmit";case"stop":return"Stop";case"afterAgentResponse":return"AgentResponse";case"afterAgentThought":return"AgentThought";case"subagentStart":case"subagentStop":return nO(t,"subagent_type");case"preToolUse":case"postToolUse":case"postToolUseFailure":return nO(t,"tool_name");default:return}}(e,l),d=[],h=(e,t,n)=>{if(!e)return;const o=oO(e,u),s=this.cwdForHookSource(r,{source:t,fallback:n??this.getCwdForSource(t)}),i=void 0===n?r?.env:{CURSOR_PROJECT_DIR:n,CLAUDE_PROJECT_DIR:n,...r?.env};for(const e of o)iD(e)?this.promptHookClient&&d.push({type:"prompt",script:e,source:t}):aD(e)&&d.push({type:"command",script:e,cwd:s,env:i,source:t})},p=await async function({repoHooks:e,targetPath:t,workspacePath:r}){if(e.length<2||void 0===t||0===t.length)return e;const n=(0,Ho.o1)(t,r),[o,i,a]=await Promise.all([(0,Ho.DN)(n),(0,Ho.DN)(s.default.dirname(n)),Promise.all(e.map((async e=>await(0,Ho.DN)(e.repoPath)??s.default.resolve(e.repoPath))))]);if(null===o||null===i)return e;const c=t=>{let r;return e.forEach(((e,n)=>{const o=a[n],i=s.default.relative(o,t);(""===i||".."!==i&&!i.startsWith(`..${s.default.sep}`)&&!s.default.isAbsolute(i))&&(void 0===r||o.length>r.repoPath.length)&&(r={repo:e,repoPath:o})})),r?.repo},l=new Set;for(const t of[o,s.default.join(i,s.default.basename(n))]){const r=c(t);if(void 0===r)return e;l.add(r)}return e.filter((e=>l.has(e)))}({repoHooks:this.config.repoHooks??[],targetPath:bO(t),workspacePath:this.workspacePath});h(this.config.enterpriseHooks?.hooks[e],"enterprise"),h(this.config.teamHooks?.hooks[e],"team"),h(this.config.projectHooks?.hooks[e],"project");for(const t of p)h(t.projectHooks?.hooks[e],"project",t.repoPath);h(this.config.userHooks?.hooks[e],"user"),h(this.options?.runtimeHooks?.hooks[e],"runtime"),h(this.config.claudeProjectLocalHooks?.hooks[e],"claude-project-local"),h(this.config.claudeProjectHooks?.hooks[e],"claude-project");for(const t of p)h(t.claudeProjectLocalHooks?.hooks[e],"claude-project-local",t.repoPath),h(t.claudeProjectHooks?.hooks[e],"claude-project",t.repoPath);h(this.config.claudeUserHooks?.hooks[e],"claude-user");for(const t of this.config.pluginHooks??[]){const n=t.config.hooks[e];if(!n?.length)continue;const o=r?.cwd??(e===Nu.stop||e===Nu.subagentStop?this.workspacePath:t.installPath),s={...void 0!==t.plugin&&{plugin:t.plugin},...void 0!==t.marketplace&&{marketplace:t.marketplace},...void 0!==t.pluginId&&{pluginId:t.pluginId},...void 0!==t.marketplaceId&&{marketplaceId:t.marketplaceId}};for(const e of oO(n,u))aD(e)&&d.push({type:"command",script:e,cwd:o,env:r?.env,source:"claude-plugin",attribution:s,pluginInstallPath:t.installPath})}if(0!==d.length)return this.executeAllAndMerge(e,d,l,r?.onCommandFailure)}async whenConfigReady(){await Promise.all(this.configReadyPromises)}async executeAllAndMerge(e,t,r,n){let o;const s=()=>o??=function(e){const t=JSON.stringify(e);return{json:t,payloadSizeBytes:Buffer.byteLength(t,"utf8")}}(r),i=t.map((async(t,o)=>{const{source:i,attribution:a}=t;try{return"prompt"===t.type?await this.executePromptHook(e,t.script,r,i,o,s,a):await this.executeCommandHook(e,t.script,t.cwd,t.env,r,i,o,s,a,t.pluginInstallPath,n)}catch(r){const n=r instanceof Error?r.message:String(r);if(!0===t.script.failClosed){const t=sO(`Hook execution failed: ${n}`),r=wD(e,t);if(r)return{success:!0,data:r,source:i,index:o}}return SO.warn((0,y.q6)(),`${e} hook error`,{source:i,index:o,error:n}),{success:!1,source:i,index:o}}})),a=await Promise.all(i),c=[];for(const e of a)e.success&&void 0!==e.data&&c.push(e.data);return function(e,t){if(0===t.length)return;if(1===t.length)return t[0];const r=uD.includes(e),n=e===Nu.sessionStart,o=e===Nu.workspaceOpen,s=sD.has(e),i={};for(const e of t){const t=e;for(const[e,l]of Object.entries(t))if(void 0!==l)if(o&&"pluginPaths"===e&&Array.isArray(l)){const t=i[e],r=Array.isArray(t)?t:[],n=new Set(r),o=[...r];for(const e of l)"string"!=typeof e||n.has(e)||(n.add(e),o.push(e));i[e]=o}else"permission"===e&&r?i[e]=(c=l,"deny"===(a=i[e])||"deny"===c?"deny":"ask"===a||"ask"===c?"ask":"allow"===a||"allow"===c?"allow":void 0):"user_message"!==e&&"agent_message"!==e?s&&"additional_context"===e&&"string"==typeof l?i[e]=hD(i[e],l):"continue"!==e||"boolean"!=typeof l?i[e]=n&&"env"===e&&"object"==typeof l&&null!==l?pD(i[e],l):l:void 0===i[e]?i[e]=l:i[e]=i[e]&&l:i[e]=hD(i[e],l)}var a,c;return i}(e,c)}async executeCommandHook(e,t,r,n,o,s,i,a,c,l,u){if(this.shouldSkipHookDueToLoopLimit(e,t,o))return{success:!1,source:s,index:i};const d=Date.now(),h=a(),p=h.payloadSizeBytes,f=(e,r)=>this.finishHookRun(e,t,o,r);let m;try{m=await this.executeCommandScript({script:t,cwd:r,request:o,jsonPayload:h.json,env:n,...void 0!==l&&{pluginInstallPath:l}})}catch(r){const n=r instanceof Error?r.message:String(r),o=n.toLowerCase().includes("timed out");this.reportCommandFailure(u,{command:t.command,source:s,exitCode:null,stderr:"",errorMessage:n});const a=Date.now()-d,l=o?"timeout":"spawn_error";if(!0===t.failClosed){const u=wD(e,sO(`Hook "${t.command}" execution failed: ${n}`));if(u)return f({hookStep:e,hookSource:s,hookType:"command",status:o?"timeout":"blocked",latencyMs:a,payloadSizeBytes:p,errorClass:l,failClosed:!0,timedOut:o,...c},{response:null,stderr:String(r)}),{success:!0,data:u,source:s,index:i}}return f({hookStep:e,hookSource:s,hookType:"command",status:o?"timeout":"failed",latencyMs:a,payloadSizeBytes:p,errorClass:l,failClosed:!0===t.failClosed,timedOut:o,...c},{response:null,stderr:String(r)}),{success:!1,source:s,index:i}}if(2===m.exitCode){const r=function(e,t,r){const n=e.trim(),o=t.trim();return n||(o?`Hook blocked with message: ${o}`:`Hook "${r}" blocked this action (exit code 2) but provided no reason.`)}(m.stdout,m.stderr,t.command),n=wD(e,r);return n?(f({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:m.duration,payloadSizeBytes:p,failClosed:!0===t.failClosed,exitCode:m.exitCode,...c},{response:n,stderr:m.stderr}),{success:!0,data:n,source:s,index:i}):(f({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:m.duration,payloadSizeBytes:p,failClosed:!0===t.failClosed,exitCode:m.exitCode,...c},{response:null,stderr:m.stderr}),{success:!1,source:s,index:i})}if(0!==m.exitCode&&null!==m.exitCode){if(this.reportCommandFailure(u,{command:t.command,source:s,exitCode:m.exitCode,stderr:m.stderr}),!0===t.failClosed){const r=wD(e,sO(`Hook "${t.command}" failed with exit code ${m.exitCode}${m.stderr?`: ${m.stderr.trim()}`:""}`));if(r)return f({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"exit_nonzero",failClosed:!0,exitCode:m.exitCode,...c},{response:null,stderr:m.stderr}),{success:!0,data:r,source:s,index:i}}return f({hookStep:e,hookSource:s,hookType:"command",status:"failed",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"exit_nonzero",failClosed:!0===t.failClosed,exitCode:m.exitCode,...c},{response:null,stderr:m.stderr}),{success:!1,source:s,index:i}}const g=m.stdout.trim();if(!g){if(!0===t.failClosed){const r=wD(e,sO(`Hook "${t.command}" returned no output.`));if(r)return f({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"empty_stdout",failClosed:!0,exitCode:m.exitCode??void 0,...c},{response:null,stderr:m.stderr}),{success:!0,data:r,source:s,index:i}}return f({hookStep:e,hookSource:s,hookType:"command",status:"failed",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"empty_stdout",failClosed:!0===t.failClosed,exitCode:m.exitCode??void 0,...c},{response:null,stderr:m.stderr}),{success:!1,source:s,index:i}}const w=function(e){const t=e.trim();if(0===t.length)return;const r=yD(t);if(void 0!==r)return r.value;if(t.endsWith("}"))for(let e=t.length-1;e>=0;e--){if("{"!==t[e])continue;const r=yD(t.slice(e));if(void 0!==r)return r.value}}(g);if(void 0===w){const r=mD({step:e,command:t.command,failClosed:!0===t.failClosed,kind:"invalid_json"});return r.blockResponse?(f({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"invalid_json",failClosed:!0===t.failClosed,exitCode:m.exitCode??void 0,...c},{response:null,stderr:m.stderr+_O}),{success:!0,data:r.blockResponse,source:s,index:i}):(f({hookStep:e,hookSource:s,hookType:"command",status:"failed",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"invalid_json",failClosed:!0===t.failClosed,exitCode:m.exitCode??void 0,...c},{response:null,stderr:m.stderr+_O}),{success:!1,source:s,index:i})}const y=lD(e,w,{enableClaudeNestedHookSpecificOutputCompatibility:this.options?.enableClaudeNestedHookSpecificOutputCompatibility});if(y.success&&null!=y.data){const r=y.data,n="object"==typeof r&&"permission"in r?r.permission:void 0;return f({hookStep:e,hookSource:s,hookType:"command",status:"deny"===n||"ask"===n?"blocked":"success",latencyMs:m.duration,payloadSizeBytes:p,failClosed:!0===t.failClosed,exitCode:m.exitCode??void 0,...c},{response:r,stderr:m.stderr}),{success:!0,data:r,source:s,index:i}}const v=mD({step:e,command:t.command,failClosed:!0===t.failClosed,kind:"invalid_response"});return v.blockResponse?(f({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"invalid_response",failClosed:!0===t.failClosed,exitCode:m.exitCode??void 0,...c},{response:w,stderr:m.stderr}),{success:!0,data:v.blockResponse,source:s,index:i}):(f({hookStep:e,hookSource:s,hookType:"command",status:"failed",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"invalid_response",failClosed:!0===t.failClosed,exitCode:m.exitCode??void 0,...c},{response:w,stderr:m.stderr}),{success:!1,source:s,index:i})}async executePromptHook(e,t,r,n,o,s,i){if(this.shouldSkipHookDueToLoopLimit(e,t,r))return{success:!1,source:n,index:o};if(!this.promptHookClient)return{success:!1,source:n,index:o};const a=1e3*(t.timeout??60),c=Date.now(),l=s(),u=l.payloadSizeBytes,d=(e,n)=>this.finishHookRun(e,t,r,n),h=(0,y.q6)(),[p,f]=h.withTimeoutAndCancel(a);try{const r=JSON.parse(l.json),s=await this.promptHookClient.evaluatePromptHook(p,{prompt:t.prompt,hookInputJson:r,modelName:t.model});if(s.ok){const r=function(e){return fD(e)?gD(0,{permission:"allow"}):e===Nu.beforeSubmitPrompt||e===Nu.sessionStart?gD(0,{continue:!0}):e===Nu.stop?gD(0,{}):void 0}(e);return d({hookStep:e,hookSource:n,hookType:"prompt",status:"success",latencyMs:Date.now()-c,payloadSizeBytes:u,failClosed:!0===t.failClosed,...i},{response:r,stderr:"",exitCode:0}),r?{success:!0,data:r,source:n,index:o}:{success:!1,source:n,index:o}}{const r=wD(e,s.reason??"Prompt hook blocked this action");return d({hookStep:e,hookSource:n,hookType:"prompt",status:"blocked",latencyMs:Date.now()-c,payloadSizeBytes:u,failClosed:!0===t.failClosed,...i},{response:r,stderr:"",exitCode:2}),r?{success:!0,data:r,source:n,index:o}:{success:!1,source:n,index:o}}}catch(r){const s=r instanceof Error?r.message:String(r),a=s.toLowerCase().includes("abort")||s.toLowerCase().includes("timed out"),l=a?"timeout":"prompt_error";if(!0===t.failClosed){const t=wD(e,sO(`Prompt hook failed: ${s}`));if(t)return d({hookStep:e,hookSource:n,hookType:"prompt",status:a?"timeout":"blocked",latencyMs:Date.now()-c,payloadSizeBytes:u,errorClass:l,failClosed:!0,timedOut:a,...i},{response:null,stderr:String(r)}),{success:!0,data:t,source:n,index:o}}return d({hookStep:e,hookSource:n,hookType:"prompt",status:a?"timeout":"failed",latencyMs:Date.now()-c,payloadSizeBytes:u,errorClass:l,failClosed:!0===t.failClosed,timedOut:a,...i},{response:null,stderr:String(r)}),{success:!1,source:n,index:o}}finally{f()}}async executeCommandScript(e){const{script:t,cwd:r,request:n,env:i,pluginInstallPath:a,jsonPayload:c}=e,l=1e3*(t.timeout??60),u=Date.now();let d;const h=new AbortController,p=setTimeout((()=>{h.abort()}),l);try{const e="win32"===process.platform,f=this.getCommandHookPayloadTransportMode(),m=this.shouldUseCommandHookDirectStdinTransport(),g=e?function(e,t){const r=function(e){let t=0;for(;t<e.length&&/\s/.test(e.charAt(t));)t++;if("&"===e.charAt(t))for(t++;t<e.length&&/\s/.test(e.charAt(t));)t++;const r=e.slice(0,t),n=e.charAt(t);if("'"===n||'"'===n){let o=e.indexOf(n,t+1);for(;"'"===n&&-1!==o&&"'"===e.charAt(o+1);)o=e.indexOf("'",o+2);if(-1===o)return;return{prefix:r,quote:n,rawPath:e.slice(t+1,o),rest:e.slice(o+1)}}const o=/^\S+/.exec(e.slice(t));if(o)return{prefix:r,quote:"",rawPath:o[0],rest:e.slice(t+o[0].length)}}(e);if(!r)return e;const{prefix:n,quote:o,rawPath:s,rest:i}=r;if(0===s.length||!/[\\/]/.test(s))return e;if(i.length>0&&!/^\s/.test(i))return e;if(/[$`{}()|;,<>]/.test(s)||""===o&&/['"]/.test(s))return e;const a=s.slice(Math.max(s.lastIndexOf("\\"),s.lastIndexOf("/"))+1);if(0===a.length||a.includes("."))return e;const c="'"===o?s.replace(/''/g,"'"):s,l=/^[A-Za-z]:[\\/]/.test(u=c)||u.startsWith("\\")||u.startsWith("/")?c:`${t.cwd.replace(/[\\/]+$/,"")}\\${c}`;var u;const d=JM.find((e=>t.isFile(l+e)));return void 0===d?e:""!==o?`${n}${o}${s}${d}${o}${i}`:`${n}'${s}${d}'${i}`}(t.command,{cwd:r,isFile:kO}):t.command;let w;if(m)w=e?ZM(g):g;else if("windows_temp_file"===f){d=await(0,fo.mkdtemp)((0,s.join)((0,o.tmpdir)(),"cursor-hooks-"));const e=(0,s.join)(d,"payload.json");await(0,fo.writeFile)(e,c,{encoding:"utf8",flag:"wx"}),w=function(e,t){return`$OutputEncoding = [System.Text.UTF8Encoding]::new($false); try { $global:cursorHookConsoleInputEncoding = [Console]::InputEncoding; $null = Register-EngineEvent -SourceIdentifier PowerShell.Exiting -Action { try { [Console]::InputEncoding = $global:cursorHookConsoleInputEncoding } catch { } }; [Console]::InputEncoding = $OutputEncoding } catch { }; Get-Content -LiteralPath '${e.replace(/'/g,"''")}' -Raw -Encoding UTF8 | & { $input | ${ZM(t)} }`+KM(t)}(e,g)}else w=e?`@'\n${c.replace(/'/g,"''")}\n'@ | & ${g}`+KM(g):`${t.command} <<'CURSOR_HOOK_EOF'\n${c}\nCURSOR_HOOK_EOF`;const v=EO(n,"conversation_id")??void 0,b=EO(n,"session_id")??void 0,S=EO(n,"transcript_path"),k=void 0===v?void 0:this.activeSessionIdsByConversationId.get(v),_=void 0===b||b===v&&!this.sessionEnvById.has(b)?void 0===v?void 0:k?.at(-1)??v:b,C=this.buildHookEnvironment({transcriptPath:S,sessionId:_,conversationId:v,executionEnv:i}),E={};for(const[e,t]of Object.entries(C))void 0!==t&&(E[e]=t);void 0!==a&&(E.CURSOR_PLUGIN_ROOT=a,E.CLAUDE_PLUGIN_ROOT=a);const x=(0,y.q6)(),P=new Xi.StringDecoder("utf8"),I=new Xi.StringDecoder("utf8");let R,T="",A="",$=null,M=!1;for await(const e of this.shellExecutor.execute(x,w,{workingDirectory:r,signal:h.signal,sandboxPolicy:{perUser:{type:"insecure_none"}},env:E,pipeStdin:m}))switch(e.type){case"stdin_ready":m&&(await this.writeCommandHookStdinPayload(e.stdin,c),M=!0);break;case"stdout":T+=P.write(e.data);break;case"stderr":A+=I.write(e.data);break;case"exit":$=e.code,R=e.aborted}if(T+=P.end(),A+=I.end(),m&&!M)throw new Error("Hook stdin transport was requested, but the executor did not signal stdin readiness");clearTimeout(p);const D=Date.now()-u;if(R??h.signal.aborted)throw new Error(`Hook script timed out after ${l}ms`);return{stdout:T,stderr:A,exitCode:$,duration:D}}catch(e){if(clearTimeout(p),Date.now(),h.signal.aborted)throw new Error(`Hook script timed out after ${l}ms`);throw e}finally{if(d)try{await(0,fo.rm)(d,{recursive:!0,force:!0})}catch{}}}}class PO{constructor(e){this.config=e,this.configuredSteps=uO.getConfiguredSteps(e)}getConfig(){return this.config}hasHookForStep(e){return this.configuredSteps.has(e)}getConfiguredSteps(){return new Set(this.configuredSteps)}}var IO=r("node:perf_hooks");const RO=(0,y.cF)(Symbol.for("@anysphere/agent-exec/toolCallHooks"),{kind:"none"});function TO(e){return"inExecute"!==e.get(RO).kind}function AO(e,t){const r=e.get(RO);return"inExecute"!==r.kind||!r.toolStepsInPreToolUse.includes(t)}(0,y.cF)(Symbol.for("@anysphere/agent-exec/hookAsk"),void 0),(0,y.cF)(Symbol.for("@anysphere/agent-exec/hookAllow"),void 0),new WeakMap,new WeakMap,(0,y.cF)(Symbol.for("@anysphere/agent-exec/toolCallRefusal"),void 0),new WeakMap,new WeakMap,new WeakMap,(0,y.cF)(Symbol.for("@anysphere/agent-exec/approvalWaits"),void 0),new WeakMap;const $O=(0,y.cF)(Symbol.for("@anysphere/agent-exec/hookStepTime"),void 0),MO=new Ru.AsyncLocalStorage;function DO(e,t){return MO.run(e,t)}function OO(e,t){void 0!==e&&t.length>0&&e.push(...t)}class FO extends Error{constructor(e){super(`Hook additional_context for ${e.hookEventName} is ${e.actualLength} chars (max ${e.maxLength}).`),this.name="HookAdditionalContextTooLargeError",this.hookEventName=e.hookEventName,this.actualLength=e.actualLength,this.maxLength=e.maxLength}}var NO=r("../proto/dist/generated/agent/v1/hook_additional_context_pb.js");function LO({hookEventName:e,additionalContext:t}){const r=function(e){const t=e?.trim();return void 0!==t&&t.length>0?t:void 0}(t);if(void 0===r)return[];if(r.length>1e4)throw new FO({hookEventName:e,actualLength:r.length,maxLength:1e4});return[new NO.C({hookEventName:e,content:r})]}Object.fromEntries(Array.from(sD).map((e=>{if(!function(e){return e===Nu.sessionStart||e===Nu.beforeSubmitPrompt||e===Nu.preToolUse||e===Nu.postToolUse||e===Nu.postToolUseFailure}(e))throw new Error(`HOOK_STEPS_SUPPORTING_ADDITIONAL_CONTEXT lists ${e} but HookStepAdditionalContextEventName does not include it. Extend the Extract<> union in spec.ts.`);return[e,{hookEventName:e}]})));const jO="Agent note: Do not suggest workarounds to the blocked tool.";function UO(e){return e.includes(jO)?e:`${e}\n\n${jO}`}class BO extends Error{constructor(e){super(`Hook denied: ${e}`),this.failureType="permission_denied",this.name="HookDeniedError",this.reason=e}}class WO extends Error{constructor(e,t){super(`Hook failed (fail-closed): ${e}`),this.failureType="error",this.name="FailClosedError",this.reason=e,this.cause=t}}const HO="To view or modify configured hooks, go to Cursor Settings > Hooks.";function qO(e,t){return UO(`${t?`${e} was blocked by a hook: ${t}`:`${e} was blocked by a hook.`}\n\n${HO}`)}function zO(e){return function(e){return e instanceof BO}(e)||function(e){return e instanceof WO}(e)}const GO=(0,l.h)("generic-hooks");function VO(e,t,r,n){try{return LO({hookEventName:r,additionalContext:n})}catch(n){if(n instanceof FO)return GO.warn(e,`${r} additional_context exceeded max size; dropping carrier`,{toolName:t,hookEventName:r,actualLength:n.actualLength,maxLength:n.maxLength}),[];throw n}}const KO=e=>Math.round(1e3*e)/1e3;function JO(e,t,r,n,o,s){const i=n(e),a=o.getToolCallId?.(t)??(0,lo.randomUUID)(),c=o.getExtraHookFields?.(t)??{},l={baseHookRequest:i,toolUseId:a,toolInput:o.createToolInput(t),extraHookFields:c,hookContextCollector:s?.hookContextCollector??o.getHookContextCollector?.(t)??[]},u=function(e,t,r,n){let{toolInput:o,extraHookFields:s,hookContextCollector:i}=n;const{baseHookRequest:a,toolUseId:c}=n;return{fireFailureAsync:async(n,l,u,d=!1)=>{try{const h=await DO(e.signal,(()=>t.executeHookForStep(Nu.postToolUseFailure,{...a,tool_name:r,tool_input:o,error_message:l,failure_type:u,duration:n,tool_use_id:c,is_interrupt:d,...s})));OO(i,VO(e,r,Nu.postToolUseFailure,h?.additional_context))}catch(t){GO.warn(e,"postToolUseFailure hook error",{toolName:r,error:t instanceof Error?t.message:String(t)})}},fireSuccessAsync:async(n,l)=>{try{const u=await DO(e.signal,(()=>t.executeHookForStep(Nu.postToolUse,{...a,tool_name:r,tool_input:o,tool_output:l,duration:n,tool_use_id:c,...s})));OO(i,VO(e,r,Nu.postToolUse,u?.additional_context))}catch(t){GO.warn(e,"postToolUse hook error",{toolName:r,error:t instanceof Error?t.message:String(t)})}},getToolInput:()=>o,setToolInput:e=>{o=e},setExtraHookFields:e=>{s=e,n.extraHookFields=e}}}(e,r,o.toolName,l);return{hookContext:l,helpers:u}}async function ZO(e,t,r,n,o,s,i,a){const{baseHookRequest:c,toolUseId:l,extraHookFields:u}=n;try{const a=await DO(e.signal,(()=>r.executeHookForStep(Nu.preToolUse,{...c,tool_name:s.toolName,tool_input:o.getToolInput(),tool_use_id:l,...u})));if("deny"===a?.permission){const r=a.user_message||`${s.toolName} blocked by preToolUse hook`,c=UO(r);try{OO(n.hookContextCollector,LO({hookEventName:Nu.preToolUse,additionalContext:a.additional_context}))}catch(t){if(!(t instanceof FO))throw t;GO.warn(e,"preToolUse deny additional_context exceeded max size; dropping carrier",{toolName:s.toolName,actualLength:t.actualLength,maxLength:t.maxLength})}return await o.fireFailureAsync(0,r,"permission_denied"),{type:"rejected",result:i(t,c),reason:c}}a?.updated_input&&s.applyUpdatedInput&&(s.applyUpdatedInput(t,a.updated_input),o.setToolInput(s.createToolInput(t)),s.getExtraHookFields&&o.setExtraHookFields(s.getExtraHookFields(t))),OO(n.hookContextCollector,LO({hookEventName:Nu.preToolUse,additionalContext:a?.additional_context}))}catch(n){const a=r.hasFailClosedHooksForStep?.(Nu.preToolUse,s.toolName)??!1,c=n instanceof FO;if(a){const e=sO(`${c?"preToolUse additional_context exceeded max size":"preToolUse hook failed"}: ${n instanceof Error?n.message:"preToolUse hook error"}`);return await o.fireFailureAsync(0,e,"error"),{type:"rejected",result:i(t,e),reason:e}}GO.warn(e,c?"preToolUse additional_context exceeded max size; dropping carrier":"preToolUse hook error",{toolName:s.toolName,error:n instanceof Error?n.message:String(n),...c?{actualLength:n.actualLength,maxLength:n.maxLength}:{}})}if(a)try{const s=await a({ctx:e,args:t,baseHookRequest:c,hookExecutor:r,toolInput:o.getToolInput(),toolUseId:l,extraHookFields:n.extraHookFields});if(void 0!==s){const e="Pre-execution hook returned rejection";return await o.fireFailureAsync(0,e,"permission_denied"),{type:"rejected",result:s,reason:e}}}catch(e){if(zO(e))return await o.fireFailureAsync(0,e.reason,e.failureType),{type:"rejected",result:i(t,e.reason),reason:e.reason};throw e}return{type:"continue"}}function XO(e){return e.toolCallId}function QO(e,t,r,n){return{async execute(o,s,i){const a=eF(o,t),{hookContext:c,helpers:l}=JO(o,s,a,r,n,i);let u;try{u=await ZO(o,s,a,c,l,n,n.createRejectedResult,n.runPreExecutionHooks)}catch(e){throw n.runCleanup?.(c.toolUseId),e}if("rejected"===u.type)return n.runCleanup?.(c.toolUseId),u.result;const d=IO.performance.now();try{const t=await e.execute(o,s,i),r=KO(IO.performance.now()-d);if(n.runPostExecutionHooks)try{const e=await n.runPostExecutionHooks({ctx:o,args:s,result:t,baseHookRequest:c.baseHookRequest,hookExecutor:a,toolInput:l.getToolInput(),toolUseId:c.toolUseId,executionDurationMs:r,extraHookFields:c.extraHookFields});if(void 0!==e)return await l.fireSuccessAsync(r,JSON.stringify(n.createSuccessOutput(s,e))),n.runCleanup?.(c.toolUseId),e}catch(e){if(zO(e))return await l.fireFailureAsync(r,e.reason,e.failureType),n.runCleanup?.(c.toolUseId),n.createRejectedResult(s,e.reason);GO.warn(o,"postExecutionHooks error",{toolName:n.toolName,error:e instanceof Error?e.message:String(e)})}return n.isSuccess(t)?await l.fireSuccessAsync(r,JSON.stringify(n.createSuccessOutput(s,t))):await l.fireFailureAsync(r,n.getErrorMessage(t),n.getFailureType?.(t)??"error",n.isInterrupt?.(t)??!1),n.runCleanup?.(c.toolUseId),t}catch(e){const t=KO(IO.performance.now()-d);throw await l.fireFailureAsync(t,e instanceof Error?e.message:String(e),"error"),n.runCleanup?.(c.toolUseId),e}}}}function*YO(e,t){const r=t.hookContextCollector;e.createHookContextEvent&&void 0!==r&&0!==r.length&&(yield e.createHookContextEvent(r))}function eF(e,t){const r=TO(e),n=e.get($O);if(r&&void 0===n)return t;const o=e=>n?.during(e)??e;return{executeHookForStep:async(e,n)=>{if(r||!function(e){return e===Nu.preToolUse||e===Nu.postToolUse||e===Nu.postToolUseFailure}(e))return o(t.executeHookForStep(e,n));await o(t.whenConfigReady())},hasFailClosedHooksForStep:(e,r)=>t.hasFailClosedHooksForStep?.(e,r)??!1,hasHooksForStep:e=>t.hasHooksForStep?.(e)??!0,whenConfigReady:()=>o(t.whenConfigReady())}}function tF(e){if("object"!=typeof e||null===e||!("code"in e))return!1;const t=e.code;return"ENOENT"===t||"ENOTDIR"===t}class rF{async readFile(e){try{return await fo.readFile(e,"utf-8")}catch(e){if("ENOENT"===e?.code)return;throw e}}async exists(e){try{return await fo.access(e),!0}catch{return!1}}async pathContainsSymlink(e,t){return async function(e,t){const r=function(e,t){const r=s.default.resolve(e),n=s.default.resolve(t),o=s.default.relative(n,r);if(0===o.length||".."===o||o.startsWith(`..${s.default.sep}`)||s.default.isAbsolute(o))return"unsafe";const i=o.split(s.default.sep).filter((e=>e.length>0)),a=[];let c=n;for(const e of i)c=s.default.join(c,e),a.push(c);return a}(e,t);if("unsafe"===r)return!0;for(const e of r)try{if((await(0,fo.lstat)(e)).isSymbolicLink())return!0}catch(e){if(tF(e))return!0;throw e}return!1}(e,t)}}var nF=r("../proto/dist/generated/agent/v1/hooks_pb.js");const oF=q("hook-executor",(e=>new B(e,Z("executeHookArgs"),X("executeHookResult"))),((e,t)=>{t.register(new R(e,Y("executeHookArgs"),Q("executeHookResult")))})),sF=new Set(Object.values(Nu));function iF(e){switch(e){case"completed":case"aborted":case"error":return e;default:return"error"}}function aF(e){switch(e){case"error":case"timeout":case"permission_denied":return e;default:return"error"}}function cF(e){const t=e?.toJson();return"object"!=typeof t||null===t||Array.isArray(t)?{}:t}class lF{constructor(e){this.hookExecutor=e}hasFailClosedHooksForStep(e,t){return!!function(e){return sF.has(e)}(e)&&(this.hookExecutor.hasFailClosedHooksForStep?.(e,t)??!1)}async execute(e,t){const r=t.request;if(!r)return new d.S1({response:void 0});switch(r.request.case){case"preCompact":{const e=r.request.value,t={conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...oD(e),trigger:"manual"===e.trigger?"manual":"auto",context_usage_percent:e.contextUsagePercent,context_tokens:Number(e.contextTokens),context_window_size:Number(e.contextWindowSize),message_count:e.messageCount,messages_to_compact:e.messagesToCompact,is_first_compaction:e.isFirstCompaction},n=await this.hookExecutor.executeHookForStep(Nu.preCompact,t);return new d.S1({response:new d.w5({response:{case:"preCompact",value:new nF.$_({userMessage:n?.user_message})}})})}case"subagentStart":{const e=r.request.value,t={conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...oD(e),subagent_id:e.subagentId,subagent_type:e.subagentType,task:e.task,parent_conversation_id:e.parentConversationId,tool_call_id:e.toolCallId,subagent_model:e.subagentModel,is_parallel_worker:e.isParallelWorker,git_branch:e.gitBranch},n=await this.hookExecutor.executeHookForStep(Nu.subagentStart,t);return new d.S1({response:new d.w5({response:{case:"subagentStart",value:new nF.W0({permission:n?.permission,userMessage:n?.user_message,additionalContext:n?.additional_context})}})})}case"subagentStop":{const e=r.request.value,t={conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...oD(e),subagent_id:e.subagentId,subagent_type:e.subagentType,status:iF(e.status),duration_ms:Number(e.durationMs),summary:e.summary,parent_conversation_id:e.parentConversationId,message_count:e.messageCount,tool_call_count:e.toolCallCount,error_message:e.errorMessage,modified_files:e.modifiedFiles,git_branch:e.gitBranch,loop_count:e.loopCount??0,task:e.task,description:e.description,...e.childConversationId?{child_conversation_id:e.childConversationId}:{}},n=await this.hookExecutor.executeHookForStep(Nu.subagentStop,t);return new d.S1({response:new d.w5({response:{case:"subagentStop",value:new nF.AH({followupMessage:n?.followup_message,additionalContext:n?.additional_context})}})})}case"beforeSubmitPrompt":{const e=r.request.value,t=await this.hookExecutor.executeHookForStep(Nu.beforeSubmitPrompt,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...oD(e),prompt:e.prompt,attachments:(n=e.attachments,n.flatMap((e=>"file"===e.type||"rule"===e.type?[{type:e.type,file_path:e.filePath}]:[]))),composer_mode:e.composerMode});return new d.S1({response:new d.w5({response:{case:"beforeSubmitPrompt",value:new nF.u1({continue:t?.continue,userMessage:t?.user_message,additionalContext:t?.additional_context})}})})}case"afterAgentResponse":{const e=r.request.value;return await this.hookExecutor.executeHookForStep(Nu.afterAgentResponse,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...oD(e),text:e.text,input_tokens:void 0!==e.inputTokens?Number(e.inputTokens):void 0,output_tokens:void 0!==e.outputTokens?Number(e.outputTokens):void 0,cache_read_tokens:void 0!==e.cacheReadTokens?Number(e.cacheReadTokens):void 0,cache_write_tokens:void 0!==e.cacheWriteTokens?Number(e.cacheWriteTokens):void 0}),new d.S1({response:new d.w5({response:{case:"afterAgentResponse",value:new nF.FW}})})}case"afterAgentThought":{const e=r.request.value;return await this.hookExecutor.executeHookForStep(Nu.afterAgentThought,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...oD(e),text:e.text,duration_ms:void 0!==e.durationMs?Number(e.durationMs):void 0}),new d.S1({response:new d.w5({response:{case:"afterAgentThought",value:new nF.H}})})}case"stop":{const e=r.request.value,t=await this.hookExecutor.executeHookForStep(Nu.stop,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...oD(e),status:iF(e.status),loop_count:e.loopCount,input_tokens:void 0!==e.inputTokens?Number(e.inputTokens):void 0,output_tokens:void 0!==e.outputTokens?Number(e.outputTokens):void 0,cache_read_tokens:void 0!==e.cacheReadTokens?Number(e.cacheReadTokens):void 0,cache_write_tokens:void 0!==e.cacheWriteTokens?Number(e.cacheWriteTokens):void 0});return new d.S1({response:new d.w5({response:{case:"stop",value:new nF.rT({followupMessage:t?.followup_message})}})})}case"preToolUse":{if(!TO(e))return this.skipToolUseStep();const t=r.request.value,n=cF(t.toolInput),o={conversation_id:t.conversationId??"",generation_id:t.generationId??"",model:t.model??"",...oD(t),...t.parentToolCallId?{parent_tool_call_id:t.parentToolCallId}:{},tool_name:t.toolName,tool_input:n,tool_use_id:t.toolUseId,cwd:t.cwd},s=await this.hookExecutor.executeHookForStep(Nu.preToolUse,o);return new d.S1({response:new d.w5({response:{case:"preToolUse",value:new nF.Wn({permission:s?.permission,userMessage:s?.user_message,agentMessage:s?.agent_message,updatedInput:s?.updated_input?JSON.stringify(s.updated_input):void 0,additionalContext:s?.additional_context})}})})}case"postToolUse":{if(!TO(e))return this.skipToolUseStep();const t=r.request.value,n=cF(t.toolInput),o={conversation_id:t.conversationId??"",generation_id:t.generationId??"",model:t.model??"",...oD(t),...t.parentToolCallId?{parent_tool_call_id:t.parentToolCallId}:{},tool_name:t.toolName,tool_input:n,tool_output:t.toolOutput,duration:Number(t.durationMs),tool_use_id:t.toolUseId,cwd:t.cwd},s=await this.hookExecutor.executeHookForStep(Nu.postToolUse,o);return new d.S1({response:new d.w5({response:{case:"postToolUse",value:new nF.uB({additionalContext:s?.additional_context})}})})}case"postToolUseFailure":{if(!TO(e))return this.skipToolUseStep();const t=r.request.value,n=cF(t.toolInput),o={conversation_id:t.conversationId??"",generation_id:t.generationId??"",model:t.model??"",...oD(t),...t.parentToolCallId?{parent_tool_call_id:t.parentToolCallId}:{},tool_name:t.toolName,tool_input:n,error_message:t.errorMessage,failure_type:aF(t.failureType),duration:Number(t.durationMs),tool_use_id:t.toolUseId,is_interrupt:t.isInterrupt},s=await this.hookExecutor.executeHookForStep(Nu.postToolUseFailure,o);return new d.S1({response:new d.w5({response:{case:"postToolUseFailure",value:new nF.U1({additionalContext:s?.additional_context})}})})}default:return new d.S1({response:void 0})}var n}async skipToolUseStep(){return await this.hookExecutor.whenConfigReady(),new d.S1({response:void 0})}}class uF{constructor(e,t,r,n){this.innerExecutor=e,this.hooksAdditionalContextPromise=t,this.teamHooksReadyPromise=r,this.hooksConfigLease=n}async execute(e,t,r){this.teamHooksReadyPromise&&await this.teamHooksReadyPromise;const n=await this.innerExecutor.execute(e,t,r),o=await this.hooksAdditionalContextPromise,s=this.hooksConfigLease?new Mr.Jy({configuredSteps:Array.from(this.hooksConfigLease.getConfiguredSteps())}):void 0;if("success"===n.result.case&&(o||s)){const e=n.result.value.requestContext,t=e?.clone()??new Mr.bb;return o&&(t.hooksAdditionalContext=o),s&&(t.hooksConfig=s),new Mr._G({result:{case:"success",value:new Mr.yW({requestContext:t,servedFromDiskCache:n.result.value.servedFromDiskCache})}})}return n}}function dF(e){return!!e&&e.type!==Ko.vc.INSECURE_NONE&&e.type!==Ko.vc.UNSPECIFIED}async function hF({hookExecutor:e,baseHookRequest:t,toolUseId:r,command:n,cwd:o,sandbox:s}){const i=await e.executeHookForStep(Nu.beforeShellExecution,{...t,command:n,cwd:o,sandbox:s,tool_use_id:r});if("deny"===i?.permission){const e=qO("Command execution",i.user_message);throw new BO(e)}if("ask"===i?.permission)return a=i.user_message,new he.In({kind:he.b.FORCE_PROMPT,reason:a});var a}const pF={toolName:gO,getToolCallId:XO,createToolInput:e=>{const t=e.workingDirectory||"";return{command:e.command,cwd:t}},applyUpdatedInput:(e,t)=>{"string"==typeof t.command&&(e.command=t.command),"string"==typeof t.cwd&&(e.workingDirectory=t.cwd)},createRejectedResult:(e,t)=>new Co.Lt({result:{case:"rejected",value:new he.pZ({command:e.command,workingDirectory:e.workingDirectory,reason:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"BackgroundShell error";case"rejected":return e.result.value.reason||"BackgroundShell rejected";case"permissionDenied":return"Permission denied";case"sandboxUnsupported":return`Sandbox policy unsupported on this host: ${e.result.value.reason}`;default:return"Unknown error"}},createSuccessOutput:(e,t)=>"success"===t.result.case?{shell_id:t.result.value.shellId,pid:t.result.value.pid}:{success:!0},getExtraHookFields:e=>({cwd:e.workingDirectory||""}),runPreExecutionHooks:async e=>{const{ctx:t,args:r,baseHookRequest:n,hookExecutor:o,toolUseId:s}=e,i=r.workingDirectory||"",a=dF(r.sandboxPolicy);AO(t,Nu.beforeShellExecution)&&bo(r,await hF({hookExecutor:o,baseHookRequest:n,toolUseId:s,command:r.command,cwd:i,sandbox:a}))}};class fF{constructor(e,t,r){this.wrappedExecutor=QO(e,t,r,pF)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const mF={toolName:"WriteShellStdin",createToolInput:e=>({shell_id:e.shellId,chars_length:e.chars.length}),createRejectedResult:(e,t)=>new Co.nt({result:{case:"error",value:new Co.Gv({error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>"error"===e.result.case?e.result.value.error||"WriteShellStdin error":"Unknown error",createSuccessOutput:e=>({shell_id:e.shellId,success:!0})};class gF{constructor(e,t,r){this.wrappedExecutor=QO(e,t,r,mF)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const wF={toolName:"ComputerUse",getToolCallId:XO,createToolInput:e=>({actions_count:e.actions.length}),createRejectedResult:(e,t)=>new Em.ks({result:{case:"error",value:new Em.Jb({error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>"error"===e.result.case?e.result.value.error||"ComputerUse error":"Unknown error",createSuccessOutput:(e,t)=>"success"===t.result.case?{action_count:t.result.value.actionCount,duration_ms:t.result.value.durationMs}:{success:!0}};class yF{constructor(e,t,r){this.wrappedExecutor=QO(e,t,r,wF)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const vF={toolName:pO,getToolCallId:XO,createToolInput:e=>({file_path:e.path}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new Pg.Pi({result:{case:"rejected",value:new Pg.iq({path:e.path,reason:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"fileNotFound":return`File not found: ${e.result.value.path}`;case"notFile":return`Not a file: ${e.result.value.path}`;case"permissionDenied":return`Permission denied: ${e.result.value.path}`;case"fileBusy":return`File busy: ${e.result.value.path}`;case"rejected":return e.result.value.reason||"Delete rejected";case"error":return e.result.value.error||"Delete error";default:return"Unknown error"}},createSuccessOutput:e=>({file_path:e.path,deleted:!0})};class bF{constructor(e,t,r){this.wrappedExecutor=QO(e,t,r,vF)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const SF={toolName:wO,getToolCallId:XO,createToolInput:e=>({file_path:e.path}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new BR.Ek({result:{case:"rejected",value:new BR.J6({path:e.path,reason:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"Diagnostics error";case"rejected":return e.result.value.reason||"Diagnostics rejected";case"fileNotFound":return`File not found: ${e.result.value.path}`;case"permissionDenied":return`Permission denied: ${e.result.value.path}`;default:return"Unknown error"}},createSuccessOutput:(e,t)=>"success"===t.result.case?{file_path:e.path,diagnostics_count:t.result.value.totalDiagnostics}:{file_path:e.path,success:!0}};class kF{constructor(e,t,r){this.wrappedExecutor=QO(e,t,r,SF)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const _F={toolName:"Fetch",getToolCallId:XO,createToolInput:e=>({url:e.url}),applyUpdatedInput:(e,t)=>{"string"==typeof t.url&&(e.url=t.url)},createRejectedResult:(e,t)=>new Dg.uN({result:{case:"error",value:new Dg.fk({url:e.url,error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>"error"===e.result.case?e.result.value.error||"Fetch error":"Unknown error",createSuccessOutput:(e,t)=>"success"===t.result.case?{url:e.url,status_code:t.result.value.statusCode,content_length:t.result.value.content.length}:{url:e.url,success:!0}};class CF{constructor(e,t,r){this.wrappedExecutor=QO(e,t,r,_F)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const EF={toolName:mO,getToolCallId:XO,createToolInput:e=>({pattern:e.pattern,file_path:e.path,glob:e.glob,output_mode:e.outputMode}),applyUpdatedInput:(e,t)=>{"string"==typeof t.pattern&&(e.pattern=t.pattern),"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new pw.Ud({result:{case:"error",value:new pw.ts({error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>"error"===e.result.case?e.result.value.error||"Grep error":"Unknown error",createSuccessOutput:e=>({pattern:e.pattern,success:!0})};class xF{constructor(e,t,r){this.wrappedExecutor=QO(e,t,r,EF)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const PF={toolName:fO,getToolCallId:XO,createToolInput:e=>({file_path:e.path,ignore:e.ignore}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new Uk.fv({result:{case:"rejected",value:new Uk.k2({path:e.path,reason:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"Ls error";case"rejected":return e.result.value.reason||"Ls rejected";case"timeout":return"Ls operation timed out";default:return"Unknown error"}},getFailureType:e=>"timeout"===e.result.case?"timeout":"error",createSuccessOutput:e=>({file_path:e.path,success:!0})};class IF{constructor(e,t,r){this.wrappedExecutor=QO(e,t,r,PF)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const RF=(0,l.h)("hooks-exec:mcp");function TF(e){return!!(null===e||"string"==typeof e||"boolean"==typeof e||"number"==typeof e&&Number.isFinite(e))||(Array.isArray(e)?e.every(TF):"object"==typeof e&&Object.values(e).every((e=>void 0!==e&&TF(e))))}function AF(e,t,r,n){try{return LO({hookEventName:r,additionalContext:n})}catch(n){if(n instanceof FO)return RF.warn(e,`${r} additional_context exceeded max size; dropping carrier`,{toolName:t,hookEventName:r,actualLength:n.actualLength,maxLength:n.maxLength}),[];throw n}}class $F{constructor(e,t,r,n,o){this.innerExecutor=e,this.hookExecutor=t,this.baseHookRequestExtractor=r,this.mcpLease=n,this.hooksConfigLease=o}async execute(e,t,r){if(t.smartModeApprovalOnly)return this.innerExecutor.execute(e,t,r);if(t.symbolicPathArguments.length>0&&(!0===this.hooksConfigLease?.hasHookForStep(Nu.preToolUse)||!0===this.hooksConfigLease?.hasHookForStep(Nu.beforeMCPExecution)))return new Za.iz({result:{case:"error",value:new Za.Nh({error:`"${dR}" arguments can't be used on this computer: hooks that inspect MCP calls are configured here, and they would not see the file's contents. Read the file and pass its contents instead.`})}});const n=eF(e,this.hookExecutor),o=this.baseHookRequestExtractor(e),s=(0,lo.randomUUID)(),i=r?.hookContextCollector??[];let a=Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t?.toJson()])));const c=`MCP:${t.toolName}`;try{const r=await n.executeHookForStep(Nu.preToolUse,{...o,tool_name:c,tool_input:a,tool_use_id:s});if("deny"===r?.permission){const t=r.user_message||"MCP tool blocked by preToolUse hook";try{OO(i,LO({hookEventName:Nu.preToolUse,additionalContext:r.additional_context}))}catch(t){if(!(t instanceof FO))throw t;RF.warn(e,"preToolUse deny additional_context exceeded max size; dropping carrier",{toolName:c,actualLength:t.actualLength,maxLength:t.maxLength})}return await this.firePostToolUseFailureAsync(e,n,o,c,a,t,"permission_denied",0,s,!1,i),new Za.iz({result:{case:"permissionDenied",value:new Za.HQ({error:qO("MCP tool execution",t),isReadonly:!1})}})}if(r?.updated_input)try{for(const[e,n]of Object.entries(r.updated_input))if(void 0!==n){if(!TF(n))throw new TypeError("updated_input value is not JSON");t.args[e]=we.Value.fromJson(n)}a=Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t?.toJson()])))}catch(t){RF.warn(e,"Failed to merge updated_input for MCP",{error:t instanceof Error?t.message:String(t)})}OO(i,LO({hookEventName:Nu.preToolUse,additionalContext:r?.additional_context}))}catch(t){const r=n.hasFailClosedHooksForStep?.(Nu.preToolUse,c)??!1,l=t instanceof FO;if(r){const r=sO(`${l?"preToolUse additional_context exceeded max size":"preToolUse hook failed"}: ${t instanceof Error?t.message:"preToolUse hook error"}`);return await this.firePostToolUseFailureAsync(e,n,o,c,a,r,"error",0,s,!1,i),new Za.iz({result:{case:"permissionDenied",value:new Za.HQ({error:qO("MCP tool execution",r),isReadonly:!1})}})}RF.warn(e,l?"preToolUse additional_context exceeded max size; dropping carrier":"preToolUse hook error in MCP executor",{toolName:c,error:t instanceof Error?t.message:String(t),...l?{actualLength:t.actualLength,maxLength:t.maxLength}:{}})}const l=await(this.mcpLease?.getClient(e,t.providerIdentifier)),u=l?.config;let d;const h=u&&"url"in u&&u.url?u.url:void 0;d=void 0!==h?{url:h}:u&&"command"in u?{command:[u.command,...u.args??[]].filter(Boolean).join(" ")}:{command:t.providerIdentifier};const p={mcp_server_name:t.providerIdentifier,...void 0!==h?{mcp_server_url:h}:{}},f={...o,tool_name:t.toolName,tool_input:JSON.stringify(a),tool_use_id:s,...p,...d},m=AO(e,Nu.beforeMCPExecution)?await n.executeHookForStep(Nu.beforeMCPExecution,f):void 0;if("deny"===m?.permission){const t=qO("MCP tool execution",m.user_message);return await this.firePostToolUseFailureAsync(e,n,o,c,a,t,"permission_denied",0,s,!1,i),new Za.iz({result:{case:"permissionDenied",value:new Za.HQ({error:t,isReadonly:!1})}})}const g=IO.performance.now();try{const l=await this.innerExecutor.execute(e,t,r),u=KO(IO.performance.now()-g);let d="{}";if("success"===l.result.case)try{const e=l.result.value.content.map((e=>"text"===e.content.case?{type:"text",text:e.content.value.text}:"image"===e.content.case?{type:"image",data:Buffer.from(e.content.value.data).toString("base64"),mimeType:e.content.value.mimeType}:{type:"unknown"}));d=JSON.stringify({content:e,isError:l.result.value.isError})}catch(t){RF.warn(e,"Failed to serialize MCP result",{error:t instanceof Error?t.message:String(t)}),d=JSON.stringify({error:"Failed to serialize result"})}else"error"===l.result.case?d=JSON.stringify({error:l.result.value.error}):"rejected"===l.result.case?d=JSON.stringify({rejected:!0,reason:l.result.value.reason}):"permissionDenied"===l.result.case&&(d=JSON.stringify({permissionDenied:!0,error:l.result.value.error}));const h={...o,tool_name:t.toolName,tool_input:JSON.stringify(a),result_json:d,duration:u,tool_use_id:s,...p};await n.executeHookForStep(Nu.afterMCPExecution,h);const f=await this.firePostToolUse(e,n,o,c,a,d,u,s,i);if(void 0!==f?.updated_mcp_tool_output)try{const e=f.updated_mcp_tool_output,t=[];if("string"==typeof e)t.push(new Za._Z({content:{case:"text",value:new Za.zN({text:e})}}));else if("object"==typeof e&&null!==e&&"content"in e&&Array.isArray(e.content)){const r=e.content;for(const e of r)"object"==typeof e&&null!==e&&"type"in e&&"text"===e.type&&"text"in e?t.push(new Za._Z({content:{case:"text",value:new Za.zN({text:String(e.text)})}})):t.push(new Za._Z({content:{case:"text",value:new Za.zN({text:JSON.stringify(e)})}}))}else t.push(new Za._Z({content:{case:"text",value:new Za.zN({text:JSON.stringify(e)})}}));const r="object"==typeof e&&null!==e&&"isError"in e&&Boolean(e.isError);return new Za.iz({result:{case:"success",value:new Za.QW({content:t,isError:r})}})}catch(t){return RF.warn(e,"Failed to process updated_mcp_tool_output",{error:t instanceof Error?t.message:String(t)}),l}return l}catch(t){const r=KO(IO.performance.now()-g),l=t instanceof Error?t.message:String(t);throw await this.firePostToolUseFailureAsync(e,n,o,c,a,l,"error",r,s,!1,i),t}}async firePostToolUse(e,t,r,n,o,s,i,a,c){try{const l=await t.executeHookForStep(Nu.postToolUse,{...r,tool_name:n,tool_input:o,tool_output:s,duration:i,tool_use_id:a});return OO(c,AF(e,n,Nu.postToolUse,l?.additional_context)),l}catch(t){return void RF.warn(e,"postToolUse hook error in MCP executor",{error:t instanceof Error?t.message:String(t)})}}async firePostToolUseFailureAsync(e,t,r,n,o,s,i,a,c,l,u){try{const d=await t.executeHookForStep(Nu.postToolUseFailure,{...r,tool_name:n,tool_input:o,error_message:s,failure_type:i,duration:a,tool_use_id:c,is_interrupt:l});OO(u,AF(e,n,Nu.postToolUseFailure,d?.additional_context))}catch(t){RF.warn(e,"postToolUseFailure hook error in MCP executor",{error:t instanceof Error?t.message:String(t)})}}}const MF={toolName:"ListMcpResources",createToolInput:e=>({server:e.server}),applyUpdatedInput:(e,t)=>{"string"==typeof t.server&&(e.server=t.server)},createRejectedResult:(e,t)=>new Za.kP({result:{case:"error",value:new Za.w2({error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"ListMcpResources error";case"rejected":return e.result.value.reason||"ListMcpResources rejected";default:return"Unknown error"}},createSuccessOutput:(e,t)=>"success"===t.result.case?{resources_count:t.result.value.resources.length}:{success:!0}};class DF{constructor(e,t,r){this.wrappedExecutor=QO(e,t,r,MF)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const OF={toolName:"FetchMcpResource",createToolInput:e=>({server:e.server,uri:e.uri,download_path:e.downloadPath}),applyUpdatedInput:(e,t)=>{"string"==typeof t.server&&(e.server=t.server),"string"==typeof t.uri&&(e.uri=t.uri),"string"==typeof t.download_path&&(e.downloadPath=t.download_path)},createRejectedResult:(e,t)=>new Za.ZD({result:{case:"error",value:new Za.Jx({error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"ReadMcpResource error";case"rejected":return e.result.value.reason||"ReadMcpResource rejected";case"notFound":return"Resource not found";default:return"Unknown error"}},createSuccessOutput:(e,t)=>{if("success"===t.result.case){const r=t.result.value;return{uri:e.uri,name:r.name,mime_type:r.mimeType,download_path:r.downloadPath,content_type:r.content.case,content_length:"text"===r.content.case||"blob"===r.content.case?r.content.value.length:void 0}}return{uri:e.uri,success:!0}}};class FF{constructor(e,t,r){this.wrappedExecutor=QO(e,t,r,OF)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const NF={toolName:dO,getToolCallId:XO,createToolInput:e=>({file_path:e.path}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new Fw.sV({result:{case:"rejected",value:new Fw.f4({path:e.path,reason:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"Read error";case"rejected":return e.result.value.reason||"Read rejected";case"fileNotFound":return`File not found: ${e.result.value.path}`;case"permissionDenied":return`Permission denied: ${e.result.value.path}`;case"invalidFile":return`Invalid file: ${e.result.value.path}`;default:return"Unknown error"}},createSuccessOutput:(e,t)=>{if("success"===t.result.case){const r="content"===t.result.value.output.case?t.result.value.output.value:"";return{file_path:e.path,content_length:r.length}}return{file_path:e.path,success:!0}},runPostExecutionHooks:async e=>{const{args:t,result:r,baseHookRequest:n,hookExecutor:o,toolUseId:s}=e;if("success"!==r.result.case||!1===o.hasHooksForStep?.(Nu.beforeReadFile))return;const i="content"===r.result.value.output.case?r.result.value.output.value:"",a=await async function(e,t){try{return await e()}catch(e){const r=function(e,t){return`${e??"Action"} was blocked because a configured hook failed to execute${t?`: ${t}`:"."}\n\nThis is a safety measure (fail-closed) - when hooks cannot be evaluated, the action is blocked to prevent potentially unsafe operations.\n\n${HO}`}(t,e instanceof Error?e.message:String(e));throw new WO(r,e)}}((()=>o.executeHookForStep(Nu.beforeReadFile,{...n,content:i,file_path:t.path,attachments:[],tool_use_id:s})),"File read");if("deny"===a?.permission){const e=qO("File read",a.user_message);throw new BO(e)}}};class LF{constructor(e,t,r){this.wrappedExecutor=new sR(QO(e,t,r,NF))}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const jF={toolName:"RecordScreen",getToolCallId:XO,createToolInput:e=>({mode:e.mode,save_as_filename:e.saveAsFilename}),createRejectedResult:(e,t)=>new DT.Tj({result:{case:"failure",value:new DT.yH({error:t})}}),isSuccess:e=>"failure"!==e.result.case,getErrorMessage:e=>"failure"===e.result.case?e.result.value.error||"RecordScreen failed":"Unknown error",createSuccessOutput:(e,t)=>({result_type:t.result.case})};class UF{constructor(e,t,r){this.wrappedExecutor=QO(e,t,r,jF)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}function BF(e){return"success"===e.result.case||"failure"===e.result.case?e.result.value.stdout+e.result.value.stderr:""}const WF={toolName:gO,createToolInput:e=>{const t=e.workingDirectory||"",r=e.timeout;return{command:e.command,cwd:t,..."number"==typeof r&&r>0&&{timeout:r}}},applyUpdatedInput:(e,t)=>{"string"==typeof t.command&&(e.command=t.command),"string"==typeof t.cwd&&(e.workingDirectory=t.cwd),"number"==typeof t.timeout&&t.timeout>=0&&(e.timeout=t.timeout)},createRejectedResult:(e,t)=>new he.W4({result:{case:"rejected",value:new he.pZ({command:e.command,workingDirectory:e.workingDirectory,reason:t})}}),isSuccess:e=>"success"===e.result.case||"failure"===e.result.case&&!e.result.value.aborted,getErrorMessage:e=>{switch(e.result.case){case"timeout":return`Command timed out after ${e.result.value.timeoutMs}ms`;case"spawnError":return e.result.value.error||"Failed to spawn command";case"failure":return e.result.value.aborted?"Command was aborted":"Command failed";case"rejected":return e.result.value.reason||"Command rejected";default:return"Unknown error"}},getFailureType:e=>"timeout"===e.result.case?"timeout":"error",isInterrupt:e=>"failure"===e.result.case&&e.result.value.aborted,createSuccessOutput:(e,t)=>({output:BF(t),exitCode:"success"===t.result.case?0:1}),getExtraHookFields:e=>({cwd:e.workingDirectory||""}),runPreExecutionHooks:async e=>{const{ctx:t,args:r,baseHookRequest:n,hookExecutor:o,toolUseId:s}=e,i=r.workingDirectory||"";AO(t,Nu.beforeShellExecution)&&bo(r,await hF({hookExecutor:o,baseHookRequest:n,toolUseId:s,command:r.command,cwd:i,sandbox:dF(r.requestedSandboxPolicy)}))},runPostExecutionHooks:async e=>{const{args:t,result:r,baseHookRequest:n,hookExecutor:o,executionDurationMs:s,toolUseId:i}=e,a=BF(r);await o.executeHookForStep(Nu.afterShellExecution,{...n,command:t.command,output:a,duration:s,sandbox:dF(t.requestedSandboxPolicy),tool_use_id:i})}};class HF{constructor(e,t,r){this.wrappedExecutor=QO(e,t,r,WF)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}class qF{constructor(){this.output=""}onEvent(e){"stdout"===e.event.case||"stderr"===e.event.case?this.output+=e.event.value.data:"exit"===e.event.case&&(this.exitEvent=e.event.value)}getOutput(){return this.output}isAborted(){return this.exitEvent?.aborted??!1}getExitCode(){return this.exitEvent?.code??0}}const zF={toolName:gO,createToolInput:e=>{const t=e.workingDirectory||"",r=e.timeout;return{command:e.command,cwd:t,..."number"==typeof r&&r>0&&{timeout:r}}},applyUpdatedInput:(e,t)=>{"string"==typeof t.command&&(e.command=t.command),"string"==typeof t.cwd&&(e.workingDirectory=t.cwd),"number"==typeof t.timeout&&t.timeout>=0&&(e.timeout=t.timeout)},createRejectedEvent:(e,t)=>new he.FI({event:{case:"rejected",value:new he.pZ({command:e.command,workingDirectory:e.workingDirectory,reason:t})}}),createHookContextEvent:e=>new he.FI({event:{case:"hookContext",value:new he.Ng({hookAdditionalContexts:[...e]})}}),getExtraHookFields:e=>({cwd:e.workingDirectory||""}),createResultCollector:()=>new qF,createSuccessOutput:(e,t)=>({output:t.getOutput(),exitCode:t.getExitCode()}),isStreamSuccess:e=>0===e.getExitCode(),getStreamErrorMessage:(e,t)=>t.getOutput().trim()||`Command failed with exit code ${t.getExitCode()}`,runPreExecutionHooks:async e=>{const{ctx:t,args:r,baseHookRequest:n,hookExecutor:o,toolUseId:s}=e,i=r.workingDirectory||"",a=dF(r.requestedSandboxPolicy);AO(t,Nu.beforeShellExecution)&&bo(r,await hF({hookExecutor:o,baseHookRequest:n,toolUseId:s,command:r.command,cwd:i,sandbox:a}))},runPostExecutionHooks:async e=>{const{args:t,baseHookRequest:r,hookExecutor:n,collector:o,executionDurationMs:s,toolUseId:i}=e,a=dF(t.requestedSandboxPolicy);await n.executeHookForStep(Nu.afterShellExecution,{...r,command:t.command,output:o.getOutput(),duration:s,sandbox:a,tool_use_id:i})}};class GF{constructor(e,t,r){this.wrappedExecutor=function(e,t,r,n){return{async*execute(o,s,i){const a=eF(o,t),{hookContext:c,helpers:l}=JO(o,s,a,r,n,i),u=n.runPreExecutionHooks?async e=>{await n.runPreExecutionHooks(e)}:void 0,d=await ZO(o,s,a,c,l,n,((e,t)=>n.createRejectedEvent(e,t)),u);if("rejected"===d.type){yield d.result;for(const e of YO(n,c))yield e;return}const h=IO.performance.now(),p=n.createResultCollector();try{for await(const t of e.execute(o,s,i))p.onEvent(t),yield t}catch(e){const t=KO(IO.performance.now()-h),r=e instanceof Error?e.message:String(e);await l.fireFailureAsync(t,r,"error");for(const e of YO(n,c))yield e;throw e}const f=KO(IO.performance.now()-h);if(n.runPostExecutionHooks)try{await n.runPostExecutionHooks({ctx:o,args:s,baseHookRequest:c.baseHookRequest,hookExecutor:a,toolInput:l.getToolInput(),toolUseId:c.toolUseId,extraHookFields:c.extraHookFields,collector:p,executionDurationMs:f})}catch(e){GO.warn(o,"postExecutionHooks error",{toolName:n.toolName,error:e instanceof Error?e.message:String(e)})}if(p.isAborted())await l.fireFailureAsync(f,"Command was aborted","error",!0);else if(n.isStreamSuccess?.(p)??1)await l.fireSuccessAsync(f,JSON.stringify(n.createSuccessOutput(s,p)));else{const e=n.getStreamErrorMessage?.(s,p)??`Command failed with exit code ${p.getExitCode()}`;await l.fireFailureAsync(f,e,"error")}for(const e of YO(n,c))yield e}}}(e,t,r,zF)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}class VF{constructor(e,t,r){const n=new Map;this.wrappedExecutor=QO(e,t,r,function(e){return{toolName:hO,getToolCallId:XO,createToolInput:e=>({file_path:e.path,content:e.fileText}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new HA.v3({result:{case:"error",value:new HA.QM({path:e.path,error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>"error"===e.result.case?e.result.value.error||"Write error":"Unknown error",createSuccessOutput:e=>({file_path:e.path,success:!0}),runPreExecutionHooks:async t=>{const{args:r,hookExecutor:n,toolUseId:o}=t;if(!1===n.hasHooksForStep?.(Nu.afterFileEdit))return;let s,i=!1;try{(await(0,fo.stat)(r.path)).size>262144?i=!0:s=await Ti(r.path)}catch(e){}e.set(o,{contentBeforeWrite:s,fileTooLarge:i})},runCleanup:t=>{e.delete(t)},runPostExecutionHooks:async t=>{const{args:r,result:n,baseHookRequest:o,hookExecutor:s,toolUseId:i}=t,a=e.get(i);if("success"!==n.result.case||!1===s.hasHooksForStep?.(Nu.afterFileEdit))return;const{contentBeforeWrite:c,fileTooLarge:l}=a??{fileTooLarge:!1};let u;u=l||void 0===c?[{old_string:"",new_string:r.fileText}]:c===r.fileText?[]:function(e,t){const r=(0,Wv.YB)("","",e,t,"","",{context:0,timeout:50});return void 0===r?[{old_string:"",new_string:t}]:0===r.hunks.length?[]:r.hunks.map((e=>{const t=[],r=[];for(const n of e.lines)n.startsWith("-")?t.push(n.slice(1)):n.startsWith("+")&&r.push(n.slice(1));return{old_string:t.join("\n"),new_string:r.join("\n")}}))}(c,r.fileText);const d={...o,file_path:r.path,edits:u},h=await s.executeHookForStep(Nu.afterFileEdit,d);if(r.returnFileContentAfterWrite&&void 0!==h){const e=n.result.value.path;try{const t=await Ti(e),r=Us(t),o=Buffer.byteLength(t,"utf8");return new HA.v3({result:{case:"success",value:new HA.j6({path:n.result.value.path,linesCreated:r,fileSize:o,fileContentAfterWrite:t})}})}catch(e){return}}}}}(n))}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}function KF(e,t,r){return t===e.symbol}function JF(e,t,r){return KF(VI,e)?new HF(t,r.hookExecutor,r.baseHookRequestExtractor):KF(ee,e)?new GF(t,r.hookExecutor,r.baseHookRequestExtractor):KF(XI,e)?new VF(t,r.hookExecutor,r.baseHookRequestExtractor):KF(Gn,e)?new $F(t,r.hookExecutor,r.baseHookRequestExtractor,r.mcpLease,r.hooksConfigLease):KF(iR,e)||KF(aR,e)?new LF(t,r.hookExecutor,r.baseHookRequestExtractor):KF(cR,e)?new IF(t,r.hookExecutor,r.baseHookRequestExtractor):KF(tR,e)?new xF(t,r.hookExecutor,r.baseHookRequestExtractor):KF(YI,e)?new CF(t,r.hookExecutor,r.baseHookRequestExtractor):KF(QI,e)?new bF(t,r.hookExecutor,r.baseHookRequestExtractor):KF(lR,e)?new kF(t,r.hookExecutor,r.baseHookRequestExtractor):KF(Vn,e)?new DF(t,r.hookExecutor,r.baseHookRequestExtractor):KF(Kn,e)?new FF(t,r.hookExecutor,r.baseHookRequestExtractor):KF(PR,e)?new fF(t,r.hookExecutor,r.baseHookRequestExtractor):KF(IR,e)?new gF(t,r.hookExecutor,r.baseHookRequestExtractor):KF(DR,e)?new yF(t,r.hookExecutor,r.baseHookRequestExtractor):KF(OR,e)?new UF(t,r.hookExecutor,r.baseHookRequestExtractor):KF(Ar,e)&&(r.hooksAdditionalContextPromise||r.hooksConfigLease)?new uF(t,r.hooksAdditionalContextPromise??Promise.resolve(void 0),r.teamHooksReadyPromise,r.hooksConfigLease):void 0}class ZF{constructor(e,t,r,n,o,s,i){this.innerAccessor=e,this.hookExecutor=t,this.baseHookRequestExtractor=r,this.mcpLease=n,this.hooksAdditionalContextPromise=o,this.teamHooksReadyPromise=s,this.hooksConfigLease=i}get(e){const t=function(e,t){if(e.symbol===oF.symbol)return new lF(t)}(e,this.hookExecutor);return void 0!==t?t:function(e,t,r){const n=JF(e.symbol,t,r);return void 0!==n?n:t}(e,this.innerAccessor.get(e),{hookExecutor:this.hookExecutor,baseHookRequestExtractor:this.baseHookRequestExtractor,mcpLease:this.mcpLease,hooksAdditionalContextPromise:this.hooksAdditionalContextPromise,teamHooksReadyPromise:this.teamHooksReadyPromise,hooksConfigLease:this.hooksConfigLease})}*entries(){for(const[e,t]of this.innerAccessor.entries()){const r=JF(e.symbol,t,{hookExecutor:this.hookExecutor,baseHookRequestExtractor:this.baseHookRequestExtractor,mcpLease:this.mcpLease,hooksAdditionalContextPromise:this.hooksAdditionalContextPromise,teamHooksReadyPromise:this.teamHooksReadyPromise,hooksConfigLease:this.hooksConfigLease});yield[e,r??t]}const e=oF;yield[e,new lF(this.hookExecutor)]}}const XF={cursor_version:process.env.AGENT_CLI_STATIC_VERSION??"1.0.0",user_email:null};function QF(e=process.cwd()){let t=e;return{getCwd:async()=>t,clone:e=>QF(e??t),async*execute(e,r,n={}){const o=n.workingDirectory??t;t=o;const s=function(e){return"win32"===process.platform?{executable:(0,Eo.oG)(),args:[...HM,"-Command",e]}:{executable:process.env.SHELL||"/bin/sh",args:["-lc",e]}}(r),i=(0,gl.spawn)(s.executable,[...s.args],{cwd:o,env:{...process.env,...n.env??{}},signal:n.signal,stdio:[!0===n.pipeStdin?"pipe":"ignore","pipe","pipe"]}),a=[];let c,l,u=!1;const d=()=>{c?.(),c=void 0},h=e=>{a.push(e),d()};for(i.on("spawn",(()=>{!0===n.pipeStdin&&h({type:"stdin_ready",stdin:i.stdin??void 0})})),i.stdout?.setEncoding("utf8"),i.stdout?.on("data",(e=>{h({type:"stdout",data:String(e)})})),i.stderr?.setEncoding("utf8"),i.stderr?.on("data",(e=>{h({type:"stderr",data:String(e)})})),i.on("error",(e=>{l=e,u=!0,d()})),i.on("close",(e=>{h({type:"exit",code:e}),u=!0}));!u||a.length>0;)0!==a.length?yield a.shift():await new Promise((e=>{c=e}));if(void 0!==l)throw l}}}function YF(e,t,...r){for(const n of r){const r=t(e[n]);if(void 0!==r)return r}}function eN(e){return"string"==typeof e&&e.length>0?e:void 0}function tN(e){return"object"==typeof e&&null!==e&&"string"==typeof e.id&&"string"==typeof e.value}function rN(e){if(Array.isArray(e)&&e.every(tN))return e.map((e=>({id:e.id,value:e.value})))}class nN{constructor(e,t){this.innerAccessor=e,this.sessionHooksRuntime=t}get(e){return this.innerAccessor.get(e)}entries(){return this.innerAccessor.entries()}async dispose(){await this.sessionHooksRuntime.dispose()}}async function oN(e,t={}){const r=await new uO(new rF,function(e,t){const r=e.projectRoot??e.workingDirectory??e.workspaceRoots[0],n=t.includeProjectHooks??!0,i=t.includeUserHooks??!0;return{enterpriseConfigPath:t.includeEnterpriseHooks??1?aO():void 0,userConfigPath:i?(0,s.join)((0,o.homedir)(),".cursor","hooks.json"):void 0,claudeUserConfigPath:i?(0,s.join)((0,o.homedir)(),".claude","settings.json"):void 0,projectConfigPath:n&&void 0!==r?(0,s.join)(r,".cursor","hooks.json"):void 0,claudeProjectConfigPath:n&&void 0!==r?(0,s.join)(r,".claude","settings.json"):void 0,claudeProjectLocalConfigPath:n&&void 0!==r?(0,s.join)(r,".claude","settings.local.json"):void 0}}(e,t)).load(),n=new PO(r),i=function(e){return e.projectRoot??e.workingDirectory??e.workspaceRoots[0]??process.cwd()}(e),a=function(e){return Object.freeze({...XF,...e.globalContext??{}})}(t);return{projectDir:e.projectRoot,workspacePath:i,hooksConfig:r,hooksConfigLease:n,globalContext:a,createSessionRuntime(){const e=new xO(r,i,a,(t.createTerminalExecutor??QF)(),t.promptHookClient,void 0,void 0,{enableClaudeNestedHookSpecificOutputCompatibility:!0,commandHookPayloadTransport:(o=t.useCommandHookStdinTransport,!0===o?"stdin":"legacy")});var o;return{hookExecutor:e,hooksConfigLease:n,async dispose(){e.clearSessionEnvironment()}}},async dispose(){}}}function sN(e={}){return{createHooksRuntime:t=>oN(t.workspaceState,e)}}var iN=r("../proto/dist/generated/aiserver/v1/dashboard_connect.js");async function aN(e){(function(e){return"object"==typeof e&&null!==e&&"dispose"in e&&"function"==typeof e.dispose})(e)&&await e.dispose()}function cN(e={}){const t=e.getThirdPartyExtensibilityEnabled??(()=>!0),r=e.importThirdPartyPlugins??!1,n=e.includeProjectExtensibility??!0,s=e.includeUserExtensibility??!0,i=e.includeManagedSkills??!0,a=e.includePluginExtensibility??!0,c=new dw,l=(0,o.homedir)(),u=cf(l).dirPath;let d,h=!0;return{async prepareLocalExtensibility(){h=i&&await async function(e){if(!e)return!1;const t=(0,ye.createClient)(iN.I,e);return"synced"===(await async function(e,t){try{const r=await t.getManagedSkills()??[],n=await D$(e,{managedSkills:[...r]});return{status:"synced",managedSkillsCount:r.length,syncResult:n}}catch(t){return F$.warn(e,"Failed to sync managed skills from source",{error:t}),{status:"fetch_failed",error:t}}}((0,y.q6)(),{getManagedSkills:async()=>(await t.getManagedSkills(new H$.X8g({}))).skills??[]})).status}(e.dashboardTransport)},async loadLocalExtensibility(o){const i=function(e){if(e.workspaceRoots.length>0)return[...e.workspaceRoots];const t=e.projectRoot??e.workingDirectory;return void 0!==t?[t]:[]}(o.workspaceState);if(0===i.length)return d=void 0,{cursorRulesService:mN(),getAgentSkills:async e=>[]};const p=(0,y.q6)(),f=e.loadNestedRules??!0,m=n?i.map((e=>new om(p,c,e,f,t,void 0))):[],g=function(e,t){const r=lN(t);return{getAllCursorRules:async t=>uN(await e.getAllCursorRules(t),r),reload(t){e.reload(t)},onDidChangeRules:t=>e.onDidChangeRules(t),dispose(){e.dispose()}}}(0===m.length?mN():1===m.length?m[0]:new nm(m,(()=>xf)),{allowedRoots:n?i:[],excludedRoots:[]}),w=function(e,t){const r=lN(t);return{getAllCursorRules:async t=>uN(await e.getAllCursorRules(t),r),getAllAgentSkills:async t=>uN(await e.getAllAgentSkills(t),r),reload(t){e.reload(t)},onDidChangeRules:t=>e.onDidChangeRules(t),onDidChangeSkills:t=>e.onDidChangeSkills(t),dispose(){e.dispose()}}}(new im(p,n?i:[],l,c,f,void 0,t,Promise.resolve(),"sdk"),{allowedRoots:[...n?i:[],...s?[l]:[],...h?[u]:[]],excludedRoots:h?[]:[u]}),v=n?i.map((e=>new wm(e,t))):[],b=0===v.length?new dm:1===v.length?v[0]:new vm(v),S=DM(o.services.pluginBootstrapOutputs),k=S&&a?new cm(p,(()=>({importThirdPartyPlugins:r})),void 0,S.pluginsService):void 0,_=S&&a?new bm((()=>({importThirdPartyPlugins:r})),S.pluginsService):void 0,C=new nm([g,w,...k?[k]:[]],(()=>xf)),E=new m$([w,...k?[k]:[]],(()=>[]),(()=>({workspacePaths:n?i:[],userHomeDirectory:l,agentStoreSkillsDirs:[]}))),x=new vm([b,..._?[_]:[]]);d={localRulesService:g,localSkillsService:w,localSubagentsService:b,pluginSkillsService:k,pluginSubagentsService:_,mergedCursorRulesService:C,mergedAgentSkillsService:E,mergedSubagentsService:x};const P={cursorRulesService:C,getAgentSkills:e=>E.getAllAgentSkills(e),subagentsService:x};return P},async disposeLocalExtensibility(){if(!d)return;const e=d;d=void 0,await async function(e){let t;const r=[e.mergedSubagentsService,e.mergedAgentSkillsService,e.mergedCursorRulesService,e.pluginSubagentsService,e.pluginSkillsService,e.localSubagentsService,e.localSkillsService,e.localRulesService];for(const e of r)try{await aN(e)}catch(e){t??=e}if(void 0!==t)throw t}(e)}}}function lN(e){const t=Promise.all(e.allowedRoots.map(pN)),r=Promise.all(e.excludedRoots.map(pN));return async e=>{const[n,o,s]=await Promise.all([fN(e.fullPath),t,r]);return void 0!==n&&!s.some((e=>dN(n,e)))&&o.some((e=>dN(n,e)))}}async function uN(e,t){const r=await Promise.all(e.map(t));return e.filter(((e,t)=>r[t]))}function dN(e,t){if(e===t)return!0;const r=`${t}/`;return e.startsWith(r)}function hN(e){return e.replace(/\\/g,"/").replace(/\/+$/,"")}async function pN(e){try{return hN(await(0,fo.realpath)(e))}catch{return hN(e)}}async function fN(e){try{return hN(await(0,fo.realpath)(e))}catch{return}}function mN(){return{getAllCursorRules:async()=>[],reload(){},onDidChangeRules:()=>()=>{},dispose(){}}}function gN(e,t){const r=e.releaseTag??t;if(e.releaseRepo&&e.releaseAsset&&r)return{kind:"release",releaseRepo:e.releaseRepo,releaseAsset:e.releaseAsset,releaseTag:r}}function wN(){const e=["-c","credential.interactive=false","-c","core.fsmonitor=false"];return"win32"===process.platform&&e.push("-c","core.longpaths=true"),e}function yN(e){return"function"==typeof e?e():e}async function vN(e,t){const r=function(e){const t={...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:void 0,VSCODE_GIT_ASKPASS_NODE:void 0,VSCODE_GIT_ASKPASS_MAIN:void 0,VSCODE_GIT_ASKPASS_EXTRA_ARGS:void 0,GCM_INTERACTIVE:"Never"};if(t.GIT_CONFIG_NOSYSTEM=void 0,!0===e?.sshBatchMode){const e=process.env.GIT_SSH_COMMAND?.trim()||"ssh";t.GIT_SSH_COMMAND=`${e} -oBatchMode=yes`}if(void 0!==e?.extraGitConfig){const r=Object.entries(e.extraGitConfig).flatMap((([e,t])=>Array.isArray(t)?t.map((t=>[e,t])):[[e,t]]));t.GIT_CONFIG_COUNT=String(r.length);for(const[e,[n,o]]of r.entries())t[`GIT_CONFIG_KEY_${e}`]=n,t[`GIT_CONFIG_VALUE_${e}`]=o}return{cwd:e?.cwd,env:t}}({cwd:t?.cwd,sshBatchMode:t?.sshBatchMode,extraGitConfig:t?.extraGitConfig});return Jg("git",[...wN(),...e],{...r,...void 0!==t?.timeoutMs&&{timeout:t.timeoutMs,killSignal:"SIGTERM"}})}const bN=/^[0-9a-f]{7,40}$/i,SN=/^[0-9a-f]{40}$/i;function kN(e){if(void 0===e||""===e)return;const t=e.split(/\r?\n/).map((e=>{const[t,r]=e.split("\t");if(t&&r&&/^[0-9a-f]{40}$/i.test(t))return{sha:t,refName:r}})).filter((e=>void 0!==e)),r=t[0];return void 0!==r?t.find((e=>e.refName.endsWith("^{}")))?.sha??r.sha:void 0}async function _N(e,t,r){const n=t.trim();if(SN.test(n))return{fullSha:n.toLowerCase()};if(bN.test(n)){try{const t=await async function(e,t,r){const{stdout:n}=await vN(["ls-remote",e,`refs/heads/${t}`,`refs/tags/${t}`,`refs/tags/${t}^{}`],{sshBatchMode:r?.sshBatchMode,extraGitConfig:r?.extraGitConfig,timeoutMs:r?.timeoutMs});return kN(n)?.toLowerCase()}(e,n,r);if(t)return{fullSha:t}}catch{}return{fullSha:n.toLowerCase()}}let o;try{if("HEAD"===n.toUpperCase()){const t=await vN(["ls-remote","--symref",e,"HEAD"],{sshBatchMode:r?.sshBatchMode,extraGitConfig:r?.extraGitConfig,timeoutMs:r?.timeoutMs}),n=kN(t.stdout);if(!n)throw new Error(`git ls-remote did not return a resolvable commit for HEAD (${e})`);return{fullSha:n.toLowerCase(),headSymrefStdout:t.stdout}}o=(await vN(["ls-remote",e,n],{sshBatchMode:r?.sshBatchMode,extraGitConfig:r?.extraGitConfig,timeoutMs:r?.timeoutMs})).stdout}catch(t){const r=t instanceof Error?t.message:String(t),o=new Error(`Failed to resolve git ref "${n}" for ${e}: ${r}`);throw o.cause=t,o}const s=kN(o);if(!s)throw new Error(`git ls-remote did not return a resolvable commit for ref "${n}" (${e})`);return{fullSha:s.toLowerCase()}}const CN=Id.map((function(e){const t=e.split("/")[0];if(void 0===t||0===t.length)throw new Error(`Marketplace manifest path has no directory: ${e}`);return t}));let EN;function xN(e){let t=e.trim().replaceAll("\\","/");for(;t.startsWith("./");)t=t.slice(2);return t=t.replace(/\/+$/,""),""===t||"."===t||t.startsWith("/")||/^[a-zA-Z]:/.test(t)||t.split("/").some((e=>""===e||"."===e||".."===e))?null:t}function PN(e){const t=[];for(const r of e){const e=xN(r);if(null===e)return"all";t.push(e)}return t}async function IN(e,t){const r="all"===e?"all":PN(e),n=t&&"all"!==r&&await(process.env.CURSOR_DISABLE_SPARSE_PLUGIN_CLONES?Promise.resolve(!1):(EN??=(async()=>{try{const{stdout:e}=await vN(["--version"]),t=function(e){const t=/git version (\d+)\.(\d+)/.exec(e);return t?{major:Number(t[1]),minor:Number(t[2])}:null}(e);return null!==t&&(t.major>2||2===t.major&&t.minor>=28)}catch{return!1}})(),EN));return{materialize:r,sparse:n,sparseDirs:n?(o=r,[...new Set([...CN,...o])]):[]};var o}function RN(e){return e.toLowerCase().includes("filtering not recognized by server")}async function TN(e,t,r){await vN(["sparse-checkout","set","--cone","--",...t],{...r,cwd:e})}async function AN(e){try{await(0,fo.access)((0,s.join)(e,".git","info","sparse-checkout"))}catch{return!1}try{const{stdout:t}=await vN(["config","--bool","--get","core.sparseCheckout"],{cwd:e});return"true"===t.trim()}catch{return!1}}async function $N(e,t,r){if("all"!==t&&0===t.length)return;if(!await AN(e))return;const n={...r,cwd:e,sshBatchMode:!0};if("all"===t)return void await vN(["sparse-checkout","disable"],n);const o=PN(t);"all"!==o?await vN(["sparse-checkout","add","--",...o],n):await vN(["sparse-checkout","disable"],n)}(0,fs.J)((function(){EN=void 0}));const MN=/\.git$/i,DN=new Set(["account","dashboard"]);function ON(e){return e.replace(MN,"")}function FN(e){let t;try{t=decodeURIComponent(e)}catch{return}return t.length>0&&!t.includes("/")?t:void 0}function NN(e){const t=e.toLowerCase();return"github.com"===t||t.endsWith(".github.com")}function LN(e){return e.toLowerCase().split(".").includes("gitlab")}function jN(e){const t=e.toLowerCase();return"bitbucket.org"===t||"www.bitbucket.org"===t}function UN(e){const t=e.toLowerCase();return LN(e)?"GitLab":t.includes("bitbucket")?"Bitbucket":t.includes("gitea")||t.includes("codeberg")?"Gitea/Codeberg":t.includes("azure")&&t.includes("dev")?"Azure DevOps":null}function BN(e){return NN(e)?"github":LN(e)?"gitlab":jN(e)?"bitbucket":function(e){const t=e.toLowerCase();return"dev.azure.com"===t||"www.dev.azure.com"===t}(e)?"azure_devops":"generic"}function WN(e){let t;try{const r=e.startsWith("git@")?`ssh://${e.replace(":","/")}`:e;t=new URL(r.includes("://")?r:`https://${r}`)}catch{return null}const r=t.hostname;let n=t.pathname.split("/").filter(Boolean);ya(r)&&"git"===n[0]?.toLowerCase()&&(n=n.slice(1));const o=n[0];void 0!==o&&n.length>=3&&"scm"===o.toLowerCase()&&(n=n.slice(1));const s=function(e){const t=e[0],r=e[1];if(!t||!r)return;const n=ON(r);return n?{owner:t,repo:n,hasSubpath:e.length>2}:void 0}(n);return void 0===s?null:{provider:BN(r),owner:s.owner,repo:s.repo,host:r}}function HN(e){const t=qN(e);if(null===t)return!1;const r=t.pathname.split("/").filter(Boolean),n=r[0];return void 0!==n&&r.length>=3&&"scm"===n.toLowerCase()}function qN(e){try{const t=e.startsWith("git@")?`ssh://${e.replace(":","/")}`:e;return new URL(t.includes("://")?t:`https://${t}`)}catch{return null}}function zN(e){const t=e.trim();if(""===t)return{error:"URL cannot be empty"};const r=WN(t);if(null===r)return{error:"Invalid URL format. Expected: github.com/owner/repo or gitlab.com/namespace/repo"};if(LN(r.host)){const e=qN(t),r=null===e?void 0:function(e){const t=e.indexOf("-"),r=-1!==t,n=r?e.slice(0,t):[...e];if(n.length<2||n.some((e=>0===e.length)))return;const o=ON(n[n.length-1]);return o?(n[n.length-1]=o,{repositorySegments:n,hasSpecialRouteSeparator:r}):void 0}(e.pathname.split("/").filter(Boolean));if(null===e||void 0===r)return{error:"Invalid GitLab repository URL format. Expected: https://gitlab.com/namespace/repo"};const n=e.host.replace(/^www\./i,""),o=r.repositorySegments[0],s=r.repositorySegments[r.repositorySegments.length-1];return void 0===o||void 0===s?{error:"Invalid GitLab repository URL format. Expected: https://gitlab.com/namespace/repo"}:{url:`https://${n}/${r.repositorySegments.join("/")}`,owner:o,repo:s,host:n,provider:"gitlab"}}if("bitbucket"===r.provider){const e=function(e){const t=qN(e.trim());if(null!==t&&jN(t.hostname))return function(e){const t=e[0],r=e[1];if(void 0===t||void 0===r)return;const n=FN(t),o=FN(r);if(void 0===n||void 0===o||DN.has(n.toLowerCase()))return;const s=ON(o);return s?{workspace:encodeURIComponent(n),repo:encodeURIComponent(s),hasSubpath:e.length>2}:void 0}(function(e){const t=e.pathname.split("/");return""===t[0]&&t.shift(),""===t[t.length-1]&&t.pop(),t}(t))}(t);if(void 0===e)return{error:"Invalid Bitbucket repository URL format. Expected: https://bitbucket.org/{workspace}/{repo}"};const n=r.host.replace(/^www\./i,"");return{url:`https://${n}/${e.workspace}/${e.repo}`,owner:e.workspace,repo:e.repo,host:n,provider:"bitbucket"}}if("azure_devops"===r.provider){const e=qN(t),n=null===e?void 0:function(e){const t=e.findIndex((e=>"_git"===e.toLowerCase()));if(t<1||t>2)return;const r=e[0],n=e[t+1];if(!r||!n)return;const o=ON(n);if(!o)return;const s=2===t?e[1]:o;return s?{organization:r,project:s,repo:o,hasSubpath:e.length>t+2}:void 0}(e.pathname.split("/").filter(Boolean));if(null===e||void 0===n)return{error:"Invalid Azure DevOps repository URL format. Expected: https://dev.azure.com/{organization}/{project}/_git/{repo}"};const o=r.host.replace(/^www\./i,"");return{url:`https://${o}/${n.organization}/${n.project}/_git/${n.repo}`,owner:n.organization,repo:n.repo,host:o,provider:"azure_devops",project:n.project}}if(function(e){switch(e.provider){case"github":return!0;case"generic":return!ya(e.host)&&null===UN(e.host);case"gitlab":case"bitbucket":case"azure_devops":return!1;default:return e.provider,!1}}(r)){const e=VN(r.host.replace(/^www\./i,""));return{url:`https://${e}/${HN(t)?"scm/":""}${r.owner}/${r.repo}`,owner:r.owner,repo:r.repo,host:e,provider:"github"}}const n=UN(r.host);return{error:"Only GitHub, GitLab, Bitbucket, and Azure DevOps URLs are currently supported."+(null!==n?` ${n} is not supported yet.`:"")}}function GN(e){const t=zN(e);if("error"in t)return null;switch(t.provider){case"github":return`git@${t.host}:${t.owner}/${t.repo}.git`;case"gitlab":return function(e){let t;try{t=new URL(e.url).pathname.replace(/^\//,"").replace(/\.git$/i,"")}catch{return null}if(0===t.length)return null;return`git@${e.host.replace(/:\d+$/,"")}:${t}.git`}(t);case"bitbucket":case"azure_devops":return null;default:return t.provider,null}}function VN(e){return NN(e)?"github.com":e}function KN(e){return!e.operatingSystems||0===e.operatingSystems.length||e.operatingSystems.includes(function(){const e=(0,o.platform)();return"win32"===e?"Windows":"darwin"===e?"Macintosh":"Linux"}())}function JN(e){return/[\n\r:#[\]{}&*!|>'"%@`]/.test(e)||e.startsWith(" ")||e.endsWith(" ")?`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:e}const ZN=new Set(["con","prn","aux","nul","com1","com2","com3","com4","com5","com6","com7","com8","com9","lpt1","lpt2","lpt3","lpt4","lpt5","lpt6","lpt7","lpt8","lpt9"]);function XN(e){const t=Vh(e).replace(/[. ]+$/g,"");return""===t||"."===t||".."===t?"_":ZN.has(t.toLowerCase())?`_${t}`:t}const QN=18e5,YN=6e5,eL={recursive:!0,force:!0,maxRetries:3},tL=["terminal prompts disabled","could not read username","host key verification failed","could not read from remote repository","permission denied","repository not found","user cancelled dialog","spawn git enoent","authentication failed","unable to get password from user"],rL=["enotempty: directory not empty, rename","/_staging/"],nL=["upload-pack: not our ref","server does not allow request for unadvertised object"];function oL(e){const t=String(e).toLowerCase().replaceAll("\\","/");return tL.some((e=>t.includes(e)))?"user_git_access":rL.every((e=>t.includes(e)))?"local_cache_race":nL.some((e=>t.includes(e)))?"stale_pinned_ref":"infrastructure"}function sL(e){return"object"==typeof e&&null!==e&&(!0===e.killed||sL(e.cause))}function iL(e){return sL(e)?"killed_by_budget":oL(e)}function aL(e){const t=zN(e);if(!("error"in t)&&"gitlab"===t.provider){let r;try{r=new URL(t.url).pathname.replace(/^\//,"")}catch{throw new Error(`Invalid git URL: ${e}`)}const n=r.split("/").filter(Boolean).map((e=>e.toLowerCase()));if(n.length<2)throw new Error(`Invalid git URL: ${e}`);return{host:t.host.toLowerCase(),pathSegments:n}}const r=WN(e);if(null===r)throw new Error(`Invalid git URL: ${e}`);return{host:VN(r.host.replace(/^www\./i,"")).toLowerCase(),pathSegments:[r.owner.toLowerCase(),r.repo.toLowerCase()]}}const cL=new Map;class lL{constructor(e,t){this.cacheRoot=e,this.options=t,this.manifestCache=new Map}get sparsePluginClones(){return this.options?.sparsePluginClones??!1}remoteTimeoutMs(){return this.sparsePluginClones?QN:void 0}localTimeoutMs(){return this.sparsePluginClones?YN:void 0}lsRemoteTimeoutMs(){return this.sparsePluginClones?3e4:void 0}async cloneResolvedRef(e,t,r,n){const o={cwd:e,sshBatchMode:n?.sshBatchMode,extraGitConfig:{...yN(this.options?.extraGitConfig),"safe.directory":e}},{sparse:s,sparseDirs:i}=await IN(n?.materialize??"all",this.sparsePluginClones);await vN(["init"],{...o,timeoutMs:this.localTimeoutMs()}),s&&await TN(e,i,{sshBatchMode:n?.sshBatchMode,extraGitConfig:yN(this.options?.extraGitConfig),timeoutMs:this.localTimeoutMs()});const{stderr:a}=await vN(["fetch","--depth","1",...s?["--filter=blob:none"]:[],t,r],{...o,timeoutMs:this.remoteTimeoutMs()});return await vN(["checkout","FETCH_HEAD"],{...o,timeoutMs:this.remoteTimeoutMs()}),{strategy:s?"sparse":"full",filterIgnoredByServer:s&&RN(a??"")}}async createStagingDir(){const e=(0,s.join)(this.cacheRoot,"_staging",(0,lo.randomUUID)());return await(0,fo.mkdir)(e,{recursive:!0}),e}async moveToCanonicalDir(e,t){return await(0,fo.mkdir)((0,s.dirname)(t),{recursive:!0}),await(0,fo.rm)(t,eL),await(0,fo.rename)(e,t),t}async cleanStaleStagingDirs(){const e=(0,s.join)(this.cacheRoot,"_staging");try{const t=await(0,fo.readdir)(e,{withFileTypes:!0}),r=Date.now();await Promise.all(t.filter((e=>e.isDirectory())).map((async t=>{try{const n=(0,s.join)(e,t.name),o=await(0,fo.stat)(n);r-o.mtimeMs>lL.STALE_STAGING_THRESHOLD_MS&&await(0,fo.rm)(n,eL)}catch{}})))}catch{}}getLegacyCloneDir(e,t){return(0,s.join)(this.cacheRoot,XN(e),XN(t))}getCanonicalCloneDir(e,t){const{host:r,pathSegments:n}=aL(e);return(0,s.join)(this.cacheRoot,XN(r),...n.map(XN),XN(t))}getCanonicalRepoRootDir(e){const{host:t,pathSegments:r}=aL(e);return(0,s.join)(this.cacheRoot,XN(t),...r.map(XN))}async pruneSiblingCloneDirs(e,t,r){const n=this.getCanonicalRepoRootDir(e),o=XN(t);try{const e=await(0,fo.readdir)(n,{withFileTypes:!0});await Promise.all(e.filter((e=>e.isDirectory()&&e.name!==o)).map((e=>(0,fo.rm)((0,s.join)(n,e.name),eL))))}catch{}if(void 0!==r)try{await(0,fo.rm)(r,eL)}catch{}}async ensureCloned(e,t,r,n=ph,o){const s=this.serializedOnRepo(this.getCanonicalRepoRootDir(t),(()=>this.ensureClonedImpl(e,t,r,n,o?.materialize??"all")));return this.sparsePluginClones?s:(0,Dr.wj)(s,3e4,`ensureCloned timed out after 30000ms for ${t} @ ${r}`)}async ensureMaterialized(e,t,r=ph){const n=this.serializedOnRepo((0,s.dirname)(e),(async()=>{const n=performance.now();try{await $N(e,t,{extraGitConfig:yN(this.options?.extraGitConfig),timeoutMs:this.remoteTimeoutMs()}),r.increment("marketplace_cache_manager.ensure_materialized.success",1),r.distribution("marketplace_cache_manager.ensure_materialized.duration",performance.now()-n)}catch(o){throw r.log("error","Failed to materialize plugin directories in sparse marketplace clone",{clonePath:e,spec:"all"===t?"all":t.join(","),error:String(o),errorCategory:iL(o)}),r.increment("marketplace_cache_manager.ensure_materialized.error",1,{error_category:iL(o)}),r.distribution("marketplace_cache_manager.ensure_materialized.duration",performance.now()-n,{outcome:"error"}),o}}));return this.sparsePluginClones?n:(0,Dr.wj)(n,3e4,`ensureMaterialized timed out after 30000ms for ${e}`)}async serializedOnRepo(e,t){const r=`${this.cacheRoot}:${e}`,n=(cL.get(r)??Promise.resolve()).catch((()=>{})).then(t);cL.set(r,n);try{return await n}finally{cL.get(r)===n&&cL.delete(r)}}async ensureClonedImpl(e,t,r,n,o){n.log("info",`MarketplaceCacheManager: Ensuring cloned ${e} at ${t}@${r}`,{marketplaceId:e,gitUrl:t,ref:r});const s=r.trim();let i,a=t.startsWith("git@")||t.startsWith("ssh://")?null:GN(t);if(null!==a)try{i=(await _N(a,s,{sshBatchMode:!0,extraGitConfig:yN(this.options?.extraGitConfig),timeoutMs:this.lsRemoteTimeoutMs()})).fullSha}catch(e){if(this.sparsePluginClones&&sL(e))throw e;n.log("debug","Failed to resolve remote ref using SSH URL, falling back to HTTPS",{gitUrl:t,ref:r,error:String(e),errorCategory:oL(e)}),a=null,i=(await _N(t,s,{extraGitConfig:yN(this.options?.extraGitConfig),timeoutMs:this.lsRemoteTimeoutMs()})).fullSha}else i=(await _N(t,s,{extraGitConfig:yN(this.options?.extraGitConfig),timeoutMs:this.lsRemoteTimeoutMs()})).fullSha;const c=this.getCanonicalCloneDir(t,i),l=this.getLegacyCloneDir(e,s);n.log("info",`MarketplaceCacheManager: Resolved clone directory for ${e} at ${t}@${r} to ${c}`,{marketplaceId:e,resolvedRef:i,originalRef:s});const u=performance.now(),d=(e,t)=>{n.increment(`marketplace_cache_manager.ensure_cloned.${e}`,1,t),n.distribution(`marketplace_cache_manager.ensure_cloned.${e}.duration`,performance.now()-u,t)};if(await this.isCloneComplete(c)){await this.pruneSiblingCloneDirs(t,i,l);const e=await AN(c);return e&&await $N(c,o,{extraGitConfig:yN(this.options?.extraGitConfig),timeoutMs:this.remoteTimeoutMs()}),d("cache_hit",{strategy:e?"sparse":"full"}),c}return n.increment("marketplace_cache_manager.ensure_cloned.cache_miss",1),this.cloneViaStaging(c,t,a,i,l,r,n,d,o)}async cloneViaStaging(e,t,r,n,o,s,i,a,c){await this.cleanStaleStagingDirs();const l=await this.createStagingDir();i.log("info",`MarketplaceCacheManager: Cloning ${t}@${s} into staging directory: ${l}`,{gitUrl:t,ref:s,cloneDir:e});const u=this.sparsePluginClones?setInterval((()=>{const e=new Date;(0,fo.utimes)(l,e,e).catch((()=>{}))}),lL.STAGING_HEARTBEAT_INTERVAL_MS):void 0;u?.unref?.();try{let u;if(null!==r)try{u=await this.cloneResolvedRef(l,r,n,{sshBatchMode:!0,materialize:c})}catch(e){if(this.sparsePluginClones&&sL(e))throw e;i.log("debug","Falling back to HTTPS clone due to SSH clone failure",{gitUrl:t,ref:s,error:String(e),errorCategory:iL(e)}),await(0,fo.rm)(l,eL),await(0,fo.mkdir)(l,{recursive:!0}),u=await this.cloneResolvedRef(l,t,n,{materialize:c})}else u=await this.cloneResolvedRef(l,t,n,{materialize:c});u.filterIgnoredByServer&&(i.log("warn","Server ignored --filter=blob:none; sparse clone downloaded a full pack",{gitUrl:t,ref:s}),i.increment("marketplace_cache_manager.ensure_cloned.filter_ignored_by_server",1));const d=await this.moveToCanonicalDir(l,e);return await this.pruneSiblingCloneDirs(t,n,o),a("cache_write_success",{strategy:u.strategy}),d}catch(e){const r=iL(e);throw a("error",{error_category:r}),i.log("error","Failed to clone marketplace repository via staging clone",{gitUrl:t,ref:s,error:String(e),errorCategory:r}),i.captureException(e,{error_type:"clone_marketplace_repository",error_category:r}),e}finally{void 0!==u&&clearInterval(u);try{await(0,fo.rm)(l,eL)}catch{}}}async isCloneComplete(e){try{if(!(await(0,fo.stat)(e)).isDirectory())return!1;const t=await(0,fo.readdir)(e);if(!t.includes(".git"))return!1;if(t.length>1)return!0;try{return(await(0,fo.stat)((0,s.join)(e,".git","info","sparse-checkout"))).isFile()}catch{return!1}}catch{return!1}}getPluginDir(e,t){return hp(e,t)}async copyPluginToDir(e,t){await(0,fo.mkdir)(t,{recursive:!0}),await(0,fo.cp)(e,t,{recursive:!0,verbatimSymlinks:!0})}async readManifest(e,t={}){const r=function(e,t){return JSON.stringify({clonePath:e,repoName:t.repoName??null,fallbackId:t.fallbackId??null})}(e,t);if(this.manifestCache.has(r))return this.manifestCache.get(r)??null;const n=await async function(e,t={}){for(const r of Id){const n=(0,s.join)(e,r);let o;try{o=await(0,fo.readFile)(n,"utf-8")}catch{continue}const i=nh(o,t);if(i.success)return i.data}return null}(e,t);return this.manifestCache.set(r,n),n}async resolvePluginPath(e,t){const r=await this.readManifest(e);if(!r)return null;const n=r.plugins.find((e=>e.name===t.toLowerCase()));if(!n)return null;const o=sh(n.source,r.metadata?.pluginRoot);return o&&ih(o)?o:null}async discoverPlugins(e){const t=await this.readManifest(e);return t?function(e){const t=[],r=function(e,t){const r=[];for(const n of e){const e=n.source;if("string"!=typeof e)switch(e.source){case"github":r.push({entry:n,kind:"external-github",externalUrl:`https://github.com/${e.repo}.git`,externalRef:e.ref,externalSha:e.sha,effectiveRef:e.sha??e.ref});break;case"url":r.push({entry:n,kind:"external-url",externalUrl:e.url,externalRef:e.ref,externalSha:e.sha,effectiveRef:e.sha??e.ref});break;case"git-subdir":r.push({entry:n,kind:"external-git-subdir",externalUrl:e.url,externalRef:e.ref,externalSha:e.sha,effectiveRef:e.sha??e.ref,subdirPath:e.path})}else{const o=sh(e,t);null!==o?r.push({entry:n,kind:"local",localPath:o}):r.push({entry:n,kind:"unresolvable",rawSource:e})}}return r}(e.plugins,e.metadata?.pluginRoot);for(const e of r){const{name:r,displayName:n,description:o,version:s}=e.entry,i={name:r,displayName:n,description:o,version:s};switch(e.kind){case"local":ih(e.localPath)&&t.push({...i,sourceType:"local",gitPath:e.localPath});break;case"external-github":t.push({...i,sourceType:"github",gitUrl:e.externalUrl,gitRef:e.externalRef,sha:e.externalSha});break;case"external-url":t.push({...i,sourceType:"url",gitUrl:e.externalUrl,gitRef:e.externalRef,sha:e.externalSha});break;case"external-git-subdir":t.push({...i,sourceType:"git-subdir",gitUrl:e.externalUrl,gitRef:e.externalRef,sha:e.externalSha,subdirPath:e.subdirPath})}}return t}(t):[]}}lL.STALE_STAGING_THRESHOLD_MS=3e5,lL.STAGING_HEARTBEAT_INTERVAL_MS=6e4;const uL=(0,Fs.debuglog)("cursor-plugins");function dL(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function hL(e){return dL(e)?e:void 0}function pL(e){const t=e.name?.trim();return void 0!==t&&t.length>0?t:e.pluginId}function fL(e,t){return void 0!==e?.marketplace?e.marketplace:void 0!==e?.marketplaceId?(t??[]).find((t=>void 0!==t.id&&String(t.id)===String(e.marketplaceId))):void 0}function mL(e,t){const r=t?.distributionGitUrl?.trim();return r?t?.gitUrl&&!xL(e,t.gitUrl)?e:r:e}function gL(e){return e?.distributionGitUrl?.trim()||e?.gitUrl}function wL(e,t){if(e.pinnedGitRef)return e.pinnedGitRef;if(e.plugin?.gitRef)return e.plugin.gitRef;const r=fL(e.plugin,t),n=e.plugin?.gitUrl,o=r?.gitUrl;return n&&o&&n!==o||!r?.gitRef?"main":r.gitRef}const yL="backend-git://";function vL(e,t,r){const n=r?`#${encodeURIComponent(r)}`:"";return`${yL}${encodeURIComponent(e)}@${encodeURIComponent(t)}${n}`}function bL(e){if(!e.startsWith(yL))return null;const t=e.slice(14),r=t.indexOf("#"),n=r>=0?t.slice(0,r):t,o=r>=0?t.slice(r+1):void 0,s=n.lastIndexOf("@");return s<0?null:{gitUrl:decodeURIComponent(n.slice(0,s)),ref:decodeURIComponent(n.slice(s+1)),gitPath:o?decodeURIComponent(o):void 0}}const SL="backend-release://";function kL(e){const t=e.tag?`@${encodeURIComponent(e.tag)}`:"";return`${SL}${encodeURIComponent(e.repo)}#${encodeURIComponent(e.asset)}${t}`}function _L(e){if(!e.startsWith(SL))return null;const t=e.slice(18),r=t.indexOf("#");if(r<0)return null;const n=decodeURIComponent(t.slice(0,r)),o=t.slice(r+1),s=o.lastIndexOf("@");return{repo:n,asset:s>=0?decodeURIComponent(o.slice(0,s)):decodeURIComponent(o),tag:s>=0?decodeURIComponent(o.slice(s+1)):void 0}}const CL=/^[0-9a-f]{7,40}$/i;function EL(e){let t;try{t=aL(e)}catch{return null}return`${t.host}\0${t.pathSegments.join("\0")}`}function xL(e,t){if(e.trim()===t.trim())return!0;const r=EL(e),n=EL(t);return null!==r&&r===n}const PL=104857600;async function IL(e,t,r,n,i,a){const c=await async function(e){const{repo:t,asset:r,tag:n}=e,{apiBase:o,ownerRepo:s,host:i}=function(e){const t=e.split("/"),r=t[0],n=t[1],o=t[2];if(3===t.length&&void 0!==r&&void 0!==n&&void 0!==o)return{apiBase:`https://${r}/api/v3`,ownerRepo:`${n}/${o}`,host:r};if(2===t.length)return{apiBase:"https://api.github.com",ownerRepo:e,host:"github.com"};throw new Error(`Invalid release repo format: ${e}`)}(t),a="github.com"===i&&void 0!==e.githubToken&&e.githubToken.length>0?{Authorization:`token ${e.githubToken}`}:{},c=n?`${o}/repos/${s}/releases/tags/${encodeURIComponent(n)}`:`${o}/repos/${s}/releases/latest`,l=await fetch(c,{headers:{Accept:"application/vnd.github.v3+json","User-Agent":"CursorPluginInstaller",...a}});if(!l.ok)throw new Error(`Failed to fetch release from ${c}: ${l.status} ${l.statusText}`);const u=await l.json();if(!(dL(d=u)&&Array.isArray(d.assets)&&d.assets.every((e=>dL(e)&&"string"==typeof e.name&&"string"==typeof e.browser_download_url&&"number"==typeof e.size))))throw new Error(`Release payload from ${c} did not include assets`);var d;const h=u,p=h.assets.find((e=>e.name===r));if(!p){const e=h.assets.map((e=>e.name)).join(", ");throw new Error(`Release asset "${r}" not found. Available assets: ${e}`)}if(p.size>PL)throw new Error(`Release asset "${r}" exceeds maximum size of 104857600 bytes (actual: ${p.size})`);const f=new URL(p.browser_download_url);if("https:"!==f.protocol||!RL(f.hostname,i))throw new Error(`Refusing to download release asset from untrusted host: ${f.hostname}`);const m=await fetch(p.browser_download_url,{headers:{"User-Agent":"CursorPluginInstaller",Accept:"application/octet-stream",...a}});if(!m.ok)throw new Error(`Failed to download release asset: ${m.status} ${m.statusText}`);if(m.url){const e=new URL(m.url);if("https:"!==e.protocol||!RL(e.hostname,i))throw new Error(`Refusing to download release asset: redirected to untrusted host: ${e.hostname}`)}const g=Buffer.from(await m.arrayBuffer());if(g.byteLength>PL)throw new Error(`Release asset "${r}" actual download size exceeds maximum of 104857600 bytes (actual: ${g.byteLength})`);if(e.expectedSha256){const t=(0,lo.createHash)("sha256").update(g).digest("hex");if(t!==e.expectedSha256)throw new Error(`Release asset "${r}" integrity check failed: expected SHA-256 ${e.expectedSha256}, got ${t}`)}return g}({repo:e,asset:t,tag:r,expectedSha256:i,githubToken:a}),l=c.byteLength;await(0,fo.mkdir)(n,{recursive:!0});const u=await(0,fo.mkdtemp)((0,s.join)((0,o.tmpdir)(),"release-asset-")),d=(0,s.join)(u,"asset.tar.gz"),h=(0,s.join)(u,"extracted");try{await(0,fo.writeFile)(d,c),await(0,fo.mkdir)(h,{recursive:!0});let e=0,t=0;await Kh.x({file:d,cwd:h,onReadEntry:r=>{if(t++,t>5e4)throw new Error("Release archive contains too many files (>50000).");if(e+=r.size,e>524288e3)throw new Error("Release archive uncompressed size exceeds maximum of 524288000 bytes.");if(l>0&&e/l>100)throw new Error("Release archive has suspicious compression ratio (>100x).")}});const r=await(0,fo.readdir)(h,{withFileTypes:!0}),o=r.filter((e=>e.isDirectory())),i=r.filter((e=>e.isFile()));let a=h;const u=o[0];if(1===o.length&&0===i.length&&void 0!==u){const e=(0,s.join)(h,u.name);(await(0,fo.readdir)(e)).some((e=>Pd.includes(e)))&&(a=e)}const p=await(0,fo.readdir)(a);await Promise.all(p.map((e=>(0,fo.cp)((0,s.join)(a,e),(0,s.join)(n,e),{recursive:!0,verbatimSymlinks:!0}))))}finally{await(0,fo.rm)(u,{recursive:!0,force:!0}).catch((()=>{}))}}function RL(e,t){return!(e!==t&&!e.endsWith(".githubusercontent.com"))||("github.com"===t?"github.com"===e:e.endsWith(`.${t}`))}class TL{constructor(e,t,r,n,o){this.getEffectiveUserPlugins=e;const s="string"==typeof t||void 0===t?{marketplaceCacheRoot:t,pluginLogger:r,marketplaceCacheOptions:n,listOptions:o}:t,i=s.marketplaceCacheOptions??n;this.pluginLogger=s.pluginLogger??r??ph,this.extraGitConfig=s.extraGitConfig,this.awaitAuthReady=s.awaitAuthReady,this.githubToken=s.githubToken,this.sparsePluginClones=s.sparsePluginClones??!1,this.marketplaceCache=s.marketplaceCacheRoot?new lL(s.marketplaceCacheRoot,{...i,extraGitConfig:i?.extraGitConfig??s.extraGitConfig,sparsePluginClones:this.sparsePluginClones}):void 0;const a=s.listOptions??o;this.allowedMarketplaceNames=a?.allowedMarketplaceNames?new Set(a.allowedMarketplaceNames):void 0,this.enableInlinePlugins=a?.enableInlinePlugins??!1}isMarketplaceAllowed(e){return void 0===this.allowedMarketplaceNames||void 0!==e?.name&&this.allowedMarketplaceNames.has(e.name)}async listEnabledPlugins(e,t){const r=await this.getEffectiveUserPlugins(),n=r.plugins??[],o=r.marketplaces??[],s=[],i=[],a=new Map,c=async(e,t)=>{const r=`${e}\0${t}`;let n=a.get(r);if(!n){const o=yN(this.extraGitConfig),s=this.sparsePluginClones?3e4:void 0,i=e.startsWith("git@")||e.startsWith("ssh://")?null:GN(e),c=async(e,r)=>{const n={};return r&&(n.sshBatchMode=!0),void 0!==o&&(n.extraGitConfig=o),void 0!==s&&(n.timeoutMs=s),(Object.keys(n).length>0?await _N(e,t,n):await _N(e,t)).fullSha};if(null!==i)try{n=await c(i,!0)}catch(t){if(this.sparsePluginClones&&sL(t))throw t;n=await c(e,!1)}else n=await c(e,!1);a.set(r,n)}return n},l=async e=>{const{preferredGitUrl:t,sourceGitUrl:r,gitRef:n,pluginId:o}=e;if(t!==r){void 0!==this.awaitAuthReady&&await this.awaitAuthReady();const e=`${t}\0${n}`,s=!a.has(e);let i;s&&this.pluginLogger.increment("marketplace.origin_distribution.fetch",1);try{i={sha:await c(t,n),gitUrl:t}}catch(e){s&&this.pluginLogger.increment("marketplace.origin_distribution.fetch.error",1),this.pluginLogger.captureException(e,{error_type:"distribution_url_fallback"}),this.pluginLogger.log("warn",`Distribution mirror ${t}@${n} unavailable (not synced yet or unreachable); falling back to source ${r}`,{pluginId:o,preferredGitUrl:t,sourceGitUrl:r,gitRef:n,error:String(e)})}if(void 0!==i){if(s)try{this.pluginLogger.log("info",`Resolved plugin ${o} from Origin distribution mirror ${t}@${n}`,{pluginId:o,preferredGitUrl:t,gitRef:n})}catch{}return i}}return{sha:await c(r,n),gitUrl:r}};for(const e of n){if(!e.isEnabled||!e.plugin?.name)continue;const t=e.plugin,r=fL(t,o);if(!this.isMarketplaceAllowed(r)){this.pluginLogger.log("info",`Skipping plugin ${t.name} because marketplace ${r?.name??"<none>"} is not allowed`,{pluginId:t.name,marketplaceName:r?.name,allowedMarketplaceNames:void 0!==this.allowedMarketplaceNames?Array.from(this.allowedMarketplaceNames):void 0});continue}const n=pL({name:t.name,pluginId:void 0!==t.id?String(t.id):t.name??""}),a=n;if(!t.gitUrl){if(!this.enableInlinePlugins){this.pluginLogger.log("info",`Skipping plugin ${n} without gitUrl (enableInlinePlugins=false)`,{pluginId:a});continue}const o=e.inlineContentJson;if(!o){this.pluginLogger.log("info",`Skipping DB-inline plugin ${n}: no inline content provided`,{pluginId:a});continue}const i=(0,lo.createHash)("sha256").update(`${t.id??"0"}:${t.updatedAt??"0"}`).digest("hex").slice(0,40),c=r?.name?{id:void 0!==r.id?`${r.name}-${r.id}`:`${r.name}-inline`,name:r.name}:void 0;this.pluginLogger.log("info",`BackendMarketplaceClient: Adding DB-inline plugin: ${a}`,{pluginId:a,marketplaceId:c?.id??"unknown",version:i}),s.push({pluginId:a,pluginDbId:void 0!==t.id?String(t.id):void 0,configuredVariables:hL(e.configuredVariables),isTeamRequired:e.isTeamRequired,name:n,version:i,downloadUrl:`inline://${t.id??a}`,marketplaceDbId:void 0!==r?.id?String(r.id):void 0,marketplace:c,inlineContentJson:o});continue}const c=t.gitUrl,u=mL(c,r),d=wL(e,o),h=gN(t,d),p=r?.gitRef??d;let f,m,g=u;try{if(void 0!==h)f=`release/${h.releaseTag}`;else{const e=await l({preferredGitUrl:u,sourceGitUrl:c,gitRef:d,pluginId:a});f=e.sha,g=e.gitUrl}}catch(e){this.pluginLogger.captureException(e,{error_type:"resolve_version_sha"}),this.pluginLogger.log("error",`Failed to resolve version for plugin ${n}@${d}, skipping plugin`,{pluginId:a,ref:d,error:String(e)});const o=e instanceof Error?e.message:String(e);i.push({pluginName:n,pluginId:a,pluginDbId:void 0!==t.id?String(t.id):void 0,marketplaceName:r?.name,errorMessage:o,errorType:/timed?\s*out/i.test(o)?"timeout":"clone"});continue}m=void 0!==h?kL({repo:h.releaseRepo,asset:h.releaseAsset,tag:h.releaseTag}):vL(g,d,t.gitPath??void 0);const w=gL(r);let y=w,v=r?.gitUrl,b=p;if(r?.gitUrl&&w){const e=xL(c,r.gitUrl),t=e?g:w,o=e?c:r.gitUrl,s=e?d:p;v=o;try{const e=await l({preferredGitUrl:t,sourceGitUrl:o,gitRef:s,pluginId:a});b=e.sha,y=e.gitUrl}catch(e){this.pluginLogger.captureException(e,{error_type:"resolve_marketplace_cache_ref"}),this.pluginLogger.log("warn",`Failed to resolve marketplace cache ref for plugin ${n} from ${t}@${s}, falling back to raw ref`,{pluginId:a,cacheRepoUrl:t,cacheRef:s,error:String(e)}),y=o}}const S=r?.name?{id:void 0!==r.id?`${r.name}-${r.id}`:`${r.name}-${encodeURIComponent(r.gitUrl??"project")}`,name:r.name,...y&&{gitUrl:y,gitRef:b}}:void 0,k=void 0!==h||g===c&&y===v?void 0:{downloadUrl:vL(c,d,t.gitPath??void 0),marketplaceGitUrl:v};this.pluginLogger.log("info",`BackendMarketplaceClient: Adding enabled plugin: ${a} from ${b} at ${t.gitPath}`,{pluginId:a,marketplaceId:S?.id??"unknown",gitPath:t.gitPath??void 0,gitRef:b}),s.push({pluginId:a,pluginDbId:void 0!==t.id?String(t.id):void 0,configuredVariables:hL(e.configuredVariables),isTeamRequired:e.isTeamRequired,name:n,version:f,downloadUrl:m,marketplaceDbId:void 0!==r?.id?String(r.id):void 0,marketplace:S,gitPath:t.gitPath??void 0,isOriginBacked:void 0===h&&g!==c||void 0,originSourceFallback:k})}return{plugins:s,listFailures:i}}isDirectInstallSameFetch(e){const t=e.marketplace;if(!t?.gitUrl||!t.gitRef)return!1;const r=bL(e.downloadUrl);return!(!r||!xL(r.gitUrl,t.gitUrl)||r.ref!==t.gitRef&&e.version!==t.gitRef)}async installPlugin(e,t){if(e.inlineContentJson)await async function(e){const{targetDir:t,inlineContentJson:r,pluginName:n}=e,o=JSON.parse(r);await(0,fo.mkdir)(t,{recursive:!0});const i={};if(o.rules&&o.rules.length>0){const e=(0,s.join)(t,"rules");await(0,fo.mkdir)(e,{recursive:!0});const r=[];for(const t of o.rules){if(!t.content)continue;if(!1===t.isActive)continue;const n=`${Vh(t.name)}.md`,o=[];o.push(`description: ${JN(t.name)}`),t.globs&&t.globs.length>0&&o.push(`globs: ${JN(t.globs.join(", "))}`),o.push(`alwaysApply: ${!0===t.isRequired}`);const i=`---\n${o.join("\n")}\n---\n\n`;await(0,fo.writeFile)((0,s.join)(e,n),i+t.content,"utf-8"),r.push(`rules/${n}`)}r.length>0&&(i.rules=r)}if(o.commands&&o.commands.length>0){const e=(0,s.join)(t,"commands");await(0,fo.mkdir)(e,{recursive:!0});const r=[];for(const t of o.commands){if(!t.content)continue;if(!1===t.isActive)continue;const n=`${Vh(t.name)}.md`,o=t.description?`---\ndescription: ${JN(t.description)}\n---\n\n`:"";await(0,fo.writeFile)((0,s.join)(e,n),o+t.content,"utf-8"),r.push(`commands/${n}`)}r.length>0&&(i.commands=r)}if(o.hooks&&o.hooks.length>0){const e=(0,s.join)(t,"hooks");await(0,fo.mkdir)(e,{recursive:!0});const r={};for(const e of o.hooks){const t=e.hookStep;t&&!1!==e.isActive&&KN(e)&&(r[t]||(r[t]=[]),"prompt"===e.hookType?r[t].push({type:"prompt",prompt:e.promptContent??"",...e.promptModel?{model:e.promptModel}:{}}):r[t].push({type:"command",command:e.scriptContent??""}))}await(0,fo.writeFile)((0,s.join)(e,"hooks.json"),JSON.stringify({version:1,hooks:r},null,2),"utf-8")}if(o.mcpServers&&o.mcpServers.length>0){const e={};for(const t of o.mcpServers)t.config&&(e[t.name]=t.config);Object.keys(e).length>0&&await(0,fo.writeFile)((0,s.join)(t,".mcp.json"),JSON.stringify({mcpServers:e},null,2),"utf-8")}const a={name:n,...i},c=(0,s.join)(t,".cursor-plugin");await(0,fo.mkdir)(c,{recursive:!0}),await(0,fo.writeFile)((0,s.join)(c,"plugin.json"),JSON.stringify(a,null,2),"utf-8")}({targetDir:t,inlineContentJson:e.inlineContentJson,pluginName:e.name});else{e.isOriginBacked&&void 0!==this.awaitAuthReady&&await this.awaitAuthReady();try{return void await this.installFromEntryUrls(e,t)}catch(r){const n=function(e){const t=e.originSourceFallback;if(void 0===t)return;let r=e.marketplace;if(void 0!==r)if(void 0!==t.marketplaceGitUrl)r={...r,gitUrl:t.marketplaceGitUrl};else{const{gitUrl:e,gitRef:t,...n}=r;r=n}return{...e,downloadUrl:t.downloadUrl,marketplace:r,isOriginBacked:void 0,originSourceFallback:void 0}}(e);if(void 0===n)throw r;this.pluginLogger.captureException(r,{error_type:"install_plugin_from_origin_distribution"}),this.pluginLogger.log("warn",`Failed to install plugin ${e.name} from the Origin distribution mirror, falling back to the source repo`,{pluginId:e.pluginId,version:e.version,sourceDownloadUrl:n.downloadUrl,sourceMarketplaceGitUrl:n.marketplace?.gitUrl,error:String(r)}),this.pluginLogger.increment("marketplace.origin_distribution.install.source_fallback",1),await(0,fo.rm)(t,{recursive:!0,force:!0});try{await this.installFromEntryUrls(n,t)}catch(e){throw this.pluginLogger.increment("marketplace.origin_distribution.install.source_fallback.error",1),e}}}}async installFromEntryUrls(e,t){if(null===_L(e.downloadUrl))try{if(await this.tryInstallFromMarketplaceCache(e,t))return void this.emitOriginLoadIfApplicable(e)}catch(t){if(this.pluginLogger.captureException(t,{error_type:"install_plugin_from_marketplace_cache"}),this.sparsePluginClones&&this.isDirectInstallSameFetch(e)&&sL(t))throw this.pluginLogger.log("warn",`Failed to install plugin ${e.name} from marketplace cache; skipping direct install fallback because it would repeat the identical fetch`,{pluginId:e.pluginId,version:e.version,error:String(t)}),t;this.pluginLogger.log("warn",`Failed to install plugin ${e.name} from marketplace cache, falling back to direct install`,{pluginId:e.pluginId,version:e.version,error:String(t)})}await async function(e,t,r=ph,n,i){const a=i?.sparsePluginClones??!1,c=a?QN:void 0,l=_L(e.downloadUrl);if(l){if(e.gitPath){const r=await(0,fo.mkdtemp)((0,s.join)((0,o.tmpdir)(),"release-plugin-"));try{await IL(l.repo,l.asset,l.tag,r,i?.expectedReleaseAssetSha256,i?.githubToken);const n=hp(r,e.gitPath);await(0,fo.mkdir)(t,{recursive:!0}),await(0,fo.cp)(n,t,{recursive:!0,verbatimSymlinks:!0})}finally{await(0,fo.rm)(r,{recursive:!0,force:!0}).catch((()=>{}))}}else await IL(l.repo,l.asset,l.tag,t,i?.expectedReleaseAssetSha256,i?.githubToken);return}const u=bL(e.downloadUrl);if(!u)throw new Error(`Invalid download URL format for plugin ${e.pluginId}: ${e.downloadUrl}`);const d=await(0,fo.mkdtemp)((0,s.join)((0,o.tmpdir)(),"backend-plugin-"));try{let o;if(await async function(e,t,r,n=ph,o,s="all",i=!1){const a=performance.now(),c=CL.test(t),l="HEAD"===t.toUpperCase(),u={...o,"safe.directory":r},d=i?QN:void 0,h=i?YN:void 0,{sparse:p,sparseDirs:f}=await IN(s,i),m=p?["--filter=blob:none","--sparse"]:[],g=!!p||void 0,w=async e=>{p&&await TN(r,f,{extraGitConfig:u,timeoutMs:e,sshBatchMode:!0})},y=async(e,n)=>{let o;return l?(({stderr:o}=await vN(["clone","--depth","1",...m,e,r],{extraGitConfig:u,timeoutMs:d,sshBatchMode:n})),await w(d)):c?(await vN(["init"],{cwd:r,extraGitConfig:u,timeoutMs:h}),await vN(["remote","add","origin",e],{cwd:r,extraGitConfig:u,timeoutMs:h}),await w(h),({stderr:o}=await vN(["fetch","--depth","1",...p?["--filter=blob:none"]:[],"origin",t],{cwd:r,extraGitConfig:u,timeoutMs:d,sshBatchMode:n})),await vN(["checkout","FETCH_HEAD"],{cwd:r,extraGitConfig:u,timeoutMs:d,sshBatchMode:n})):(({stderr:o}=await vN(["clone","--depth","1","--branch",t,...m,e,r],{extraGitConfig:u,timeoutMs:d,sshBatchMode:n})),await w(d)),o},v=e.startsWith("git@")||e.startsWith("ssh://")?null:GN(e);let b;if(null!==v)try{b=await y(v,!0)}catch(t){if(i&&sL(t))throw t;await(0,fo.rm)(r,{recursive:!0,force:!0}),await(0,fo.mkdir)(r,{recursive:!0}),b=await y(e,g)}else b=await y(e,g);p&&RN(b)&&(n.log("warn",`shallowClone: server ignored --filter=blob:none for ${e}; sparse clone downloaded a full pack`),n.increment("backend_marketplace_client.shallow_clone.filter_ignored_by_server",1));const S=(performance.now()-a).toFixed(1);uL("shallowClone %s@%s completed in %sms",e,t,S),n.log("info",`shallowClone ${e}@${t} completed in ${S}ms (${p?"sparse":"full"})`)}(u.gitUrl,u.ref,d,r,n,u.gitPath?PN([u.gitPath]):[],a),u.gitPath)o=hp(d,u.gitPath);else{const t=await async function(e,t){for(const r of Id){const n=(0,s.join)(e,r);let o;try{o=await(0,fo.readFile)(n,"utf-8")}catch{continue}const i=nh(o);if(!i.success)return{type:"manifest-unresolved",reason:`Invalid marketplace manifest at ${r}: ${i.error}`};const a=i.data,c=a.plugins.find((e=>e.name===t.toLowerCase()));if(!c)return{type:"manifest-unresolved",reason:`Plugin ${JSON.stringify(t)} not found in ${r}`};if("string"!=typeof c.source&&"git-subdir"===c.source.source)return{type:"manifest-unresolved",reason:`Plugin ${JSON.stringify(t)} uses unsupported git-subdir source`};const l=sh(c.source,a.metadata?.pluginRoot);return l&&ih(l)?{type:"resolved",gitPath:l}:{type:"manifest-unresolved",reason:`Plugin ${JSON.stringify(t)} has unresolved or unsafe source path`}}return{type:"no-manifest"}}(d,e.name);if("resolved"===t.type)await $N(d,PN([t.gitPath]),{extraGitConfig:n,timeoutMs:c}),o=hp(d,t.gitPath);else{if("manifest-unresolved"===t.type)throw new Error(`Unable to install plugin ${JSON.stringify(e.name)} without gitPath: ${t.reason}`);await $N(d,"all",{extraGitConfig:n,timeoutMs:c}),o=d}}await(0,fo.mkdir)(t,{recursive:!0}),await(0,fo.cp)(o,t,{recursive:!0,verbatimSymlinks:!0})}finally{await(0,fo.rm)(d,{recursive:!0,force:!0}).catch((()=>{}))}}(e,t,this.pluginLogger,yN(this.extraGitConfig),{githubToken:this.githubToken,sparsePluginClones:this.sparsePluginClones}),this.emitOriginLoadIfApplicable(e)}emitOriginLoadIfApplicable(e){if(e.isOriginBacked)try{this.pluginLogger.increment("marketplace.origin_distribution.load",1),this.pluginLogger.log("info",`Loaded plugin ${e.pluginId} from Origin distribution (fetch complete)`,{pluginId:e.pluginId})}catch{}}async prewarmMarketplaceClones(e){const t=this.marketplaceCache;if(!t)return;const r=new Map;for(const t of e){const e=t.marketplace;if(!e?.gitUrl)continue;const n=e.gitRef??"main",o=`${e.id}\0${e.gitUrl}\0${n}`;let s=r.get(o);void 0===s&&(s={marketplaceId:e.id,gitUrl:e.gitUrl,gitRef:n,gitPaths:[]},r.set(o,s)),t.gitPath&&s.gitPaths.push(t.gitPath)}for(const e of r.values()){const r=PN(e.gitPaths),n=performance.now();try{await t.ensureCloned(e.marketplaceId,e.gitUrl,e.gitRef,this.pluginLogger,{materialize:r}),this.pluginLogger.log("info",`Prewarmed marketplace clone ${e.gitUrl}@${e.gitRef} for ${e.gitPaths.length} plugin directories`,{marketplaceId:e.marketplaceId,gitUrl:e.gitUrl,gitRef:e.gitRef,requestedDirs:e.gitPaths.length,materialize:"all"===r?"all":r.length}),this.pluginLogger.increment("marketplace_cache_manager.prewarm.success",1,{materialize:"all"===r?"all":"dirs"})}catch(t){this.pluginLogger.captureException(t,{error_type:"prewarm_marketplace_clone"}),this.pluginLogger.log("warn",`Failed to prewarm marketplace clone ${e.gitUrl}@${e.gitRef}; falling back to per-plugin materialization`,{marketplaceId:e.marketplaceId,gitUrl:e.gitUrl,gitRef:e.gitRef,error:String(t)}),this.pluginLogger.increment("marketplace_cache_manager.prewarm.error",1)}this.pluginLogger.distribution("marketplace_cache_manager.prewarm.duration",performance.now()-n)}}async tryInstallFromMarketplaceCache(e,t){const r=this.marketplaceCache,n=e.marketplace;if(!r||!n||!n.gitUrl)return this.pluginLogger.log("info","No marketplace cache or marketplace metadata, skipping cache check",{pluginId:e.pluginId,name:e.name,version:e.version,marketplaceId:e.marketplace?.id}),!1;const o=await r.ensureCloned(n.id,n.gitUrl,n.gitRef??"main",this.pluginLogger,{materialize:e.gitPath?PN([e.gitPath]):[]}),s=e.gitPath??await r.resolvePluginPath(o,e.name);if(!s)return this.pluginLogger.log("info","No git path found for plugin, skipping cache check",{pluginId:e.pluginId,name:e.name,version:e.version,marketplaceId:e.marketplace?.id}),!1;void 0===e.gitPath&&await r.ensureMaterialized(o,PN([s]),this.pluginLogger);const i=r.getPluginDir(o,s);return await r.copyPluginToDir(i,t),!0}async discoverMarketplacePlugins(e,t,r){const n=this.marketplaceCache;if(!n)throw new Error("discoverMarketplacePlugins requires a MarketplaceCacheManager (marketplaceCacheRoot)");const o=await n.ensureCloned(e,t,r,this.pluginLogger,{materialize:[]});return n.discoverPlugins(o)}}function AL(e,t,r,n,o){return new TL(e,t,r,n,o)}function $L(e){const t=e.trim();if(!t)return!1;if(t.startsWith("git@"))return/^git@[a-zA-Z0-9.-]+:[a-zA-Z0-9._~\-/]+(?:\.git)?$/.test(t);try{const e=new URL(t);return"https:"===e.protocol&&""===e.username&&""===e.password&&""===e.search&&""===e.hash}catch{return!1}}class ML extends Error{constructor(e){super(e),this.name="SettingsParseError"}}function DL(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function OL(e){return 65279===e.charCodeAt(0)?e.slice(1):e}async function FL(e){try{return OL(await(0,fo.readFile)(function(e){return(0,s.join)(e,".cursor","settings.json")}(e),"utf-8"))}catch(e){if(function(e){return e instanceof Error&&"code"in e}(e)&&("ENOENT"===e.code||"ENOTDIR"===e.code))return;throw e}}async function NL(e){const t=await FL(e);return void 0===t?[]:function(e){const t=function(e){const t=OL(e);if(0===t.trim().length)return{};const r=[],n=(0,ah.qg)(t,r,{allowTrailingComma:!0});if(r.length>0){const e=r.slice(0,3).map((e=>`${(0,ah._n)(e.error)} at offset ${e.offset}`)).join("; ");throw new ML(`.cursor/settings.json contains syntax errors: ${e}`)}if(!DL(n))return{};const o=n.plugins;if(void 0===o)return{};if(!DL(o))return{};const s={};for(const[e,t]of Object.entries(o))DL(t)&&(s[e]=t);return{plugins:s}}(e);return t.plugins?Object.entries(t.plugins).filter((([,e])=>!0===e.enabled)).filter((([,e])=>!e.gitUrl||$L(e.gitUrl))).map((([e,t])=>({key:e,entry:t}))):[]}(t)}function LL(e){const t=e.indexOf("/");return-1===t?{name:e}:{name:e.slice(t+1),marketplaceName:e.slice(0,t)}}function jL(e={}){const t=e.userHomeDirectory??(0,o.homedir)(),r=e.importThirdPartyPlugins??!1,n=e.pluginLogger??{log(e,t,r){switch(e){case"warn":mM.Jz.warn("[local-plugins-bootstrap]",t,r??{});break;case"error":mM.Jz.error("[local-plugins-bootstrap]",t,r??{})}},increment(){},distribution(){},captureException(e,t){mM.Jz.error("[local-plugins-bootstrap] Unexpected plugin exception:",e,t??{})}},i=UL(e.marketplaceOptions),a=void 0!==e.dashboardTransport,c=e.loadCursorFirstParty??(i||a);return{async loadPluginBootstrapOutputs(o){const i=(a=o.workspaceState).projectRoot??a.workspaceRoots[0]??a.workingDirectory;var a;const{discoveredEntries:l,failures:u}=await async function(e){if(void 0===e)return{discoveredEntries:[],failures:[]};try{return{discoveredEntries:(await NL(e)).map((({key:t,entry:r})=>({source:"project-settings",workspacePath:e,key:t,entry:r}))),failures:[]}}catch(e){return{discoveredEntries:[],failures:[{stage:"discovery",source:"project-settings",message:e instanceof Error?`Failed to read project plugin settings: ${e.message}`:`Failed to read project plugin settings: ${String(e)}`,detail:e}]}}}(i),d=e.marketplaceOptions??(e.dashboardTransport?function(e){const t=(0,s.join)(e.userHomeDirectory,".cursor","plugins","marketplaces"),r=(0,ye.createClient)(iN.I,e.dashboardTransport),n=AL((async()=>{try{return await r.getEffectiveUserPlugins(new H$.EwF({}))}catch{return{plugins:[]}}}),t,void 0,void 0,{allowedMarketplaceNames:["cursor-public"]}),o=e.workspacePath,i=AL((async()=>{if(void 0===o)return{plugins:[]};try{const e=await NL(o);if(0===e.length)return{plugins:[]};const t=e.filter((e=>e.entry.gitUrl)),n=e.filter((e=>!e.entry.gitUrl)),s=t.filter((({entry:e})=>{const t=e.gitUrl;return!t||$L(t)})).map((({key:e,entry:t})=>{const r=LL(e),n=t.gitUrl;return{plugin:{name:r.name,gitUrl:n,gitRef:t.gitRef,gitPath:t.gitPath,marketplace:{name:r.marketplaceName,gitUrl:n,gitRef:t.gitRef}},isEnabled:!0}}));let i=[];if(n.length>0)try{const e=n.map((e=>{const t=LL(e.key);return new H$.vwy({name:t.name,marketplaceName:t.marketplaceName})})),t=await r.resolvePluginsByRef(new H$.WvV({refs:e}));i=t.plugins?.map((e=>({plugin:e,isEnabled:!0})))??[]}catch{}return{plugins:[...s,...i]}}catch{return{plugins:[]}}}),t,void 0,void 0,{allowedMarketplaceNames:["cursor-public"]});return[{client:n,userId:"",cacheManager:new Yh(e.userHomeDirectory),pruneOldVersions:!0},{client:i,userId:"",cacheManager:new Yh(e.userHomeDirectory),pruneOldVersions:!0}]}({dashboardTransport:e.dashboardTransport,workspacePath:i,userHomeDirectory:t}):void 0),h=UL(d),p=new W$(void 0!==i?[i]:[],t,(()=>({importThirdPartyPlugins:r,loadCursorFirstParty:c})),d,n);let f=[];const m=[...u];try{f=await p.getAllEnabledPlugins()}catch(e){m.push({stage:"resolution",source:"plugin-loader",message:e instanceof Error?`Failed to load plugins: ${e.message}`:`Failed to load plugins: ${String(e)}`,detail:e})}l.length>0&&!h&&m.push({stage:"resolution",source:"plugin-loader",message:"Project plugin entries were discovered, but no marketplace-backed project plugin source was configured. Those entries remain available through discoveredEntries only.",detail:{workspacePath:i,discoveredEntryCount:l.length}});const g={kind:MM,discoveredEntries:l,loadedPlugins:f,loadFailures:p.getLoadFailures(),bootstrapFailures:m,pluginsService:p,async dispose(){}};for(const e of m)mM.Jz.warn("[local-plugins-bootstrap] Plugin bootstrap failure:",{workspacePath:i,stage:e.stage,source:e.source,message:e.message,detail:e.detail});for(const e of g.loadFailures)mM.Jz.warn("[local-plugins-bootstrap] Plugin load failure:",{workspacePath:i,pluginName:e.pluginName,pluginId:e.pluginId,marketplaceName:e.marketplaceName,errorType:e.errorType,errorMessage:e.errorMessage});return[g]}}}function UL(e){return void 0!==e&&(!Array.isArray(e)||e.length>0)}class BL{async getAllCursorRules(e){return[]}reload(e){}dispose(){}onDidChangeRules(e){return()=>{}}}const WL=["projectFolder","terminalsFolder","agentSharedNotesFolder","agentConversationNotesFolder","agentTranscriptsFolder","processWorkingDirectory","artifactsFolder"];function HL(e){if(e.length<=1)return e;let t=e.length;for(;t>1&&("/"===(r=e[t-1])||"\\"===r)&&(3!==t||":"!==e[1]);)t-=1;var r;return e.slice(0,t)}function qL(e){const t=HL(e).replaceAll("\\","/");return/^[A-Za-z]:\/$/.test(t)?t.slice(0,-1):t}function zL(e){const t=HL(e.reportedWorkspacePath);if(""===e.suffix)return t;const r=t.replaceAll("\\","/"),n="/"===r?e.suffix:`${r}${e.suffix}`;return t.includes("\\")?n.replaceAll("/","\\"):n}function GL(e){const t=qL(e.value),r=e.roots.filter((e=>e.host.length>0)).sort(((e,t)=>qL(t.host).length-qL(e.host).length));for(const e of r){const r=qL(e.host);if(t===r)return zL({reportedWorkspacePath:e.reported,suffix:""});const n="/"===r?"/":`${r}/`;if(t.startsWith(n)){const n="/"===r?t:t.slice(r.length);return zL({reportedWorkspacePath:e.reported,suffix:n})}}}const VL={powershellUtf8Console:!1,powershellUtf8ChildEnv:!1};class KL extends a${constructor(e,t){super(e),this.sessionMcpLease=t}async dispose(){try{await super.dispose()}finally{await aN(this.sessionMcpLease)}}}function JL(e){const t=new dw;return{async createResources(r){const n=e.createSessionDependencies?.(r)??{pendingDecisionStore:e.pendingDecisionStore,fileChangeTracker:e.fileChangeTracker,permissionsService:e.permissionsService};if(!n.pendingDecisionStore||!n.fileChangeTracker||!n.permissionsService)throw new Error("Local resource provider factory requires either shared dependencies or a per-session dependency factory.");const o=r.workspaceServices.cursorRulesService??new BL,s=r.workspaceServices.subagentsService??new dm,i=r.workspaceServices.mcpLease??new pP,a=!0===r.options.excludeProjectMcp,c=void 0!==r.options.mcpServersOverride||a?void 0!==e.createSessionMcpLease?await e.createSessionMcpLease(r,r.options.mcpServersOverride):a?new pP:void 0:void 0,l=(u=c??i,0===(d=r.options.extraMcpTools??[]).length?u:"onDidChange"in(h=u)&&"function"==typeof h.onDidChange?new Mg(u,d):new $g(u,d));var u,d,h;try{const i=await async function(e,t){return void 0===e?{}:"function"==typeof e?await e({sessionId:t.sessionState.sessionId,metadata:t.metadata}):e}(r.options.localResourceProviderOptions,r),a=await async function(e){if(void 0===e)return VL;try{const t=await e();return{powershellUtf8Console:t.powershellUtf8Console,powershellUtf8ChildEnv:t.powershellUtf8ChildEnv}}catch{return VL}}(e.getPowershellUtf8Options),u={pendingDecisionStore:n.pendingDecisionStore,fileChangeTracker:n.fileChangeTracker,gitExecutor:t,ignoreService:e.ignoreService,grepProvider:e.grepProvider,permissionsService:n.permissionsService,workspacePaths:e.workspacePaths,diagnosticsProvider:e.diagnosticsProvider,mcpLease:l,mcpStateAccessor:e.createMcpStateAccessor?.(l),cursorRulesService:o,subagentsService:s,repositoryProvider:e.repositoryProvider,projectDir:e.projectDir,shellManager:e.shellManager,_defaultSandboxPolicy:e.defaultSandboxPolicy??{type:"insecure_none"},_defaultSandboxPolicySources:e.defaultSandboxPolicySources,getSandboxEnabled:e.getSandboxEnabled,getSandboxSupported:e.getSandboxSupported,getNetworkAllowlistInfo:e.getNetworkAllowlistInfo,getSmartModeClassifierAutoModeEnabled:e.getSmartModeClassifierAutoModeEnabled,devForceNextSmartModeClassifierBlockToken:e.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:e.getMockPromptTime,mcpFileOutputThresholdBytes:e.mcpFileOutputThresholdBytes,mcpMetaToolEnabled:e.mcpMetaToolEnabled,getAgentSkills:r.workspaceServices.getAgentSkills,powershellUtf8Console:a.powershellUtf8Console,powershellUtf8ChildEnv:a.powershellUtf8ChildEnv,...i},d=void 0===c?new a$(u):new KL(u,c);return void 0===r.options.reportedWorkspacePath&&void 0===r.options.reportedProjectFolder||function(e,t){const r=e.get(Ar);if(void 0===r)return;const{reportedWorkspacePath:n,reportedProjectFolder:o}=t,s=void 0===n?[]:t.workspacePaths.map((e=>({host:e,reported:n}))),i=o??n;void 0!==i&&s.push({host:t.projectDir,reported:i}),e.register(Ar,{execute:async(e,t,o)=>function(e,t){if("success"!==e.result.case||void 0===e.result.value.requestContext?.env)return e;const r=e.clone();if("success"!==r.result.case)return e;const n=r.result.value.requestContext?.env;if(void 0===n)return r;const{roots:o,reportedWorkspacePath:s}=t;n.workspacePaths=n.workspacePaths.map((e=>GL({value:e,roots:o})??e));for(const e of WL){const t=n[e];if(void 0===t||""===t)continue;const r=GL({value:t,roots:o});n[e]="processWorkingDirectory"===e&&void 0!==s?r??HL(s):r??t}return r}(await r.execute(e,t,o),{roots:s,reportedWorkspacePath:n})})}(d,{reportedWorkspacePath:r.options.reportedWorkspacePath,reportedProjectFolder:r.options.reportedProjectFolder,workspacePaths:u.workspacePaths,projectDir:u.projectDir}),d}catch(e){throw await aN(c),e}}}}const ZL=["cursorRulesService","getAgentSkills","subagentsService"],XL=new WeakSet;function QL(e){("object"==typeof e&&null!==e||"function"==typeof e)&&XL.add(e)}function YL(e){return("object"==typeof e&&null!==e||"function"==typeof e)&&XL.has(e)}function ej(e,t){const r=Object.keys(t).filter((e=>!ZL.includes(e)));if(r.length>0)throw new Error(`Workspace service contributors may only provide ${ZL.join(", ")}. Received unsupported service keys: ${r.join(", ")}.`);for(const r of ZL)Object.hasOwn(t,r)&&(e[r]=t[r])}async function tj(e,t,r){const n={config:void 0,plugins:[],pluginBootstrapOutputs:[],cursorRulesService:void 0,getAgentSkills:void 0,subagentsService:void 0,mcpLease:void 0,hooksRuntime:void 0};try{n.config=e.config?await e.config.loadConfig(t):void 0,n.plugins=e.plugins?await e.plugins.loadPlugins(t):[];const o=()=>({workspaceState:t,policy:r,services:n});n.pluginBootstrapOutputs=e.pluginBootstrap?await e.pluginBootstrap.loadPluginBootstrapOutputs(o()):n.pluginBootstrapOutputs,n.mcpLease=e.mcp?await e.mcp.createLease(o()):void 0,n.hooksRuntime=e.hooks?await e.hooks.createHooksRuntime(o()):void 0,e.localExtensibility?.prepareLocalExtensibility&&await e.localExtensibility.prepareLocalExtensibility(o());const s=e.localExtensibility?await e.localExtensibility.loadLocalExtensibility(o()):void 0;void 0!==s&&(QL(s.cursorRulesService),QL(s.subagentsService),Object.assign(n,s));for(const t of e.workspaceServicesContributors??[]){const e=await t.contributeServices(o());void 0!==e&&ej(n,e)}return n}catch(t){try{await rj(n,{disposeLocalExtensibility:void 0===e.localExtensibility?void 0:()=>e.localExtensibility?.disposeLocalExtensibility?.()})}catch(e){throw function(e,t){return new AggregateError([t],"Workspace service loading failed and resource cleanup also failed.",{cause:e})}(t,e)}throw t}}async function rj(e,t){const r=t?.preserveSharedContributorsFrom;let n;const o=async e=>{try{await aN(e)}catch(e){n??=e}};if(e.subagentsService===r?.subagentsService||YL(e.subagentsService)||await o(e.subagentsService),e.cursorRulesService===r?.cursorRulesService||YL(e.cursorRulesService)||await o(e.cursorRulesService),t?.disposeLocalExtensibility)try{await t.disposeLocalExtensibility()}catch(e){n??=e}await o(e.hooksRuntime),await o(e.mcpLease);try{await async function(e){let t;for(let r=e.length-1;r>=0;r-=1)try{await aN(e[r])}catch(e){t??=e}if(void 0!==t)throw t}(e.pluginBootstrapOutputs)}catch(e){n??=e}if(void 0!==n)throw n}const nj=["project","user","team","mdm","plugins"],oj=new Set([...nj,"all"]);function sj(e){if(void 0===e||0===e.length)return aj([]);for(const t of e)if(!oj.has(t))throw new Error(`Unsupported setting source "${t}"`);if(e.includes("all")){if(e.length>1)throw new Error('settingSources cannot mix "all" with individual setting sources');return{...aj(nj),all:!0}}return aj(e.filter((e=>"all"!==e)))}function ij(e,t){return e[t]}function aj(e){const t=new Set(e);return{project:t.has("project"),user:t.has("user"),team:t.has("team"),mdm:t.has("mdm"),plugins:t.has("plugins"),all:!1}}const cj=Object.freeze({}),lj=Object.freeze({allowMcpServers:!0,allowPlugins:!0,allowBackgroundSessions:!0,requireMcpApproval:!1,maxParallelSessions:void 0,sandboxMode:void 0,metadata:cj});async function uj(e){const t=new Set;let r;for(let n=e.length-1;n>=0;n-=1){const o=e[n];if(!t.has(o)){t.add(o);try{await aN(o)}catch(e){r??=e}}}if(void 0!==r)throw r}async function dj(e={}){const t=function(e={}){return{workspace:e.workspace??hM,config:e.config,plugins:e.plugins,pluginBootstrap:e.pluginBootstrap,mcp:e.mcp,hooks:e.hooks,localExtensibility:e.localExtensibility,resourceFactory:e.resourceFactory,resourceWrappers:e.resourceWrappers,workspaceServicesContributors:e.workspaceServicesContributors,lifecycle:e.lifecycle}}(e.adapters),r=await t.workspace.resolveWorkspaceState({workingDirectory:e.workingDirectory,projectRoot:e.projectRoot,projectDirectory:e.projectDirectory,workspaceRoots:e.workspaceRoots}),n=await async function(e,t){return e.resolvePolicy(t)}(e.policyAdapter??function(e={}){const t=Object.freeze({...lj.metadata,...e.metadata}),r={...lj,...e,metadata:t};return{name:"permissive-sdk-local",resolvePolicy:()=>r}}(),{workspaceState:r});let o=await tj(t,r,n),s=!1,i=Promise.resolve();const a=e=>{const t=i.then(e);return i=t.catch((()=>{})),t},c=t.localExtensibility,l=void 0===c?void 0:()=>c.disposeLocalExtensibility?.();return{state:r,get services(){return o},policy:n,async createSessionRuntime(e={}){if(s)throw new Error("Cannot create a session runtime after the workspace runtime has been disposed.");return async function(e){const t={sessionId:e.options?.sessionId??(0,ge.C)(),createdAt:new Date},r=Object.freeze({...e.options?.metadata??{}}),n={options:e.options??{},workspaceState:e.workspaceState,workspaceServices:e.workspaceServices,policy:e.policy,sessionState:t,metadata:r,getAgentSkills:e.workspaceServices.getAgentSkills};let o,s;const i=[];try{o=e.adapters.resourceFactory?await e.adapters.resourceFactory.createResources(n):void 0,s=o,i.push(o);for(const t of e.adapters.resourceWrappers??[])s=await t.wrapResources({...n,baseResources:o,resources:s}),i.push(s);await(e.adapters.lifecycle?.onSessionCreated?.(t))}catch(e){try{await uj(i)}catch(t){throw function(e,t){return new AggregateError([t],"Session creation failed and resource cleanup also failed.",{cause:e})}(e,t)}throw e}let a=!1;return{state:t,resources:{base:o,wrapped:s},metadata:r,workspaceServices:e.workspaceServices,policy:e.policy,async dispose(){if(!a){a=!0;try{await uj(i)}finally{await(e.adapters.lifecycle?.onSessionDisposed?.(t))}}}}}({options:e,workspaceState:r,workspaceServices:o,policy:n,adapters:t})},async reload(){s||await a((async()=>{if(s)return;const e=o,i=await tj(t,r,n);s?await rj(i,{disposeLocalExtensibility:l}):(o=i,await rj(e,{preserveSharedContributorsFrom:i,disposeLocalExtensibility:l}),await(t.lifecycle?.onWorkspaceReload?.(r)))}))},async dispose(){s||(s=!0,await a((async()=>{try{await rj(o,{disposeLocalExtensibility:l})}finally{await(t.lifecycle?.dispose())}})))}}}class hj{async requestApproval(e){return{approved:!0}}}class pj{constructor(e,t,r,n){this.approvalMode=e,this.userConfiguredPolicy=t,this.teamSettingsService=r,this.respectAdminControls=n}async getPermissions(){const e=!(!this.respectAdminControls||"insecure_none"===this.userConfiguredPolicy.type)&&(await this.teamSettingsService.getSandboxingControls()).sandboxingDisabled;return{allow:[],deny:[],approvalMode:this.approvalMode,userConfiguredPolicy:e?{type:"insecure_none"}:this.userConfiguredPolicy}}async updatePermissions(){}}class fj{async open(e,t){}async getDiagnostics(e,t){return[]}}class mj{async getCodebaseReference(e,t){}}class gj{constructor(e){this.inner=e}async getState(e){const t=await this.inner.getState(e);return{...t,servers:t.servers.filter((e=>"needsAuth"!==e.status))}}}class wj{constructor(e){this.subagents=e.map((e=>new lm.zz({fullPath:`sdk-inline://${e.name}`,name:e.name,description:e.description,tools:[],model:e.model,prompt:e.prompt,permissionMode:lm.b$.DEFAULT,isBackground:!1,source:"sdk"})))}async getAllSubagents(){return this.subagents}async reload(){return this.subagents}}class yj{constructor(e={}){this.options=e,this.states=new Map,this.runCounterBySession=new Map,this.dispatchQueueBySession=new Map,this.dispatchInProgress=new Set,this.releaseRequestedBySession=new Set}getState(e){return this.states.get(e)??{status:"idle"}}isBusy(e){return"idle"!==this.getState(e).status}startRun(e,t){const r=this.nextRunId(e);return this.enqueueEvent(e,{type:"startRun",runId:r,abort:t?.abort}),r}queueResume(e,t){this.enqueueEvent(e,{type:"queueResume",queuedResume:t.queuedResume,targetRunId:t.targetRunId,mergeQueuedResume:t.mergeQueuedResume})}finishRun(e,t){this.enqueueEvent(e,{type:"runFinished",runId:t})}clearQueuedResume(e){this.enqueueEvent(e,{type:"clearQueuedResume"})}abort(e){this.enqueueEvent(e,{type:"abort"})}release(e){this.enqueueEvent(e,{type:"release"})}nextRunId(e){const t=(this.runCounterBySession.get(e)??0)+1;return this.runCounterBySession.set(e,t),t}enqueueEvent(e,t){const r=this.dispatchQueueBySession.get(e)??[];r.push(t),this.dispatchQueueBySession.set(e,r),this.drainEventQueue(e)}drainEventQueue(e){if(this.dispatchInProgress.has(e))return;let t;this.dispatchInProgress.add(e);try{const r=this.dispatchQueueBySession.get(e);if(!r)return;for(;r.length>0;){const n=r.shift();if(n)try{this.processEvent(e,n)}catch(e){t??=e}}}finally{this.dispatchQueueBySession.delete(e),this.dispatchInProgress.delete(e)}if(t)throw t}processEvent(e,t){const r=this.getState(e),{nextState:n,effects:o}=function(e,t){switch(e.status){case"idle":return function(e,t){switch(t.type){case"startRun":return{nextState:{status:"running",runId:t.runId,abort:t.abort},effects:[]};case"queueResume":return void 0===t.targetRunId?{nextState:e,effects:[]}:{nextState:{status:"runningWithQueuedResume",runId:t.targetRunId,queuedResume:t.queuedResume},effects:[]};case"runFinished":case"clearQueuedResume":case"abort":case"release":return{nextState:e,effects:[]};default:throw new Error(`Unhandled idle-state event: ${String(t)}`)}}(e,t);case"running":return function(e,t){switch(t.type){case"startRun":return{nextState:{status:"running",runId:t.runId,abort:t.abort},effects:[{type:"abortActiveRun",abort:e.abort}]};case"queueResume":return{nextState:{status:"runningWithQueuedResume",runId:e.runId,abort:e.abort,queuedResume:t.queuedResume},effects:[]};case"runFinished":return t.runId!==e.runId?{nextState:e,effects:[]}:{nextState:{status:"idle"},effects:[]};case"clearQueuedResume":case"release":return{nextState:e,effects:[]};case"abort":return{nextState:{status:"idle"},effects:[{type:"abortActiveRun",abort:e.abort}]};default:throw new Error(`Unhandled running-state event: ${String(t)}`)}}(e,t);case"runningWithQueuedResume":return function(e,t){switch(t.type){case"startRun":return{nextState:{status:"runningWithQueuedResume",runId:t.runId,abort:t.abort,queuedResume:e.queuedResume},effects:[{type:"abortActiveRun",abort:e.abort}]};case"queueResume":return{nextState:{...e,queuedResume:t.mergeQueuedResume(e.queuedResume,t.queuedResume)},effects:[]};case"runFinished":return t.runId!==e.runId?{nextState:e,effects:[]}:{nextState:{status:"running",runId:e.runId,abort:e.abort},effects:[{type:"startQueuedRun",sourceRunId:e.runId,queuedResume:e.queuedResume}]};case"clearQueuedResume":return{nextState:{status:"running",runId:e.runId,abort:e.abort},effects:[]};case"abort":return{nextState:{status:"idle"},effects:[{type:"abortActiveRun",abort:e.abort}]};case"release":return{nextState:e,effects:[]};default:throw new Error(`Unhandled runningWithQueuedResume-state event: ${String(t)}`)}}(e,t);default:return{nextState:e,effects:[]}}}(r,t);this.states.set(e,n),this.options.onStateChange?.({sessionId:e,previousState:r,nextState:n});for(const t of o)switch(t.type){case"abortActiveRun":t.abort?.();break;case"startQueuedRun":this.options.onQueuedRunReady?.({sessionId:e,sourceRunId:t.sourceRunId,queuedResume:t.queuedResume});break;default:throw new Error(`Unhandled lifecycle manager effect: ${String(t)}`)}const s=this.getState(e);"release"===t.type&&"idle"!==s.status&&this.releaseRequestedBySession.add(e),"idle"!==s.status||"release"!==t.type&&!this.releaseRequestedBySession.has(e)||(this.states.delete(e),this.runCounterBySession.delete(e),this.releaseRequestedBySession.delete(e))}}function vj(e){return"string"==typeof e&&e.trim().length>0}function bj(e,t){return new he.jn({command:t.command??"",workingDirectory:t.workingDirectory??"",error:e,isReadonly:!0})}function Sj(e){return{execute:async(t,r)=>new HA.v3({result:{case:"permissionDenied",value:new HA.U7({path:r.path,error:e,isReadonly:!0})}})}}function kj(e){return{execute:async(t,r)=>new Pg.Pi({result:{case:"permissionDenied",value:new Pg.QG({path:r.path,clientVisibleError:e,isReadonly:!0})}})}}function _j(e){return{execute:async(t,r)=>new Za.iz({result:{case:"permissionDenied",value:new Za.HQ({error:`${e} Tool: ${r.name}`,isReadonly:!0})}})}}var Cj=r("../agent-kv/dist/subagent-states.js");let Ej;function xj(e){const t=process.env.CURSOR_DATA_DIR;if(t?.trim())return po(e);let r;try{r=(0,o.homedir)()}catch{r=void 0}return function(e){const t=e.cursorDataDir?.trim();return t?(0,s.join)(t,"projects",(0,uo.r_)(e.workspacePath)):void 0!==e.homeDir&&function(e){if(""===e.trim())return!1;try{return!!(0,go.statSync)(e).isDirectory()&&((0,go.accessSync)(e,go.constants.W_OK),!0)}catch{return!1}}(e.homeDir)?(0,s.join)(e.homeDir,".cursor","projects",(0,uo.r_)(e.workspacePath)):(0,s.join)(e.ensureFallbackRoot(e.tempDir),(0,uo.r_)(e.workspacePath))}({workspacePath:e,homeDir:r,tempDir:(0,o.tmpdir)(),ensureFallbackRoot:e=>(void 0===Ej&&(Ej=function(e){return(0,go.mkdtempSync)((0,s.join)(e,"cursor-transcripts-"))}(e)),Ej)})}async function Pj(e,t){const r=(0,s.dirname)(e);await(0,fo.mkdir)(r,{recursive:!0}),await(0,fo.writeFile)(e,t,"utf-8")}class Ij{constructor(e){this.writeChain=Promise.resolve(),this.workspacePath=e.workspacePath,this.conversationId=e.conversationId,this.parentConversationId=e.parentConversationId,this.blobStore=e.blobStore,this.projectDir=xj(this.workspacePath);const t=this.parentConversationId?(e,t)=>{const r=xD({conversationId:e,ext:t,kind:"subagent",parentConversationId:this.parentConversationId});return(0,s.join)(this.projectDir,r)}:void 0;this.transcriptStore=new rO(this.projectDir,e.blobStore,Pj,{writeText:!1,writeJsonl:!0,...t?{pathResolver:t}:{}}),this.nestedSubagentTranscriptStore=new rO(this.projectDir,e.blobStore,Pj,{writeText:!1,writeJsonl:!0,pathResolver:(e,t)=>{const r=xD({conversationId:e,ext:t,kind:"subagent",parentConversationId:this.conversationId});return(0,s.join)(this.projectDir,r)}})}enqueueWrite(e,t){const r=this.writeChain;return this.writeChain=r.then((async()=>{try{await e()}catch(e){mM.Jz.warn(`${t} ${e instanceof Error?e.message:String(e)}`)}})),this.writeChain}async writeFromState(e,t){return this.enqueueWrite((async()=>{await this.transcriptStore.writeFromStateFull(e,t,this.conversationId);const r=await(0,Cj.Vn)(e,t,this.blobStore);for(const[t,n]of Object.entries(r))n?.conversationState&&await this.nestedSubagentTranscriptStore.writeFromStateFull(e,n.conversationState,t)}),"[LocalTranscriptWriter] Failed to write transcript:")}async writeTurnEndedFromState(e,t,r){return this.enqueueWrite((async()=>{await this.transcriptStore.writeFromStateFull(e,t,this.conversationId,{turnEnded:r})}),"[LocalTranscriptWriter] Failed to write turn-ended transcript:")}waitForPendingWrites(){return this.writeChain}getTranscriptPath(){if(this.parentConversationId){const e=xD({conversationId:this.conversationId,ext:"jsonl",kind:"subagent",parentConversationId:this.parentConversationId});return(0,s.join)(this.projectDir,e)}return function(e,t){const r=xD({conversationId:t,ext:"jsonl",kind:"primary"});return(0,s.join)(xj(e),r)}(this.workspacePath,this.conversationId)}getProjectDir(){return this.projectDir}}const Rj=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Tj="User aborted/interrupted manually.";class Aj{constructor(e){this.sessions=new Map,this.backgroundRuns=new Map,this.activeForegroundExecutions=new Map,this.backgroundPromises=new Set,this.pendingReleaseSessions=new Set,this.childParentIds=new Map,this.parentChildIds=new Map,this.queuedChildCompletions=new Map,this.childCompletionWaiters=new Map,this.agentClient=e.agentClient,this.getResources=e.getResources,this.mcpTools=e.mcpTools??[],this.workspacePath=e.workspacePath,this.parentConversationId=e.parentConversationId,this.headers=e.headers,this.endlessRetries=e.endlessRetries,this.onSessionCreated=e.onSessionCreated,this.onInteractionUpdate=e.onInteractionUpdate,this.onSessionCompleted=e.onSessionCompleted,this.onSessionReleased=e.onSessionReleased,this.onSubagentTokenDelta=e.onSubagentTokenDelta,this.lifecycleStore=new yj}async createOrResumeSession(e,t){if(t.forkAgentId)throw new Error("forkAgentId is not supported in local subagents.");const r=t.resumeAgentId;if(r&&function(e){if(!Rj.test(e))throw new Error(`Invalid resumeAgentId format: ${e}`)}(r),r&&!t.prompt)return r;if(r&&vj(t.prompt)&&this.isBackgroundRunBusy(r))throw new Error("Sub-agent is currently running. You may send the follow-up message when it has completed.");if(r&&this.sessions.get(r))return r;const n=r??(0,ge.C)(),o=function(e){const t=new re.We,r=(0,gM.sh)(e),n=new gM.pH(new re.ve,t);return n.setMetadata("agentId",r.agentId),n.setMetadata("latestRootBlobId",r.latestRootBlobId),n.setMetadata("name",r.name),n.setMetadata("createdAt",r.createdAt),n.setMetadata("mode",r.mode),n.setMetadata("isRunEverything",r.isRunEverything),n.setMetadata("lastUsedModel",r.lastUsedModel),n.setMetadata("lastDebugServerPort",r.lastDebugServerPort),n.setMetadata("currentPlanUri",r.currentPlanUri),n.setMetadata("subagentInfo",r.subagentInfo),n.setMetadata("blobEncryptionKey",r.blobEncryptionKey),n}(n),s=new Ij({workspacePath:this.workspacePath,conversationId:n,parentConversationId:this.parentConversationId,blobStore:o.getBlobStore()});return this.sessions.set(n,{agentStore:o,transcriptWriter:s,toolCallId:t.toolCallId}),this.onSessionCreated?.({agentId:n,toolCallId:t.toolCallId,subagentType:t.subagentType,parentAgentId:t.parentConversationId}),n}async runSession(e,t,r,n){if(this.isAwaitBackgroundMode(r))return this.awaitBackgroundRun(r.resumeAgentId,e.signal);const o=this.sessions.get(t);if(!o)return{status:"error",error:`Subagent session not found: ${t}`};if(r.runInBackground){const[n,s]=e.withDetached().withCancel();return this.registerBackgroundRun(t,this.executeSubagent(n,t,r,o),r.parentConversationId,s),{status:"background",backgroundReason:lm.qL.AGENT_REQUEST,toolCallCount:0}}const[s,i]=e.withDetached().withCancel();let a=!1;const c=()=>{a||i()};e.signal.addEventListener("abort",c,{once:!0}),e.signal.aborted&&c();let l=()=>{};const u=new Promise((e=>{l=e})),d={requestBackground:()=>!!a||!s.signal.aborted&&(a=!0,e.signal.removeEventListener("abort",c),l(),!0)};this.activeForegroundExecutions.set(r.toolCallId,d),this.activeForegroundExecutions.set(t,d);try{const e=this.executeSubagent(s,t,r,o),n=await Promise.race([e.then((e=>({handedOff:!1,outcome:e}))),u.then((()=>({handedOff:!0})))]);return n.handedOff?(this.registerBackgroundRun(t,e,r.parentConversationId,i),{status:"background",backgroundReason:lm.qL.USER_REQUEST,toolCallCount:0}):(this.onSessionCompleted?.(t,n.outcome),n.outcome)}finally{this.clearForegroundExecution(r.toolCallId,d),this.clearForegroundExecution(t,d),a||e.signal.removeEventListener("abort",c)}}forceBackgroundByToolCallId(e){const t=this.activeForegroundExecutions.get(e);return t?.requestBackground()?new Zn.a3({status:Zn.jh.ACCEPTED}):new Zn.a3({status:Zn.jh.NOT_FOUND})}clearForegroundExecution(e,t){this.activeForegroundExecutions.get(e)===t&&this.activeForegroundExecutions.delete(e)}releaseSession(e){this.lifecycleStore.release(e),this.isBackgroundRunBusy(e)?this.pendingReleaseSessions.add(e):this.cleanupSession(e)}async awaitBackgroundWorkers(){for(;this.backgroundPromises.size>0;)await Promise.allSettled([...this.backgroundPromises])}async waitForBackgroundCompletions(e,t){return this.collectAvailableChildCompletions(e,t)}isBackgroundRunBusy(e){return this.lifecycleStore.isBusy(e)||this.backgroundRuns.has(e)}registerBackgroundRun(e,t,r,n){this.registerParentChildLink(e,r);const o=this.lifecycleStore.startRun(e,{abort:n}),s=t.catch((e=>({status:"error",error:e instanceof Error?e.message:String(e)}))),i={runId:o,promise:s};this.backgroundRuns.set(e,i),this.backgroundPromises.add(s),s.then((t=>{this.lifecycleStore.finishRun(e,o);const r=this.backgroundRuns.get(e);if(r?.runId===o){this.backgroundRuns.delete(e),this.enqueueChildCompletion(e,o,t),this.maybeCleanupReleasedSession(e);try{this.onSessionCompleted?.(e,t)}catch(t){mM.Jz.error("[LocalSubagentHostAdapter] onSessionCompleted threw after background run",{agentId:e,error:t instanceof Error?t.message:String(t)})}}return t})).finally((()=>this.backgroundPromises.delete(s)))}maybeCleanupReleasedSession(e){this.pendingReleaseSessions.has(e)&&!this.isBackgroundRunBusy(e)&&this.cleanupSession(e)}cleanupSession(e){this.pendingReleaseSessions.delete(e);const t=this.sessions.get(e);if(!t)return;const r=this.parentChildIds.get(e);if(r)for(const e of r)this.childParentIds.delete(e);this.removeParentChildLink(e),this.parentChildIds.delete(e),this.queuedChildCompletions.delete(e),this.childCompletionWaiters.delete(e),t.transcriptWriter.waitForPendingWrites().catch((()=>{})),this.sessions.delete(e),this.onSessionReleased?.(e)}async executeSubagent(e,t,r,n){return r.continuationConfig?this.executeSubagentWithContinuation(e,t,r,n,r.continuationConfig):this.executeSubagentOnce(e,t,r,n)}async executeSubagentWithContinuation(e,t,r,n,o){const s=o.maxLoops>0?o.maxLoops:Number.POSITIVE_INFINITY;let i=await this.runContinuationLoop(e,t,r,n,o,s);if(!o.collectBackgroundChildren||"completed"!==i.status)return i;for(let a=0;a<500;a++){if(e.signal.aborted)return{status:"error",error:"Subagent was aborted by the user"};let a;try{a=await this.collectAvailableChildCompletions(t,e.signal)}catch{return{status:"error",error:"Subagent was aborted by the user"}}if(0===a.length)return i;const c=this.buildChildrenCompletedMessage(a,o.childrenCompletedMessageTemplate);if(i=await this.runContinuationLoop(e,t,new Zn.Pw({...r,prompt:c,resumeAgentId:t,runInBackground:!1}),n,o,s),"completed"!==i.status)return i}return i}async runContinuationLoop(e,t,r,n,o,s){let i,a,c=0;for(let l=0;l<s;l++){if(e.signal.aborted)return{status:"error",error:"Subagent was aborted by the user"};const s=0===l?r.prompt:this.computeContinuationNudge(o,c,i),u=0===l?new Zn.Pw({...r,runInBackground:!1}):new Zn.Pw({...r,prompt:s,resumeAgentId:t,runInBackground:!1});if(a=await this.executeSubagentOnce(e,t,u,n),"completed"!==a.status)return a;const d=a.toolCallCount??0,h=a.finalMessage??"";if(void 0!==i&&h.includes(i))return a;d>0?(c=0,i=void 0):(c+=1,i=c>=o.idleThreshold?`DONE_${(0,ge.C)().replace(/-/g,"").slice(0,8)}`:void 0)}return a??{status:"error",error:"Subagent continuation exited unexpectedly"}}computeContinuationNudge(e,t,r){return t>=e.idleThreshold&&void 0!==r?e.escapeMessageTemplate.replace("{idle_count}",String(t)).replace("{escape_token}",r):e.nudgeMessage}async executeSubagentOnce(e,t,r,n){let o,s=0;const a=new i.QFf({action:{case:"userMessageAction",value:new i.Vtf({userMessage:new i.RGk({text:r.prompt})})}}),c=new i.Gmx({modelId:r.modelId,displayModelId:r.modelId,displayName:r.modelId});void 0!==r.credentials.case&&(c.credentials=r.credentials);const l=new fM,u={sendUpdate:async(e,r)=>{"tokenDelta"===r.message.case&&this.onSubagentTokenDelta?.(t,r.message.value.tokens),"toolCallStarted"!==r.message.case&&"toolCallCompleted"!==r.message.case&&"partialToolCall"!==r.message.case||this.onInteractionUpdate?.(t,r),"toolCallCompleted"===r.message.case&&s++,"textDelta"===r.message.case&&(o=(o??"")+r.message.value.text)},query:async(e,t)=>function(e){const t=e.query.case;switch(t){case"webSearchRequestQuery":return dr(e.id,"Web search is not supported in local subagent");case"webFetchRequestQuery":return pr(e.id,"Web fetch is not supported in local subagent");case"switchModeRequestQuery":return gr(e.id,"Subagent mode switches are not supported in local subagent");case"askQuestionInteractionQuery":{const t=new Qt.tz({result:{case:"rejected",value:new Qt.ox({reason:"Interactive questions are not supported in local subagent mode"})}});return fr(e.id,t)}default:throw new Error(`Unhandled interaction query type in local subagent: ${String(t)}`)}}(t)},d={handleCheckpoint:async(e,t)=>{await n.agentStore.handleCheckpoint(e,t),n.transcriptWriter.writeFromState(e,t)},getLatestCheckpoint:()=>n.agentStore.getLatestCheckpoint()};try{const i=r.rootParentConversationId?.trim(),h=r.parentConversationId?.trim(),p=void 0!==i&&""!==i?i:void 0!==h&&""!==h?h:t,f=await this.getResources({agentId:t,parentAgentId:r.parentConversationId}),m=r.readonly?new J(f,function(e){const t=[G(XI,Sj(e.errorMessage)),G(QI,kj(e.errorMessage)),G(Gn,_j(e.errorMessage))];return e.wrapShell&&t.push(G(VI,function(e){return{execute:async(t,r)=>new he.W4({result:{case:"permissionDenied",value:bj(e,r)}})}}(e.errorMessage)),G(ee,function(e){return{async*execute(t,r){yield new he.FI({event:{case:"permissionDenied",value:bj(e,r)}})}}}(e.errorMessage)),G(PR,function(e){return{execute:async(t,r)=>new Co.Lt({result:{case:"permissionDenied",value:bj(e,r)}})}}(e.errorMessage))),e.includeWriteBackgroundShellStdin&&t.push(G(IR,function(e){return{execute:async(t,r)=>new Co.nt({result:{case:"error",value:new Co.Gv({error:e})}})}}(e.errorMessage))),t}({errorMessage:"This operation is not allowed in readonly mode. The subagent was launched with readonly: true, which restricts shell, write, delete, and MCP operations.",wrapShell:!0,includeWriteBackgroundShellStdin:!0})):f;return await this.agentClient.run(e,n.agentStore.getConversationStateStructure(),a,c,u,m,n.agentStore.getBlobStore(),l,d,[...this.mcpTools],{conversationGroupId:p,conversationId:t,...n.transcriptWriter.parentConversationId?{transcriptParentConversationId:n.transcriptWriter.parentConversationId}:{},subagentTypeName:r.subagentType||void 0,headers:yM(n.agentStore.getMetadata("blobEncryptionKey"),this.headers),endlessRetries:this.endlessRetries,subagentModelOverrides:[]}),await n.transcriptWriter.writeTurnEndedFromState(e,n.agentStore.getConversationStateStructure(),e.signal.aborted?{status:"aborted",error:Tj}:{status:"success"}),{status:"completed",finalMessage:o,toolCallCount:s}}catch(r){const o=r instanceof Error?r.message:String(r);return mM.Jz.error("[LocalSubagentHostAdapter] Subagent session failed",{agentId:t,error:o}),await n.transcriptWriter.writeTurnEndedFromState(e,n.agentStore.getLatestCheckpoint()??n.agentStore.getConversationStateStructure(),this.getTurnEndedFromError(e,o)),e.signal.aborted?{status:"aborted",error:Tj}:{status:"error",error:o}}}getTurnEndedFromError(e,t){return e.signal.aborted?{status:"aborted",error:Tj}:{status:"error",error:t}}isAwaitBackgroundMode(e){if(!Boolean(e.resumeAgentId&&!vj(e.prompt)&&e.readonly&&!0!==e.runInBackground))return!1;if(0===(e.parentConversationId??"").trim().length)throw new Error(`Missing parentConversationId for subagent await/status check (subagentId: ${e.resumeAgentId})`);return!0}async awaitBackgroundRun(e,t){const r=this.backgroundRuns.get(e);return r?this.awaitBackgroundEntry(r,t):this.isBackgroundRunBusy(e)?this.awaitBusyLifecycleRun(e,t):{status:"error",error:`No background subagent found for id: ${e}`}}async awaitBackgroundRunBounded(e,t){const r=t.agentId;if(e.signal.aborted)return new Zn.zJ({result:{case:"stillRunning",value:new Zn.L5({agentId:r})}});const n=this.backgroundRuns.get(r);if(void 0===n){const e=this.takeQueuedChildCompletion(r);return void 0!==e?"success"===e.status?new Zn.zJ({result:{case:"complete",value:new Zn.bE({agentId:r,finalMessage:e.finalMessage,toolCallCount:e.toolCallCount??0})}}):new Zn.zJ({result:{case:"error",value:new Zn.Y({agentId:r,error:e.finalMessage||"Subagent was aborted"})}}):this.isBackgroundRunBusy(r)?new Zn.zJ({result:{case:"stillRunning",value:new Zn.L5({agentId:r})}}):new Zn.zJ({result:{case:"notFound",value:new Zn.Hq({agentId:r})}})}const[o,s]=e.withTimeoutAndCancel(Math.max(0,t.timeoutMs)),i=await new Promise((e=>{const t=()=>e(void 0);o.signal.addEventListener("abort",t,{once:!0}),n.promise.then(e).finally((()=>{o.signal.removeEventListener("abort",t),s()}))}));return void 0===i||"background"===i.status||e.signal.aborted?new Zn.zJ({result:{case:"stillRunning",value:new Zn.L5({agentId:r})}}):(this.takeQueuedChildCompletion(r,n.runId),"completed"===i.status?new Zn.zJ({result:{case:"complete",value:new Zn.bE({agentId:r,finalMessage:i.finalMessage,toolCallCount:i.toolCallCount??0})}}):new Zn.zJ({result:{case:"error",value:new Zn.Y({agentId:r,error:i.error??"Subagent was aborted"})}}))}takeQueuedChildCompletion(e,t){for(const[r,n]of this.queuedChildCompletions){const o=n.findIndex((r=>r.agentId===e&&(void 0===t||r.runId===t)));if(-1===o)continue;const[s]=n.splice(o,1);return 0===n.length&&this.queuedChildCompletions.delete(r),s}}async awaitBusyLifecycleRun(e,t){for(;this.isBackgroundRunBusy(e);){if(t.aborted)return{status:"error",error:"Await timed out while task is still running"};const r=this.backgroundRuns.get(e);if(r)return this.awaitBackgroundEntry(r,t);await new Promise((e=>setTimeout(e,50)))}return{status:"completed",toolCallCount:0}}async awaitBackgroundEntry(e,t){if(t.aborted)return{status:"error",error:"Await timed out while task is still running"};const r={status:"error",error:"Await timed out while task is still running"};return new Promise((n=>{const o=()=>{n(r)};t.addEventListener("abort",o,{once:!0}),e.promise.then(n).finally((()=>t.removeEventListener("abort",o)))}))}registerParentChildLink(e,t){const r=t?.trim();if(!r||r===e||!this.sessions.has(r)&&r!==this.parentConversationId)return;const n=this.childParentIds.get(e);if(n===r)return;n&&(this.parentChildIds.get(n)?.delete(e),0===(this.parentChildIds.get(n)?.size??0)&&this.parentChildIds.delete(n)),this.childParentIds.set(e,r);const o=this.parentChildIds.get(r)??new Set;o.add(e),this.parentChildIds.set(r,o)}removeParentChildLink(e){const t=this.childParentIds.get(e);if(!t)return;this.childParentIds.delete(e);const r=this.parentChildIds.get(t);r?.delete(e),0===(r?.size??0)&&this.parentChildIds.delete(t)}enqueueChildCompletion(e,t,r){const n=this.childParentIds.get(e);if(!n)return;const o=this.queuedChildCompletions.get(n)??[];o.push({agentId:e,runId:t,status:"completed"===r.status?"success":"error"===r.status?"error":"aborted",finalMessage:"completed"===r.status?r.finalMessage??"":"error"===r.status?r.error:"Subagent was aborted by the user",..."completed"===r.status&&void 0!==r.toolCallCount?{toolCallCount:r.toolCallCount}:{}}),this.queuedChildCompletions.set(n,o),this.removeParentChildLink(e);const s=this.childCompletionWaiters.get(n);if(s){this.childCompletionWaiters.delete(n);for(const e of s)e()}}async collectAvailableChildCompletions(e,t){const r=this.drainChildCompletions(e);return r.length>0?r:this.hasPendingChildSubagents(e)?(await this.waitForChildCompletion(e,t),this.drainChildCompletions(e)):[]}hasPendingChildSubagents(e){return(this.parentChildIds.get(e)?.size??0)>0}drainChildCompletions(e){const t=this.queuedChildCompletions.get(e)??[];return this.queuedChildCompletions.delete(e),t}async waitForChildCompletion(e,t){if(t.aborted)throw new Error("aborted");await new Promise(((r,n)=>{const o=this.childCompletionWaiters.get(e)??new Set,s=()=>{a(),r()},i=()=>{a(),n(new Error("aborted"))},a=()=>{o.delete(s),0===o.size&&this.childCompletionWaiters.delete(e),t.removeEventListener("abort",i)};o.add(s),this.childCompletionWaiters.set(e,o),t.addEventListener("abort",i,{once:!0})}))}buildChildrenCompletedMessage(e,t){const r=e.map((e=>{const t="success"===e.status?"SUCCESS":"FAILED";return`## Agent ${e.agentId} -- ${t}\n\n${e.finalMessage}`})).join("\n\n---\n\n");return t.replace("{summaries}",r)}}var $j=r("../proto/dist/generated/agent/v1/agent_service_connect.js"),Mj=r("../proto/dist/generated/agent/v1/requested_model_pb.js"),Dj=r("../proto/dist/generated/agent/v1/selected_context_pb.js"),Oj=r("./src/agent/analytics.ts"),Fj=r("../proto/dist/generated/agent/v1/todo_tool_pb.js");const Nj={[Em.w3.UNSPECIFIED]:"unspecified",[Em.w3.LEFT]:"left",[Em.w3.RIGHT]:"right",[Em.w3.MIDDLE]:"middle",[Em.w3.BACK]:"back",[Em.w3.FORWARD]:"forward"},Lj={[Em.Dh.UNSPECIFIED]:"unspecified",[Em.Dh.UP]:"up",[Em.Dh.DOWN]:"down",[Em.Dh.LEFT]:"left",[Em.Dh.RIGHT]:"right"},jj={[Em.EB.UNSPECIFIED]:"unspecified",[Em.EB.TAP]:"tap",[Em.EB.DOWN]:"down",[Em.EB.UP]:"up"};function Uj(e){return Nj[e]??"unspecified"}function Bj(e){return void 0===e?void 0:{x:e.x,y:e.y}}function Wj({result:e}){switch(e.case){case"success":return{status:"success",value:{actionCount:e.value.actionCount,durationMs:e.value.durationMs,settleMs:e.value.settleMs,screenshotPath:e.value.screenshotPath,cursorPosition:Bj(e.value.cursorPosition),log:e.value.log}};case"error":return{status:"error",error:{message:e.value.error,actionCount:e.value.actionCount,durationMs:e.value.durationMs,screenshotPath:e.value.screenshotPath,log:e.value.log}};default:return}}function Hj(e,t){switch(e.message.case){case"textDelta":return{type:"text-delta",text:e.message.value.text};case"thinkingDelta":return{type:"thinking-delta",text:e.message.value.text};case"thinkingCompleted":return{type:"thinking-completed",thinkingDurationMs:e.message.value.thinkingDurationMs};case"userMessageAppended":return{type:"user-message-appended",userMessage:{type:"user_message",session_id:t,text:e.message.value.userMessage?.text??""}};case"tokenDelta":return{type:"token-delta",tokens:e.message.value.tokens};case"summary":return{type:"summary",summary:e.message.value.summary};case"summaryStarted":return{type:"summary-started"};case"summaryCompleted":{const{failed:t,fallback:r}=e.message.value;return{type:"summary-completed",...t?{failed:t}:{},...r?{fallback:r}:{}}}case"shellOutputDelta":return{type:"shell-output-delta",event:e.message.value.event.case?{case:e.message.value.event.case,value:e.message.value.event.value?.toJson?.()??e.message.value.event.value}:{}};case"toolCallStarted":return qj("tool-call-started",e.message.value);case"partialToolCall":return qj("partial-tool-call",e.message.value);case"toolCallCompleted":return qj("tool-call-completed",e.message.value);case"heartbeat":return null;case"turnEnded":{const t=e.message.value;return{type:"turn-ended",...(void 0!==t.inputTokens||void 0!==t.outputTokens||void 0!==t.cacheReadTokens||void 0!==t.cacheWriteTokens)&&{usage:{inputTokens:Number(t.inputTokens??BigInt(0)),outputTokens:Number(t.outputTokens??BigInt(0)),cacheReadTokens:Number(t.cacheReadTokens??BigInt(0)),cacheWriteTokens:Number(t.cacheWriteTokens??BigInt(0)),...t.reasoningTokens&&{reasoningTokens:Number(t.reasoningTokens)}}}}}case"modelCallCompleted":{const t=e.message.value;return{type:"model-call-completed",modelCallId:t.modelCallId,usage:{inputTokens:Number(t.inputTokens),outputTokens:Number(t.outputTokens),cacheReadTokens:Number(t.cacheReadTokens),cacheWriteTokens:Number(t.cacheWriteTokens),...t.reasoningTokens&&{reasoningTokens:Number(t.reasoningTokens)}}}}case"toolCallDelta":{const r=e.message.value,n=r.toolCallDelta;if("taskToolCallDelta"!==n?.delta.case)return null;const o=n.delta.value.interactionUpdate;if(void 0===o)return null;const s=Hj(o,t);return null!==s&&function(e){switch(e.type){case"text-delta":case"thinking-delta":case"thinking-completed":case"tool-call-started":case"tool-call-completed":case"partial-tool-call":case"step-started":case"step-completed":case"tool-requests-listed":return!0;default:return!1}}(s)?{type:"tool-call-delta",callId:r.callId,modelCallId:r.modelCallId,taskUpdate:s}:null}case"stepStarted":return{type:"step-started",stepId:Number(e.message.value.stepId)};case"toolRequestsListed":return{type:"tool-requests-listed",callCount:e.message.value.callCount};case"stepCompleted":return{type:"step-completed",stepId:Number(e.message.value.stepId),stepDurationMs:Number(e.message.value.stepDurationMs)};case"postRequestPrompt":case"activeBranchChange":case"feedbackRequest":case"responseComparison":case"contextInjectionState":case"routedModel":case"grokBotNudge":case"thinkingNote":case"voiceCallUtterance":case void 0:return null;default:return e.message,null}}function qj(e,t){const r=function(e){if(!e?.tool)return null;switch(e.tool.case){case"shellToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"shell",args:{command:t.command,...t.workingDirectory?{workingDirectory:t.workingDirectory}:{},...t.timeout?{timeout:t.timeout}:{}},...r?{result:Zj(r)}:{}}:null}case"deleteToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"delete",args:{path:t.path},...r?{result:Xj(r)}:{}}:null}case"globToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"glob",args:{globPattern:t.globPattern,...t.targetDirectory?{targetDirectory:t.targetDirectory}:{}},...r?{result:Qj(r)}:{}}:null}case"grepToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"grep",args:{pattern:t.pattern,...t.path?{path:t.path}:{},...t.glob?{glob:t.glob}:{},...t.outputMode?{outputMode:t.outputMode}:{},...t.contextBefore?{contextBefore:t.contextBefore}:{},...t.contextAfter?{contextAfter:t.contextAfter}:{},...t.context?{context:t.context}:{},...t.caseInsensitive?{caseInsensitive:t.caseInsensitive}:{},...t.type?{type:t.type}:{},...t.headLimit?{headLimit:t.headLimit}:{},...void 0!==t.offset?{offset:t.offset}:{},...t.multiline?{multiline:t.multiline}:{},...t.sort?{sort:t.sort}:{},...t.sortAscending?{sortAscending:t.sortAscending}:{}},...r?{result:Yj(r)}:{}}:null}case"readToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"read",args:{path:t.path},...r?{result:tU(r)}:{}}:null}case"editToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"edit",args:{path:t.path},...r?{result:rU(r)}:{}}:null}case"lsToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"ls",args:{path:t.path,...t.ignore&&t.ignore.length>0?{ignore:t.ignore}:{}},...r?{result:nU(r)}:{}}:null}case"readLintsToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"readLints",args:{paths:t.paths},...r?{result:sU(r)}:{}}:null}case"mcpToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"mcp",args:{...t.providerIdentifier?{providerIdentifier:t.providerIdentifier}:{},...t.toolName?{toolName:t.toolName}:{},...t.args?{args:Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t.toJson()])))}:{}},...r?{result:iU(r)}:{}}:null}case"generateImageToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"generateImage",args:{description:t.description,...t.filePath?{filePath:t.filePath}:{}},...r?{result:cU(r)}:{}}:null}case"recordScreenToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"recordScreen",args:{mode:lU(t.mode)},...r?{result:uU(r)}:{}}:null}case"semSearchToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"semSearch",args:{query:t.query,...t.targetDirectories&&t.targetDirectories.length>0?{targetDirectories:t.targetDirectories}:{},...t.explanation?{explanation:t.explanation}:{}},...r?{result:aU(r)}:{}}:null}case"createPlanToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"createPlan",args:{plan:t.plan},...r?{result:dU(r)}:{}}:null}case"updateTodosToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"updateTodos",args:{todos:t.todos.map((e=>({content:e.content,status:pU(e.status)})))},...r?{result:hU(r)}:{}}:null}case"fetchToolCall":case"switchModeToolCall":return null;case"computerUseToolCall":return function({args:e,result:t}){return e?{type:"computerUse",args:{actions:e.actions.flatMap((e=>function({action:e}){switch(e.case){case"mouseMove":return{type:"mouseMove",coordinate:Bj(e.value.coordinate)};case"click":return{type:"click",coordinate:Bj(e.value.coordinate),button:Uj(e.value.button),count:e.value.count,modifierKeys:e.value.modifierKeys};case"mouseDown":case"mouseUp":return{type:e.case,button:Uj(e.value.button)};case"drag":return{type:"drag",path:e.value.path.map((e=>({x:e.x,y:e.y}))),button:Uj(e.value.button),modifierKeys:e.value.modifierKeys};case"scroll":return{type:"scroll",coordinate:Bj(e.value.coordinate),direction:Lj[e.value.direction]??"unspecified",amount:e.value.amount,modifierKeys:e.value.modifierKeys};case"type":return{type:"type",text:e.value.text};case"key":return{type:"key",key:e.value.key,holdDurationMs:e.value.holdDurationMs,stroke:jj[e.value.stroke]??"unspecified"};case"wait":return{type:"wait",durationMs:e.value.durationMs};case"screenshot":case"cursorPosition":return{type:e.case};default:return}}(e)??[])),description:e.description},result:t?Wj(t):void 0}:null}(e.tool.value);case"readTodosToolCall":case"webSearchToolCall":case"listMcpResourcesToolCall":case"readMcpResourceToolCall":return null;case"taskToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"task",args:zj(t),...r?{result:Kj(r)}:{}}:null}case"applyAgentDiffToolCall":case"askQuestionToolCall":case"writeShellStdinToolCall":case"reflectToolCall":case"setupVmEnvironmentToolCall":case"replaceEnvToolCall":case"startGrindExecutionToolCall":case"startGrindPlanningToolCall":case"truncatedToolCall":case"webFetchToolCall":case"reportBugfixResultsToolCall":case"aiAttributionToolCall":case"prManagementToolCall":case"editPrLabelsToolCall":case"fetchCloudAgentDataToolCall":case"mcpAuthToolCall":case"connectScmToolCall":case"searchConversationsToolCall":case"awaitToolCall":case"blameByFilePathToolCall":case"getMcpToolsToolCall":case"reportBugToolCall":case"setActiveBranchToolCall":case"communicateUpdateToolCall":case"sendFinalSummaryToolCall":case"updateOriginPrCodeTourToolCall":case"getOriginPrCodeTourToolCall":case"recordCiInvestigationFindingsToolCall":case"sendMessageToolCall":case"sendToUserToolCall":case"createGoalToolCall":case"updateGoalToolCall":case"getAgentStatusToolCall":case"sendToAgentToolCall":case"readAgentTranscriptToolCall":case"createAgentToolCall":case"createProjectToolCall":case"startProjectUpdatesToolCall":case"stopProjectUpdatesToolCall":case"manageAccessToolCall":case"stopAgentToolCall":case"listTrackedTasksToolCall":case"createTrackedTasksToolCall":case"updateTrackedTasksToolCall":case"deleteTrackedTasksToolCall":case"updateTrackedTaskStatusesToolCall":case"updateTrackedTaskTagsToolCall":case"writeCanvasToolCall":case"readCanvasToolCall":case"generateVideoToolCall":case"xSearchToolCall":case"executeToolCall":case void 0:return null;default:return e.tool}}(t.toolCall);return r?{type:e,callId:t.callId,toolCall:r,modelCallId:t.modelCallId}:null}function zj(e){return{description:e.description??"",prompt:e.prompt??"",...e.subagentType?{subagentType:Gj(e.subagentType)}:{},...e.model?{model:e.model}:{},...e.resume?{resume:e.resume}:{},...e.agentId?{agentId:e.agentId}:{},...e.attachments&&e.attachments.length>0?{attachments:e.attachments}:{},...void 0!==e.mode?{mode:Vj(e.mode)}:{},...e.respondingToMessageIds&&e.respondingToMessageIds.length>0?{respondingToMessageIds:e.respondingToMessageIds}:{}}}function Gj(e){const t=e.type.case;return t?"custom"===t?{kind:t,name:e.type.value.name}:{kind:t}:{kind:"unspecified"}}function Vj(e){switch(e){case lm.FL.AGENT:return"agent";case lm.FL.PLAN:return"plan";default:return"unspecified"}}function Kj(e){if(e.result?.case)switch(e.result.case){case"success":{const t=e.result.value;return{status:"success",value:{...t.conversationSteps&&t.conversationSteps.length>0?{conversationSteps:t.conversationSteps.map((e=>e.toJson?.()??e))}:{},...t.agentId?{agentId:t.agentId}:{},isBackground:t.isBackground??!1,...void 0!==t.durationMs?{durationMs:Number(t.durationMs)}:{},...t.resultSuffix?{resultSuffix:t.resultSuffix}:{},backgroundReason:Jj(t.backgroundReason),...t.transcriptPath?{transcriptPath:t.transcriptPath}:{}}}}case"error":return{status:"error",error:{message:e.result.value.error??"Task failed"}};default:return}}function Jj(e){switch(e){case lm.qL.AGENT_REQUEST:return"agentRequest";case lm.qL.USER_REQUEST:return"userRequest";case lm.qL.QUEUED_FOLLOW_UP:return"queuedFollowUp";default:return"unspecified"}}function Zj(e){if(e.result?.case)switch(e.result.case){case"success":case"failure":{const t=e.result.value;return{status:"success",value:{exitCode:t.exitCode??0,signal:t.signal??"",stdout:t.stdout??"",stderr:t.stderr??"",executionTime:t.executionTime??0}}}case"timeout":return{status:"error",error:{message:`Command timed out after ${e.result.value.timeoutMs}ms`,command:e.result.value.command,workingDirectory:e.result.value.workingDirectory}};case"rejected":return{status:"error",error:{message:e.result.value.reason??"Command rejected",command:e.result.value.command,workingDirectory:e.result.value.workingDirectory}};case"spawnError":return{status:"error",error:{message:e.result.value.error??"Failed to spawn command",command:e.result.value.command,workingDirectory:e.result.value.workingDirectory}};default:return}}function Xj(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{fileSize:Number(e.result.value.fileSize??0)}}:{status:"error",error:{message:e.result.value.error??e.result.value.reason??e.result.value.clientVisibleError??e.result.case,path:e.result.value.path}}}function Qj(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{files:e.result.value.files??[],totalFiles:e.result.value.totalFiles??0,clientTruncated:e.result.value.clientTruncated??!1,ripgrepTruncated:e.result.value.ripgrepTruncated??!1}}:{status:"error",error:{message:e.result.value.error??e.result.value.reason??e.result.case}}}function Yj(e){if(e.result?.case){if("success"===e.result.case){const t=e.result.value,r={};if(t.workspaceResults)for(const[e,n]of Object.entries(t.workspaceResults))r[e]=eU(n);return{status:"success",value:{...Object.keys(r).length>0?{workspaceResults:r}:{},...t.activeEditorResult?{activeEditorResult:eU(t.activeEditorResult)}:{}}}}return{status:"error",error:{message:e.result.value.error??e.result.case}}}}function eU(e){if(e?.result?.case)switch(e.result.case){case"content":return{type:"content",output:{matches:e.result.value.matches?.map((e=>({file:e.file,...void 0!==e.lineNumber?{lineNumber:e.lineNumber}:{},line:e.line,...e.beforeContext?{beforeContext:e.beforeContext}:{},...e.afterContext?{afterContext:e.afterContext}:{}})))??[],totalMatches:e.result.value.totalMatches??0}};case"files":return{type:"files",output:{files:e.result.value.files??[],count:e.result.value.count??0}};case"count":return{type:"count",output:{counts:e.result.value.counts?.map((e=>({file:e.file,count:e.count})))??[],total:e.result.value.total??0}};default:return}}function tU(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{content:"content"===e.result.value.output.case?e.result.value.output.value:"",totalLines:e.result.value.totalLines??0,fileSize:Number(e.result.value.fileSize??0)}}:{status:"error",error:{message:e.result.value.error??e.result.value.reason??e.result.case,path:e.result.value.path}}}function rU(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{...void 0!==e.result.value.linesAdded?{linesAdded:e.result.value.linesAdded}:{},...void 0!==e.result.value.linesRemoved?{linesRemoved:e.result.value.linesRemoved}:{},...e.result.value.diffString?{diffString:e.result.value.diffString}:{}}}:{status:"error",error:{message:e.result.value.error??e.result.value.reason??e.result.case,path:e.result.value.path}}}function nU(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{directoryTreeRoot:oU(e.result.value.directoryTreeRoot)}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function oU(e){if(e)return{absPath:e.absPath??"",childrenDirs:e.childrenDirs?.map(oU)??[],childrenFiles:e.childrenFiles?.map((e=>({name:e.name})))??[],childrenWereProcessed:e.childrenWereProcessed??!1,fullSubtreeExtensionCounts:e.fullSubtreeExtensionCounts??{},numFiles:e.numFiles??0}}function sU(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{fileDiagnostics:e.result.value.fileDiagnostics?.map((e=>({path:e.path,diagnostics:e.diagnostics?.map((e=>({severity:fU(e.severity),...e.range?{range:{...e.range.start?{start:{line:e.range.start.line,character:e.range.start.character}}:{},...e.range.end?{end:{line:e.range.end.line,character:e.range.end.character}}:{}}}:{},message:e.message,source:e.source,code:e.code})))??[],diagnosticsCount:e.diagnosticsCount??0})))??[],totalFiles:e.result.value.totalFiles??0,totalDiagnostics:e.result.value.totalDiagnostics??0}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function iU(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{content:e.result.value.content?.map((e=>{const t={};return"text"===e.content?.case?t.text={text:e.content.value.text}:"image"===e.content?.case&&(t.image={data:e.content.value.data,...e.content.value.mimeType?{mimeType:e.content.value.mimeType}:{}}),t}))??[],isError:e.result.value.isError??!1}}:{status:"error",error:{message:e.result.value.error??e.result.value.reason??e.result.case}}}function aU(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{results:e.result.value.results??""}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function cU(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{filePath:e.result.value.filePath??""}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function lU(e){switch(e){case DT.$u.START_RECORDING:return"START_RECORDING";case DT.$u.SAVE_RECORDING:return"SAVE_RECORDING";case DT.$u.DISCARD_RECORDING:return"DISCARD_RECORDING";default:throw new Error(`Unknown RecordingMode: ${e}`)}}function uU(e){if(e.result?.case)switch(e.result.case){case"startSuccess":return{status:"success",value:{wasPriorRecordingCancelled:e.result.value.wasPriorRecordingCancelled??!1}};case"saveSuccess":return{status:"success",value:{path:e.result.value.path??"",recordingDurationMs:Number(e.result.value.recordingDurationMs??0)}};case"discardSuccess":return{status:"success",value:{}};case"failure":return{status:"error",error:{message:e.result.value.error??"Unknown error"}};default:return}}function dU(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function hU(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{todos:e.result.value.todos?.map((e=>({content:e.content,status:pU(e.status)})))??[],totalCount:e.result.value.totalCount??0}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function pU(e){switch(e){case Fj.Vj.UNSPECIFIED:case Fj.Vj.PENDING:return"pending";case Fj.Vj.IN_PROGRESS:return"inProgress";case Fj.Vj.COMPLETED:return"completed";case Fj.Vj.CANCELLED:return"cancelled";default:return"pending"}}function fU(e){switch(e){case BR.h_.UNSPECIFIED:case BR.h_.ERROR:return"error";case BR.h_.WARNING:return"warning";case BR.h_.INFORMATION:return"information";case BR.h_.HINT:return"hint";default:return"error"}}const mU={type:"object",properties:{},additionalProperties:!0};function gU(e){const t={};for(const[r,n]of Object.entries(e))t[r]=n;return t}function wU(e){return"text"===e.type?new Za._Z({content:{case:"text",value:new Za.zN({text:e.text})}}):new Za._Z({content:{case:"image",value:new Za.do({data:n.Buffer.from(e.data,"base64"),mimeType:e.mimeType??""})}})}function yU(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var vU=r("./src/agent/errors.ts");const bU="Shell is not available when local.fs is set: the agent's files live in a FileSystem, and a shell would run on the host disk. Use Read, Grep, Glob, LS, and the edit tools instead.";function SU(e){return{async execute(){throw new Error(e)}}}function kU(e){var t;e.register(VI,SU(bU)),e.register(ee,(t=bU,{async*execute(){throw new Error(t)}})),e.register(PR,SU(bU)),e.register(MR,SU(bU)),e.register(IR,SU(bU)),e.register(KI,SU(bU)),e.register(lR,SU("ReadLints is not available when local.fs is set: lint diagnostics come from a host language service, not the FileSystem.")),e.register(eR,SU("Git is not available when local.fs is set: the agent's files live in a FileSystem, not a host git checkout."))}var _U=r("./src/agent/filesystem/executors.ts"),CU=r("./src/agent/filesystem/compose.ts"),EU=r("./src/agent/filesystem/trees.ts"),xU=r("./src/agent/filesystem/walk.ts");const PU="/tmp",IU=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.txt$/i;function RU(e){const{write:t,hostProjectDir:r}=e;return{async execute(e,n,o){const i=function(e){if(t=e.writePath,!/^([/\\]|[A-Za-z]:[/\\])/.test(t))return;var t;const r=function(e){if(void 0===e.hostProjectDir||""===e.hostProjectDir)return;const t=(0,xU.eI)(e.hostProjectDir),r=(0,xU.eI)(e.writePath);return"/"!==t&&(0,xU.hJ)({path:r,prefix:t})?r.slice(t.length):void 0}(e),n=void 0===r?(0,xU.eI)(e.writePath):(0,xU.eI)(`${PU}/${r}`);if(!(0,xU.hJ)({path:n,prefix:PU}))return;const o=s.default.posix.basename(n),i=s.default.posix.join(PU,Xa);return s.default.posix.dirname(n)===i&&IU.test(o)?s.default.posix.join(PU,o):n}({writePath:n.path,hostProjectDir:r});if(void 0===i||i===n.path)return await t.execute(e,n,o);const a=n.clone();a.path=i;const c=await t.execute(e,a,o);return"success"===c.result.case&&(c.result.value.path=i),c}}}class TU{constructor(e,t="/"){this.fs=e,this.listeners=new Set,this.workspace=(0,xU.eI)(t)}getAllCursorRules(e){return this.rules??=async function(e,t){const[r,n]=await Promise.all([AU(e,s.posix.join(t,".cursor/rules")),$U(e,s.posix.join(t,"AGENTS.md"))]);return void 0===n?r:[...r,n]}(this.fs,this.workspace),this.rules}reload(e){this.rules=void 0;for(const e of this.listeners)e()}onDidChangeRules(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}dispose(){this.listeners.clear()}}async function AU(e,t){const r=[];try{for await(const n of e.list(t))"directory"!==n.kind&&n.path.endsWith(".mdc")&&r.push(n.path)}catch{return[]}return(await(0,Dr.PH)(r,(async t=>{const r=await MU(e,t),n=void 0===r?null:Xr(r);if(null!==n)return rm({path:t,body:n.body,frontmatter:n.frontmatter,rawFrontmatter:n.rawFrontmatter})}),{max:8})).filter((e=>void 0!==e))}async function $U(e,t){const r=await MU(e,t);if(void 0!==r)return rm({path:t,body:Jr({content:r,filename:"AGENTS.md"}),frontmatter:{alwaysApply:!0}})}async function MU(e,t){try{const r=await e.read(t);return"string"==typeof r?r:(new TextDecoder).decode(r)}catch{return}}const DU={getAllCursorRules:async()=>[],reload(){},onDidChangeRules:()=>()=>{},dispose(){}},OU={async exec(){throw new Error("git is not available in a FileSystem session")}},FU={isIgnoredByAny:async()=>!1,isGitIgnored:async()=>!1,isCursorIgnored:async()=>!1,isRepoBlocked:async()=>!1,listCursorIgnoreFilesByRoot:async()=>[],getCursorIgnoreMapping:async()=>({}),getShellSandboxIgnoreMapping:async()=>({}),getGitIgnoreMapping:async()=>({}),getRepoBlockExcludeGlobs:async()=>[]};function NU(e){return{cursorRulesService:!0===e.includeProjectRules?new TU(e.fs,e.workspace):DU,getAgentSkills:async()=>[],subagentsService:e.subagentsService??new dm,gitExecutor:OU,ignoreService:FU,requestContextIsWorkingDirHomeDir:!1,reportProcessWorkingDirectory:!1}}function LU(e,t){const r=t.workspace??"/",n=(0,_U.c9)(e,{workspace:r});return{localResourceProviderOptions:{overrideReadExecutor:n.read,overrideWriteExecutor:RU({write:n.write,hostProjectDir:t.hostProjectDir}),overrideGrepExecutor:n.grep,overrideLsExecutor:n.ls,overrideDeleteExecutor:n.delete,suppressDefaultShellExecutor:!0,...NU({...t.settings,fs:e,workspace:r})},reportedWorkspacePath:r,reportedProjectFolder:PU,excludeHooks:!0,excludeProjectMcp:!0}}var jU=r("./src/agent/executor-common.ts");class UU{constructor(){this.countsByMode=new Map,this.record=e=>{let t=this.countsByMode.get(e.mode);switch(void 0===t&&(t={mode:e.mode,checked_calls:0,outside_limit_calls:0,settings_unavailable_calls:0,unknown_server_calls:0},this.countsByMode.set(e.mode,t)),e.outcome){case"within_limit":return void(t.checked_calls+=1);case"outside_limit":return t.checked_calls+=1,void(t.outside_limit_calls+=1);case"settings_unavailable":return void(t.settings_unavailable_calls+=1);case"unknown_server":return void(t.unknown_server_calls+=1);default:return e.outcome}}}take(){const e=[...this.countsByMode.values()];return this.countsByMode.clear(),e}}var BU=r("./src/agent/native/vendored-tree-sitter.ts"),WU=r("./src/agent/platform-package-locator.ts"),HU=r("./src/agent/sdk-config.ts"),qU=r("../../node_modules/.pnpm/@statsig+js-client@3.31.0/node_modules/@statsig/js-client/src/index.js"),zU=r("./src/agent/utils/logger.ts");const GU={checkFeatureGate:()=>!1,getDynamicConfigValue:({defaultValue:e})=>e},VU=new Map;async function KU(e){try{const t=await async function(e){const t=await(0,jU.dC)(e,jU.EV);if(!t)return;const r=jU.EV.endsWith("/")?jU.EV.slice(0,-1):jU.EV,n=await fetch(`${r}/aiserver.v1.AnalyticsService/BootstrapStatsig`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json","x-cursor-client-type":"sdk","x-cursor-client-version":(0,jU.tF)(),"x-ghost-mode":(0,jU.U)(e)},body:JSON.stringify({})});if(!n.ok)return void zU.v.log(`Failed to bootstrap SDK Statsig: ${n.status} ${n.statusText}`);const o=await n.json();return JU(o)&&"string"==typeof o.config&&o.config.length>0?o.config:void 0}(e);if(!t)return GU;const r=new qU.StatsigClient("client-Bm4HJ0aDjXHQVsoACMREyLNxm5p6zzuzhO50MgtoT5D",function(e){try{const r=JSON.parse(e);if(JU(r)&&"object"==typeof(t=r.user)&&null!==t&&!Array.isArray(t))return{...r.user,custom:{...r.user.custom,clientType:"sdk",clientVersion:(0,jU.tF)()}}}catch(e){zU.v.log(`Failed to parse SDK Statsig bootstrap user: ${e instanceof Error?e.message:String(e)}`)}var t;return{custom:{clientType:"sdk",clientVersion:(0,jU.tF)()}}}(t),{disableLogging:!0,disableStorage:!0,networkConfig:{preventAllNetworkTraffic:!0}});return r.dataAdapter.setData(t),r.initializeSync(),{checkFeatureGate:(e,t)=>{try{return r.checkGate(e,t)}catch{return!1}},getDynamicConfigValue({configName:e,paramName:t,defaultValue:n}){try{return r.getDynamicConfig(e).get(t,n)}catch{return n}}}}catch(e){return zU.v.log(`Failed to initialize SDK Statsig: ${e instanceof Error?e.message:String(e)}`),GU}}function JU(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function ZU(e){let t;return e?.then((e=>{t=e}),(()=>{})),()=>t?.checkFeatureGate("grok_bot_mcp_app_payment_token_filter",{disableExposureLog:!0})??!1}var XU=r("./src/agent/tools-option.ts");class QU{async requestApproval(){return{approved:!0}}}function YU(e,t){if(!function(e){return void 0!==e&&Object.keys(e).length>0}(t))return;const r=e.resources.base;if(!(r instanceof a$))throw new vU.j1("SDK custom tools require the default local workspace resource provider.",{isRetryable:!1});const n=r.getMcpExecutionPolicyDeps(),o=r.get(Gn),s=function(e,t){return{async execute(r,n,o){const s=n.toolName||function(e){const t=`${Nn}-`;return e.startsWith(t)?e.slice(t.length):e}(n.name),i=e[s];if(void 0===i)return new Za.iz({result:{case:"error",value:new Za.Nh({error:`Unknown custom tool: ${s}`})}});try{return function(e){const t=function(e){return"object"==typeof(t=e)&&null!==t&&!Array.isArray(t)&&"content"in t&&Array.isArray(t.content)?{content:e.content,isError:e.isError,structuredContent:e.structuredContent}:"string"==typeof e?{content:[{type:"text",text:e}]}:{content:[{type:"text",text:JSON.stringify(e)}],structuredContent:yU(e)?e:void 0};var t}(e),r=void 0!==t.structuredContent?we.Struct.fromJson(t.structuredContent):void 0;return new Za.iz({result:{case:"success",value:new Za.QW({content:t.content.map(wU),isError:t.isError??!1,structuredContent:r})}})}(await i.execute(function(e){return Object.fromEntries(Object.entries(e.args).map((([e,t])=>[e,t.toJson()])))}(n),{toolCallId:n.toolCallId||void 0,...void 0===t||""===t?{}:{sessionId:t}}))}catch(e){return new Za.iz({result:{case:"error",value:new Za.Nh({error:e instanceof Error?e.message:String(e)})}})}}}}(t,e.state.sessionId),i=new QU;e.resources.base.register(Gn,{async execute(e,t,r){if(function(e){return e.providerIdentifier===Nn}(t)){const o=await OI(e,t,{...n,pendingDecisionProvider:i,toolDef:{source:"internal"}});return void 0!==o?o:s.execute(e,t,r)}return o.execute(e,t,r)}})}const eB=new Set(["127.0.0.1","localhost","[::1]"]);function tB(e){if(void 0===e)return{};const t=e.resourceProviderOptions;return{...void 0!==t?{localResourceProviderOptions:t}:{},...void 0!==e.reportedWorkspacePath?{reportedWorkspacePath:e.reportedWorkspacePath}:{}}}function rB(){const e=process.env.CURSOR_SDK_MOCK_PROMPT_TIME;if(void 0===e||""===e)return;const t=new Date(e);return Number.isNaN(t.getTime())?void 0:t}const nB={warn(){},error(){}},oB={log(){}};class sB{async requestApproval(e){return{approved:!1,reason:`Local SDK runs cannot request interactive approval for ${iB(e)}. Keep the action within the configured sandbox policy or Smart Auto Review's auto-approval boundary, or re-run without sandboxing/autoReview enabled.`}}}function iB(e){switch(e.type){case xg.Shell:return"this shell command";case xg.Mcp:return"this MCP tool call";case xg.Write:return"this file edit";case xg.Delete:return"this file deletion";default:return"this operation"}}function aB(e){return void 0!==e&&"insecure_none"!==e.type}async function cB(e,t){const r="string"==typeof e||void 0===e?{workingDirectory:e,apiKey:t}:e,a=(0,y.q6)().with(l._O,oB),c=sj(r.settingSources),u=void 0===r.hostMcpBridgeUrls?void 0:r.hostMcpBridgeUrls.filter((e=>{let t;try{t=new URL(e)}catch{t=void 0}const r=void 0!==t&&"http:"===t.protocol&&""===t.username&&""===t.password&&eB.has(t.hostname);return r||console.warn(`[cursor-sdk] ignoring local.hostMcpBridgeUrls entry ${e}: not an http URL on 127.0.0.1, localhost or [::1]`),r}));!function(e){if(void 0!==e&&(!Number.isFinite(e)||e<=0))throw new Error(`Workspace scan cache TTL must be a positive number of milliseconds, got ${e}`);la=e}((0,HU.Mu)()),/:\/\/(localhost|127\.0\.0\.1)/.test(jU.EV)&&(process.env.NODE_TLS_REJECT_UNAUTHORIZED="0");const d=performance.now();let h=0;if(r.apiKey){const e=performance.now();await Promise.all([(0,jU.ly)(r.apiKey),(0,jU.mU)(r.apiKey)]),h=performance.now()-e}const p=r.workingDirectory||process.cwd();(0,BU.configureVendoredTreeSitterWorkspaceDir)(p);for(const e of r.dirs??[])(0,BU.configureVendoredTreeSitterWorkspaceDir)(e);const f=(0,uo.Rv)((0,o.homedir)(),p),m={hostProjectDir:f,settings:{includeProjectRules:ij(c,"project"),subagentsService:new wj(r.customSubagents??[])}};let g;const w="win32"===process.platform?"rg.exe":"rg",v=process.env.CURSOR_RIPGREP_PATH;g=v&&(0,s.isAbsolute)(v)?v:(0,WU.hQ)({binaryName:w,excludedWorkspaceDir:p}),g||(g=(0,Eo.xS)()),g&&(0,Eo.J)(g);let b,S,k={getDotCursorProtection:async()=>!1,getShouldBlockMcp:async()=>!1,getDeleteFileProtection:async()=>!1,getIsHeadlessDisabled:async()=>!1,isServerBlocked:async()=>!1,getTeamRepos:async()=>{},getAutoRunControls:async()=>({enabled:!1,allowed:[],blocked:[],enableAllowlistMode:!0,enableRunEverything:!1,enableSmartAuto:!0,mcpToolAllowlist:[]}),getAdminCommandDenylist:async()=>({rules:[]}),getMcpToolControls:async()=>{},getNetworkAccessControls:async()=>({allowlist:[],denylist:[],available:!0}),getMcpNetworkControlsConfig:async()=>({enabled:!1}),getDefaultNetworkAllowlist:async()=>({allowlist:[],available:!0}),getSandboxingControls:async()=>({sandboxingDisabled:!1,networkingDisabled:!1,gitDisabled:!1}),isAttributionDisabledByAdmin:async()=>!1,invalidateCache:()=>{}};if(r.apiKey)try{b=(0,jU.KU)(r.apiKey,r.teamId);const e=(0,ye.createClient)(iN.I,b),t=function(e){let t=VU.get(e);return t||(t=KU(e),VU.set(e,t),t.then((r=>{r===GU&&VU.get(e)===t&&VU.delete(e)}),(()=>{VU.get(e)===t&&VU.delete(e)}))),t}(r.apiKey);S=t;const n={getDefaultNetworkAllowlist:async()=>(await t).getDynamicConfigValue({configName:"sandbox_default_network_allowlist",paramName:"allowlist",defaultValue:[]})};k=new uM(new aM(e,{supportsHostMcpBridgeExemption:!0}),n,{...void 0===u?{}:{hostMcpBridgeUrls:u},isMcpAccessNetworkAllowlistEnabled:async()=>(await t).checkFeatureGate("mcp_access_network_allowlist"),isMcpSettingsOverhaulEnabled:async e=>(await t).checkFeatureGate("mcp_settings_overhaul",e),isWin32UserExtensionStdioUnsandboxEnabled:async e=>(await t).checkFeatureGate("mcp_user_extension_stdio_unsandboxed_win32",e),isAdminCommandDenylistEnforcementKilled:async()=>(await t).checkFeatureGate("admin_command_denylist_enforcement_killswitch")})}catch(e){zU.v.log(`Failed to initialize authenticated dashboard services: ${e instanceof Error?e.message:String(e)}`)}const _=performance.now(),C=r.apiKey?await(0,Eo.tv)(`${(0,o.homedir)()}/.cursor/sandbox.json`,(0,o.homedir)()):void 0,E=void 0!==r.apiKey?await async function(e){const{cwd:t,perUserSandboxPolicy:r,sandboxOptions:n}=e;if(!1===n?.enabled)return{defaultSandboxPolicy:{type:"insecure_none"},defaultSandboxPolicySources:void 0};const o=aB(r)?r:!0===n?.enabled?function(e,t={}){return{type:e,...t}}("workspace_readwrite",{networkPolicy:(0,Eo.Po)()}):void 0;if(void 0===o)return{defaultSandboxPolicy:{type:"insecure_none"},defaultSandboxPolicySources:void 0};if(function(e){const t="win32"===process.platform?"cursorsandbox.exe":"cursorsandbox",r=(0,WU.hQ)({binaryName:t,excludedWorkspaceDir:e});r&&(0,Eo.St)({sandboxBinaryPath:r})}(t),!(0,Eo.K3)(void 0,{ctx:e.initializationCtx}))throw new vU.j1("Local SDK sandboxing was requested, but sandboxing is not supported in this environment. Disable local.sandboxOptions.enabled or remove ~/.cursor/sandbox.json to run without sandboxing.",{isRetryable:!1});const s={};s.perUser=o;const{policy:i}=await(0,Eo.resolveSandboxPolicyForWorkspace)(t,s);return{defaultSandboxPolicy:i,defaultSandboxPolicySources:s}}({cwd:p,perUserSandboxPolicy:C,sandboxOptions:r.sandboxOptions,initializationCtx:a}):void 0,x=performance.now()-_,P=E?.defaultSandboxPolicy,I=E?.defaultSandboxPolicySources,R=aB(P),T=performance.now(),A=(()=>{const e=[],t=new Set;for(const n of[p,...r.dirs??[]]){const r=(0,s.resolve)(n);t.has(r)||(t.add(r),e.push(n))}return e.length>1?e:void 0})(),M={powershellUtf8Console:!1,powershellUtf8ChildEnv:!1},D=await async function(e){const{workingDirectory:t,projectDir:r}=e,n=function(e,t){const r=[],n=new Set;for(const o of[e,...t??[]]){const e=(0,s.resolve)(o);n.has(e)||(n.add(e),r.push(o))}return r}(t,e.dirs),o=n.length>1?n:void 0,i=sj(e.settingSources),a=e.teamSettingsService??{getDotCursorProtection:async()=>!1,getShouldBlockMcp:async()=>!1,getDeleteFileProtection:async()=>!1,getIsHeadlessDisabled:async()=>!1,isServerBlocked:async()=>!1,getTeamRepos:async()=>{},getAutoRunControls:async()=>({enabled:!1,allowed:[],blocked:[],enableAllowlistMode:!0,enableRunEverything:!1,enableSmartAuto:!0,mcpToolAllowlist:[]}),getAdminCommandDenylist:async()=>({rules:[]}),getMcpToolControls:async()=>{},getNetworkAccessControls:async()=>({allowlist:[],denylist:[],available:!0}),getMcpNetworkControlsConfig:async()=>({enabled:!1}),getDefaultNetworkAllowlist:async()=>({allowlist:[],available:!0}),getSandboxingControls:async()=>({sandboxingDisabled:!1,networkingDisabled:!1,gitDisabled:!1}),isAttributionDisabledByAdmin:async()=>!1,invalidateCache:()=>{}},c=e.defaultSandboxPolicy??{type:"insecure_none"},l=e.getSandboxSupported??(()=>(0,Eo.K3)(c,{ctx:e.initializationCtx})),u=e.getSandboxEnabled??(()=>"insecure_none"!==c.type&&l()),d=new dw,h=new za(d,a,n),p=new fj,f=new mj,m=e.getSmartModeClassifierAutoModeEnabled?.(),g=new pj(m?"allowlist":e.approvalMode??"unrestricted",c,a,e.respectAdminControls??!1),w=e.pendingDecisionProvider,y={executeIndexedGrep:void 0},v=()=>!0,b=ij(i,"plugins"),S=e.importThirdPartyPlugins??!1,k=e.mcpMetaToolEnabled??!0,_=void 0!==e.mcpServers&&Object.keys(e.mcpServers).length>0,C=void 0!==e.customSubagents&&e.customSubagents.length>0,E=_||ij(i,"project")||ij(i,"user")||b,x=ij(i,"project")||ij(i,"user")||ij(i,"mdm"),P=ij(i,"team"),I=P&&void 0!==e.dashboardTransport,R=ij(i,"project")||ij(i,"user")||P||I||b,T={teamSettingsService:a,initializationCtx:e.initializationCtx,importThirdPartyPlugins:S,ignoreApprovals:!0,includeProjectMcp:ij(i,"project"),includeUserMcp:ij(i,"user"),includePluginMcp:b,isLinkSharedPaymentTokenLogRedactionEnabled:e.isLinkSharedPaymentTokenLogRedactionEnabled},A=s=>dj({workingDirectory:t,...void 0!==o?{workspaceRoots:o}:{},adapters:{...s.includeMcp?{mcp:jM({...T,inlineMcpServers:e.mcpServers})}:{},...b?{pluginBootstrap:jL({importThirdPartyPlugins:S,dashboardTransport:e.dashboardTransport})}:{},...x?{hooks:sN({includeProjectHooks:ij(i,"project"),includeUserHooks:ij(i,"user"),includeEnterpriseHooks:ij(i,"mdm"),useCommandHookStdinTransport:e.useCommandHookStdinTransport})}:{},...R?{localExtensibility:cN({includeProjectExtensibility:ij(i,"project"),includeUserExtensibility:ij(i,"user"),includeManagedSkills:I,includeTeamExtensibility:P,includePluginExtensibility:b,teamSettingsService:a,getThirdPartyExtensibilityEnabled:v,dashboardTransport:e.dashboardTransport,importThirdPartyPlugins:S})}:{},resourceFactory:JL({ignoreService:h,grepProvider:y,workspacePaths:n,diagnosticsProvider:p,repositoryProvider:f,projectDir:r??t,shellManager:void 0,defaultSandboxPolicy:c,defaultSandboxPolicySources:e.defaultSandboxPolicySources,getSandboxEnabled:u,getSandboxSupported:l,getNetworkAllowlistInfo:e.getNetworkAllowlistInfo,getSmartModeClassifierAutoModeEnabled:e.getSmartModeClassifierAutoModeEnabled,devForceNextSmartModeClassifierBlockToken:e.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:e.getMockPromptTime,getPowershellUtf8Options:e.getPowershellUtf8Options,mcpFileOutputThresholdBytes:void 0,mcpMetaToolEnabled:k,createMcpStateAccessor:e=>new gj(new lA(e)),createSessionMcpLease:(t,r)=>jM({...T,includeProjectMcp:T.includeProjectMcp&&!0!==t.options.excludeProjectMcp,inlineMcpServers:r??e.mcpServers}).createLease({workspaceState:t.workspaceState,services:t.workspaceServices,policy:t.policy}),createSessionDependencies:r=>{const n=w??new hj;return{pendingDecisionStore:n,fileChangeTracker:new Rg(t),permissionsService:new xS(h,n,g,a,t,e.respectAdminControls??!1,{enforceMcpAdminToolLimits:e.isMcpAdminToolLimitEnforced,onMcpAdminToolLimitCheck:r.options.onMcpAdminToolLimitCheck})}}}),resourceWrappers:x?[{wrapResources(e){const t=e.workspaceServices.hooksRuntime;if(!0===e.options.excludeHooks||"object"!=typeof(r=t)||null===r||!("hooksConfigLease"in r)||!("createSessionRuntime"in r)||"function"!=typeof r.createSessionRuntime||!function(e){return"object"==typeof e&&null!==e&&"get"in e&&"function"==typeof e.get&&"entries"in e&&"function"==typeof e.entries}(e.resources))return e.resources;var r;const n=t.createSessionRuntime({sessionState:e.sessionState,metadata:e.metadata});return new nN(new ZF(e.resources,n.hookExecutor,(()=>function(e,t){const r=YF(t,eN,"conversationId","conversation_id")??e.sessionId??"";return{conversation_id:r,generation_id:YF(t,eN,"generationId","generation_id")??r,model:YF(t,eN,"model")??"unknown",...oD({modelId:YF(t,eN,"modelId","model_id"),modelParams:YF(t,rN,"modelParams","model_params")})}}(e.sessionState,e.metadata)),e.workspaceServices.mcpLease,void 0,void 0,t.hooksConfigLease),n)}}]:[],...C?{workspaceServicesContributors:[{contributeServices:t=>{const r=new wj(e.customSubagents??[]),n=t.services.subagentsService;return{subagentsService:void 0===n?r:new vm([r,n])}}}]}:{}}});if(!E)return A({includeMcp:!1});try{return await A({includeMcp:!0})}catch(e){return mM.Jz.warn("[default-local-workspace-runtime] Failed to initialize MCP-enabled runtime, retrying without MCP:",{error:e,workingDirectory:t,projectDir:r,enablePlugins:b,importThirdPartyPlugins:S}),A({includeMcp:!1})}}({workingDirectory:p,...void 0!==A?{dirs:A}:{},projectDir:f,teamSettingsService:k,initializationCtx:a,dashboardTransport:b,settingSources:r.settingSources,mcpServers:r.mcpServers,customSubagents:r.customSubagents,defaultSandboxPolicy:P,defaultSandboxPolicySources:I,approvalMode:R?"allowlist":void 0,pendingDecisionProvider:R||!0===r.autoReview?new sB:void 0,getNetworkAllowlistInfo:R?()=>async function(e,t,r){const[n,o]=await Promise.all([e.getDefaultNetworkAllowlist(),e.getNetworkAccessControls()]),s=[...o.allowlist],i=`${t}/.cursor/sandbox.json`,a=await(0,Eo.tv)(i,t);if(a&&"insecure_none"!==a.type&&a.networkPolicy?.allow&&s.push(...a.networkPolicy.allow),r){const e=`${r}/.cursor/sandbox.json`,t=await(0,Eo.tv)(e,r);t&&"insecure_none"!==t.type&&t.networkPolicy?.allow&&s.push(...t.networkPolicy.allow)}const c=[...new Set(s)];return{hasDefaults:n.available&&n.allowlist.length>0,explicitEntries:c}}(k,(0,o.homedir)(),p):void 0,getSmartModeClassifierAutoModeEnabled:()=>!0===r.autoReview,devForceNextSmartModeClassifierBlockToken:r.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:rB,getPowershellUtf8Options:async()=>{if(void 0===S)return M;try{const e=await S;return{powershellUtf8Console:e.checkFeatureGate("shell_exec_powershell_utf8_console"),powershellUtf8ChildEnv:e.checkFeatureGate("shell_exec_powershell_utf8_child_env")}}catch{return M}},isLinkSharedPaymentTokenLogRedactionEnabled:ZU(S),respectAdminControls:void 0!==r.apiKey,isMcpAdminToolLimitEnforced:void 0===S?void 0:(O=S,async()=>{try{return(await O).checkFeatureGate("sdk_local_mcp_admin_tool_limits",{disableExposureLog:!0})}catch{return!1}}),useCommandHookStdinTransport:!0});var O;const F=performance.now()-T;let N,L;return(0,Oj.ou)(r.apiKey,{runtime:"local",ensure_ghost_mode_ms:Math.round(h),bootstrap_statsig_ms:0,create_workspace_runtime_ms:Math.round(F),load_sandbox_policy_ms:Math.round(x),total_ms:Math.round(performance.now()-d)}),{run:async(e,t,o)=>(0,mM.ni)(nB,(async()=>{const s=(0,$.VI)((0,y.q6)().withName("sdk.run").with(l._O,oB)),[a,c]=s.ctx.withCancel(),u=t.sessionId??(0,ge.C)(),d=t.mcpServersOverride,h=void 0===(f=t.customTools)?[]:Object.entries(f).map((([e,t])=>({clientKey:Nn,providerIdentifier:Nn,toolName:e,name:`${Nn}-${e}`,description:t.description??"",inputSchema:t.inputSchema??mU,...void 0===t.outputSchema?{}:{outputSchema:t.outputSchema},...void 0===t.annotations?{}:{annotations:gU(t.annotations)},source:"internal"})));var f;let g;const w={...m,workspace:t.fileSystemWorkspace},v=void 0===t.fileSystem?void 0:(k=await async function(e,t){return"function"==typeof e?await e(t):e}(t.fileSystem,{agentId:u,sessionId:u}),_=k,(0,CU.VL)({"/":_,[PU]:(0,EU.Om)()})),b=void 0===t.onMcpAdminToolLimitCounts?void 0:new UU,S=()=>{for(const e of b?.take()??[])try{t.onMcpAdminToolLimitCounts?.(e)}catch{}};var k,_;g=await D.createSessionRuntime({sessionId:u,mcpServersOverride:d,extraMcpTools:h,onMcpAdminToolLimitCheck:b?.record,...void 0===v?tB(t.sessionResources):LU(v,w)});const C=new Map;try{const s=g.resources.wrapped;YU(g,t.customTools),void 0!==v&&kU(g.resources.base);const l=t.blobStore??new re.ve;let f=t.initialState??new i.Y9z({});const m=void 0!==t.model?new Mj.G4({modelId:t.model.id,...!0===t.model.maxMode?{maxMode:!0}:{},parameters:(t.model.params??[]).map((e=>new Mj.SR({id:e.id,value:e.value})))}):void 0,y=!0===e.summarize?void 0:e.images,k=Array.isArray(y)?y.map((e=>{const t=(0,ge.C)(),r=new Uint8Array(n.Buffer.from(e.data,"base64")),o=(0,jU.v8)(r);return new Dj.d({uuid:t,...o?{mimeType:o}:{},dataOrBlobId:{case:"data",value:r}})})):[],_=k.length>0?new Dj.xv({selectedImages:k}):void 0,P=function(e){switch(e){case"agent":return i.xyI.AGENT;case"plan":return i.xyI.PLAN;default:return}}(t.mode),I=!0===e.summarize?new i.QFf({action:{case:"summarizeAction",value:new i.Scs}}):new i.QFf({action:{case:"userMessageAction",value:new i.Vtf({userMessage:new i.RGk({text:e.text,selectedContext:_,...void 0!==P?{mode:P}:{}})})}}),R={sendUpdate:async(e,t)=>{const r=Hj(t,u);null!==r&&await o.sendUpdate(r)},query:async(e,t)=>function(e){switch(e.query.case){case"webSearchRequestQuery":return ur(e.id);case"webFetchRequestQuery":return hr(e.id);case"switchModeRequestQuery":return mr(e.id);case"askQuestionInteractionQuery":return fr(e.id,new Qt.tz({result:{case:"rejected",value:new Qt.ox({reason:"Interactive questions are not supported in local SDK runs"})}}));case"createPlanRequestQuery":return wr(e.id,new Yt.bK({result:{case:"success",value:new Yt.Jo},planUri:""}));case"setupVmEnvironmentArgs":return yr(e.id,new rr.r$({result:{case:"success",value:new rr.JH}}));case"replaceEnvArgs":return vr(e.id,new tr.dV({result:{case:"failure",value:new tr.uq({errorMessage:"Environment replacement is not supported in local SDK runs",setupLogs:""})}}));case"prManagementRequestQuery":return br(e.id,new er.HL({result:{case:"error",value:new er.K$({error:"PR management is only available in cloud agents"})}}));case"mcpAuthRequestQuery":return Sr(e.id,"MCP authentication is not supported in local SDK runs");case"connectScmRequestQuery":return kr(e.id,"Connecting GitHub is not supported in local SDK runs");case"generateImageRequestQuery":return _r(e.id,e.query.value.args?.description);case void 0:throw new vU.j1("Missing interaction query type",{isRetryable:!1});default:throw e.query,new vU.j1("Unhandled interaction query type",{isRetryable:!1})}}(t)};if(N!==t.apiKey||!L){await Promise.all([(0,jU.ly)(t.apiKey),(0,jU.mU)(t.apiKey)]);const e=(0,jU.KU)(t.apiKey,r.teamId),n=co((0,ye.createClient)($j.N,e),{injectTraceHeaders:!0});L=new Dn(n),N=t.apiKey}const T=(0,jU.Vh)(L,(()=>{const e=(0,jU.KU)(t.apiKey,r.teamId),n=co((0,ye.createClient)($j.N,e),{injectTraceHeaders:!0}),o=new Dn(n);return L=o,N=t.apiKey,o})),A=function(e){return{...void 0!==e.allowedTools?{[XU.$$]:e.allowedTools.join(",")}:{},...void 0!==e.disallowedTools&&e.disallowedTools.length>0?{[XU.VJ]:e.disallowedTools.join(",")}:{}}}(t),$=new Aj({agentClient:T,getResources:async({agentId:e})=>{let r=C.get(e);return r||(r=await D.createSessionRuntime({sessionId:e,mcpServersOverride:d,extraMcpTools:h,onMcpAdminToolLimitCheck:b?.record,...void 0===v?tB(t.subagentInherit):LU(v,w)}),YU(r,t.customTools),void 0!==v&&kU(r.resources.base),r.resources.base.register(Qn,M),r.resources.base.register(Yn,O),r.resources.base.register(eo,F),C.set(e,r)),r.resources.wrapped},mcpTools:h,workspacePath:p,parentConversationId:u,...(void 0!==t.subagentInherit||void 0!==v)&&Object.keys(A).length>0?{headers:A}:{},onSessionReleased:e=>{const t=C.get(e);t&&(t.dispose(),C.delete(e))}}),M=function(e){const t=new Map,r=new Map;async function n(t,r,n){let o;try{o=await e.createOrResumeSession(t,r);const s=await e.runSession(t,o,r,{execId:n?.execId});return"error"===s.status?new Zn.vS({result:{case:"error",value:new Zn.od({agentId:o,error:s.error})}}):"aborted"===s.status?new Zn.vS({result:{case:"error",value:new Zn.od({agentId:o,error:s.error??"Subagent was aborted by the user"})}}):"background"===s.status?new Zn.vS({result:{case:"success",value:new Zn.HJ({agentId:o,finalMessage:s.finalMessage,toolCallCount:s.toolCallCount??0,backgroundReason:s.backgroundReason,transcriptPath:s.transcriptPath})}}):new Zn.vS({result:{case:"success",value:new Zn.HJ({agentId:o,finalMessage:s.finalMessage,toolCallCount:s.toolCallCount??0})}})}catch(t){if(o&&e.releaseSession&&e.releaseSession(o),t instanceof lr)throw t;const n=t instanceof Error?t.message:String(t),s=o??function(e){return e instanceof Xn&&e.agentId||e&&"object"==typeof e&&"agentId"in e&&"string"==typeof e.agentId?e.agentId:void 0}(t)??r.resumeAgentId;return new Zn.vS({result:{case:"error",value:new Zn.od({...s?{agentId:s}:{},error:n})}})}}return{execute(e,o,s){const i=function(e){if(e.toolCallId&&e.parentConversationId)return[e.parentConversationId,e.toolCallId,e.resumeAgentId??"",e.forkAgentId??""].join("\0")}(o);if(void 0===i)return n(e,o,s);const a=r.get(i);if(void 0!==a)return Promise.resolve(a);const c=t.get(i);if(void 0!==c)return c;const l=n(e,o,s).then((e=>("success"===e.result.case&&(r.set(i,e),r.size>1e3&&r.delete(r.keys().next().value)),e))).finally((()=>{t.delete(i)}));return t.set(i,l),l}}}($),O=(x=$,{execute:(e,t)=>x.awaitBackgroundRunBounded(e,t)}),F=function(e){return{execute:async(t,r)=>e.forceBackgroundByToolCallId(r.toolCallId)}}($);g.resources.base.register(Qn,M),g.resources.base.register(Yn,O),g.resources.base.register(eo,F);const j=D.services.hooksRuntime,U="object"==typeof(E=j)&&null!==E&&"workspacePath"in E&&"string"==typeof E.workspacePath&&"createSessionRuntime"in E&&"function"==typeof E.createSessionRuntime?j:void 0,B=void 0!==U&&void 0===v&&!0!==e.summarize?function(e){const{workspaceRuntime:t}=e;if(!(t.hooksConfigLease.hasHookForStep(Nu.sessionStart)||t.hooksConfigLease.hasHookForStep(Nu.sessionEnd)||t.hooksConfigLease.hasHookForStep(Nu.stop)||t.hooksConfigLease.hasHookForStep(Nu.beforeSubmitPrompt)))return{};const r=t.createSessionRuntime({sessionState:e.sessionState,metadata:e.metadata}),{hookExecutor:n}=r;let o;return{async onSessionStart(e){if(o=e,n.hasHooksForStep(Nu.sessionStart))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...oD(e),is_background_agent:!1},r=await n.executeHookForStep(Nu.sessionStart,t);if(r)return r.env&&n.setSessionEnvironment(r.env),{env:r.env,additionalContext:r.additional_context,blocked:!1===r.continue,blockedReason:r.user_message}}catch(e){mM.Jz.warn("[hooks-adapter] sessionStart hook failed:",e)}},async onSessionEnd(e,t){if(n.hasHooksForStep(Nu.sessionEnd))try{const r={conversation_id:o?.conversationId??"",generation_id:o?.generationId??"",model:o?.model??"unknown",...o?oD(o):{},reason:e,duration_ms:t,is_background_agent:!1,final_status:e};await n.executeHookForStep(Nu.sessionEnd,r)}catch(e){mM.Jz.warn("[hooks-adapter] sessionEnd hook failed:",e)}finally{n.clearSessionEnvironment()}else n.clearSessionEnvironment()},async onBeforeSubmitPrompt(e){if(n.hasHooksForStep(Nu.beforeSubmitPrompt))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...oD(e),prompt:e.promptText??"",attachments:[]};await n.executeHookForStep(Nu.beforeSubmitPrompt,t)}catch(e){mM.Jz.warn("[hooks-adapter] beforeSubmitPrompt hook failed:",e)}},async onTurnCompleted(e){if(!n.hasHooksForStep(Nu.stop))return;const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...oD(e),status:"completed",loop_count:e.loopCount},r=await n.executeHookForStep(Nu.stop,t),o="string"==typeof r?.followup_message?r.followup_message.trim():"";return o.length>0?o:void 0},async onTurnError(e){if(n.hasHooksForStep(Nu.stop))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...oD(e),status:"error",loop_count:e.loopCount};await n.executeHookForStep(Nu.stop,t)}catch(e){mM.Jz.warn("[hooks-adapter] onTurnError stop hook failed:",e)}},async onTurnAborted(e){if(n.hasHooksForStep(Nu.stop))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...oD(e),status:"aborted",loop_count:e.loopCount};await n.executeHookForStep(Nu.stop,t)}catch(e){mM.Jz.warn("[hooks-adapter] onTurnAborted stop hook failed:",e)}},async dispose(){await r.dispose()}}}({workspaceRuntime:U,sessionState:g.state,metadata:g.metadata}):void 0,W=new Ij({workspacePath:p,conversationId:u,blobStore:l}),H=function(e,t,r){const{hooks:n}=r,[o,s]=e.withCancel(),a=new fM;let c;const l=new Map,u=(e,t)=>{const r=l.get(e);void 0!==r&&(l.delete(e),clearTimeout(r.ackTimer),r.resolve(t))};let d;const h=[],p=e=>{for(const t of h.splice(0))t.resolve(e)},f=()=>{if(0===h.length)return;const e=h.map((e=>e.text)).join("\n\n");return p("complete_delivered"),kM(e)},m=r.interactionListener,g={async sendUpdate(e,t){const r=t.message;if("contextInjectionState"===r?.case){const e=r.value,t="object"==typeof e&&null!==e&&"injectionId"in e&&"string"==typeof e.injectionId?e.injectionId:void 0,n=function(e){if("object"!=typeof e||null===e||!("state"in e))return;const t=e.state;if("object"!=typeof t||null===t||!("state"in t))return;const r=t.state;return"object"==typeof r&&null!==r&&"case"in r&&"string"==typeof r.case?r.case:void 0}(e),o=function(e){switch(e){case"queued":return"queued";case"delivered":return"delivered";case"queuedForNextTurn":return"queued_for_next_turn";case"cancelled":return"cancelled";default:return"rejected"}}(n),s=void 0===t?void 0:l.get(t);if(void 0!==s&&void 0!==t){const e=function(e){switch(e){case"queued":return"confirm_steering";case"delivered":return"complete_delivered";case"queued_for_next_turn":case"cancelled":case"rejected":return"revert_to_followup";default:throw new Error(`Unknown steer ack state: ${String(e)}`)}}(o);"confirm_steering"===e?clearTimeout(s.ackTimer):(l.delete(t),s.resolve(e))}}await m.sendUpdate(e,t)},query:(e,t)=>m.query(e,t),...void 0!==m.enqueuePostTurnEndedWork?{enqueuePostTurnEndedWork:e=>m.enqueuePostTurnEndedWork?.(e)}:{},...void 0!==m.flushPostTurnEndedWork?{flushPostTurnEndedWork:e=>m.flushPostTurnEndedWork?.(e)??Promise.resolve()}:{}};let w=r.initialState;const y={async handleCheckpoint(e,t){w=t,await(r.onCheckpoint?.(t))},getLatestCheckpoint:()=>w};let v="completed";const b=Date.now(),S=yM(function(e,t){if((0,gM.TU)(t))return t;const r=vM.get(e);if(void 0!==r)return r;const n=(0,gM.sh)(e).blobEncryptionKey;if(void 0===n)throw new Error("getDefaultAgentMetadata did not seed a blobEncryptionKey");return vM.set(e,n),n}(r.conversationId,r.blobEncryptionKey),r.runOptions?.headers);return{done:(async()=>{const e=SM(r,0,bM(t));try{const t=await(n?.onSessionStart?.(e));if(t?.blocked)throw v="error",new Error(t.blockedReason??"Session blocked by sessionStart hook")}catch(e){if("completed"!==v)throw e;mM.Jz.warn("[agent-session-runner] sessionStart hook failed:",e)}let s=t,i=0;for(;s;){const e=SM(r,i,bM(s));try{await(n?.onBeforeSubmitPrompt?.(e))}catch(e){mM.Jz.warn("[agent-session-runner] beforeSubmitPrompt hook failed:",e)}c=r.runOptions?.generationUUID??(0,ge.C)();try{await r.agentClient.run(o,w,s,void 0,g,r.resources,r.blobStore,a,y,r.mcpTools??[],{conversationId:r.conversationId,...r.runOptions,generationUUID:c,headers:S,subagentModelOverrides:r.runOptions?.subagentModelOverrides??[]})}catch(t){throw v=_M(t)?"aborted":"error",CM("aborted"===v?n?.onTurnAborted?.(e):n?.onTurnError?.(e)),t}finally{c=void 0;for(const e of[...l.keys()])u(e,"revert_to_followup")}let t;try{t=await(n?.onTurnCompleted?.(e))}catch(e){throw v="error",e}const h="string"==typeof t?t.trim():"";let m;if(h.length>0)m=kM(h);else{const t=new AbortController;d=t;try{m=await(r.nextAction?.(e,AbortSignal.any([o.signal,t.signal])))}catch(r){if(o.signal.aborted||!t.signal.aborted)throw v=o.signal.aborted||_M(r)?"aborted":"error",CM("aborted"===v?n?.onTurnAborted?.(e):n?.onTurnError?.(e)),r}finally{d=void 0}void 0===m?m=f():p("revert_to_followup")}void 0!==m?(i+=1,a.resetStream(),s=m):s=void 0}})().finally((async()=>{p("revert_to_followup");const e=Date.now()-b;try{await(n?.onSessionEnd?.(v,e))}catch(e){mM.Jz.warn("[agent-session-runner] sessionEnd hook failed:",e)}try{await(n?.dispose?.())}catch(e){mM.Jz.warn("[agent-session-runner] hooks dispose failed:",e)}})),abort(){s()},async steer(e){if(""===e.trim())return"revert_to_followup";const t=c;if(void 0===t){const t=d;if(void 0===t)return"revert_to_followup";const r=new Promise((t=>{h.push({text:e,resolve:t})}));return t.abort(),await r}const r=(0,ge.C)(),n=new Promise((e=>{const t=setTimeout((()=>{u(r,"revert_to_followup")}),15e3);t.unref?.(),l.set(r,{resolve:e,ackTimer:t})}));try{return await a.submitConversationAction(new i.QFf({action:{case:"injectContextAction",value:new i.hGJ({injectionId:r,expectedRunId:t,payload:{case:"userContext",value:new i.oW$({userMessage:new i.RGk({messageId:(0,ge.C)(),text:e})})}})}})),await n}catch(e){return u(r,"revert_to_followup"),mM.Jz.warn("[agent-session-runner] context injection failed:",e),"revert_to_followup"}}}}(a,I,{agentClient:T,interactionListener:R,resources:s,blobStore:l,initialState:f,conversationId:u,mcpTools:h,blobEncryptionKey:t.blobEncryptionKey,runOptions:{generationUUID:t.requestId,requestedModel:m,enableAgentRetries:!1!==r.enableAgentRetries,emitModelCallUsage:!0,...Object.keys(A).length>0?{headers:A}:{},...void 0!==t.systemPrompt?{customSystemPrompt:t.systemPrompt}:{}},hooks:B,async nextAction(e,t){const r=await $.waitForBackgroundCompletions(u,t);return r.length>0?function(e){return new i.QFf({action:{case:"backgroundTaskCompletionAction",value:new i.Kwc({completions:e.map((e=>new i.KFq({taskId:e.agentId,kind:i.aZc.SUBAGENT,status:"success"===e.status?i.uHL.SUCCESS:"aborted"===e.status?i.uHL.ABORTED:i.uHL.ERROR,...e.finalMessage.length>0?{detail:e.finalMessage}:{}})))})}})}(r):void 0},async onCheckpoint(e){f=e,W.writeFromState(a,e),await(t.onCheckpoint?.(e))}}),q=H.done.finally((async()=>{try{await $.awaitBackgroundWorkers()}finally{await W.waitForPendingWrites().catch((()=>{}));for(const e of C.values())try{await e.dispose()}catch(e){zU.v.log(`Failed to dispose subagent session runtime: ${e instanceof Error?e.message:String(e)}`)}C.clear();try{await g.dispose()}finally{S()}}})).catch((e=>{throw e}));return{abort(){H.abort(),c()},done:q,steer:e=>H.steer(e)}}catch(e){for(const e of C.values())try{await e.dispose()}catch{}C.clear();try{await g.dispose()}finally{S()}throw e}var E,x})),async reload(){await D.reload()},async dispose(){await D.dispose()}}}},"./src/agent/native/tree-sitter-bash.webpack.cjs"(e,r,n){const{loadVendoredTreeSitterModule:o}=n("./src/agent/native/vendored-tree-sitter.ts"),s=o({packageName:"tree-sitter-bash",nativeRequire:t});e.exports=s.available?s.module:{}},"./src/agent/native/tree-sitter.webpack.cjs"(e,r,n){const{createUnavailableParserClass:o,loadVendoredTreeSitterModule:s}=n("./src/agent/native/vendored-tree-sitter.ts"),i=s({packageName:"tree-sitter",nativeRequire:t});e.exports=i.available?i.module:o(i.reason)},"../context/dist/otel.js"(e,t,r){r.d(t,{F:()=>E,HF:()=>_,MG:()=>k,Mf:()=>v,OA:()=>y,V5:()=>C,VI:()=>P,fR:()=>g,fU:()=>w,mJ:()=>b,r2:()=>x,xd:()=>I});var n=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/span_kind.js"),o=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/context-api.js"),s=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace-api.js"),i=r("../context/dist/core.js");const a=(0,i.cF)(Symbol("otel.span"),void 0),c=(0,i.cF)(Symbol("otel.root_span"),void 0),l=(0,i.cF)(Symbol("otel.root_start_ms"),void 0),u=(0,i.cF)(Symbol("otel.suppress_child_spans"),!1),d=(0,i.cF)(Symbol("otel.inheritable_span_attributes"),{});function h(e,t){const r=t.get(d);for(const t in r){const n=r[t];"string"!=typeof n&&"number"!=typeof n&&"boolean"!=typeof n||e.setAttribute(t,n)}}function p(e){return e.name||"anonymous-context"}function f(e,t){return!!t&&(e.get(u)||(p(e),!1))}function m(e="context-tracer"){return s.u.getTracer(e)}function g(e,t){const r=m(),n=e.get(a);if(f(e,n))return e;const i=p(e);let u;if(n){const e=s.u.setSpan(o._.active(),n);u=r.startSpan(i,t,e)}else u=r.startSpan(i,t);h(u,e);const d=Date.now();let g=e.with(a,u);return n||(g=g.with(c,u).with(l,d)),g}function w(e){return e.get(a)}function y(e){return e.with(u,!0)}function v(e,t,r){const n=e.get(d),o=w(e);return o&&null!==r&&o.setAttribute(t,r),e.with(d,{...n,[t]:r})}function b(e){try{const t=w(e);if(!t)return;const r=t.spanContext(),n=e.get(u);return{traceId:r.traceId,spanId:r.spanId,traceFlags:n?0:r.traceFlags,traceState:r.traceState?.serialize()}}catch{return}}const S=Symbol.for("anysphere.context.activeOtelSpanAls");function k(e,t){const r=()=>o._.with(s.u.setSpan(o._.active(),e),t),n=function(){const e=globalThis;if("object"!=typeof(t=e)||null===t||!(S in e))return;var t;const r=e[S];return function(e){return"object"==typeof e&&null!==e&&"run"in e&&"function"==typeof e.run&&"getStore"in e&&"function"==typeof e.getStore}(r)?r:void 0}();return void 0===n?r():n.run(e,r)}function _(e,t){try{const r=m(),n=w(e);if(!n)return;const i=s.u.setSpan(o._.active(),n),a=r.startSpan(t,void 0,i);h(a,e);const u=Date.now(),d=e.get(l),p="number"==typeof d?u-d:0,f=`event.${t}`;(e.get(c)??n).setAttribute(f,p),a.setAttribute(f,p),a.end()}catch{}}function C(e,t,r){const c=m(),l={traceId:e.traceId,spanId:e.spanId,traceFlags:e.traceFlags,isRemote:!0},u=s.u.setSpanContext(o._.active(),l),d=t||"child.span",h=c.startSpan(d,{kind:n.v.INTERNAL},u),p=r??(0,i.q6)();return(t?p.withName(t):p).with(a,h)}function E(e,t,r){const n=s.u.wrapSpanContext({traceId:e.traceId,spanId:e.spanId,traceFlags:e.traceFlags,isRemote:!0}),o=r??(0,i.q6)();return(t?o.withName(t):o).with(a,n)}class x{constructor(e,t,r=!0){this.ctx=e,this.span=t,this.shouldEnd=r}[Symbol.dispose](){this.shouldEnd&&this.span.end()}}function P(e,t){const r=f(e,w(e)),n=g(e,t),o=w(n);return new x(n,o,!r)}function I(e,t,r){const n=w(e);if(!n||f(e,n))return;const o=w(g(e,t));return o.end(r),o}},"../mcp-core/dist/transport/mcp-url-utils.js"(e,t,r){r.d(t,{$H:()=>Q,ME:()=>G,_N:()=>X,b6:()=>z,bi:()=>P,eA:()=>j,mD:()=>A,rM:()=>J,vc:()=>L});const n=BigInt(0),o=BigInt(8),s=BigInt(16),i=BigInt(65535);function a(e){const t=e.split(".");if(4!==t.length)return;let r=n;for(const e of t){if(!/^\d{1,3}$/.test(e))return;const t=Number(e);if(!Number.isInteger(t)||t<0||t>255)return;r=r<<o|BigInt(t)}return{version:4,value:r}}function c(e){if(0===e.length)return[];const t=[],r=e.split(":");for(let e=0;e<r.length;e++){const n=r[e];if(0===n.length)return;if(n.includes(".")){if(e!==r.length-1)return;const o=a(n);if(!o)return;t.push(Number(o.value>>s&i)),t.push(Number(o.value&i))}else{if(!/^[0-9a-f]{1,4}$/i.test(n))return;t.push(Number.parseInt(n,16))}}return t}function l(e){return a(e)??function(e){const t=H(e);if(0===t.length||t.includes(":::"))return;const r=t.indexOf("::");if(-1===r){const e=c(t);if(!e||8!==e.length)return;return{version:6,value:e.reduce(((e,t)=>e<<s|BigInt(t)),n)}}if(-1!==t.indexOf("::",r+1))return;const o=t.slice(0,r),i=t.slice(r+2),a=c(o),l=c(i);if(!a||!l)return;const u=a.length+l.length;return u>7?void 0:{version:6,value:[...a,...new Array(8-u).fill(0),...l].reduce(((e,t)=>e<<s|BigInt(t)),n)}}(e)}const u=new Map,d=new Map;function h(e,t){return function(e,t){switch(t.kind){case"matchAll":return!0;case"invalidCidr":return!1;case"cidr":{const r=function(e){if(d.has(e))return d.get(e);d.size>=I&&d.clear();const t=l(e);return d.set(e,t),t}(e);return void 0!==r&&r.version===t.version&&r.value>>t.shift===t.shiftedNetwork}case"subdomainOrBase":return e===t.suffix||e.endsWith(`.${t.suffix}`);case"exact":return e===t.value;default:return t}}(H(e),function(e){const t=u.get(e);if(t)return t;u.size>=I&&u.clear();const r=function(e){const t=H(e);if("*"===t)return{kind:"matchAll"};if(t.includes("/")){const e=t.lastIndexOf("/");if(e<=0||e===t.length-1)return{kind:"invalidCidr"};const r=l(t.slice(0,e));if(!r)return{kind:"invalidCidr"};const n=Number(t.slice(e+1)),o=4===r.version?32:128;if(!Number.isInteger(n)||n<0||n>o)return{kind:"invalidCidr"};const s=BigInt(o-n);return{kind:"cidr",version:r.version,shift:s,shiftedNetwork:r.value>>s}}return t.startsWith("*.")?{kind:"subdomainOrBase",suffix:t.slice(2)}:{kind:"exact",value:t}}(e);return u.set(e,r),r}(t))}new Set(["airtable.com","anysphere.co","api.aws","apify.com","asana.com","ashbyhq.com","atlassian.com","atlassian.net","azuredatabricks.net","box.com","buildkite.com","calendly.com","canva.com","clickhouse.cloud","clickup.com","cloudflare.com","composio.dev","context7.com","cursor.com","cursor.sh","cursorapi.com","databricks.com","datadoghq.com","datadoghq.eu","ddog-gov.com","dropbox.com","elevenlabs.io","exa.ai","figma.com","firecrawl.dev","github.com","githubcopilot.com","gitlab.com","google.com","googleapis.com","granola.ai","hex.tech","hubspot.com","huggingface.co","intercom.com","linear.app","monday.com","neon.tech","notion.com","plain.com","posthog.com","prisma.io","railway.com","ramp.com","render.com","salesforce.com","sentry.dev","sentry.io","slack.com","snowflakecomputing.com","spacelift.io","statsig.com","stripe.com","supabase.com","todoist.net","vercel.com","workos.com","x.ai","x.com","zapier.com"]);const p="Blocked by MCP Network Admin Server Controls";function f(e){return/\s/.test(e)}const m="[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?",g=new RegExp(`^(?:${m}\\.)*${m}$`),w=new RegExp(`^\\*\\.(?:${m}\\.)*${m}$`),y="(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)",v=new RegExp(`^${y}(?:\\.${y}){3}$`),b=/^[0-9a-f:]+$/,S=new RegExp(`^(?:${y}(?:\\.${y}){3}|[0-9a-f:]+)\\/\\d{1,3}$`);function k(e){const t=H(e);return t.length>0&&t.length<=253&&g.test(t)}function _(e){const t=H(e);return v.test(t)||function(e){const t=H(e);if(!b.test(t))return!1;try{return new URL(`https://[${t}]`),!0}catch{return!1}}(t)}function C(e,t){return""===t||"http:"===e&&"80"===t||"https:"===e&&"443"===t}function E(e){const t=new URL(e.pathname||"/",e.origin);if(t.search=e.search,t.pathname.endsWith("/")&&t.pathname.length>1&&(t.pathname=t.pathname.slice(0,-1)),"/"===t.pathname&&""===t.search){const t=e.protocol.toLowerCase();let r=`${t}//${e.hostname.toLowerCase()}`;return C(t,e.port)||(r+=`:${e.port}`),r}const r=e.protocol.toLowerCase();let n=`${r}//${e.hostname.toLowerCase()}`;return C(r,e.port)||(n+=`:${e.port}`),`${n}${t.pathname}${t.search}`}function x(e){if(e.includes("://"))return function(e){try{const t=new URL(e);return("http:"===t.protocol||"https:"===t.protocol)&&!(0===t.hostname.length||t.username.length>0||t.password.length>0)&&""===t.hash&&function(e){const t=e.toLowerCase();return!t.includes("*")&&(k(t)||_(t))}(t.hostname)}catch{return!1}}(e);const t=H(e);return"*"===t||!!w.test(t)||(t.includes("/")?function(e){const t=H(e);if(!S.test(t))return!1;const[r]=t.split("/");return void 0!==r&&h(r,t)}(t):k(t)||_(t))}function P(e){if(R.has(e))return R.get(e);R.size>=I&&R.clear();const t=function(e){const t=e.trim();if(0===t.length)return;const r=t.lastIndexOf("/");if(!t.includes("://")&&r>0&&/^\d+$/.test(t.slice(r+1).trim())){const e=`${H(t.slice(0,r))}/${t.slice(r+1).trim()}`;return x(e)?e:void 0}if(f(t)||t.includes("#")||t.includes("@"))return;const n=t.indexOf("://");if(-1!==n){const e=t.slice(0,n).toLowerCase();if("http"!==e&&"https"!==e)return;try{const e=new URL(t);if(0===e.hostname.length||e.username.length>0||e.password.length>0)return;const r="/"!==e.pathname&&""!==e.pathname,n=""!==e.search;if(e.hostname.includes("*"))return;if(r||n){const t=E(e);if(!x(t))return;return t}{const t=E(e);if(!x(t))return;return t}}catch{return}}else if(t.includes("/"))return;const o=t.trim().toLowerCase(),s=function(e){const t=e.indexOf(":");if(-1===t)return e;const r=e.slice(t+1);return/^\d+$/.test(r)?e.slice(0,t):e}(o);return 0===s.length||!x(s)||s!==o&&"*"===s?void 0:s}(e);return R.set(e,t),t}const I=2048,R=new Map,T=new Map;function A(e,t){if(!e.includes("*"))return e===t;const r=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${r}$`).test(t)}function $(e){return e.endsWith("/")&&e.length>1?e.slice(0,-1):e}function M(e,t){return function(e,t,r){const n=D(t);if(!n)return!1;let o;try{o=new URL(e)}catch{return!1}return""===o.username&&""===o.password&&""===n.username&&""===n.password&&o.protocol===n.protocol&&o.port===n.port&&(s=o.hostname,i=n.hostname,!s.includes("*")&&H(s)===H(i)&&(A(a=o.pathname,c=n.pathname)||A($(a),$(c)))&&function(e,t,r){return""===e?r.allowRequestQueryWhenPatternOmitsQuery||""===t:A(e,t)}(o.search,n.search,r));var s,i,a,c}(e,t,{allowRequestQueryWhenPatternOmitsQuery:!0})}function D(e){const t=e.trim();if(0===t.length||f(t))return;if(function(e){const t=e.indexOf("[");return-1!==t&&-1===e.indexOf("]",t)}(t))return;const r=q(t);if(r&&("http:"===r.protocol||"https:"===r.protocol)&&""===r.username&&""===r.password&&0!==r.hostname.length&&(!H(r.hostname).includes(":")||t.includes("["))){if(t.includes("[")){const e=t.indexOf("["),n=t.indexOf("]",e);if(-1===n)return;const o=t.slice(e+1,n);if(H(r.hostname)!==H(o))return}return r}}function O(e,t){const r=e.toLowerCase(),n=t.toLowerCase();if("*"===r)return!0;if(void 0!==a(n))return A(r,n);if(!r.includes("*"))return r===n;const o=r.slice(1);if(r.startsWith("*.")&&!o.includes("*"))return n.endsWith(o)&&n.length>o.length;const s=r.split("."),i=n.split(".");return s.length===i.length&&!s[s.length-1]?.includes("*")&&A(r,n)}const F=/^([^/?#]+\/\/[^/?#]*):\*(?=[/?#]|$)/,N=/^[^/?#]+\/\/[^/?#]*\*$/;function L(e,t){if("*"===e||e===t)return!0;let r;T.has(t)?r=T.get(t):(T.size>=I&&T.clear(),r=q(t),T.set(t,r));const n=function(e){if(void 0===e||!/[^.]\.$/.test(e.hostname))return;const t=new URL(e.href);return t.hostname=e.hostname.slice(0,-1),t.href}(r);if(void 0!==n&&L(e,n))return!0;const o=function(e){const t=e.trim(),r=t.indexOf("://");if(-1===r)return/^[^/?#]*[^.*/?#]\.$/.test(t)?t.slice(0,-1):void 0;if(!t.includes("*"))return;const n=r+3,o=n+(t.slice(n).split(/[/?#]/,1)[0]??"").replace(/:(?:\d+|\*)$/,"").length;return/[^.*]\.$/.test(t.slice(n,o))?`${t.slice(0,o-1)}${t.slice(o)}`:void 0}(e);return!(void 0===o||!L(o,t))||!!r&&(e.includes("://")?function(e,t){const r=N.test(e),n=r||F.test(e),o=e.indexOf("://"),s=e.slice(0,o).toLowerCase(),i=t.protocol.slice(0,-1),a=q((s.includes("*")&&A(s,i)?`${i}${e.slice(o)}`:e).replace(F,"$1"));if(void 0===a||""!==a.username||""!==a.password||""!==t.username||""!==t.password||a.protocol!==t.protocol||!n&&a.port!==t.port)return!1;const c=a.hostname.replace(/%2a/gi,"*");return(O(c,t.hostname)||r&&O(c.replace(/\*$/,""),t.hostname))&&(r||A(`${a.pathname}${a.search}`,`${t.pathname}${t.search}`))}(e,r):h(r.hostname,e))}function j(e,t){if(A(e,t)||L(e,t))return!0;const r=function(e){const t=e.trim();if(t.includes("*")||!t.includes("://"))return;const r=q(t);return void 0!==r&&""===r.search&&""===r.hash?W(r):void 0}(e);if(void 0===r)return!1;const n=q(t.trim());return void 0!==n&&W(n)===r}const U=/%[0-9a-f]{2}/gi,B=/^[A-Za-z0-9\-._~]$/;function W(e){const t="http:"===e.protocol||"https:"===e.protocol?"http(s):":e.protocol,r=e.hostname.endsWith(".")?e.hostname.slice(0,-1):e.hostname,n=""===e.port?"":`:${e.port}`,o=e.pathname.replace(U,(e=>{const t=String.fromCharCode(Number.parseInt(e.slice(1),16));return B.test(t)?t:e.toUpperCase()})).replace(/\/{2,}/g,"/");return`${t}//${r}${n}${o.endsWith("/")?o.slice(0,-1):o}`}function H(e){const t=e.trim().toLowerCase();return t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t}function q(e){const t=e.trim();if(0===t.length)return;const r=t.includes("://")?t:`https://${t}`;try{return new URL(r)}catch{return}}function z(e){return(e.mcpNetworkAllowlist??[]).flatMap((e=>{const t=P(e);return void 0===t?[]:[t]}))}function G(e,t){if(!0!==t.enabled)return{allowed:!0};if("no_sandbox"===t.mcpNetworkMode)return{allowed:!0};if(!D(e))return{allowed:!1,message:t.blockMessage??p};const r=z(t);return r.length>0&&r.some((t=>function(e,t){const r=D(t);if(!r)return!1;if(!e.includes("://"))return h(H(r.hostname),e);if(M(e,t))return!0;const n=function(e){try{const t=new URL(e);if(""!==t.username||""!==t.password||"/"!==t.pathname||""!==t.search||""!==t.hash)return;return`${t.protocol}//${t.host}/*`}catch{return}}(e);return void 0!==n&&M(n,t)}(t,e)))?{allowed:!0}:{allowed:!1,message:t.blockMessage??p}}function V(e){const t=e?.trim();return t&&t.length>0?t:void 0}function K(e){return V(e)?.toLowerCase()}function J(e,t){const r=K(e.builtinServer),n=K(t.builtinServer);if(void 0!==r||void 0!==n)return void 0!==r&&r===n;const o=V(e.command),s=V(e.serverUrl);if(void 0===o&&void 0===s)return!1;const i=void 0===o||void 0!==t.command&&A(o,t.command),a=void 0===s||void 0!==t.url&&L(s,t.url);return i&&a}function Z(e,t,r){return void 0!==r?.command&&void 0===r.url&&void 0===t&&!0===e?.allowUserOverrideMcpServers}function X({allowedMcpConfiguration:e,server:t,localAgentNetworkAllowlist:r,blockMessage:n,unmatchedServerAllowlist:o,aggregateManagedServerNetworkAllowlists:s=!0,stdioPlatform:i,unsandboxUserExtensionStdio:a}){const c=e?.allowedMcpServers,l=function(e){if(!0!==e?.allowUserOverrideMcpServers)return;const t=(e.deniedMcpServers??[]).flatMap((e=>{const t=V(e.serverUrl),r=void 0===t?void 0:function(e){const t=e.trim();if(0===t.length)return;if(function(e){const t=e.indexOf("://");if(-1===t)return!1;const r=e.slice(t+3),n=r.indexOf("/");return-1===n?r.includes("?"):r.slice(n).includes("*")}(t)){const e=t.indexOf("://");if(-1!==e){const r=t.slice(e+3).split(/[/?#]/,1)[0];if(r?.includes("*")){const e=P(r.replace(/:\d+$/,""));if(void 0!==e)return e}}return}if(!t.includes("://")&&t.includes("*")&&"*"!==t&&!t.startsWith("*."))return;const r=P(e);if(void 0!==r)return r;const n=e.indexOf("://");if(-1===n)return;const o=e.slice(0,n).toLowerCase();if("http"!==o&&"https"!==o)return;const s=e.slice(n+3).split(/[/?#]/,1)[0];if(void 0===s||s.includes("@"))return;const i=P(s.replace(/:\d+$/,""));if(void 0!==i)return i;try{return P(new URL(e).hostname)}catch{return}}(t);return void 0===r?[]:[r]}));return t.length>0?t:void 0}(e),u=void 0===t?void 0:function(e,t){return e?.find((e=>J(e,t)))}(c,t),d=Z(e,u,t),h=function({allowedMcpConfiguration:e,matchedServer:t,server:r}){return void 0===r?(e?.allowedMcpServers?.length??0)>0:void 0!==t||Z(e,t,r)}({allowedMcpConfiguration:e,matchedServer:u,server:t})||void 0===t&&void 0!==l,p=void 0===t?s?c?.flatMap((e=>e.networkAllowlist??[])):void 0:d?[]:function(e,t,r){return void 0===e?r:[...e.networkAllowlist??[],...void 0!==V(e.serverUrl)&&void 0!==t.url?[t.url]:[]]}(u,t,o),f=d&&"win32"===i&&!0===a;let m;m=void 0===t?void 0:f?"no_sandbox":d?"allow_all":function(e,t){var r;if(void 0!==V(e?.command)&&void 0!==t.command&&void 0===t.url)return r=e?.networkMode,("allow_all"===r||"allowlist"===r||"deny_all"===r||"no_sandbox"===r?r:void 0)??"no_sandbox"}(u,t);const g=void 0===t||d?l:void 0;return{enabled:h,mcpNetworkAllowlist:p,...void 0!==m?{mcpNetworkMode:m}:{},...void 0!==g?{mcpNetworkDenylist:g}:{},...void 0!==r?{localAgentNetworkAllowlist:r}:{},...void 0!==n?{blockMessage:n}:{},...f?{win32UserExtensionUnsandbox:!0}:{}}}function Q(e){if(!0===e?.enabled&&"no_sandbox"!==e.mcpNetworkMode)return e}},"../shell-exec/dist/api/index.js"(e,t,r){r.d(t,{BM:()=>qn,Ls:()=>p,SandboxUnsupportedError:()=>ar,J:()=>E,St:()=>lr,Fn:()=>Hn,Qw:()=>i,ue:()=>o,r5:()=>Pe,getLastSandboxFailureReason:()=>ir,oG:()=>wn,Ko:()=>R,CG:()=>st,W1:()=>J,G6:()=>Wn,dA:()=>Be,_B:()=>Ze,OK:()=>Ke,$b:()=>Je,K3:()=>hr,tv:()=>nt,wG:()=>dt,fZ:()=>pt,s9:()=>at,XX:()=>ut,T6:()=>Qe,Po:()=>Xe,$6:()=>tt,l7:()=>ot,xS:()=>C,resolveSandboxPolicyForWorkspace:()=>wt,spawnInSandbox:()=>ur,Xw:()=>I});const n=["SSH_CLIENT","SSH2_CLIENT"];function o(e){const t=e||process.env,{ELECTRON_RUN_AS_NODE:r,...o}=t;for(const e of Object.keys(o))e.startsWith("AGENT_HOST_DAEMON_")&&delete o[e];for(const e of n)delete o[e];return o}const s="NODE_COMPILE_CACHE";function i(e){const{[s]:t,...r}=e;return r.NODE_DISABLE_COMPILE_CACHE="1",r}const a=["SSH_AUTH_SOCK","DBUS_SESSION_BUS_ADDRESS","XDG_RUNTIME_DIR","WAYLAND_DISPLAY"];function c(e){const t={...e};for(const e of a)delete t[e];return t}const l=[["core.quotePath","false"]];function u(e){const t=function(e){const t=e.GIT_CONFIG_COUNT;if(void 0===t||""===t)return 0;const r=Number.parseInt(t,10);return Number.isFinite(r)&&r>=0?r:0}(e),r=new Set;for(let n=0;n<t;n++){const t=e[`GIT_CONFIG_KEY_${n}`];void 0!==t&&r.add(t.toLowerCase())}let n=t;for(const[t,o]of l)r.has(t.toLowerCase())||(e[`GIT_CONFIG_KEY_${n}`]=t,e[`GIT_CONFIG_VALUE_${n}`]=o,n++);n!==t&&(e.GIT_CONFIG_COUNT=String(n))}var d,h=r("node:perf_hooks");!function(e){e[e.SampleIntervalMs=250]="SampleIntervalMs",e[e.EventLoopResolutionMs=20]="EventLoopResolutionMs"}(d||(d={})),h.monitorEventLoopDelay;const p="\n[This shell is producing too much output to stream. The command will still run.]\n";var f=r("node:path"),m=r("node:fs"),g=r("../utils/dist/lru-cache.js");const w="undefined"!=typeof process&&"win32"===process.platform,y=new g.q({max:512});function v(e){try{return m.statSync(e)}catch{return null}}function b(e,t){if(e.match(/[\\/]/))return e;const r=t?`${e}\0${t.source}\0${t.flags}`:e,n=y.get(r);if(void 0!==n)return n;const o=f.join(".",e);if(v(o))return y.set(r,o),o;const s=process.env.PATH.split(w?";":":");for(const n of s){const o=f.join(n,e);if(v(o)&&(!t||t.test(o)))return y.set(r,o),o}return y.set(r,e),e}function S(e,t,r){if("win32"!==process.platform)return{cmd:b(e),args:t};if(!m.existsSync(e)){const n=[".exe",".bat",".cmd",".ps1"],o=e.toLowerCase();if(n.some((e=>o.endsWith(e)))){const n=b(e,r);if(m.existsSync(n))return S(n,t,r)}for(const o of n){const n=b(`${e}${o}`,r);if(m.existsSync(n))return S(n,t,r)}}return e.match(/\.ps1$/i)?{cmd:f.join(process.env.SYSTEMROOT,"System32","WindowsPowerShell","v1.0","PowerShell.exe"),args:["-ExecutionPolicy","Unrestricted","-NoLogo","-NonInteractive","-File",e].concat(t)}:e.match(/\.(bat|cmd)$/i)?{cmd:f.join(process.env.SYSTEMROOT,"System32","cmd.exe"),args:["/C",e,...t]}:e.match(/\.(js)$/i)?{cmd:process.execPath,args:[e].concat(t)}:{cmd:e,args:t}}let k;const _=["/usr/local/bin","/usr/bin","/bin"];function C(){const e=S("rg",[]).cmd;return"rg"!==e?e:void 0}function E(e){if(!e)throw new Error("configureRipgrepPath: path must not be empty");k=e}function x(e){const t=Object.keys(e).filter((e=>"path"===e.toLowerCase()));if(0!==t.length)return"win32"===process.platform?t.find((e=>"Path"===e))??t[0]:t.find((e=>"PATH"===e))??t[0]}function P(e,t){const r=(0,f.dirname)(t);if(!r||"."===r)return e;let n=function(e){const t=x(e);return void 0!==t?e[t]??"":""}(e).split(f.delimiter).filter(Boolean);return 0===n.length&&"win32"!==process.platform&&(n=_),function(e,t){const r=x(e)??("win32"===process.platform?"Path":"PATH"),n={...e};for(const e of Object.keys(n))e!==r&&"path"===e.toLowerCase()&&delete n[e];return n[r]=t,n}(e,[r,...n.filter((e=>e!==r))].join(f.delimiter))}function I(e){return k&&(0,f.isAbsolute)(k)?{...P(e,k),CURSOR_RIPGREP_PATH:k}:e}function R(){if(!k)throw new Error("Ripgrep path not configured. Call configureRipgrepPath() at startup.");return k}const T="win32"===process.platform;function A(e){return!T&&!!e?.SUDO_ASKPASS}function $(e){return A(e)?"alias sudo='sudo -A'; ":""}function M(e){const t=[];let r=0;for(;r<e.length;){const n=0===r||"&&"===e.slice(Math.max(0,r-2),r)||"||"===e.slice(Math.max(0,r-2),r)||"|"===e[r-1]||";"===e[r-1],o=Math.max(0,r-10),s=e.slice(o,r),i=/(?:&&|\|\||[|;])\s*$/.test(s)||0===r&&/^\s*$/.test(s);if((n||i)&&"sudo"===e.slice(r,r+4)){const n=r+4;if(n>=e.length||/\s/.test(e[n])){let o=n;for(;o<e.length&&/\s/.test(e[o]);)o++;let s=!1;if(o<e.length&&"-"===e[o]){let t=o+1;for(;t<e.length&&/[^\s]/.test(e[t]);)t++;const r=e.slice(o,t);s=/^-[a-zA-Z]*A[a-zA-Z]*$/.test(r)}s?(t.push("sudo"),r=n):(t.push("sudo -A"),r=n);continue}}t.push(e[r]),r++}return t.join("")}function D(e,t){const r=t.toUpperCase();return Object.entries(e).some((([e,t])=>void 0!==t&&e.toUpperCase()===r))}const O=["PYTHONIOENCODING","PYTHONUTF8","PYTHONLEGACYWINDOWSSTDIO"];function F(e){O.some((t=>D(e,t)))||(e.PYTHONIOENCODING="utf-8:surrogateescape")}function N(e){D(e,"WSL_UTF8")||(e.WSL_UTF8="1")}const L="-Dsun.stdout.encoding=UTF-8 -Dsun.stderr.encoding=UTF-8 -Dstdout.encoding=UTF-8 -Dstderr.encoding=UTF-8",j=["sun.stdout.encoding","sun.stderr.encoding","stdout.encoding","stderr.encoding"],U=`case " \${MAVEN_OPTS-} \${JAVA_TOOL_OPTIONS-} \${JDK_JAVA_OPTIONS-} \${_JAVA_OPTIONS-} " in ${j.map((e=>`*[[:space:]]-D${e}=*`)).join("|")}) ;; *) builtin export MAVEN_OPTS="\${MAVEN_OPTS:+$MAVEN_OPTS }${L}";; esac; `,B=`if ("$env:MAVEN_OPTS $env:JAVA_TOOL_OPTIONS $env:JDK_JAVA_OPTIONS \${env:_JAVA_OPTIONS}" -cnotmatch '(^|\\s)-D(${j.map((e=>e.replace(/\./g,"\\."))).join("|")})=') {\n if ($env:MAVEN_OPTS) { $env:MAVEN_OPTS = "$env:MAVEN_OPTS ${L}" } else { $env:MAVEN_OPTS = '${L}' }\n}`;var W=r("node:crypto?8af2"),H=r("node:os"),q=r("../utils/dist/workspace-paths.js"),z=r("../utils/dist/test-resets.js");let G;function V(e,t){const r=(0,m.lstatSync)(e);return r.isDirectory()&&r.uid===t&&!(18&r.mode)}function K(e){try{(0,m.mkdirSync)(e,{mode:448})}catch(e){if(!(e instanceof Error&&"code"in e&&"EEXIST"===e.code))throw e}}function J(e){return Z(e,{create:!1})}function Z(e,{create:t}){const r=process.getuid?.();if(void 0===r)return;const n=(0,f.join)((0,H.tmpdir)(),`cursor-sandbox-${(0,q.r_)((0,f.resolve)(e))}`);try{for(const e of[n,(0,f.join)(n,"tmp")])if(t&&K(e),!V(e,r))return;return n}catch{return}}(0,z.J)((function(){G=void 0}));const X='builtin eval "${__CURSOR_SANDBOX_TEMP_RESTORE:-}" 2>/dev/null; ',Q=["TMPDIR","TMP","TEMP","TMPPREFIX","NODE_COMPILE_CACHE","NODE_DISABLE_COMPILE_CACHE"],Y="builtin export NODE_DISABLE_COMPILE_CACHE=1; builtin unset NODE_COMPILE_CACHE; ";function ee(e=(0,f.join)((0,H.tmpdir)(),"cursor-sandbox-cache",function(){return G||(G=(0,W.randomBytes)(16).toString("hex")),G}())){return{NPM_CONFIG_CACHE:(0,f.join)(e,"npm"),PNPM_STORE_PATH:(0,f.join)(e,"pnpm-store"),GOCACHE:(0,f.join)(e,"go-build"),GOMODCACHE:(0,f.join)(e,"go-mod"),CARGO_TARGET_DIR:(0,f.join)(e,"cargo-target"),PIP_CACHE_DIR:(0,f.join)(e,"pip"),UV_CACHE_DIR:(0,f.join)(e,"uv"),BUN_INSTALL_CACHE_DIR:(0,f.join)(e,"bun"),YARN_CACHE_FOLDER:(0,f.join)(e,"yarn"),npm_config_devdir:(0,f.join)(e,"node-gyp"),PLAYWRIGHT_BROWSERS_PATH:(0,f.join)(e,"playwright"),PUPPETEER_CACHE_DIR:(0,f.join)(e,"puppeteer"),TURBO_CACHE_DIR:(0,f.join)(e,"turbo"),GRADLE_USER_HOME:(0,f.join)(e,"gradle"),CONDA_PKGS_DIRS:(0,f.join)(e,"conda"),POETRY_CACHE_DIR:(0,f.join)(e,"poetry"),GEM_SPEC_CACHE:(0,f.join)(e,"gem-specs"),BUNDLE_PATH:(0,f.join)(e,"bundle"),COMPOSER_HOME:(0,f.join)(e,"composer"),HOMEBREW_CACHE:(0,f.join)(e,"homebrew"),CYPRESS_CACHE_FOLDER:(0,f.join)(e,"cypress"),NX_CACHE_DIRECTORY:(0,f.join)(e,"nx"),NUGET_PACKAGES:(0,f.join)(e,"nuget"),CCACHE_DIR:(0,f.join)(e,"ccache"),CP_HOME_DIR:(0,f.join)(e,"cocoapods")}}var te=r("node:fs/promises"),re=r("../utils/dist/safe-spawn-cwd.js"),ne=r("../../node_modules/.pnpm/ignore@7.0.5/node_modules/ignore/index.js");function oe(){const e=process.env.CURSOR_SANDBOX_POLICY_DIR?.trim();return e?f.resolve(e):f.resolve(f.join(H.homedir(),".cursor","sandbox-policies"))}let se=0;function ie(){const e=oe();m.mkdirSync(e,{recursive:!0,mode:448});try{m.chmodSync(e,448)}catch{}const t=Date.now();return t-se>=9e5&&(se=t,function(e){let t;try{t=m.readdirSync(e)}catch{return}const r=Date.now();for(const n of t){if(!n.startsWith("sandbox-policy-"))continue;const t=f.join(e,n);try{const e=m.statSync(t);if(!e.isFile())continue;r-e.mtimeMs>36e5&&m.unlinkSync(t)}catch{}}}(e)),e}function ae(e){const t=ie(),r=W.randomBytes(8).toString("hex"),n=f.join(t,`sandbox-policy-${r}`);return m.writeFileSync(n,e,{encoding:"utf-8",mode:384}),n}const ce="/tmp/node-compile-cache",le="cursor-compile-cache",ue=Symbol.for("cursor.startupNodeCompileCache"),de=process.platform;function he(e=H.tmpdir(),t=process.platform){if("win32"===t||0===e.length)return[];const r=f.posix.join(e,"node-compile-cache");return r===ce?[]:[r]}function pe(e=H.tmpdir(),t=process.env,r=process.platform){if("win32"===r)return[];const n=new Set(he(e,r));for(const e of["TMPDIR","TMP","TEMP"]){const o=t[e];if(void 0!==o&&f.posix.isAbsolute(o))for(const e of he(f.posix.resolve(o),r))n.add(e)}return[...n]}function fe(e=process.env,t=H.homedir(),r=process.platform){if("darwin"===r)return t.length>0?f.posix.join(t,"Library/Caches",le):void 0;if("linux"!==r)return;const n=e.XDG_CACHE_HOME;return void 0!==n&&f.posix.isAbsolute(n)?f.posix.join(n,le):t.length>0?f.posix.join(t,".cache",le):void 0}function me(e=process.env,t=process.platform){if("win32"===t)return;const r=Object.getOwnPropertyDescriptor(globalThis,ue)?.value,n="string"==typeof r?r:e.NODE_COMPILE_CACHE;if(void 0===n||!f.posix.isAbsolute(n))return;const o=f.posix.resolve(n);return"/"===o?void 0:o}function ge(e=H.homedir(),t=H.tmpdir(),r=process.env,n=process.platform){if("win32"===n)return[];const o=new Set([ce]);e.length>0&&(o.add(f.posix.join(e,".cache",le)),o.add(f.posix.join(e,"Library/Caches",le)));const s=[];for(const i of[...pe(t,r,n),fe(r,e,n),me(r,n)])void 0===i||o.has(i)||(o.add(i),s.push(i));return s}function we(e=H.homedir(),t=H.tmpdir(),r=process.platform,n=process.env){if("win32"===r)return[];const o=[ce,...pe(t,n,r)],s=fe(n,e,r);return void 0===s||o.includes(s)||o.push(s),o}function ye(e,t){return e.isSymbolicLink()?"a link, not followed":e.isDirectory()?e.uid!==t?`owned by uid ${e.uid}`:void 0:"not a folder"}function ve(e){return"object"!=typeof e||null===e?{}:Object.fromEntries(Object.entries(e).filter((e=>"string"==typeof e[1])))}function be(e){return"object"==typeof e&&null!==e&&"code"in e&&"string"==typeof e.code?e.code:"error"}const Se=[".local/bin",".local/share/mise",".local/share/pnpm",".nvm",".volta",".asdf",".pyenv",".rbenv",".rustup",".cargo/bin",".cargo/registry",".cargo/git"],ke=["bin","sbin","lib","opt","Cellar","share","Frameworks","etc/gitconfig","etc/openssl@3/cert.pem","etc/openssl@3/openssl.cnf","etc/ca-certificates"],_e=(e,t)=>t.flatMap((t=>ke.map((r=>({platform:e,scope:"global",path:`${t}/${r}`}))))),Ce={linux:[".cache/node",".cache/yarn"],darwin:[".cache/node","Library/Caches/Yarn"]},Ee=e=>[...Se,...Ce[e]].map((t=>({platform:e,scope:"home-dir",path:t}))),xe=[{platform:"linux",scope:"global",path:"/bin"},{platform:"linux",scope:"global",path:"/sbin"},{platform:"linux",scope:"global",path:"/usr/bin"},{platform:"linux",scope:"global",path:"/usr/sbin"},{platform:"linux",scope:"global",path:"/lib"},{platform:"linux",scope:"global",path:"/lib64"},{platform:"linux",scope:"global",path:"/usr/lib"},{platform:"linux",scope:"global",path:"/usr/lib64"},{platform:"linux",scope:"global",path:"/usr/libexec"},{platform:"linux",scope:"global",path:"/usr/share"},{platform:"linux",scope:"global",path:"/etc/ld.so.cache"},{platform:"linux",scope:"global",path:"/etc/ld.so.conf"},{platform:"linux",scope:"global",path:"/etc/ld.so.conf.d"},{platform:"linux",scope:"global",path:"/etc/ssl/certs"},{platform:"linux",scope:"global",path:"/etc/ssl/openssl.cnf"},{platform:"linux",scope:"global",path:"/etc/ssl/cert.pem"},{platform:"linux",scope:"global",path:"/etc/ssl/ca-bundle.pem"},{platform:"linux",scope:"global",path:"/etc/ssl/certs/ca-certificates.crt"},{platform:"linux",scope:"global",path:"/etc/pki/tls/certs"},{platform:"linux",scope:"global",path:"/etc/pki/tls/openssl.cnf"},{platform:"linux",scope:"global",path:"/etc/pki/ca-trust/extracted"},{platform:"linux",scope:"global",path:"/etc/resolv.conf"},{platform:"linux",scope:"global",path:"/etc/hosts"},{platform:"linux",scope:"global",path:"/etc/nsswitch.conf"},{platform:"linux",scope:"global",path:"/etc/gai.conf"},{platform:"linux",scope:"global",path:"/etc/alternatives"},{platform:"linux",scope:"global",path:"/etc/mime.types"},{platform:"linux",scope:"global",path:"/etc/profile"},{platform:"linux",scope:"global",path:"/etc/bash.bashrc"},{platform:"linux",scope:"global",path:"/etc/zsh/zshenv"},{platform:"linux",scope:"global",path:"/etc/zsh/zprofile"},{platform:"linux",scope:"global",path:"/etc/zsh/zshrc"},{platform:"linux",scope:"global",path:"/etc/zsh/zlogin"},{platform:"linux",scope:"global",path:"/etc/gitconfig"},{platform:"linux",scope:"home",path:".bashrc"},{platform:"linux",scope:"home",path:".bash_profile"},{platform:"linux",scope:"home",path:".profile"},{platform:"linux",scope:"home",path:".zshenv"},{platform:"linux",scope:"home",path:".zprofile"},{platform:"linux",scope:"home",path:".zshrc"},{platform:"linux",scope:"home",path:".zlogin"},{platform:"linux",scope:"home",path:".gitconfig"},{platform:"linux",scope:"home",path:".ssh/known_hosts"},{platform:"linux",scope:"home",path:".config/mise/config.toml"},{platform:"linux",scope:"home-dir",path:".cache/dotslash"},...Ee("linux"),..._e("linux",["/usr/local","/home/linuxbrew/.linuxbrew"]),{platform:"linux",scope:"global",path:"/usr/local/go"},{platform:"linux",scope:"global",path:"/nix/store"},{platform:"linux",scope:"global",path:"/nix/var/nix/profiles"},{platform:"linux",scope:"bundled",path:"ripgrep"},{platform:"darwin",scope:"global",path:"/bin"},{platform:"darwin",scope:"global",path:"/usr/bin"},{platform:"darwin",scope:"global",path:"/usr/lib"},{platform:"darwin",scope:"global",path:"/usr/libexec"},{platform:"darwin",scope:"global",path:"/usr/share"},{platform:"darwin",scope:"global",path:"/System/Library"},{platform:"darwin",scope:"global",path:"/System/Cryptexes"},{platform:"darwin",scope:"global",path:"/Library/Apple"},{platform:"darwin",scope:"global",path:"/Library/Developer/CommandLineTools"},{platform:"darwin",scope:"global",path:"/Applications/Xcode.app"},{platform:"darwin",scope:"global",path:"/Library/Preferences/com.apple.dt.Xcode.plist"},{platform:"darwin",scope:"global",path:"/private/etc/ssl/cert.pem"},{platform:"darwin",scope:"global",path:"/private/etc/ssl/certs"},{platform:"darwin",scope:"global",path:"/private/etc/ssl/openssl.cnf"},{platform:"darwin",scope:"global",path:"/private/etc/hosts"},{platform:"darwin",scope:"global",path:"/private/etc/resolv.conf"},{platform:"darwin",scope:"global",path:"/private/etc/apache2/mime.types"},{platform:"darwin",scope:"global",path:"/etc/profile"},{platform:"darwin",scope:"global",path:"/etc/bashrc"},{platform:"darwin",scope:"global",path:"/etc/zshenv"},{platform:"darwin",scope:"global",path:"/etc/zprofile"},{platform:"darwin",scope:"global",path:"/etc/zshrc"},{platform:"darwin",scope:"global",path:"/etc/zlogin"},{platform:"darwin",scope:"global",path:"/etc/gitconfig"},{platform:"darwin",scope:"home",path:".bashrc"},{platform:"darwin",scope:"home",path:".bash_profile"},{platform:"darwin",scope:"home",path:".profile"},{platform:"darwin",scope:"home",path:".zshenv"},{platform:"darwin",scope:"home",path:".zprofile"},{platform:"darwin",scope:"home",path:".zshrc"},{platform:"darwin",scope:"home",path:".zlogin"},{platform:"darwin",scope:"home",path:".gitconfig"},{platform:"darwin",scope:"home",path:".ssh/known_hosts"},{platform:"darwin",scope:"home",path:"Library/Preferences/.GlobalPreferences.plist"},{platform:"darwin",scope:"home",path:".config/mise/config.toml"},{platform:"darwin",scope:"home-dir",path:"Library/Python"},{platform:"darwin",scope:"home-dir",path:"Library/Caches/dotslash"},...Ee("darwin"),..._e("darwin",["/opt/homebrew","/usr/local"]),{platform:"darwin",scope:"global",path:"/nix/store"},{platform:"darwin",scope:"global",path:"/nix/var/nix/profiles"},{platform:"darwin",scope:"bundled",path:"ripgrep"},{platform:"darwin",scope:"global",path:"/dev/null"},{platform:"darwin",scope:"global",path:"/dev/zero"},{platform:"darwin",scope:"global",path:"/dev/random"},{platform:"darwin",scope:"global",path:"/dev/urandom"}];function Pe(e=process.platform,t=H.default.homedir(),r={}){const n=[];for(const o of xe){if(o.platform!==e)continue;if("global"===o.scope){n.push(o.path);continue}const s="bundled"===o.scope?r[o.path]:(0,f.join)(t,o.path);if(s)try{let e;switch(o.scope){case"home":e=(0,m.lstatSync)(s).isFile();break;case"home-dir":e=(0,m.lstatSync)(s).isDirectory();break;case"bundled":e=(0,m.statSync)(s).isFile()}e&&n.push(s)}catch{}}return n}const Ie=[{type:"workspace",pattern:"**/.cursor/*.json"},{type:"workspace",pattern:"**/.cursor/**/*.json"},{type:"workspace",pattern:"**/.cursor/.workspace-trusted"},{type:"workspace",pattern:"!**/.cursor/rules"},{type:"workspace",pattern:"!**/.cursor/rules/**"},{type:"workspace",pattern:"!**/.cursor/commands"},{type:"workspace",pattern:"!**/.cursor/commands/**"},{type:"workspace",pattern:"!**/.cursor/worktrees"},{type:"workspace",pattern:"!**/.cursor/worktrees/**"},{type:"workspace",pattern:"!**/.cursor/skills"},{type:"workspace",pattern:"!**/.cursor/skills/**"},{type:"workspace",pattern:"!**/.cursor/agents"},{type:"workspace",pattern:"!**/.cursor/agents/**"},{type:"workspace",pattern:"**/.claude/*.json"},{type:"workspace",pattern:"**/.claude/**/*.json"},{type:"workspace",pattern:"**/.vscode/**"},{type:"workspace",pattern:"**/.idea/**"},{type:"workspace",pattern:"**/.venv/"},{type:"workspace",pattern:"**/venv/"},{type:"workspace",pattern:"**/*.code-workspace"},{type:"workspace",pattern:"**/.cursorignore"},{type:"workspace",pattern:"**/.workspace-trusted"},{type:"workspace",pattern:"**/.cursor/**/cli.json"},{type:"workspace",pattern:"**/.cursor/**/cli-config.json"},{type:"workspace",pattern:"**/.cursor/**/mcp.json"},{type:"workspace",pattern:"**/.cursor/**/mcp-approvals.json"},{type:"workspace",pattern:"**/.cursor/**/permissions.json"},{type:"git",pattern:"**/.git/hooks/**"},{type:"git",pattern:"**/.git/config"},{type:"git",pattern:"**/.git/config.worktree"},{type:"git",pattern:"**/.git/info/attributes"},{type:"git",pattern:"**/.git/commondir"},{type:"git",pattern:"**/.git/worktrees/*/commondir"},{type:"git",pattern:"**/.git/worktrees/*/gitdir"},{type:"worktree",pattern:".git"},{type:"absolute",pattern:"/etc/ssl/cert.pem"},{type:"absolute",pattern:"/etc/ssl/ca-bundle.pem"},{type:"absolute",pattern:"/private/etc/ssl/cert.pem"},{type:"absolute",pattern:"/etc/ssl/certs/ca-certificates.crt"},{type:"absolute",pattern:"/etc/pki/tls/certs/ca-bundle.crt"},{type:"absolute",pattern:"/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem"},{type:"home",pattern:".cursor/sandbox-policies"},{type:"absolute",pattern:"/tmp/node-compile-cache"},{type:"home",pattern:".cache/cursor-compile-cache"},{type:"home",pattern:"Library/Caches/cursor-compile-cache"}];function Re(e){const t=Ie.filter((e=>"workspace"===e.type)).map((e=>e.pattern));return{[e]:t}}function Te(e){const t=Ie.filter((e=>"git"===e.type)).map((e=>e.pattern));return{[e]:t}}function Ae(e){const t=Ie.filter((e=>"worktree"===e.type)).map((e=>e.pattern));return{[e]:t}}Ie.filter((e=>"git"===e.type)).map((e=>e.pattern)),Ie.filter((e=>"workspace"===e.type&&e.pattern.startsWith("!")&&!e.pattern.endsWith("/**"))).map((e=>e.pattern.replace(/^!(\*\*\/)?/,"")));const $e=[];let Me=null,De=null;function Oe(e){if(!(e instanceof Error&&"code"in e&&"string"==typeof e.code)||e.code.startsWith("ERR_"))throw e}async function Fe(e,t=""){const r=await(0,te.lstat)(e).catch(Oe);if(void 0===r||!r.isFile()||r.size>4096)return;const n=await(0,te.readFile)(e,"utf8").catch(Oe),o=n?.split("\n",1)[0]?.replace(/\r$/,"");if(void 0===o||!o.startsWith(t))return;const s=o.slice(t.length);return s.length>0&&!s.includes("\0")?s:void 0}async function Ne(e){if(!(0,re.$f)(e))return(0,te.realpath)(e).catch(Oe)}async function Le(e){const t=await Fe((0,f.join)(e,".git"),"gitdir: ");if(void 0===t)return;const r=await Ne((0,f.resolve)(e,t));if(void 0===r)return;const n=await Fe((0,f.join)(r,"commondir")),o=void 0===n?r:await Ne((0,f.resolve)(r,n));return void 0===o?void 0:{gitDir:r,commonDirLink:n,commonDir:o}}async function je(e){const t=await Le(e);if(void 0===t||void 0===t.commonDirLink||"worktrees"!==(0,f.basename)((0,f.dirname)(t.gitDir)))return;const r=(0,f.dirname)((0,f.dirname)(t.gitDir));if(".git"!==(0,f.basename)(r)||(He?t.commonDir.toLowerCase()!==r.toLowerCase():t.commonDir!==r))return;const n=await Fe((0,f.join)(t.gitDir,"gitdir"));if(void 0===n)return;const o=(0,f.join)(e,".git"),[s,i]=await Promise.all([Ne((0,f.resolve)(t.gitDir,n)),Ne(o)]);return void 0!==s&&void 0!==i&&(He?s.toLowerCase()===i.toLowerCase():s===i)?r:void 0}let Ue=null;function Be(e){return function(){const e=H.default.homedir();if(null===Ue){const t=[];for(const r of Ie)switch(r.type){case"absolute":t.push(r.pattern);break;case"home":e.length>0&&t.push((0,f.join)(e,r.pattern))}Ue=t}return[...Ue,...ge(e)]}().some((t=>{if(Ge(e,t))return!0;const r=function(e){let t;try{t=m.realpathSync.native((0,f.dirname)(e))}catch(e){const t=e instanceof Error&&"code"in e?e.code:void 0;return"ENOENT"===t||"ENOTDIR"===t?void 0:We}const r=(0,f.join)(t,(0,f.basename)(e));return r===(0,f.dirname)(r)?void 0:r}(t);return r===We||void 0!==r&&Ge(e,r)}))}const We=Symbol("unresolved parent");const He="win32"===process.platform||"darwin"===process.platform;function qe(e){if(!e.endsWith(f.sep))return e;const t=e.slice(0,-1);return""===t||"win32"===process.platform&&/^[a-zA-Z]:$/.test(t)?e:t}function ze(e){return e.endsWith(f.sep)?e:e+f.sep}function Ge(e,t){const r=qe(t);if(He){const t=e.toLowerCase(),n=r.toLowerCase();return t===n||t.startsWith(ze(n))}return e===r||e.startsWith(ze(r))}function Ve(e,t){const r=qe(e);return He?(0,f.relative)(r.toLowerCase(),t.toLowerCase()).replace(/\\/g,"/"):(0,f.relative)(r,t).replace(/\\/g,"/")}async function Ke(e,t){if(Ge(e,t)){const r=Ve(t,e);if((null===Me&&(Me=ne({ignoreCase:!0}),Me.add(Ie.filter((e=>"workspace"===e.type)).map((e=>e.pattern)))),Me).ignores(r))return!0}const{isWorktree:r,gitDirParent:n}=await async function(e){const t=await(0,te.lstat)((0,f.join)(e,".git")).catch(Oe);if(!t?.isFile())return{isWorktree:!1,gitDirParent:e};const r=await async function(e){return(await Le(e))?.commonDir}(e);return{isWorktree:!0,gitDirParent:void 0===r?e:(0,f.dirname)(r)}}(t);for(const r of new Set([n,t]))if(Ge(e,r)){const t=Ve(r,e);if((null===De&&(De=ne({ignoreCase:!0}),De.add(Ie.filter((e=>"git"===e.type)).map((e=>e.pattern)))),De).ignores(t))return!0}return!(!r||!Ge(e,t)||".git"!==Ve(t,e))||Be(e)}function Je(e){return void 0!==e&&("allow"===e.default||void 0!==e.allow&&e.allow.length>0)}function Ze(e){return void 0!==e&&"allow"===e.default}function Xe(){return{version:1,default:"deny"}}function Qe(){return{version:1,default:"allow"}}var Ye=r("../utils/dist/path-utils.js");function et(e){if(!e)return;const t={version:1};if("allow"!==e.default&&"deny"!==e.default||(t.default=e.default),Array.isArray(e.allow)&&e.allow.length>0&&(t.allow=e.allow.filter((e=>"string"==typeof e))),Array.isArray(e.deny)&&e.deny.length>0&&(t.deny=e.deny.filter((e=>"string"==typeof e))),e.logging){const r={};"string"==typeof e.logging.decisionLogPath&&(r.decisionLogPath=e.logging.decisionLogPath),"jsonl"===e.logging.logFormat&&(r.logFormat="jsonl"),Object.keys(r).length>0&&(t.logging=r)}return t}function tt(e){const t=e.type??"workspace_readwrite",r={debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,enableSharedBuildCache:e.enableSharedBuildCache};if("insecure_none"===t)return{type:"insecure_none",...r};let n;if(Array.isArray(e.additionalReadonlyPaths)){const t=e.additionalReadonlyPaths;n=t.length>0?t:void 0}const o={...r,networkAccess:e.networkAccess,networkPolicy:et(e.networkPolicy),networkPolicyStrict:e.networkPolicyStrict,additionalReadonlyPaths:n,readBoundary:e.readBoundary,additionalReadPaths:Array.isArray(e.additionalReadPaths)?e.additionalReadPaths:void 0,disableTmpWrite:e.disableTmpWrite};return"workspace_readonly"===t?{type:"workspace_readonly",...o}:{type:"workspace_readwrite",...o,additionalReadwritePaths:e.additionalReadwritePaths}}function rt(e){if("object"!=typeof e||null===e)return"Expected an object";const t=Object.fromEntries(Object.entries(e));if(void 0!==t.type){const e=["insecure_none","workspace_readwrite","workspace_readonly"];if("string"!=typeof t.type||!e.includes(t.type))return`Invalid type: expected one of ${e.join(", ")}`}const r=["networkAccess","networkPolicyStrict","disableTmpWrite","enableSharedBuildCache","captureDenies"];for(const e of r)if(void 0!==t[e]&&"boolean"!=typeof t[e])return`Invalid ${e}: expected boolean`;const n=["debugOutputDir"];for(const e of n)if(void 0!==t[e]&&"string"!=typeof t[e])return`Invalid ${e}: expected string`;const o=["additionalReadwritePaths","additionalReadonlyPaths","additionalReadPaths"];for(const e of o)if(void 0!==t[e]){if(!Array.isArray(t[e]))return`Invalid ${e}: expected array`;if(!t[e].every((e=>"string"==typeof e)))return`Invalid ${e}: expected array of strings`}if(void 0!==t.readBoundary&&"system"!==t.readBoundary&&"workspace"!==t.readBoundary)return'Invalid readBoundary: expected "system" or "workspace"';if(void 0!==t.networkPolicy){if("object"!=typeof t.networkPolicy||null===t.networkPolicy)return"Invalid networkPolicy: expected object";const e=Object.fromEntries(Object.entries(t.networkPolicy));if(void 0!==e.default&&"allow"!==e.default&&"deny"!==e.default)return'Invalid networkPolicy.default: expected "allow" or "deny"';if(void 0!==e.allow&&!Array.isArray(e.allow))return"Invalid networkPolicy.allow: expected array";if(void 0!==e.deny&&!Array.isArray(e.deny))return"Invalid networkPolicy.deny: expected array"}}async function nt(e,t){const r=await async function(e,t){try{const r=await(0,te.readFile)(e,"utf-8"),n=JSON.parse(r);if(void 0!==rt(n))return{success:!1,error:`Invalid sandbox policy: ${rt(n)??""}`};let o=tt(n);return t&&(o=ot(o,t)),{success:!0,policy:o}}catch(e){return e instanceof Error?"code"in e&&"ENOENT"===e.code?{success:!1,error:"File not found"}:e instanceof SyntaxError?{success:!1,error:`Invalid JSON: ${e.message}`}:{success:!1,error:e.message}:{success:!1,error:"Unknown error"}}}(e,t);if(r.success)return r.policy}function ot(e,t){if("insecure_none"===e.type)return e;const r=e.additionalReadonlyPaths?.map((e=>(0,Ye.o1)(e,t))),n=e.additionalReadPaths?.map((e=>(0,Ye.o1)(e,t)));if("workspace_readonly"===e.type)return{...e,additionalReadonlyPaths:r,additionalReadPaths:n};const o=e.additionalReadwritePaths?.map((e=>(0,Ye.o1)(e,t)));return{...e,additionalReadonlyPaths:r,additionalReadPaths:n,additionalReadwritePaths:o}}function st(e){return e.teamAdmin?.type??e.perRepo?.type??e.perUser?.type??"insecure_none"}function it(...e){return e.some((e=>!0===e))}function at(...e){const t=new Set;for(const r of e)if(r)for(const e of r)t.add(ht(e));return[...t]}const ct=function({defaultValue:e,rank:t}){return{defaultValue:e,merge:(...r)=>{const n=r.filter((e=>void 0!==e));return 0===n.length?e:n.reduce(((e,r)=>t[r]<t[e]?r:e))}}}({defaultValue:"system",rank:{workspace:0,system:1}}),lt=(...e)=>function(...e){const t=e.filter((e=>void 0!==e));if(0===t.length)return[];if(t.some((e=>0===e.length)))return[];if(1===t.length)return function(e){const t=new Set,r=[];for(const n of e){const e=ht(n);t.has(e)||(t.add(e),r.push(n))}return r}(t[0]).map(ht);let r=new Set(t[0].map(ht));for(let e=1;e<t.length;e++){const n=new Set(t[e].map(ht));r=new Set([...r].filter((e=>n.has(e))))}return[...r]}(...e);function ut(...e){return ct.merge(...e)}function dt(...e){return lt(...e)}function ht(e){const t=e.replace(/\\/g,"/").replace(/\/+$/,"");return""===t?"/":/^[a-zA-Z]:$/.test(t)?`${t}/`:t}function pt(...e){const t=e.filter((e=>void 0!==e));if(0===t.length)return;let r;for(const e of t){if("deny"===e.default){r="deny";break}"allow"===e.default&&void 0===r&&(r="allow")}const n=new Set;for(const e of t)if(e.deny)for(const t of e.deny)n.add(t);const o=new Set;for(const e of t)if(e.allow)for(const t of e.allow)o.add(t);const s=o.size>0?[...o]:void 0;let i;for(let e=t.length-1;e>=0;e--)if(void 0!==t[e].logging){i=t[e].logging;break}const a={version:1};return void 0!==r&&(a.default=r),void 0!==s&&(a.allow=s),n.size>0&&(a.deny=[...n]),void 0!==i&&(a.logging=i),void 0!==a.default||void 0!==a.allow&&0!==a.allow.length||void 0!==a.deny&&0!==a.deny.length||void 0!==a.logging?a:void 0}function ft(e,t){if(!e||0===e.length)return[...t];const r=new Set(e);for(const e of t)r.has(e)&&r.delete(e),r.add(e);return[...r]}function mt(...e){const t=e.filter((e=>void 0!==e));if(0===t.length)return;const r={};for(const e of t)for(const[t,n]of Object.entries(e))r[t]=ft(r[t],n);return 0!==Object.keys(r).length?r:void 0}function gt(...e){for(let t=e.length-1;t>=0;t--)if(void 0!==e[t])return e[t]}async function wt(e,t,r={}){if(!t)return{policy:{type:"insecure_none"}};if((0,re.$f)(e))return St(t,{workspaceDir:e});if("workspace_readwrite"!==(bt(t)??"workspace_readwrite"))return St(t,{workspaceDir:e});const n=r.stat??te.stat,o=await async function(e,t){for(let r=e;;r=(0,f.dirname)(r)){if((0,re.$f)(r))return;const e=await yt(r,t);if(void 0!==e)return e;if((0,f.dirname)(r)===r)return}}(e,n);let s=o?.root??e;if(o?.isFile){const e=await je(o.root);void 0!==e&&(s=(0,f.dirname)(e)),t=vt(t,void 0===e?[]:[e],Ae(o.root))}return t=await async function(e,t,r){const n=_t(e,"workspace_readwrite"),o=at(n.perUser?.additionalReadwritePaths,n.perRepo?.additionalReadwritePaths,n.teamAdmin?.additionalReadwritePaths);if(0===o.length)return e;const s=(await Promise.all(o.map((async e=>{if(t.has(ht(e))||(0,re.$f)(e))return[];const n=await yt(e,r);if(void 0===n)return[];const o=[Re(e),Te(e)];if(n.isFile){o.push(Ae(e));const t=await je(e);void 0!==t&&o.push(Te((0,f.dirname)(t)))}return o})))).flat();return 0===s.length?e:vt(e,[],...s)}(t,new Set([ht(e)]),n),St(t,{workspaceDir:e,gitDirParent:s})}async function yt(e,t){const r=await t((0,f.join)(e,".git")).catch(Oe);return r?.isFile()||r?.isDirectory()?{root:e,isFile:r.isFile()}:void 0}function vt(e,t,...r){const n="workspace_readwrite"===e.perRepo?.type||void 0===e.perRepo?e.perRepo:void 0;return{...e,perRepo:{...n,type:"workspace_readwrite",additionalReadwritePaths:t.length>0?[...n?.additionalReadwritePaths??[],...t]:n?.additionalReadwritePaths,writeProtectionMapping:mt(n?.writeProtectionMapping,...r)}}}function bt(e){const{perUser:t,perRepo:r,teamAdmin:n}=e,o=[t,r,n].filter((e=>void 0!==e));if(0===o.length)return;const s=o[0].type;for(const e of o)if(e.type!==s)throw new Error(`Cannot merge policies of different types: found "${s}" and "${e.type}". All policies must be of the same type (all workspace_readwrite, all workspace_readonly, or all insecure_none).`);return s}function St(e,t){return function(e,t){const r=bt(e);if(void 0===r)return xt({},t);switch(r){case"workspace_readwrite":return xt(_t(e,r),t);case"workspace_readonly":return function(e,t){const r=t?.debug,n=Ct(e,t),o={policy:Et({type:"workspace_readonly",disableTmpWrite:n.disableTmpWrite,networkPolicyStrict:n.networkPolicyStrict,readBoundary:n.readBoundary,additionalReadPaths:n.additionalReadPaths,additionalReadonlyPaths:n.additionalReadonlyPaths,networkPolicy:n.networkPolicy,debugOutputDir:n.debugOutputDir,captureDenies:n.captureDenies,enableSharedBuildCache:n.enableSharedBuildCache,ignoreMapping:n.ignoreMapping,writeProtectionMapping:n.writeProtectionMapping},"workspace_readonly")};return r&&(o.debug={fieldSources:n.fieldSources}),o}(_t(e,r),t);case"insecure_none":return function(e,t){const{perUser:r,perRepo:n,teamAdmin:o}=e,s=t?.debug,i={policy:Et({type:"insecure_none",allowlistEscalated:it(r?.allowlistEscalated,n?.allowlistEscalated,o?.allowlistEscalated)||void 0,debugOutputDir:gt(r?.debugOutputDir,n?.debugOutputDir,o?.debugOutputDir),captureDenies:it(r?.captureDenies,n?.captureDenies,o?.captureDenies)||void 0,enableSharedBuildCache:gt(r?.enableSharedBuildCache,n?.enableSharedBuildCache,o?.enableSharedBuildCache)},"insecure_none")};return s&&(i.debug={fieldSources:{}}),i}(_t(e,r),t);default:throw new Error(`Unknown policy type: ${String(r)}`)}}(e,t)}function kt(e,t){return e?.type===t}function _t(e,t){const{perUser:r,perRepo:n,teamAdmin:o}=e;return{perUser:kt(r,t)?r:void 0,perRepo:kt(n,t)?n:void 0,teamAdmin:kt(o,t)?o:void 0}}function Ct(e,t){const r=t?.debug,{perUser:n,perRepo:o,teamAdmin:s}=e,i=t?.workspaceDir??process.cwd(),a=function(e){const t=function(){if(0!==$e.length)return{version:1,deny:[...$e]}}(),r=H.default.homedir(),n=[];for(const e of Ie)switch(e.type){case"workspace":case"git":case"worktree":break;case"absolute":n.push(e.pattern);break;case"home":r.length>0&&n.push((0,f.join)(r,e.pattern));break;default:{const t=e.type;throw new Error(`Unknown entry type: ${String(t)}`)}}return n.push(...ge(r)),{type:"workspace_readwrite",additionalReadonlyPaths:n,writeProtectionMapping:Re(e),...t&&{networkPolicy:t},networkPolicyStrict:!0}}(i),c={},l=[n,o,s],u=["perUser","perRepo","teamAdmin","hardcoded"],d=(e,t)=>{r&&(c[e]=u[t]??"unknown")},h=it(n?.disableTmpWrite,o?.disableTmpWrite,s?.disableTmpWrite);for(let e=l.length-1;e>=0;e--)if(!0===l[e]?.disableTmpWrite){d("disableTmpWrite",e);break}const p=it(n?.networkPolicyStrict,o?.networkPolicyStrict,s?.networkPolicyStrict,a.networkPolicyStrict);a.networkPolicyStrict&&d("networkPolicyStrict",3);const m=gt(n?.readBoundary,o?.readBoundary,s?.readBoundary)??"system",g=gt(n?.additionalReadPaths,o?.additionalReadPaths),w=!1===s?.allowUserOverrideReadPaths?at(s.additionalReadPaths):at(g,s?.additionalReadPaths),y="workspace"===m?w:void 0,v=at(n?.additionalReadonlyPaths,o?.additionalReadonlyPaths,s?.additionalReadonlyPaths,a.additionalReadonlyPaths),b=v.length>0?v:void 0;let S=pt(n?.networkPolicy,o?.networkPolicy,s?.networkPolicy,a.networkPolicy);const k=s?.networkPolicy?.allow;void 0!==k&&k.length>0&&void 0!==S&&(S={...S,allow:[...k]},r&&(c["networkPolicy.allow"]="teamAdmin (replace)"));const _=void 0!==(C=S)?C:{version:1,default:"deny"};var C;const E=gt(n?.debugOutputDir,o?.debugOutputDir,s?.debugOutputDir),x=it(n?.captureDenies,o?.captureDenies,s?.captureDenies),P=gt(n?.enableSharedBuildCache,o?.enableSharedBuildCache,s?.enableSharedBuildCache),I=mt(n?.ignoreMapping,o?.ignoreMapping,s?.ignoreMapping,a.ignoreMapping),R=Te(t?.gitDirParent??i);return{disableTmpWrite:h||void 0,networkPolicyStrict:p,readBoundary:m,additionalReadPaths:y,additionalReadonlyPaths:b,networkPolicy:_,debugOutputDir:E,captureDenies:x||void 0,enableSharedBuildCache:P,ignoreMapping:I,writeProtectionMapping:mt(n?.writeProtectionMapping,o?.writeProtectionMapping,s?.writeProtectionMapping,a.writeProtectionMapping,R),fieldSources:c}}function Et(e,t){const r={...e,type:t};for(const[e,t]of Object.entries(r))void 0===t&&Reflect.deleteProperty(r,e);return r}function xt(e,t){const{perUser:r,perRepo:n,teamAdmin:o}=e,s=t?.debug,i=Ct(e,t),a=at(r?.additionalReadwritePaths,n?.additionalReadwritePaths,o?.additionalReadwritePaths),c={policy:Et({type:"workspace_readwrite",disableTmpWrite:i.disableTmpWrite,networkPolicyStrict:i.networkPolicyStrict,readBoundary:i.readBoundary,additionalReadPaths:i.additionalReadPaths,additionalReadwritePaths:a.length>0?a:void 0,additionalReadonlyPaths:i.additionalReadonlyPaths,networkPolicy:i.networkPolicy,debugOutputDir:i.debugOutputDir,captureDenies:i.captureDenies,enableSharedBuildCache:i.enableSharedBuildCache,ignoreMapping:i.ignoreMapping,writeProtectionMapping:i.writeProtectionMapping},"workspace_readwrite")};return s&&(c.debug={fieldSources:i.fieldSources}),c}var Pt=r("node:child_process"),It=r("../utils/dist/workload-spawn.js"),Rt=r("../context/dist/logger.js"),Tt=r("../context/dist/core.js");const At=Pt.execFile,$t=new WeakMap;function Mt(e,t,r){return e===t?"related":r?.has(e)?"probably_unrelated":"maybe_related"}const Dt="darwin"===process.platform,Ot="linux"===process.platform,Ft=(0,Rt.h)("shell-exec:sandbox");function Nt(e){const t=ie();return e&&0!==e.length?e.includes(t)?e:[...e,t]:[t]}let Lt,jt=!0,Ut=!1;function Bt(){return Lt}function Wt(e){"linux"===process.platform&&Object.assign(e,I(e))}let Ht=null,qt=null,zt=null,Gt=null,Vt=!1,Kt=null;function Jt(e){return{...e,additionalReadonlyPaths:Nt(e.additionalReadonlyPaths)}}function Zt(e,t,r){let n;e.ignoreMapping&&(n=function(e){return nr(e)}(e.ignoreMapping));const o=function(e,t,r){const n=e&&e.length>0?function(...e){const t={};for(const r of e){let e=!1;try{e=(0,m.existsSync)(r)&&(0,m.statSync)(r).isDirectory()}catch{}if(e)t[r]||(t[r]=[]),t[r].push("**");else{const e=r.lastIndexOf("/"),n=e>0?r.slice(0,e):"/",o=e>=0?r.slice(e+1):r;t[n]||(t[n]=[]),o?t[n].push(o,`${o}/**`):t[n].push("**")}}return t}(...e):{},o=!Ot||rr(r),s={...n};for(const[e,r]of Object.entries(t??{})){const t=e.startsWith("file://")?or(e):e;(o||rr(t))&&(s[e]=ft(s[e],r))}if(0!==Object.keys(s).length)return nr(s)}(e.additionalReadonlyPaths,e.writeProtectionMapping,t),s=(i=e.readBoundary,r?.workspaceReadEnabled??function(){const e=jt;return"function"==typeof e?e():e}()?i??"system":"system");var i;const a=function(e=process.platform){const t=[],r=new Set,n={};try{n.ripgrep=R()}catch{}for(const o of Pe(e,H.homedir(),n))r.has(o)||(r.add(o),t.push(o));return t}(),c="workspace"===s?function(e){const t=[],r=new Set;for(const n of e){let e=n.trim();if(!e)continue;"~"===e?e=H.homedir():(e.startsWith("~/")||e.startsWith("~\\"))&&(e=f.join(H.homedir(),e.slice(2))),e=e.replace(/\/\*\*$/,"").replace(/\/\*$/,""),e=e.replace(/\\\*\*$/,"").replace(/\\\*$/,"");const o=f.basename(e);if((o.includes("*")||o.includes("?"))&&(e=f.dirname(e)),!e||"."===e)continue;const s=f.normalize(e);r.has(s)||(r.add(s),t.push(s))}return t}(e.additionalReadPaths??[]):[],l=[...a],u=new Set(a);for(const e of c)u.has(e)||(u.add(e),l.push(e));const d={cwd:t,readBoundary:s,hardcodedReadPaths:l,additionalReadonlyPaths:o,networkAccess:Je(e.networkPolicy),ignoreMapping:n};return"workspace_readonly"===e.type?{type:e.type,...d}:{type:e.type,...d,additionalReadwritePaths:e.additionalReadwritePaths||[],disableTmpWrite:e.disableTmpWrite||!1}}function Xt(e){const t={sandbox:e};return Ot&&function(){const e=Ut;return"function"==typeof e?e():e}()&&(t.kernelMountBudget=!0),t}function Qt(e){if(null!==Ht)return Ht;try{const t=Bt();return Ft.info(e,`[checkBinaryAvailable] Resolved binary path: ${t}`),t?(Ht=m.existsSync(t),Ht?Ft.info(e,`[checkBinaryAvailable] Binary path exists: ${String(Ht)}`):(qt=new Error(`Sandbox binary not found at ${t}`),Ft.info(e,`[checkBinaryAvailable] Binary not found at: ${t}`)),Ht):(qt=new Error("Sandbox binary path was not configured"),Ht=!1,Ft.info(e,"[checkBinaryAvailable] Binary path not set, returning false"),!1)}catch(t){return qt=t instanceof Error?t:new Error(String(t)),Ht=!1,Ft.info(e,`[checkBinaryAvailable] Exception checking binary: ${String(t)}`),!1}}function Yt(e){if(null!==Gt)return Gt;const t=e??(0,Tt.q6)();if(Ft.info(t,"[isSandboxHelperSupported] Starting sandbox support check..."),!Qt(t)){const e=qt?.message||"Binary check failed";return zt=e,Ft.info(t,`[isSandboxHelperSupported] Binary not available, returning false. Reason: ${e}`),Gt=!1,Gt}if("win32"===process.platform)return zt="Windows sandbox helper only provides network proxy, not filesystem isolation",Ft.info(t,"[isSandboxHelperSupported] win32: returning false (proxy-only, no filesystem sandbox)"),Gt=!1,Gt;if("darwin"===process.platform)return zt=null,Ft.info(t,`[isSandboxHelperSupported] ${process.platform} platform, binary available, sandbox supported!`),Gt=!0,Gt;const{binaryPath:r,args:n,env:o}=function(e,t){const r=Xt(Zt(Jt({type:"workspace_readwrite"}),t)),n=String(Bt());Ft.info(e,`[sandboxPreflight] Running preflight with binary: ${n}`),Ft.info(e,`[sandboxPreflight] CWD: ${t}`);const o={...process.env};return Wt(o),{binaryPath:n,args:["--policy",ae(JSON.stringify(r)),"--preflight-only","--","/bin/true"],env:o}}(t,process.cwd());try{const e=Date.now();(0,It.D9)(Pt.execFileSync,r,n,{stdio:["ignore","ignore","pipe"],timeout:er,env:o,shell:!1});const s=Date.now()-e;return zt=null,Ft.info(t,`[isSandboxHelperSupported] Preflight succeeded in ${s}ms, sandbox supported!`),Gt=!0,Gt}catch(e){return function(e,t){const{message:r,status:n,stderrText:o}=t;return Ft.error(e,`[sandboxPreflight] Preflight failed: ${r}`),Ft.error(e,`[sandboxPreflight] Exit status: ${n}`),o&&Ft.error(e,`[sandboxPreflight] Stderr: ${o}`),zt=2===n?`Linux preflight failed with exit code 2 (unsupported kernel features). stderr: ${o||"none"}`:`Linux preflight failed: ${r||"unknown error"}. Exit status: ${n}. stderr: ${o||"none"}`,Gt=!1,!1}(t,function(e){if("object"!=typeof e||null===e)return{stderrText:""};const t="message"in e&&"string"==typeof e.message?e.message:void 0,r=!("status"in e)||"number"!=typeof e.status&&null!==e.status?void 0:e.status,n="stderr"in e?e.stderr:void 0;return{message:t,status:r,stderrText:Buffer.isBuffer(n)||"string"==typeof n?n.toString():""}}(e))}}(0,z.J)((function(){Gt=null,Vt=!1,Kt=null,zt=null,Ht=null,qt=null}));const er=15e3;function tr(e,t=[],r={},n){const s=(0,Tt.q6)();if(r.env=i(o(r.env)),!Qt(s))throw new Error(`Sandbox binary not available: ${qt?.message||"binary not configured"}. Please build the binary or use 'insecure_none' policy.`);if("insecure_none"===n.type)return(0,It.D9)(Pt.spawn,e,t,{...r,windowsHide:!0});if("workspace_readwrite"===n.type||"workspace_readonly"===n.type)return function(e,t,r,n){if("workspace_readwrite"!==n.type&&"workspace_readonly"!==n.type)throw new Error("Expected workspace_readwrite or workspace_readonly policy");const s=String(r.cwd??process.cwd()),a=n.sandboxWorkspaceRoot??s;let l=e,u=t;r.shell&&("win32"===process.platform?(l="string"==typeof r.shell?r.shell:"cmd.exe",u=["/c",`${e} ${t.join(" ")}`]):(l="string"==typeof r.shell?r.shell:"/bin/sh",u=["-c",`${e} ${t.join(" ")}`]));const d=function({workspaceRoot:e,executionCwd:t}){const r=f.resolve(e),n=f.resolve(t),o=sr(r);if(n===r||n===o)return;const s=e=>(0,Ye.ZU)({basePath:o,targetPath:e})?f.join(r,f.relative(o,e)):void 0,i=(0,Ye.ZU)({basePath:r,targetPath:n})?n:s(n)??n;return{directory:i,fallbackDirectory:s(sr(n))??i}}({workspaceRoot:a,executionCwd:s});"win32"!==process.platform&&void 0!==d&&({command:l,args:u}=(0,re.kO)(l,u,d));const h=Zt(Jt(n),a),p=(0,Tt.q6)();!function({log:e,dirs:t=we(H.homedir(),H.tmpdir(),de),createOnly:r=[me(process.env,de)].filter((e=>void 0!==e)),policyDir:n=oe(),uid:o=process.getuid?.()??-1}){const s=f.join(n,"node-compile-cache-removed-1"),{record:i,problem:a}=function(e){const t=e=>({record:{cleaned:[],kept:{},failed:{}},problem:e});let r,n;try{r=m.readFileSync(e,"utf8")}catch(e){const r=be(e);return t("ENOENT"===r?void 0:r)}try{n=JSON.parse(r)}catch(e){return t(e instanceof SyntaxError?"not JSON":be(e))}if("object"!=typeof n||null===n)return t("not a record");const o="cleaned"in n?n.cleaned:void 0;return{record:{cleaned:Array.isArray(o)?o.filter((e=>"string"==typeof e)):[],kept:ve("kept"in n?n.kept:void 0),failed:ve("failed"in n?n.failed:void 0)}}}(s);void 0!==a&&e(`node compile cache: starting a new cleanup record (${a})`);const c=new Set(i.cleaned),l=new Set(t);let u=!1;for(const n of[...t,...r.filter((e=>!l.has(e)))])try{const t=m.lstatSync(n,{throwIfNoEntry:!1});if(void 0!==t){const r=ye(t,o);if(void 0!==r){i.kept[n]!==r&&(e(`node compile cache: kept ${n} (${r})`),i.kept[n]=r,u=!0);continue}l.has(n)&&!c.has(n)&&(m.rmSync(n,{recursive:!0,force:!0}),e(`node compile cache: removed ${n}`))}m.mkdirSync(n,{recursive:!0,mode:448}),l.has(n)&&!c.has(n)&&(c.add(n),u=!0),void 0===i.kept[n]&&void 0===i.failed[n]||(delete i.kept[n],delete i.failed[n],u=!0)}catch(t){const r=be(t);i.failed[n]!==r&&(e(`node compile cache: could not prepare ${n} (${r})`),i.failed[n]=r,u=!0)}u&&function(e,t){const r=`${e}.${process.pid}.tmp`;try{m.writeFileSync(r,`${JSON.stringify(t)}\n`,{mode:384}),m.renameSync(r,e)}catch{m.rmSync(r,{force:!0})}}(s,{...i,cleaned:[...c]})}({log:e=>Ft.info(p,e)});const g=function(e){if(!("workspace"!==e.readBoundary||"workspace_readwrite"===e.type&&e.disableTmpWrite||"win32"===process.platform))return Z(e.cwd,{create:!0})}(h);g&&(h.additionalReadwritePaths=[...h.additionalReadwritePaths??[],g]);const w=function(e){if("insecure_none"===e.type)return;const t=e.networkPolicy;if(void 0===t)return;if(!Je(t))return;const r=void 0!==t.deny&&t.deny.length>0;return"allow"!==t.default||r?{version:1,...t}:void 0}(n),y=Xt(h);void 0!==w&&(y.networkPolicy=w),!1===n.networkPolicyStrict&&(y.networkPolicyStrict=!1);const v=["--policy",ae(JSON.stringify(y)),"--",l,...u],b=o(process.env),S={..."linux"===process.platform?c(b):b,..."linux"===process.platform&&r.env?c(r.env):r.env,CURSOR_SANDBOX:"native"};Wt(S);const k=new Set(Q);if(g){const e=function(e,t,r){const n=function(e){const t=(0,f.join)(e,"tmp");return{TMPDIR:t,TMP:t,TEMP:t,TMPPREFIX:(0,f.join)(t,"sh-")}}(e);if(r){const r=ee();for(const[o,s]of Object.entries(ee(e)))t[o]===r[o]&&(n[o]=s)}return n}(g,S,n.enableSharedBuildCache);Object.assign(S,e);for(const t of Object.keys(e))k.add(t);S.__CURSOR_SANDBOX_TEMP_RESTORE=Object.entries(e).map((([e,t])=>`builtin export ${e}='${t.replace(/'/g,"'\\''")}'`)).join("; ")}S.__CURSOR_SANDBOX_OWNED_ENV=[...k].join(" ");const _={cwd:r.cwd||s,env:i(S),stdio:r.stdio||["pipe","pipe","pipe"],detached:r.detached,windowsHide:!0};try{const e=new Date,t=(0,It.D9)(Pt.spawn,String(Bt()),v,_);return Dt&&t.pid&&function(e,t){$t.set(e,t)}(t,{startTime:e,pid:t.pid}),t}catch(e){throw new Error(`Failed to spawn sandboxed process: ${String(e)}`)}}(e,t,r,n);throw new Error(`Unsupported sandbox policy: ${String(n)}`)}function rr(e,t=e=>m.existsSync(e)){if((0,re.$f)(e))return!0;let r=f.resolve(e);for(;;){try{if(t(f.join(r,".git")))return!0}catch{}const e=f.dirname(r);if(e===r)return!1;r=e}}function nr(e,t,r,n){const o={};for(const[t,r]of Object.entries(e)){const e=t.startsWith("file://")?or(t):t;o[e]=ft(o[e],r);const n=sr(e);n!==e&&(o[n]=ft(o[n],r))}return o}function or(e){let t=e.replace(/^file:\/\//,"");return t=decodeURIComponent(t),t.length>1&&t.endsWith("/")&&(t=t.slice(0,-1)),t}function sr(e,t){if((0,re.$f)(e))return e;try{return(t??m.realpathSync)(e)}catch{return e}}function ir(){return zt}class ar extends Error{reason;constructor(e,t){super(e),this.reason=t,this.name="SandboxUnsupportedError"}}const cr="darwin"===process.platform;function lr(e){!function(e){R();const{sandboxBinaryPath:t,workspaceReadEnabled:r,kernelMountBudget:n}=e;Lt||(Lt=t),void 0!==r&&(jt=r),void 0!==n&&(Ut=n)}(e)}function ur(e,t=[],r={},n){if(r.env=o(r.env),n.enableSharedBuildCache&&(r={...r,env:{...o(process.env),...ee(),...r.env}}),"insecure_none"!==n.type){if(Yt())return tr(e,t,r,n);const o=ir();throw new ar(`Sandbox policy '${n.type}' is not supported on this system. Ensure the sandbox helper binary is available, or use 'insecure_none'. Reason: ${o||"unknown"}`,o??void 0)}return function(e,t,r,n={spawn:Pt.spawn,spawnWorkload:It.D9}){return n.spawnWorkload(n.spawn,e,t,{...r,env:i(r.env??process.env),windowsHide:!0})}(e,t,r)}function dr(e){return cr?async function(e){const t=$t.get(e);return t?(r=t.pid,n=t.startTime,o=t.unrelatedPids,new Promise((e=>{try{const t=new Date,s=["show","--style","ndjson","--predicate",'process=="kernel" AND eventMessage CONTAINS "Sandbox:" AND eventMessage contains "deny"',"--last",Math.ceil((t.getTime()-n.getTime())/1e3).toString()];(0,It.D9)(At,"/usr/bin/log",s,((t,n)=>{if(t)return void e([{raw:t.message}]);const s=n.split(/\r?\n/).filter((e=>e.trim().length>0)),i=[];for(const e of s)try{const t=JSON.parse(e),n=t?.eventMessage??"";if(!n||"string"!=typeof n)continue;const s=/^Sandbox:\s+([^(]+)\((\d+)\)\s+([a-zA-Z-]+)\((\d+)\)\s+([^\s]+)\s+(.+)$/.exec(n);if(s){const[,e,a,c,l,u,d]=s,h=Number(a);i.push({timestamp:t.timestamp,processName:e.trim(),pid:h,decision:c.toLowerCase(),decisionCode:Number(l),operation:u,target:d,duplicateCount:1,raw:n,relationship:Mt(h,r,o)});continue}const a=/^(\d+) duplicate report for Sandbox: (.+)$/.exec(n);if(a){const e=Number(a[1]),s=a[2],c=/^([^(]+)\((\d+)\)\s+([a-zA-Z-]+)\((\d+)\)\s+([^\s]+)\s+(.+)$/.exec(s);if(c){const[,s,a,l,u,d,h]=c,p=Number(a);i.push({timestamp:t.timestamp,processName:s.trim(),pid:p,decision:l.toLowerCase(),decisionCode:Number(u),operation:d,target:h,duplicateCount:e,raw:n,relationship:Mt(p,r,o)})}else i.push({timestamp:t.timestamp,duplicateCount:e,raw:n});continue}i.push({timestamp:t.timestamp,raw:n})}catch{}e(i)}))}catch(t){e([{raw:String(t)}])}}))):(console.log("No sandbox metadata found on child process"),[]);var r,n,o}(e):Promise.resolve([])}function hr(e,t){if(cr)try{(0,m.accessSync)("/usr/bin/sandbox-exec",m.constants.X_OK)}catch{return!1}return Yt(t?.ctx)}var pr=r("node:stream"),fr=r("../context/dist/otel.js"),mr=r("../utils/dist/writable-iterable.js");const gr="--",wr='builtin eval "$1" 3<&- 4>&-';var yr=r("node:string_decoder");const vr=50,br=262144;class Sr{writable;pending=[];pendingBytes=0;flushTimeout;flushPromise;flushIntervalMs;maxBufferedBytes;constructor(e,t){this.writable=e,this.flushIntervalMs=t?.flushIntervalMs??vr,this.maxBufferedBytes=t?.maxBufferedBytes??br}async push(e,t){0!==t.length&&(this.pending.push({type:e,data:t}),this.pendingBytes+=t.length,this.pendingBytes>=this.maxBufferedBytes?await this.flush():this.scheduleFlush())}async flush(){if(this.clearFlushTimeout(),this.flushPromise)return await this.flushPromise,void(this.pendingBytes>0&&await this.flush());if(0===this.pendingBytes)return;const e=this.pending;this.pending=[],this.pendingBytes=0,this.flushPromise=this.writeBufferedOutput(e);try{await this.flushPromise}finally{this.flushPromise=void 0}}async close(){await this.flush()}scheduleFlush(){void 0===this.flushTimeout&&(this.flushTimeout=setTimeout((()=>{this.flushTimeout=void 0,this.flush()}),this.flushIntervalMs))}clearFlushTimeout(){void 0!==this.flushTimeout&&(clearTimeout(this.flushTimeout),this.flushTimeout=void 0)}async writeBufferedOutput(e){for(const t of function(e){if(0===e.length)return[];const t=[];let r=e[0].type,n=[e[0].data];for(let o=1;o<e.length;o++){const s=e[o];s.type!==r?(t.push({type:r,data:Buffer.concat(n)}),r=s.type,n=[s.data]):n.push(s.data)}return t.push({type:r,data:Buffer.concat(n)}),t}(e))try{await this.writable.write(t)}catch{}}}function kr(e){const t=new re.Zv;if(!e.bufferOutputEvents){const r=(t,r)=>{e.writable.write({type:t,data:r}).catch((()=>{}))};return e.stdout?.on("data",(e=>{const n=t.note(e);void 0!==n&&n.length>0&&r("stdout",n)})),e.stderr?.on("data",(e=>{r("stderr",e)})),{get stdoutBytes(){return t.bytes},get stdoutPrefix(){return t.stdoutPrefix},async waitForOutput(){},async releaseHeldStdout(){const e=t.takeHeld();void 0!==e&&e.length>0&&r("stdout",e)},dropHeldStdout(){t.takeHeld()},async flush(){await this.releaseHeldStdout()}}}const r=new Sr(e.writable,e.outputLimiterOptions);let n;const o=Promise.all([_r(e.stdout,r,t),Cr(e.stderr,"stderr",r)]).then((()=>{})).catch((e=>{n=e}));return{get stdoutBytes(){return t.bytes},get stdoutPrefix(){return t.stdoutPrefix},async waitForOutput(){if(await o,void 0!==n)throw(e=n)instanceof Error?e:new Error(String(e));var e},async releaseHeldStdout(){const e=t.takeHeld();void 0!==e&&e.length>0&&await r.push("stdout",e)},dropHeldStdout(){t.takeHeld()},async flush(){await this.releaseHeldStdout(),await r.flush()}}}async function _r(e,t,r){if(e)for await(const n of e){const e=r.note(n);void 0!==e&&e.length>0&&await t.push("stdout",e)}}async function Cr(e,t,r,n){if(e)for await(const o of e)n?.(o),await r.push(t,o)}var Er;!function(e){e.Zsh="zsh",e.ZshLight="zsh-light",e.Bash="bash",e.PowerShell="powershell",e.Naive="naive"}(Er||(Er={}));const xr={TERM:"dumb",NO_COLOR:"1",FORCE_COLOR:"0",_ZO_DOCTOR:"0"};function Pr(e){return"win32"===e.platform?"windows_tree":e.detached?"process_group":"single_process"}function Ir(e,t,r,n={spawn:Pt.spawn,killPid:process.kill.bind(process)}){const o=e.pid;if(void 0===o)return;const s=()=>{try{e.kill(r)}catch{}};switch(t){case"process_group":try{n.killPid(-o,r)}catch{s()}return;case"windows_tree":try{n.spawn("taskkill",["/pid",String(o),"/t","/f"],{stdio:"ignore",windowsHide:!0}).on("error",s)}catch{s()}return;case"single_process":return void s();default:throw new Error(`Unknown process tree kill mode: ${String(t)}`)}}function Rr(e,t=[],r={},n,o){const s=ur(e,t,{...r,env:I(r.env??process.env)},n);return o&&Tr(s,{detached:!0===r.detached},o),s}function Tr(e,t,r){const n=Pr({platform:process.platform,detached:t.detached}),o=()=>{if(!e.pid)return;Ir(e,n,"SIGTERM");const t=setTimeout((()=>{!e.killed&&e.pid&&Ir(e,n,"SIGKILL")}),1e3);"process_group"!==n&&e.once("exit",(()=>{clearTimeout(t)}))};r.aborted?o():(r.addEventListener("abort",o,{once:!0}),e.once("exit",(()=>{r.removeEventListener("abort",o)})))}function Ar(e,t,r){if(e){try{process.kill(-e,t)}catch{return}"SIGTERM"===t&&void 0!==r&&r>0&&setTimeout((()=>{try{process.kill(-e,"SIGKILL")}catch{}}),r)}}const $r=new Set(["SIGTERM","SIGINT","SIGHUP","SIGQUIT","SIGKILL"]);function Mr(e,t,r){null!==t&&$r.has(t)&&!r&&"win32"!==process.platform&&Ar(e,t)}function Dr(e,{shellName:t,closeGraceMs:r,timeoutMs:n}){const o=r??5e3,s=n??6e4;return new Promise((r=>{const n=[];let i;const a=e=>{n.push(e)},c=()=>{clearTimeout(d),o<=0||(i=setTimeout((()=>{console.warn(`[shell-exec] ${t} state init exited but its stdio did not close within ${o}ms; a startup file left a background process holding the output pipe. Proceeding with the dump received so far.`),u("exit_without_close")}),o))},l=()=>{u("closed")},u=t=>{clearTimeout(d),clearTimeout(i),e.off("exit",c),e.off("close",l),e.stdout?.off("data",a),e.stdout?.resume(),r({outcome:t,stdout:Buffer.concat(n).toString("utf8")})},d=s>0?setTimeout((()=>{console.warn(`[shell-exec] ${t} state init did not exit within ${s}ms; a startup file is blocking. Killing it and falling back to an empty state.`),Ir(e,Pr({platform:process.platform,detached:!0}),"SIGKILL"),u("timed_out")}),s):void 0;e.stdout?.on("data",a),Or(e.stdout),e.on("exit",c),e.on("close",l)}))}function Or(e){e?.on("error",(()=>{}))}function Fr(e){e.removeAllListeners(),e.on("error",(()=>{})),e.stdout?.removeAllListeners("close"),e.stderr?.removeAllListeners("close");for(const t of e.stdio.slice(3))t?.destroy()}const Nr="IFS= builtin read -r -d '' __cursor_command <&5 2>/dev/null || { builtin printf '%s\\n' 'The command did not run: a shell startup file ($BASH_ENV or .zshenv) closed or replaced file descriptor 5, which carries the command. Run it again; this shell now passes commands as arguments.' >&2; builtin exit 126; }; exec 5<&-; builtin set -- \"$__cursor_command\"; builtin unset __cursor_command; ";function Lr(e,t){return 126===e&&""===t}function jr(){return"win32"!==process.platform}function Ur(e,t){const r=e.stdio.at(5);r instanceof pr.default.Writable&&(Or(r),r.end(`${t}\0`))}function Br(e,t){e&&(Or(e),e.write(t),e.end())}function Wr(e,t){if(!e)return;Or(e);const r=new yr.StringDecoder("utf8");e.on("data",(e=>{const n=r.write(e);""!==n&&t(n)})),e.on("end",(()=>{const e=r.end();""!==e&&t(e)}))}function Hr(e){const t=e.indexOf("\n");return{cwd:Buffer.from(e.substring(0,t),"utf16le").toString("utf16le"),rest:e.substring(t)}}function qr(e,t){const r=`${t}\n`,n=e.indexOf(r);return n>=0?e.slice(n+r.length):e}function zr(e){return!1===e?.isLoginShellEnabled?"-ic":"-ilc"}function Gr(e,t,r){const n=`${t}\n`;if(!e.startsWith(n))return;const o=e.indexOf(`\n${r}\n`,n.length-1);return o<0?void 0:e.slice(n.length,o+1)}const Vr="__CURSOR_BASH_STATE_START__",Kr="__CURSOR_BASH_STATE_END__";var Jr=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function Zr(e){if("win32"===process.platform){const t=/git.*bash/i;if(e&&t.test(e))return e;const r=S("bash",[],t).cmd;return t.test(r)?r:null}const t=process.env.SHELL;return t?.includes("bash")?t:S("bash",[]).cmd}function Xr(e){if("win32"!==process.platform)return e;const t=f.default.normalize(e),r=t[0]?.toLowerCase();return r&&":"===t[1]&&t[2]===f.default.sep?`/${r}${t.slice(2).replace(/\\/g,"/")}`:t.replace(/\\/g,"/")}function Qr(e){const t=e.pipeStdin?wr:`${wr} < /dev/null`,r=e.useFileTransport?'snap=$(command cat "$CURSOR_STATE_INPUT_FILE")':"snap=$(command cat <&3)",n=e.useFileTransport?'mkdir -p "$(dirname "$CURSOR_STATE_OUTPUT_FILE")" 2>/dev/null; dump_bash_state > "$CURSOR_STATE_OUTPUT_FILE"':"dump_bash_state >&4";return(e.pipeCommand?Nr:"")+`${r} && builtin shopt -s extglob && builtin eval -- "$snap"; { builtin set +u 2>/dev/null || true; builtin eval "\${__CURSOR_SANDBOX_ENV_RESTORE:-}" 2>/dev/null; `+X+Y+(e.envInjection??"")+`builtin export PWD="$(builtin pwd)"; builtin shopt -s expand_aliases 2>/dev/null; ${e.sudoAliasInjection}${t}; }; `+`COMMAND_EXIT_CODE=$?; ${n}; builtin exit $COMMAND_EXIT_CODE`}class Yr{cwd;state;userTerminalHint;useFileStateTransport;commandPipeUnreadable;constructor(e,t,r,n=!1,o=!1){this.cwd=e,this.state=t,this.userTerminalHint=r,this.useFileStateTransport=n,this.commandPipeUnreadable=o}async getCwd(){return this.cwd}clone(e){return new Yr(e??this.cwd,this.state,this.userTerminalHint,this.useFileStateTransport,this.commandPipeUnreadable)}resetSessionCwdAfterHopCdFailure(e){const{cwd:t,sandboxWorkspaceRoot:r}=e;f.default.resolve(t)===f.default.resolve(this.cwd)&&(this.cwd=void 0===r||f.default.resolve(r)===f.default.resolve(t)||(0,re.A)(r)?(0,re.D1)():r)}async*execute(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(n,(0,fr.VI)(e.withName("BashState.execute")),!1),s=r?.pipeStdin??!1,a=(0,mr.Jt)(),c=r?.workingDirectory??this.cwd,l=function(e,t=process.platform,r=process.env){const n={...r,...xr,...e?.env};return u(n),"win32"===t&&(F(n),N(n)),i(n)}(r),d=$(l),h=this.useFileStateTransport,p=!h&&!this.commandPipeUnreadable;let m,g,w;if(h){m=await(0,te.mkdtemp)(f.default.join(H.default.tmpdir(),"cursor-bash-state-")),g=f.default.join(m,"state-in"),w=f.default.join(m,"state-out"),await(0,te.writeFile)(g,this.state,"utf8"),await(0,te.writeFile)(w,"","utf8").catch((()=>{}));const e=Xr(g),t=Xr(w);l.CURSOR_STATE_INPUT_FILE=e,l.CURSOR_STATE_OUTPUT_FILE=t}const y=function(e){return["-O","extglob","-c",e.script,gr,...void 0===e.command?[]:[e.command]]}({script:Qr({pipeCommand:p,useFileTransport:h,sudoAliasInjection:d,pipeStdin:s,envInjection:"win32"===process.platform&&!0===r?.powershellUtf8ChildEnv?U:""}),command:p?void 0:t}),v=Zr(this.userTerminalHint);if(!v)throw new Error("Can't find Bash");const b=r?.sandboxWorkspaceRoot??c,S=(await wt(b,r?.sandboxPolicy)).policy,k="insecure_none"!==S.type?{...S,sandboxWorkspaceRoot:b}:S;let _="";const C=async()=>{if(h){if(!w)return void(_=this.state);try{_=await(0,te.readFile)(w,"utf8")}catch(e){console.warn("[shell-exec] Failed to read bash state file",e),_=this.state}}},E=async()=>{if(m)try{await(0,te.rm)(m,{recursive:!0,force:!0})}catch{}};let x;(0,re.$Y)(c)&&(0,fr.HF)(o.ctx,re.yo);try{x=Rr(v,y,{env:l,stdio:[s?"pipe":"ignore","pipe","pipe","pipe","pipe",p?"pipe":"ignore"],cwd:c,detached:!0},k,r?.signal)}catch(e){throw await E(),e}x.on("spawn",(async()=>{try{await a.write({type:"stdin_ready",stdin:x.stdin??void 0,pid:x.pid,shell:"bash"})}catch(e){}}));const P=kr({stdout:x.stdout,stderr:x.stderr,writable:a,bufferOutputEvents:r?.bufferOutputEvents,outputLimiterOptions:r?.outputLimiterOptions});x.on("error",(async e=>{if((0,re.fK)(e,c)){this.resetSessionCwdAfterHopCdFailure({cwd:c,sandboxWorkspaceRoot:r?.sandboxWorkspaceRoot}),(0,fr.HF)(o.ctx,re.Gq);const e=(0,re.iA)(c);console.warn(`[shell-exec] working directory is not accessible (${e.cwdKind}:${e.cwdHash})`)}await E(),a.throw(e)}));let I=null,R=null,T=null,A=!1;const M=async e=>{if(A)return;if(A=!0,T&&(clearTimeout(T),T=null),(0,fr.HF)(o.ctx,"exit"),e)try{await P.waitForOutput()}catch(e){return await E(),void a.throw(e instanceof Error?e:new Error(String(e)))}const t=(0,re.wz)({exitCode:I,stdoutBytes:P.stdoutBytes,stdoutPrefix:P.stdoutPrefix,cwd:c})&&""===_;if(t&&P.dropHeldStdout(),await P.flush(),p&&Lr(I,_)&&(this.commandPipeUnreadable=!0),t){this.resetSessionCwdAfterHopCdFailure({cwd:c,sandboxWorkspaceRoot:r?.sandboxWorkspaceRoot}),await E(),(0,fr.HF)(o.ctx,re.Gq);const e=(0,re.iA)(c);return console.warn(`[shell-exec] working directory is not accessible (${e.cwdKind}:${e.cwdHash})`),void a.throw((0,re.Vn)(c))}if(!r?.signal?.aborted){await C();const e=`${Vr}\n`,t=`${Kr}\n`;if(_.startsWith(e)&&_.endsWith(t)){let t=_.slice(e.length);t=t.slice(0,-26);const{cwd:r,rest:n}=Hr(t);this.state=n,"win32"!==process.platform&&r?.startsWith("/")&&(this.cwd=r)}}if(k.captureDenies)try{const e=await dr(x);e&&e.length>0&&await a.write({type:"sandbox_denies",events:e})}catch{}try{await a.write({type:"exit",code:I,signal:R??void 0,data:"",aborted:r?.signal?.aborted??!1}),a.close()}catch{a.close()}await E()};x.on("exit",((e,t)=>{I=e,R=t,Mr(x.pid,t,r?.signal?.aborted??!1);const n=r?.closeTimeout??5e3;n>0&&(T=setTimeout((()=>{console.warn(`[shell-exec] Close event did not fire within ${n}ms after exit. This may indicate a background process is holding file descriptors open. Proceeding anyway to prevent hang.`),M(!1).finally((()=>{Fr(x)}))}),n))})),x.on("close",(async()=>{await M(!0)}));const D=x.stdio[3],O=x.stdio[4],L=D instanceof pr.default.Writable?D:null,j=O instanceof pr.default.Readable?O:null;p&&Ur(x,t),h||(Br(L,this.state),Wr(j,(e=>{_+=e}))),yield*a}catch(e){n.error=e,n.hasError=!0}finally{Jr(n)}}}async function en(e,t){const r={...process.env,...xr,...e?.env},n="__CURSOR_STATE_MARKER__",o=["-O","extglob",zr(e),`#!/usr/bin/env bash\n\n# Usage:\n# source dump_bash_state.bash\n# dump_bash_state OUTPUT_FILE\n# Or execute directly (captures a subshell's state):\n# ./dump_bash_state.bash OUTPUT_FILE\n\ndump_bash_state() {\n set -euo pipefail\n\n # Helper to log timing, only if DUMP_BASH_STATE_TIMING is set\n if [[ -n "\${DUMP_BASH_STATE_TIMING:-}" ]]; then\n # Timing setup\n if [[ "\${BASH_VERSION%%.*}" -ge 5 ]]; then\n # Use EPOCHREALTIME if available (bash 5+)\n local start_time=\${EPOCHREALTIME}\n local step_start=\${EPOCHREALTIME}\n _log_timing() {\n local step_name="$1"\n local now=\${EPOCHREALTIME}\n local step_duration=$(command awk "BEGIN {printf "%.3f", $now - $step_start}")\n local total_duration=$(command awk "BEGIN {printf "%.3f", $now - $start_time}")\n builtin printf "[TIMING] %-20s: %6.3fs (total: %6.3fs)\n" "$step_name" "$step_duration" "$total_duration" >&2\n step_start=$now\n }\n else\n # Fallback for older bash versions\n local start_time=$(command date +%s.%N)\n local step_start=$(command date +%s.%N)\n _log_timing() {\n local step_name="$1"\n local now=$(command date +%s.%N)\n local step_duration=$(command awk "BEGIN {printf "%.3f", $now - $step_start}")\n local total_duration=$(command awk "BEGIN {printf "%.3f", $now - $start_time}")\n builtin printf "[TIMING] %-20s: %6.3fs (total: %6.3fs)\n" "$step_name" "$step_duration" "$total_duration" >&2\n step_start=$now\n }\n fi\n else\n _log_timing() { :; }\n fi\n\n # Helper to append a line to output file\n _emit() {\n builtin printf '%s\n' "$1"\n }\n\n # Helper to safely encode and emit unsafe values. printf %q quotes the value for eval\n # without starting a process, and every command pays this dump and its restore.\n _emit_encoded() {\n local content="$1"\n local var_name="$2"\n if [[ -n "$content" ]]; then\n local quoted\n builtin printf -v quoted '%q' "$content"\n builtin printf 'cursor_snap_%s=%s\n' "$var_name" "$quoted"\n builtin printf 'builtin eval "$cursor_snap_%s"\n' "$var_name"\n fi\n }\n\n # Aliases replay after the functions, so a user function named alias would run in place of\n # each alias line. Only a line that starts an alias gets builtin: a quoted value can span\n # lines, and a continuation line can start with "alias ". awk reads bytes under LC_ALL=C, so a\n # value that is not valid UTF-8 does not make it warn. Without awk the lines stay as they are.\n _builtin_alias_lines() {\n [[ -n "$1" ]] || return 0\n builtin printf '%s\n' "$1" | LC_ALL=C command awk -v sq="'" '\n !q && /^alias / { $0 = "builtin " $0 }\n {\n print\n for (i = 1; i <= length($0); i++) {\n c = substr($0, i, 1)\n if (q == 1) { if (c == sq) q = 0 }\n else if (q == 2) { if (c == "\\\\") i++; else if (c == sq) q = 0 }\n else if (c == "\\\\") i++\n else if (c == "$" && substr($0, i + 1, 1) == sq) { q = 2; i++ }\n else if (c == sq) q = 1\n }\n }' 2>/dev/null ||\n builtin printf '%s\n' "$1"\n }\n\n # Start fresh\n _log_timing "file_init"\n\n # Emit start marker at the very beginning of the output\n _emit "__CURSOR_BASH_STATE_START__"\n\n # Working directory\n _emit "$PWD"\n _log_timing "working_dir"\n\n # The shell starts in POSIX mode when it inherits POSIXLY_CORRECT. POSIX_MODE\n # turns it back on after the functions if the session had it on.\n _emit "builtin set +o posix; builtin unset POSIXLY_CORRECT"\n\n # Drop ELECTRON_RUN_AS_NODE by exact name so one command exporting it can't\n # bake it into the snapshot that every later command re-evals (IDE-2911:\n # Cypress boots as plain Node until a new chat). Exact unset rather than the\n # line-based grep below, which would also eat vars whose name or multiline\n # value merely contains the token. The shell exits right after the dump.\n builtin unset ELECTRON_RUN_AS_NODE 2>/dev/null || true\n\n # Environment variables (export statements)\n # Filter out: proxy settings plus request/session-scoped vars that must not\n # leak across shell executions.\n local env_vars\n env_vars=$(builtin export -p 2>/dev/null | command grep -viE '_proxy=|CURSOR_SANDBOX|SUDO_ASKPASS|CURSOR_ASKPASS|CURSOR_CONVERSATION_ID|CURSOR_REQUEST_ID|CURSOR_AGENT_STORE' | command grep -vE '^(declare|export)( -[a-zA-Z]+)* POSIXLY_CORRECT(=|$)' || true)\n if [[ -n "\${__CURSOR_SANDBOX_OWNED_ENV:-}" ]]; then\n env_vars=$(builtin printf '%s\n' "$env_vars" | command grep -vE "^(export|declare|typeset)( -[a-zA-Z]+)* (\${__CURSOR_SANDBOX_OWNED_ENV// /|})=" || true)\n fi\n _emit_encoded "$env_vars" "ENV_VARS"\n _log_timing "environment"\n\n # POSIX shell options (replayable as set +/-o lines). Exclude the errexit/nounset/\n # pipefail this function force-enables above, so they are not baked into the restored\n # snapshot and leaked onto every subsequent command (a stray pipefail makes a\n # successful 'cmd | head' report exit 141). Exclude monitor too: the interactive login\n # shell of bash 3.2 reports it on, and a command shell that restored it would run every\n # command in a process group of its own, where a signal to the shell's group misses it.\n local posix_opts\n posix_opts=$(builtin shopt -po 2>/dev/null | command grep -vE '^set [-+]o (errexit|monitor|nounset|pipefail|posix)$' || true)\n _emit_encoded "$posix_opts" "POSIX_OPTS"\n _log_timing "posix_options"\n\n # Bash shopt options (replayable as shopt -s/-u lines)\n local bash_opts\n bash_opts=$(builtin shopt -p 2>/dev/null || true)\n _emit_encoded "$bash_opts" "BASH_OPTS"\n _log_timing "bash_options"\n\n # Functions: capture all functions\n local all_functions\n all_functions=$(builtin declare -f 2>/dev/null || true)\n _emit_encoded "$all_functions" "FUNCTIONS"\n _log_timing "functions"\n\n # Aliases\n local aliases\n aliases=$(_builtin_alias_lines "$(builtin alias -p 2>/dev/null || true)" || true)\n _emit_encoded "$aliases" "ALIASES"\n _log_timing "aliases"\n\n # POSIX mode makes a function name that is not a POSIX identifier, such as my-fn, a\n # fatal error, so it is replayed after the functions. Turning it on resets shopt\n # options such as inherit_errexit, so the shopt state is replayed again after it.\n local posix_mode=""\n if builtin shopt -qo posix; then\n posix_mode=$(builtin printf 'builtin set -o posix\n'; builtin export -p | command grep -E '^(declare|export)( -[a-zA-Z]+)* POSIXLY_CORRECT=' || true; command sed 's/^shopt /builtin shopt /' <<<"$bash_opts")\n fi\n _emit_encoded "$posix_mode" "POSIX_MODE"\n _log_timing "posix_mode"\n\n # Done\n _emit "# end of bash state dump"\n _emit "__CURSOR_BASH_STATE_END__"\n _log_timing "finalize"\n}\n builtin printf '${n}\\n'; dump_bash_state`],s=Zr(e?.userTerminalHint);if(!s)throw new Error("Can't find Bash");const i=Rr(s,o,{env:r,detached:!0,stdio:["ignore","pipe","ignore"]},{type:"insecure_none"},e?.signal);i.on("error",(e=>{console.warn(`[shell-exec] bash state init spawn failed; falling back to empty state: ${e instanceof Error?e.message:String(e)}`)}));const{stdout:a}=await Dr(i,{shellName:"bash",...t}),c=Gr(qr(a,n),Vr,Kr)??`${process.cwd()}\n`,{cwd:l,rest:u}=Hr(c),d="win32"===process.platform,h="win32"===process.platform?process.cwd():l;return new Yr(h,u,e?.userTerminalHint,d)}var tn=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class rn{initializer;promise;constructor(e){this.initializer=e}getExecutor(){return void 0===this.promise&&(this.promise=this.initializer()),this.promise}async getCwd(){return(await this.getExecutor()).getCwd()}clone(e){return new rn((async()=>(await this.getExecutor()).clone(e)))}async*execute(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(n,(0,fr.VI)(e.withName("LazyTerminalExecutor.execute")),!1);const o=await this.getExecutor();for await(const n of o.execute(e,t,r))yield n}catch(e){n.error=e,n.hasError=!0}finally{tn(n)}}}var nn=r("../metrics/dist/index.js");const on="\n Emit $PWD.Path\n #Log-Timing \"working_dir\"\n\n function ShouldPersistEnvVar {\n param([string]$Name)\n if ($Name -eq 'CURSOR_CONVERSATION_ID') {\n return $false\n }\n if ($Name -eq 'CURSOR_REQUEST_ID') {\n return $false\n }\n if ($Name -like 'CURSOR_AGENT_STORE*') {\n return $false\n }\n if ($Name -like '*CURSOR_SANDBOX*') {\n return $false\n }\n if ($Name -eq 'ELECTRON_RUN_AS_NODE') {\n return $false\n }\n return $true\n }\n\n $envVars = Get-ChildItem Env: | Sort-Object Name\n foreach ($var in $envVars) {\n if (-not (ShouldPersistEnvVar -Name $var.Name)) {\n continue\n }\n $encoded = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes([string]$var.Value))\n Emit ('Set-Item -LiteralPath ''Env:{0}'' -Value ([System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String(''{1}'')))' -f $var.Name, $encoded)\n }\n #Log-Timing \"environment\"\n\n $aliases = Get-Alias | Sort-Object Name\n foreach ($alias in $aliases) {\n $definition = $alias.Definition\n\n if ($alias.Options -band [System.Management.Automation.ScopedItemOptions]::ReadOnly) {\n }\n elseif ($alias.Options -band [System.Management.Automation.ScopedItemOptions]::Constant) {\n }\n elseif ($alias.Options -band [System.Management.Automation.ScopedItemOptions]::AllScope) {\n }\n else {\n Emit ('Set-Alias -Name \"{0}\" -Value \"{1}\"' -f $alias.Name, $definition)\n }\n }\n\n #Log-Timing \"finalize\"\n",sn=`\nfunction Dump-PowerShellState {\n param(\n [Parameter(Mandatory = $true)]\n [string]$OutputFile\n )\n\n function Emit {\n param([string]$Content)\n Add-Content -Path $OutputFile -Value $Content -Encoding UTF8\n }\n\n if (Test-Path $OutputFile) {\n Remove-Item $OutputFile -Force\n }\n New-Item -Path $OutputFile -ItemType File -Force | Out-Null\n #Log-Timing "file_init"\n${on}}\n`,an=`\nfunction Dump-PowerShellState {\n param(\n [Parameter(Mandatory = $true)]\n [string]$OutputFile,\n [string]$Trailer\n )\n\n $__cursorDumpText = New-Object System.Text.StringBuilder\n $__cursorDumpNewLine = [Environment]::NewLine\n function Emit {\n param([string]$Content)\n [void]$__cursorDumpText.Append($Content).Append($__cursorDumpNewLine)\n }\n${on}\n if ($Trailer) {\n Emit $Trailer\n }\n [System.IO.File]::WriteAllText($OutputFile, $__cursorDumpText.ToString(), (New-Object System.Text.UTF8Encoding ($PSVersionTable.PSVersion.Major -lt 6)))\n}\n`,cn="# cursor-shell-timings ",ln="[long](([DateTime]::UtcNow.Ticks - 621355968000000000) / 10000)",un="\ntry { [Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false) } catch { }\ntry { [Console]::InputEncoding = [System.Text.UTF8Encoding]::new($false) } catch { }\ntry { $global:OutputEncoding = [System.Text.UTF8Encoding]::new($false) } catch { }\n",dn=e=>e.map((e=>`'${e}'`)).join(", "),hn=`\ntry {\n if ($PSVersionTable.PSVersion.Major -lt 6 -and [Console]::OutputEncoding.CodePage -eq 65001) {\n # Windows PowerShell calls UTF-8 with a BOM 'UTF8'; PowerShell 7 calls it 'utf8BOM' and\n # reaches this block only when a test fakes the version.\n $__cursorUtf8 = if ($PSVersionTable.PSEdition -eq 'Core') { 'utf8BOM' } else { 'UTF8' }\n $__cursorGetContentNames = @('Get-Content') + @(Get-Alias -Definition Get-Content -ErrorAction Ignore | ForEach-Object { $_.Name })\n $__cursorHasEncodingDefault = $false\n foreach ($__cursorKey in @($PSDefaultParameterValues.Keys)) {\n $__cursorKeyParts = "$__cursorKey" -split ':', 2\n if ($__cursorKeyParts.Count -ne 2 -or 'Encoding' -notlike $__cursorKeyParts[1].Trim()) { continue }\n foreach ($__cursorName in $__cursorGetContentNames) {\n if ($__cursorName -like $__cursorKeyParts[0].Trim()) { $__cursorHasEncodingDefault = $true }\n }\n }\n # The body of the proxy for Get-Content. Its param block comes from the cmdlet itself.\n # Every step of its own is guarded, so a failure in the proxy reads the file as the\n # default did.\n $__cursorReaderBody = @'\nbegin {\n $__cursorStopped = $false\n $__cursorLeave = $false\n # A 64 KiB window of the file and the file's length: the first 64 KiB, the window an\n # editor's encoding guess reads, or the last 64 KiB, the end that -Tail reads; $null for a\n # path that is not a file.\n $__cursorWindowOf = {\n param([string]$__cursorFile, [bool]$__cursorFromEnd)\n if (-not [System.IO.File]::Exists($__cursorFile)) { return $null }\n $__cursorHead = New-Object byte[] 65536\n $__cursorCount = 0\n $__cursorStream = [System.IO.File]::Open($__cursorFile, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read, [System.IO.FileShare]::ReadWrite -bor [System.IO.FileShare]::Delete)\n try {\n $__cursorLength = $__cursorStream.Length\n if ($__cursorFromEnd -and $__cursorLength -gt $__cursorHead.Length) { $__cursorStream.Position = $__cursorLength - $__cursorHead.Length }\n while ($__cursorCount -lt $__cursorHead.Length) {\n $__cursorRead = $__cursorStream.Read($__cursorHead, $__cursorCount, $__cursorHead.Length - $__cursorCount)\n if ($__cursorRead -le 0) { break }\n $__cursorCount += $__cursorRead\n }\n } finally { $__cursorStream.Dispose() }\n return @{ Length = $__cursorLength; Head = $__cursorHead; Count = $__cursorCount; FromEnd = $__cursorFromEnd }\n }\n # How a file reads: 'ansi' for text in the code page the cmdlet reads by default, 'either'\n # for a file that reads the same under UTF-8 and under that default, 'utf8' for everything\n # else, which the default for the cmdlet read as UTF-8 before this proxy.\n $__cursorReadingOf = {\n param($__cursorWas, $__cursorAnsi)\n $__cursorHead = $__cursorWas.Head\n $__cursorStart = 0\n $__cursorEnd = $__cursorWas.Count\n # Nothing, or a byte order mark, which the cmdlet reads by whatever encoding it was given.\n if ($__cursorEnd -eq 0) { return 'either' }\n $__cursorFull = $__cursorEnd -eq $__cursorHead.Length\n if ($__cursorWas.FromEnd) {\n # A window from the end may start inside a character; the rest of that character\n # is left out. It ends where the file does.\n while ($__cursorStart -lt 3 -and $__cursorStart -lt $__cursorEnd -and ($__cursorHead[$__cursorStart] -band 0xC0) -eq 0x80) { $__cursorStart++ }\n } else {\n if ($__cursorEnd -ge 3 -and $__cursorHead[0] -eq 0xEF -and $__cursorHead[1] -eq 0xBB -and $__cursorHead[2] -eq 0xBF) { return 'either' }\n if ($__cursorEnd -ge 2 -and (($__cursorHead[0] -eq 0xFF -and $__cursorHead[1] -eq 0xFE) -or ($__cursorHead[0] -eq 0xFE -and $__cursorHead[1] -eq 0xFF))) { return 'either' }\n if ($__cursorFull) {\n # A full window may end inside a character; that character is left out.\n $__cursorAt = $__cursorEnd - 1\n while ($__cursorAt -gt $__cursorEnd - 4 -and ($__cursorHead[$__cursorAt] -band 0xC0) -eq 0x80) { $__cursorAt-- }\n if ($__cursorHead[$__cursorAt] -ge 0xC0) {\n $__cursorNeed = if ($__cursorHead[$__cursorAt] -ge 0xF0) { 4 } elseif ($__cursorHead[$__cursorAt] -ge 0xE0) { 3 } else { 2 }\n if ($__cursorEnd - $__cursorAt -lt $__cursorNeed) { $__cursorEnd = $__cursorAt }\n }\n }\n }\n # Bytes that are not UTF-8 decode to U+FFFD; a decoder that threw instead would leave a\n # record in $Error for every such file. A character beyond ASCII takes more bytes than\n # code units, so all-ASCII content is the one that decodes to as many; it reads the\n # same either way when the window is the whole file, or the end of one.\n $__cursorText = [System.Text.UTF8Encoding]::new($false, $false).GetString($__cursorHead, $__cursorStart, $__cursorEnd - $__cursorStart)\n if ($__cursorText.IndexOf([char]0xFFFD) -lt 0) {\n if ($__cursorStart -eq 0 -and $__cursorText.Length -eq $__cursorEnd -and ($__cursorWas.FromEnd -or $__cursorEnd -eq $__cursorWas.Length)) { return 'either' }\n return 'utf8'\n }\n # A NUL byte is binary content or UTF-16 without a BOM.\n if ($__cursorText.IndexOf([char]0) -ge 0) { return 'utf8' }\n # Of the bytes beyond ASCII, those in a UTF-8 sequence against the rest: text in a legacy\n # code page forms a sequence here and there by chance, UTF-8 text with a stray byte loses\n # that byte, and the file reads as the encoding that keeps more. Counted over a view\n # with one character per byte, where U+FFFD written in UTF-8 is a sequence like any other.\n $__cursorView = [System.Text.Encoding]::GetEncoding(28591).GetString($__cursorHead, $__cursorStart, $__cursorEnd - $__cursorStart)\n $__cursorBeyondAscii = $__cursorView.Length - [regex]::Replace($__cursorView, '[^\\x00-\\x7F]', '').Length\n $__cursorKept = $__cursorView.Length - [regex]::Replace($__cursorView, '[\\xC2-\\xDF][\\x80-\\xBF]|\\xE0[\\xA0-\\xBF][\\x80-\\xBF]|[\\xE1-\\xEC\\xEE\\xEF][\\x80-\\xBF]{2}|\\xED[\\x80-\\x9F][\\x80-\\xBF]|\\xF0[\\x90-\\xBF][\\x80-\\xBF]{2}|[\\xF1-\\xF3][\\x80-\\xBF]{3}|\\xF4[\\x80-\\x8F][\\x80-\\xBF]{2}', '').Length\n if ($__cursorKept * 2 -ge $__cursorBeyondAscii) { return 'utf8' }\n # Text in the code page decodes and encodes back to the same bytes, to no control\n # character but whitespace or an escape (as in a color code), and to no private-use or\n # replacement character, which stand for bytes the code page leaves undefined. A full\n # window may end, or one from the end may start, inside a two-byte character; that\n # byte is left out on a second try.\n foreach ($__cursorCut in @(0, 1)) {\n if ($__cursorCut -gt 0 -and -not $__cursorFull) { break }\n $__cursorFrom = 0\n $__cursorTo = $__cursorEnd - $__cursorCut\n if ($__cursorWas.FromEnd) { $__cursorFrom = $__cursorCut; $__cursorTo = $__cursorEnd }\n $__cursorAnsiText = $__cursorAnsi.GetString($__cursorHead, $__cursorFrom, $__cursorTo - $__cursorFrom)\n $__cursorBack = $__cursorAnsi.GetBytes($__cursorAnsiText)\n if ($__cursorBack.Length -ne $__cursorTo - $__cursorFrom -or [System.Convert]::ToBase64String($__cursorBack) -ne [System.Convert]::ToBase64String($__cursorHead, $__cursorFrom, $__cursorTo - $__cursorFrom)) { continue }\n if ([regex]::IsMatch($__cursorAnsiText, '[\\x00-\\x08\\x0E-\\x1A\\x1C-\\x1F\\x7F-\\x9F\\uE000-\\uF8FF\\uFFFD]')) { return 'utf8' }\n return 'ansi'\n }\n return 'utf8'\n }\n try {\n $__cursorBound = $null\n if ($PSBoundParameters.ContainsKey('Path')) { $__cursorBound = @{ Path = $PSBoundParameters['Path'] } }\n elseif ($PSBoundParameters.ContainsKey('LiteralPath')) { $__cursorBound = @{ LiteralPath = $PSBoundParameters['LiteralPath'] } }\n # The cmdlet takes its -Encoding parameter from the provider of its first path, or of\n # the current location when the path comes from the pipeline; another provider has\n # none, and reads as it did.\n if ($null -eq $__cursorBound) {\n if ($ExecutionContext.SessionState.Path.CurrentLocation.Provider.Name -ne 'FileSystem') { $__cursorLeave = $true }\n } else {\n $__cursorLiteral = $__cursorBound.ContainsKey('LiteralPath')\n $__cursorFiles = New-Object System.Collections.Generic.List[string]\n $__cursorFirst = $true\n foreach ($__cursorPath in @(@($__cursorBound.Values)[0])) {\n $__cursorProvider = $null\n $__cursorDrive = $null\n if ($__cursorLiteral -or -not [System.Management.Automation.WildcardPattern]::ContainsWildcardCharacters("$__cursorPath")) {\n $__cursorResolved = @($ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath("$__cursorPath", [ref]$__cursorProvider, [ref]$__cursorDrive))\n } else {\n $__cursorResolved = @($ExecutionContext.SessionState.Path.GetResolvedProviderPathFromPSPath("$__cursorPath", [ref]$__cursorProvider))\n }\n if ($null -eq $__cursorProvider -or $__cursorProvider.Name -ne 'FileSystem') {\n if ($__cursorFirst) { $__cursorLeave = $true }\n $__cursorFiles = $null\n break\n }\n $__cursorFirst = $false\n $__cursorFiles.AddRange([string[]]$__cursorResolved)\n }\n # -Filter, -Include and -Exclude change which files the cmdlet reads, and -Stream reads\n # another stream than the one the window comes from. The call is left to the cmdlet\n # when a file it names is text in the code page and none reads as UTF-8.\n if ($null -ne $__cursorFiles -and -not $PSBoundParameters.ContainsKey('Stream') -and\n -not $PSBoundParameters.ContainsKey('Filter') -and -not $PSBoundParameters.ContainsKey('Include') -and\n -not $PSBoundParameters.ContainsKey('Exclude')) {\n # The encoding the cmdlet reads a file in when the call names none: the system's\n # ANSI code page on Windows PowerShell. PowerShell 7 reaches this block only when\n # a test fakes the version, and its Default is UTF-8 on every system, so the\n # culture's code page stands in there. A system whose code page is UTF-8 reads\n # every file the same either way.\n $__cursorAnsi = if ($PSVersionTable.PSEdition -eq 'Core') { [System.Text.Encoding]::GetEncoding([System.Globalization.CultureInfo]::CurrentCulture.TextInfo.ANSICodePage) } else { [System.Text.Encoding]::Default }\n $__cursorAnsiFile = $false\n $__cursorUtf8File = $false\n if ($__cursorAnsi.CodePage -ne 65001) {\n foreach ($__cursorFile in $__cursorFiles) {\n $__cursorWas = & $__cursorWindowOf $__cursorFile $false\n if ($null -eq $__cursorWas) { continue }\n $__cursorReading = & $__cursorReadingOf $__cursorWas $__cursorAnsi\n # -Tail reads the end of the file, which a log appended to by more than\n # one program need not write in the code page of its start.\n if ($__cursorReading -eq 'ansi' -and $PSBoundParameters.ContainsKey('Tail') -and $__cursorWas.Length -gt $__cursorWas.Head.Length) {\n if ((& $__cursorReadingOf (& $__cursorWindowOf $__cursorFile $true) $__cursorAnsi) -eq 'utf8') { $__cursorReading = 'utf8' }\n }\n if ($__cursorReading -eq 'ansi') { $__cursorAnsiFile = $true }\n elseif ($__cursorReading -eq 'utf8') { $__cursorUtf8File = $true; break }\n }\n }\n $__cursorLeave = $__cursorAnsiFile -and -not $__cursorUtf8File\n }\n }\n } catch { $__cursorLeave = $false }\n # An -Encoding on the command line or from a default is the caller's, and -AsByteStream\n # (PowerShell 7's -Encoding Byte) reads no text.\n if (-not $__cursorLeave -and -not $PSBoundParameters.ContainsKey('Encoding') -and -not $PSBoundParameters.ContainsKey('AsByteStream')) {\n $PSBoundParameters['Encoding'] = 'UTF8'\n }\n # An error the caller asked to stop on ends the caller too, as it does from the cmdlet.\n # Any other terminating error of the cmdlet ends the statement and the caller goes on, as\n # with the writers' proxy; the pipeline it ended is not stepped again.\n try {\n $outBuffer = $null\n if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { $PSBoundParameters['OutBuffer'] = 1 }\n $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('__CURSORTARGET__', [System.Management.Automation.CommandTypes]::Cmdlet)\n $scriptCmd = { & $wrappedCmd @PSBoundParameters }\n $steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)\n # The cmdlet binds here in a scope under this call's, where the variable the\n # dynamicparam block set keeps the default for the module-qualified call off, so the\n # reading above stands.\n $steppablePipeline.Begin($PSCmdlet)\n } catch [System.Management.Automation.ActionPreferenceStopException] { throw }\n catch { $__cursorStopped = $true; $PSCmdlet.ThrowTerminatingError($_) }\n}\nprocess {\n if ($__cursorStopped) { return }\n try { $steppablePipeline.Process($_) }\n catch [System.Management.Automation.ActionPreferenceStopException] { throw }\n catch { $__cursorStopped = $true; $PSCmdlet.ThrowTerminatingError($_) }\n}\nend {\n if ($__cursorStopped) { return }\n try { $steppablePipeline.End() }\n catch [System.Management.Automation.ActionPreferenceStopException] { throw }\n catch { $__cursorStopped = $true; $PSCmdlet.ThrowTerminatingError($_) }\n}\n'@\n if (-not $__cursorHasEncodingDefault) {\n try {\n # A function of this name that a profile defined stays in charge; the proxy is built on the cmdlet alone.\n $__cursorCmdlet = @(Microsoft.PowerShell.Core\\Get-Command -Name Get-Content -ErrorAction Stop)[0]\n if ($__cursorCmdlet.CommandType -eq 'Cmdlet') {\n $__cursorTarget = "$($__cursorCmdlet.ModuleName)\\$($__cursorCmdlet.Name)"\n $__cursorMetadata = New-Object System.Management.Automation.CommandMetadata $__cursorCmdlet\n $__cursorProxyText = @(\n '<#', ".ForwardHelpTargetName $__cursorTarget", '.ForwardHelpCategory Cmdlet', '#>',\n [System.Management.Automation.ProxyCommand]::GetCmdletBindingAttribute($__cursorMetadata),\n 'param(', [System.Management.Automation.ProxyCommand]::GetParamBlock($__cursorMetadata), ')',\n # The proxy's own -Encoding is bound after this block runs, and must stay unbound\n # unless the caller gave one: the default below is off while this variable is in\n # scope, which it is from here, through the binding of the cmdlet the proxy steps,\n # to the end of the call. It is a variable of the call's own scope, so a call whose\n # body never runs, as when a completer or Get-Command binds the parameters or a\n # bind fails, leaves nothing behind.\n 'dynamicparam {', '$__cursorGetContentBinding = $true',\n [System.Management.Automation.ProxyCommand]::GetDynamicParam($__cursorMetadata), '}',\n $__cursorReaderBody.Replace('__CURSORTARGET__', $__cursorTarget)\n ) -join [Environment]::NewLine\n # Global, as a profile would define it, so that a module's code reaches it too.\n Microsoft.PowerShell.Management\\Set-Item -LiteralPath 'function:global:Get-Content' -Value ([scriptblock]::Create($__cursorProxyText)) -ErrorAction Stop\n }\n } catch { }\n # A call that names the cmdlet by its module, Microsoft.PowerShell.Management\\Get-Content,\n # bypasses a function of the cmdlet's name; this default keeps it reading UTF-8, as the\n # default this proxy replaced did. A default from a script block is not applied when the\n # block returns nothing, which it does while the proxy binds: the block runs in the scope\n # of the call being bound, where the proxy's variable is in scope. The global, never set\n # to anything else, is what the block reads outside such a call, and under strict mode a\n # variable it could not read would be an error. The string is the name of the encoding\n # on Windows PowerShell; PowerShell 7 takes an encoding object from a block.\n try {\n $global:__cursorGetContentBinding = $false\n $PSDefaultParameterValues['Get-Content:Encoding'] = {\n if (-not $__cursorGetContentBinding) {\n if ($PSVersionTable.PSEdition -eq 'Core') { [System.Text.UTF8Encoding]::new($true) } else { 'UTF8' }\n }\n }\n } catch { }\n }\n # The body of the proxy for Set-Content and Export-Csv. Its param block comes from the\n # cmdlet itself. Every step of its own is guarded, so a failure in the proxy leaves the\n # file as the cmdlet writes it.\n $__cursorProxyBody = @'\nbegin {\n # The file system paths the call writes, each with its own 'bom' or 'nobom', and what each\n # held before the call; the call gets -Encoding only when every path has a decision.\n $__cursorFiles = $null\n $__cursorDecisions = @{}\n $__cursorBefore = @{}\n $__cursorDecided = $false\n # The command line asked for UTF8 by name, for files whose readers take it without a BOM.\n $__cursorAsked = $false\n $__cursorStrip = $false\n $__cursorStopped = $false\n $__cursorScopeBound = $null\n $__cursorInvoked = "$($MyInvocation.InvocationName)"\n # The first 8 KiB of the file and its length; $null for a file that does not exist.\n $__cursorHeadOf = {\n param([string]$__cursorFile)\n if (-not [System.IO.File]::Exists($__cursorFile)) { return $null }\n $__cursorHead = New-Object byte[] 8192\n $__cursorCount = 0\n $__cursorStream = [System.IO.File]::Open($__cursorFile, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read, [System.IO.FileShare]::ReadWrite -bor [System.IO.FileShare]::Delete)\n try {\n $__cursorLength = $__cursorStream.Length\n while ($__cursorCount -lt $__cursorHead.Length) {\n $__cursorRead = $__cursorStream.Read($__cursorHead, $__cursorCount, $__cursorHead.Length - $__cursorCount)\n if ($__cursorRead -le 0) { break }\n $__cursorCount += $__cursorRead\n }\n } finally { $__cursorStream.Dispose() }\n return @{ Length = $__cursorLength; Head = $__cursorHead; Count = $__cursorCount }\n }\n # 'bom' or 'nobom' for a file the proxy writes in UTF-8, $null for one it leaves to the\n # cmdlet: the file's own bytes decide when it has content, its extension otherwise.\n $__cursorEncodingOf = {\n param([string]$__cursorFile, $__cursorWas)\n $__cursorExtension = [System.IO.Path]::GetExtension($__cursorFile).ToLowerInvariant()\n if ($__cursorExtension -in @(${dn([".bat",".cmd",".reg",".ini",".inf",".vbs",".vbe",".wsf"])})) { return $null }\n if ([System.IO.Directory]::Exists($__cursorFile)) { return $null }\n if ($null -ne $__cursorWas -and $__cursorWas.Count -gt 0) {\n $__cursorHead = $__cursorWas.Head\n $__cursorEnd = $__cursorWas.Count\n if ($__cursorEnd -ge 3 -and $__cursorHead[0] -eq 0xEF -and $__cursorHead[1] -eq 0xBB -and $__cursorHead[2] -eq 0xBF) { return 'bom' }\n if ($__cursorEnd -ge 2 -and (($__cursorHead[0] -eq 0xFF -and $__cursorHead[1] -eq 0xFE) -or ($__cursorHead[0] -eq 0xFE -and $__cursorHead[1] -eq 0xFF))) { return $null }\n if ($__cursorEnd -eq $__cursorHead.Length) {\n # A full header may end inside a character; that character is left out.\n $__cursorAt = $__cursorEnd - 1\n while ($__cursorAt -gt $__cursorEnd - 4 -and ($__cursorHead[$__cursorAt] -band 0xC0) -eq 0x80) { $__cursorAt-- }\n if ($__cursorHead[$__cursorAt] -ge 0xC0) {\n $__cursorNeed = if ($__cursorHead[$__cursorAt] -ge 0xF0) { 4 } elseif ($__cursorHead[$__cursorAt] -ge 0xE0) { 3 } else { 2 }\n if ($__cursorEnd - $__cursorAt -lt $__cursorNeed) { $__cursorEnd = $__cursorAt }\n }\n }\n # A strict decode throws on bytes that are not UTF-8; a character beyond ASCII takes\n # more bytes than code units, so all-ASCII content is the one that decodes to as many.\n try { $__cursorText = [System.Text.UTF8Encoding]::new($false, $true).GetString($__cursorHead, 0, $__cursorEnd) } catch { return $null }\n if ($__cursorText.Length -lt $__cursorEnd) { return 'nobom' }\n }\n if ($__cursorExtension -in @(${dn([".ps1",".psm1",".psd1"])})) { return 'bom' }\n if ($__cursorExtension -in @(${dn([".py",".pyw",".pyi",".js",".mjs",".cjs",".jsx",".ts",".tsx",".mts",".cts",".go",".rs",".kt",".kts",".scala",".swift",".dart",".rb",".cs",".fs",".fsx",".vb",".razor",".cshtml",".sh",".bash",".zsh",".html",".htm",".css",".scss",".sass",".less",".vue",".svelte",".json",".jsonc",".json5",".yaml",".yml",".toml",".xml",".xsd",".xsl",".xslt",".svg",".csproj",".props",".targets",".graphql",".gql",".proto",".tf",".hcl",".md",".markdown",".mdx",".rst",".adoc",".gitignore",".gitattributes",".gitmodules",".editorconfig",".cursorignore",".cursorindexingignore",".mdc"])})) { return 'nobom' }\n return $null\n }\n # Whether the -Encoding the call bound is the UTF-8 with a BOM that Windows PowerShell names\n # UTF8. PowerShell 7 binds the encoding object of that name, and reaches this only when a\n # test fakes the version.\n $__cursorIsUtf8Bom = {\n param($__cursorEncoding)\n if ($__cursorEncoding -is [System.Text.Encoding]) { return ($__cursorEncoding -is [System.Text.UTF8Encoding] -and $__cursorEncoding.GetPreamble().Length -gt 0) }\n return ("$__cursorEncoding" -eq 'UTF8')\n }\n # Whether a default under $PSDefaultParameterValues can reach this call's -Encoding: under\n # the cmdlet's name, an alias it had when the proxy was built, or the name the call used. A\n # value such a default put in $PSBoundParameters is not one the command line asked for.\n $__cursorHasEncodingDefault = {\n param([string]$__cursorInvoked)\n foreach ($__cursorKey in @($PSDefaultParameterValues.Keys)) {\n $__cursorKeyParts = "$__cursorKey" -split ':', 2\n if ($__cursorKeyParts.Count -ne 2 -or 'Encoding' -notlike $__cursorKeyParts[1].Trim()) { continue }\n foreach ($__cursorName in @(__CURSORNAMES__, $__cursorInvoked)) {\n if ($__cursorName -like $__cursorKeyParts[0].Trim()) { return $true }\n }\n }\n return $false\n }\n # Whether a UTF8 asked for by name is UTF-8 without a BOM for this file: one whose reader\n # rejects a BOM, and that is new, empty or starts with no BOM of any encoding.\n $__cursorTakesNoBom = {\n param([string]$__cursorFile, $__cursorWas)\n if ([System.IO.Directory]::Exists($__cursorFile)) { return $false }\n if ([System.IO.Path]::GetExtension($__cursorFile).ToLowerInvariant() -notin @(${dn([".json",".py",".js",".ts",".sh",".yaml",".toml",".mdc"])}) -and\n [System.IO.Path]::GetFileName($__cursorFile).ToLowerInvariant() -notin @(${dn([".gitignore",".editorconfig"])})) { return $false }\n if ($null -eq $__cursorWas -or $__cursorWas.Count -lt 2) { return $true }\n $__cursorHead = $__cursorWas.Head\n if ($__cursorWas.Count -ge 3 -and $__cursorHead[0] -eq 0xEF -and $__cursorHead[1] -eq 0xBB -and $__cursorHead[2] -eq 0xBF) { return $false }\n if (($__cursorHead[0] -eq 0xFF -and $__cursorHead[1] -eq 0xFE) -or ($__cursorHead[0] -eq 0xFE -and $__cursorHead[1] -eq 0xFF)) { return $false }\n if ($__cursorWas.Count -ge 4 -and $__cursorHead[0] -eq 0 -and $__cursorHead[1] -eq 0 -and $__cursorHead[2] -eq 0xFE -and $__cursorHead[3] -eq 0xFF) { return $false }\n return $true\n }\n # Takes a UTF-8 BOM off the front of the file in place, unless it is to stay and the\n # content has a character beyond ASCII. A file the cmdlet left as it was is not touched.\n $__cursorStripBom = {\n param([string]$__cursorFile, [bool]$__cursorKeepUnlessAscii, $__cursorWas)\n if (-not [System.IO.File]::Exists($__cursorFile)) { return }\n $__cursorStream = $null\n # The cmdlet may still hold the file for a moment after it returns.\n for ($__cursorAttempt = 0; $__cursorAttempt -lt 5 -and $null -eq $__cursorStream; $__cursorAttempt++) {\n try { $__cursorStream = [System.IO.File]::Open($__cursorFile, [System.IO.FileMode]::Open, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None) }\n catch [System.IO.FileNotFoundException] { return }\n catch [System.IO.DirectoryNotFoundException] { return }\n catch [System.IO.IOException] { Start-Sleep -Milliseconds 20 }\n catch { return }\n }\n if ($null -eq $__cursorStream) { return }\n try {\n $__cursorBuffer = New-Object byte[] 65536\n if ($null -ne $__cursorWas -and $__cursorWas.Length -eq $__cursorStream.Length) {\n $__cursorCount = 0\n while ($__cursorCount -lt $__cursorWas.Count) {\n $__cursorRead = $__cursorStream.Read($__cursorBuffer, $__cursorCount, $__cursorWas.Count - $__cursorCount)\n if ($__cursorRead -le 0) { break }\n $__cursorCount += $__cursorRead\n }\n if ($__cursorCount -eq $__cursorWas.Count -and [System.Convert]::ToBase64String($__cursorBuffer, 0, $__cursorCount) -eq [System.Convert]::ToBase64String($__cursorWas.Head, 0, $__cursorCount)) { return }\n $__cursorStream.Position = 0\n }\n if ($__cursorStream.Read($__cursorBuffer, 0, 3) -ne 3 -or $__cursorBuffer[0] -ne 0xEF -or $__cursorBuffer[1] -ne 0xBB -or $__cursorBuffer[2] -ne 0xBF) { return }\n if ($__cursorKeepUnlessAscii) {\n while (($__cursorRead = $__cursorStream.Read($__cursorBuffer, 0, $__cursorBuffer.Length)) -gt 0) {\n if ([regex]::IsMatch([System.Text.Encoding]::UTF8.GetString($__cursorBuffer, 0, $__cursorRead), '[^\\x00-\\x7F]')) { return }\n }\n }\n $__cursorReadAt = 3L\n $__cursorWriteAt = 0L\n while ($__cursorReadAt -lt $__cursorStream.Length) {\n $__cursorStream.Position = $__cursorReadAt\n $__cursorRead = $__cursorStream.Read($__cursorBuffer, 0, $__cursorBuffer.Length)\n if ($__cursorRead -le 0) { break }\n $__cursorStream.Position = $__cursorWriteAt\n $__cursorStream.Write($__cursorBuffer, 0, $__cursorRead)\n $__cursorReadAt += $__cursorRead\n $__cursorWriteAt += $__cursorRead\n }\n $__cursorStream.SetLength($__cursorWriteAt)\n } catch { } finally { $__cursorStream.Dispose() }\n }\n try {\n $__cursorBound = $null\n if ($PSBoundParameters.ContainsKey('Path')) { $__cursorBound = @{ Path = $PSBoundParameters['Path'] } }\n elseif ($PSBoundParameters.ContainsKey('LiteralPath')) { $__cursorBound = @{ LiteralPath = $PSBoundParameters['LiteralPath'] } }\n if ($null -ne $__cursorBound) {\n # The file system paths that -Path or -LiteralPath names; none when one is on another\n # provider or a wildcard matches nothing.\n $__cursorLiteral = $__cursorBound.ContainsKey('LiteralPath')\n $__cursorFiles = New-Object System.Collections.Generic.List[string]\n foreach ($__cursorPath in @(@($__cursorBound.Values)[0])) {\n $__cursorProvider = $null\n $__cursorDrive = $null\n if ($__cursorLiteral -or -not [System.Management.Automation.WildcardPattern]::ContainsWildcardCharacters("$__cursorPath")) {\n $__cursorResolved = @($ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath("$__cursorPath", [ref]$__cursorProvider, [ref]$__cursorDrive))\n } else {\n $__cursorResolved = @($ExecutionContext.SessionState.Path.GetResolvedProviderPathFromPSPath("$__cursorPath", [ref]$__cursorProvider))\n }\n if ($null -ne $__cursorProvider -and $__cursorProvider.Name -in @('Variable', 'Function', 'Alias')) { $__cursorScopeBound = $__cursorProvider.Name }\n if ($null -eq $__cursorProvider -or $__cursorProvider.Name -ne 'FileSystem' -or $__cursorResolved.Count -eq 0) { $__cursorFiles = $null; break }\n $__cursorFiles.AddRange([string[]]$__cursorResolved)\n }\n }\n # -WhatIf sets $WhatIfPreference and -Confirm sets $ConfirmPreference in this scope.\n if ($null -ne $__cursorFiles -and $__cursorFiles.Count -gt 0 -and -not $PSBoundParameters.ContainsKey('Encoding') -and\n -not $WhatIfPreference -and $ConfirmPreference -notin @('Low', 'Medium') -and -not $PSBoundParameters.ContainsKey('Stream') -and\n -not $PSBoundParameters.ContainsKey('Filter') -and -not $PSBoundParameters.ContainsKey('Include') -and\n -not $PSBoundParameters.ContainsKey('Exclude')) {\n $__cursorAppend = ($PSBoundParameters.ContainsKey('Append') -and $PSBoundParameters['Append']) -or ($PSBoundParameters.ContainsKey('NoClobber') -and $PSBoundParameters['NoClobber'])\n $__cursorDecided = $true\n $__cursorStrip = $true\n foreach ($__cursorFile in $__cursorFiles) {\n $__cursorBefore[$__cursorFile] = & $__cursorHeadOf $__cursorFile\n $__cursorDecisions[$__cursorFile] = & $__cursorEncodingOf $__cursorFile $__cursorBefore[$__cursorFile]\n if ($null -eq $__cursorDecisions[$__cursorFile]) { $__cursorDecided = $false; break }\n # An append onto a file with content writes no BOM, so there is none to take off.\n if ($__cursorAppend -and $null -ne $__cursorBefore[$__cursorFile] -and $__cursorBefore[$__cursorFile].Length -gt 0) { $__cursorStrip = $false }\n }\n }\n elseif ($null -ne $__cursorFiles -and $__cursorFiles.Count -gt 0 -and $PSBoundParameters.ContainsKey('Encoding') -and\n (& $__cursorIsUtf8Bom $PSBoundParameters['Encoding']) -and -not (& $__cursorHasEncodingDefault $__cursorInvoked) -and\n -not $WhatIfPreference -and $ConfirmPreference -notin @('Low', 'Medium') -and -not $PSBoundParameters.ContainsKey('Stream') -and\n -not $PSBoundParameters.ContainsKey('Filter') -and -not $PSBoundParameters.ContainsKey('Include') -and\n -not $PSBoundParameters.ContainsKey('Exclude')) {\n # The UTF8 the command line asked for is UTF-8 with a BOM on this shell and without\n # one on PowerShell 7. For a file whose reader rejects a BOM, and that has none, it\n # means what it means there: the cmdlet writes its BOM, and the proxy takes it off.\n $__cursorAsked = $true\n foreach ($__cursorFile in $__cursorFiles) {\n $__cursorBefore[$__cursorFile] = & $__cursorHeadOf $__cursorFile\n if (-not (& $__cursorTakesNoBom $__cursorFile $__cursorBefore[$__cursorFile])) { $__cursorAsked = $false; break }\n $__cursorDecisions[$__cursorFile] = 'nobom'\n }\n $__cursorStrip = $__cursorAsked\n }\n } catch { $__cursorDecided = $false; $__cursorAsked = $false }\n if ($__cursorDecided) { $PSBoundParameters['Encoding'] = '__CURSORUTF8__' }\n if ($null -ne $__cursorScopeBound) {\n Write-Warning "__CURSORNAME__ runs through a function in this shell, so an item it writes to the $__cursorScopeBound provider lives in a scope that ends with the call. Use an assignment, a function definition or Set-Alias instead."\n }\n # An error the caller asked to stop on ends the caller too, as it does from the cmdlet: it\n # goes on as it is, as from the proxy PowerShell itself generates, which rethrows everything\n # with 'throw'. Any other terminating error of the cmdlet ends the statement and the caller\n # goes on; ThrowTerminatingError keeps that rule, where 'throw' would end the caller's whole\n # script, and the pipeline it ended is not stepped again. Of the two, only the cmdlet's own\n # terminating error names this function rather than the cmdlet's type in the suffix of its\n # FullyQualifiedErrorId; the record of an error the caller asked to stop on is the cmdlet's.\n try {\n $outBuffer = $null\n if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { $PSBoundParameters['OutBuffer'] = 1 }\n $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('__CURSORTARGET__', [System.Management.Automation.CommandTypes]::Cmdlet)\n $scriptCmd = { & $wrappedCmd @PSBoundParameters }\n $steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)\n $steppablePipeline.Begin($PSCmdlet)\n } catch [System.Management.Automation.ActionPreferenceStopException] { throw }\n catch { $__cursorStopped = $true; $PSCmdlet.ThrowTerminatingError($_) }\n}\nprocess {\n if ($__cursorStopped) { return }\n try { $steppablePipeline.Process($_) }\n catch [System.Management.Automation.ActionPreferenceStopException] { throw }\n catch { $__cursorStopped = $true; $PSCmdlet.ThrowTerminatingError($_) }\n}\nend {\n if ($__cursorStopped) { return }\n try { $steppablePipeline.End() }\n catch [System.Management.Automation.ActionPreferenceStopException] { throw }\n catch { $__cursorStopped = $true; $PSCmdlet.ThrowTerminatingError($_) }\n if (-not $__cursorStrip -or -not ($__cursorDecided -or $__cursorAsked)) { return }\n try {\n foreach ($__cursorFile in $__cursorFiles) { & $__cursorStripBom $__cursorFile ($__cursorDecisions[$__cursorFile] -eq 'bom') $__cursorBefore[$__cursorFile] }\n } catch { }\n}\n'@\n foreach ($__cursorWriter in @('Set-Content', 'Export-Csv')) {\n $__cursorWriterNames = @($__cursorWriter) + @(Get-Alias -Definition $__cursorWriter -ErrorAction Ignore | ForEach-Object { $_.Name })\n $__cursorHasWriterDefault = $false\n foreach ($__cursorKey in @($PSDefaultParameterValues.Keys)) {\n $__cursorKeyParts = "$__cursorKey" -split ':', 2\n if ($__cursorKeyParts.Count -ne 2 -or 'Encoding' -notlike $__cursorKeyParts[1].Trim()) { continue }\n foreach ($__cursorName in $__cursorWriterNames) {\n if ($__cursorName -like $__cursorKeyParts[0].Trim()) { $__cursorHasWriterDefault = $true }\n }\n }\n if ($__cursorHasWriterDefault) { continue }\n try {\n # A function of this name that a profile defined stays in charge; the proxy is built on the cmdlet alone.\n $__cursorCmdlet = @(Microsoft.PowerShell.Core\\Get-Command -Name $__cursorWriter -ErrorAction Stop)[0]\n if ($__cursorCmdlet.CommandType -eq 'Cmdlet') {\n $__cursorTarget = "$($__cursorCmdlet.ModuleName)\\$($__cursorCmdlet.Name)"\n $__cursorMetadata = New-Object System.Management.Automation.CommandMetadata $__cursorCmdlet\n $__cursorNamesList = @($__cursorWriterNames | ForEach-Object { "'" + $_.Replace("'", "''") + "'" }) -join ', '\n $__cursorProxyText = @(\n '<#', ".ForwardHelpTargetName $__cursorTarget", '.ForwardHelpCategory Cmdlet', '#>',\n [System.Management.Automation.ProxyCommand]::GetCmdletBindingAttribute($__cursorMetadata),\n 'param(', [System.Management.Automation.ProxyCommand]::GetParamBlock($__cursorMetadata), ')',\n 'dynamicparam {', [System.Management.Automation.ProxyCommand]::GetDynamicParam($__cursorMetadata), '}',\n $__cursorProxyBody.Replace('__CURSORTARGET__', $__cursorTarget).Replace('__CURSORNAMES__', $__cursorNamesList).Replace('__CURSORNAME__', $__cursorCmdlet.Name).Replace('__CURSORUTF8__', $__cursorUtf8)\n ) -join [Environment]::NewLine\n # Global, as a profile would define it, so that a module's code reaches it too.\n Microsoft.PowerShell.Management\\Set-Item -LiteralPath "function:global:$__cursorWriter" -Value ([scriptblock]::Create($__cursorProxyText)) -ErrorAction Stop\n }\n } catch { }\n }\n }\n} catch { }\n`,pn=String.raw`
|
|
2
|
-
try {
|
|
3
|
-
if ($PSVersionTable.PSVersion.Major -lt 6 -and [Console]::OutputEncoding.CodePage -eq 65001) {
|
|
4
|
-
function global:__cursorUtf8FromLatin1 {
|
|
5
|
-
param([string]$Text)
|
|
6
|
-
Set-StrictMode -Off
|
|
7
|
-
if ($Text.Length -eq 0 -or $Text -cnotmatch '[\u0080-\u00FF]' -or $Text -cmatch '[\u0100-\uFFFF]') { return $null }
|
|
8
|
-
try {
|
|
9
|
-
$bytes = [System.Text.Encoding]::GetEncoding(28591).GetBytes($Text)
|
|
10
|
-
$decoded = (New-Object System.Text.UTF8Encoding($false, $true)).GetString($bytes)
|
|
11
|
-
} catch { return $null }
|
|
12
|
-
if ($decoded.Length -gt 0 -and $decoded[0] -eq [char]0xFEFF) { $decoded = $decoded.Substring(1) }
|
|
13
|
-
return $decoded
|
|
14
|
-
}
|
|
15
|
-
function global:__cursorDeclaresOtherCharset {
|
|
16
|
-
param([string]$Text)
|
|
17
|
-
Set-StrictMode -Off
|
|
18
|
-
if ($Text.Length -eq 0) { return $false }
|
|
19
|
-
$head = $Text.Substring(0, [Math]::Min($Text.Length, 1024))
|
|
20
|
-
$options = [System.Text.RegularExpressions.RegexOptions]'IgnoreCase, Singleline, CultureInvariant'
|
|
21
|
-
$declared = [regex]::Match($head, '<meta\s.*[^.><]*charset\s*=\s*["''\n]?(?<charset>[A-Za-z].[^\s"''\n<>]*)[\s"''\n>]', $options)
|
|
22
|
-
if (-not $declared.Success) { $declared = [regex]::Match($head, '<\?xml\s.*[^.><]*encoding\s*=\s*["''\n]?(?<charset>[A-Za-z].[^\s"''\n<>]*)[\s"''\n>]', $options) }
|
|
23
|
-
if (-not $declared.Success) { return $false }
|
|
24
|
-
try { return [System.Text.Encoding]::GetEncoding($declared.Groups['charset'].Value).CodePage -ne 65001 } catch { return $false }
|
|
25
|
-
}
|
|
26
|
-
function global:__cursorFixWebResponse {
|
|
27
|
-
param([Parameter(ValueFromPipeline = $true)]$Response)
|
|
28
|
-
process {
|
|
29
|
-
Set-StrictMode -Off
|
|
30
|
-
try {
|
|
31
|
-
if ($null -ne $Response -and $Response.Content -is [string]) {
|
|
32
|
-
$contentType = $null
|
|
33
|
-
try { $contentType = [string]$Response.BaseResponse.ContentType } catch { }
|
|
34
|
-
if (-not $contentType -and $Response.Headers) {
|
|
35
|
-
foreach ($name in @($Response.Headers.Keys)) {
|
|
36
|
-
if ($name -ieq 'Content-Type') { $contentType = [string]$Response.Headers[$name] }
|
|
37
|
-
}
|
|
38
|
-
}
|
|
39
|
-
if ($contentType -notmatch '(?i);\s*charset\s*=' -and -not (__cursorDeclaresOtherCharset $Response.Content)) {
|
|
40
|
-
$content = $Response.Content
|
|
41
|
-
$fixed = __cursorUtf8FromLatin1 $content
|
|
42
|
-
if ($null -ne $fixed) {
|
|
43
|
-
$raw = $Response.RawContent
|
|
44
|
-
$fixedRaw = $null
|
|
45
|
-
if ($raw -is [string] -and $raw.EndsWith($content)) { $fixedRaw = $raw.Substring(0, $raw.Length - $content.Length) + $fixed }
|
|
46
|
-
$Response | Add-Member -NotePropertyName Content -NotePropertyValue $fixed -Force -ErrorAction Stop
|
|
47
|
-
if ($null -ne $fixedRaw) {
|
|
48
|
-
# Content and RawContent change together or not at all.
|
|
49
|
-
try { $Response | Add-Member -NotePropertyName RawContent -NotePropertyValue $fixedRaw -Force -ErrorAction Stop }
|
|
50
|
-
catch { $Response | Add-Member -NotePropertyName Content -NotePropertyValue $content -Force -ErrorAction Stop }
|
|
51
|
-
}
|
|
52
|
-
}
|
|
53
|
-
}
|
|
54
|
-
}
|
|
55
|
-
} catch { }
|
|
56
|
-
,$Response
|
|
57
|
-
}
|
|
58
|
-
}
|
|
59
|
-
function global:__cursorIsRestContainer {
|
|
60
|
-
param($Value)
|
|
61
|
-
Set-StrictMode -Off
|
|
62
|
-
return $Value -is [System.Management.Automation.PSCustomObject] -or $Value -is [System.Collections.IList] -or $Value -is [System.Xml.XmlNode]
|
|
63
|
-
}
|
|
64
|
-
function global:__cursorRestOutputText {
|
|
65
|
-
param($Value)
|
|
66
|
-
Set-StrictMode -Off
|
|
67
|
-
if ($Value -is [string]) { return $Value }
|
|
68
|
-
if ($Value -is [System.Xml.XmlNode]) { return [string]$Value.OuterXml }
|
|
69
|
-
# Windows PowerShell's serializer writes every character above U+007F as a \uXXXX
|
|
70
|
-
# escape, so the text alone would never show one; the escapes are read back, in
|
|
71
|
-
# .NET, before the string test sees the text.
|
|
72
|
-
return [regex]::Unescape([string](ConvertTo-Json -InputObject $Value -Depth 100 -Compress -WarningAction SilentlyContinue))
|
|
73
|
-
}
|
|
74
|
-
function global:__cursorFixRestValue {
|
|
75
|
-
param($Value)
|
|
76
|
-
Set-StrictMode -Off
|
|
77
|
-
if ($Value -is [string]) {
|
|
78
|
-
$fixed = __cursorUtf8FromLatin1 $Value
|
|
79
|
-
if ($null -eq $fixed) { return ,$Value }
|
|
80
|
-
return ,$fixed
|
|
81
|
-
}
|
|
82
|
-
if (-not (__cursorIsRestContainer $Value)) { return ,$Value }
|
|
83
|
-
# A slot is a list and an index, a property or an XML node and no index, or neither
|
|
84
|
-
# for the value itself. Every rewrite is noted against its slot and made at the end,
|
|
85
|
-
# once every string with a character of U+0080-U+00FF has passed the strict round
|
|
86
|
-
# trip: one that does not, or one character above U+00FF, which no Latin-1 read
|
|
87
|
-
# produces, leaves the whole value as the cmdlet returned it.
|
|
88
|
-
$root = $Value
|
|
89
|
-
$edits = New-Object System.Collections.Generic.List[object]
|
|
90
|
-
$pending = New-Object System.Collections.Stack
|
|
91
|
-
$pending.Push(@{ Target = $null; Key = $null; Value = $Value; Depth = 0 })
|
|
92
|
-
while ($pending.Count -gt 0) {
|
|
93
|
-
$entry = $pending.Pop()
|
|
94
|
-
$current = $entry.Value
|
|
95
|
-
if ($entry.Depth -gt 100) { continue }
|
|
96
|
-
if ($current -is [System.Management.Automation.PSCustomObject]) {
|
|
97
|
-
$renamed = $false
|
|
98
|
-
foreach ($property in $current.PSObject.Properties) {
|
|
99
|
-
if ($property.Name -cmatch '[\u0080-\uFFFF]') {
|
|
100
|
-
if ($null -eq (__cursorUtf8FromLatin1 $property.Name)) { return ,$Value }
|
|
101
|
-
$renamed = $true
|
|
102
|
-
}
|
|
103
|
-
}
|
|
104
|
-
if ($renamed) {
|
|
105
|
-
$rebuilt = New-Object System.Management.Automation.PSObject
|
|
106
|
-
foreach ($property in $current.PSObject.Properties) {
|
|
107
|
-
$name = $property.Name
|
|
108
|
-
if ($name -cmatch '[\u0080-\uFFFF]') { $name = __cursorUtf8FromLatin1 $name }
|
|
109
|
-
$rebuilt | Add-Member -NotePropertyName $name -NotePropertyValue $property.Value -ErrorAction Stop
|
|
110
|
-
}
|
|
111
|
-
$edits.Add(@{ Target = $entry.Target; Key = $entry.Key; Value = $rebuilt })
|
|
112
|
-
$current = $rebuilt
|
|
113
|
-
}
|
|
114
|
-
foreach ($property in $current.PSObject.Properties) {
|
|
115
|
-
$item = $property.Value
|
|
116
|
-
if ($item -is [string]) {
|
|
117
|
-
if ($item -cmatch '[\u0080-\uFFFF]') {
|
|
118
|
-
$fixed = __cursorUtf8FromLatin1 $item
|
|
119
|
-
if ($null -eq $fixed) { return ,$Value }
|
|
120
|
-
$edits.Add(@{ Target = $property; Key = $null; Value = $fixed })
|
|
121
|
-
}
|
|
122
|
-
} elseif (__cursorIsRestContainer $item) {
|
|
123
|
-
$pending.Push(@{ Target = $property; Key = $null; Value = $item; Depth = $entry.Depth + 1 })
|
|
124
|
-
}
|
|
125
|
-
}
|
|
126
|
-
} elseif ($current -is [System.Collections.IList]) {
|
|
127
|
-
for ($i = 0; $i -lt $current.Count; $i++) {
|
|
128
|
-
$item = $current[$i]
|
|
129
|
-
if ($item -is [string]) {
|
|
130
|
-
if ($item -cmatch '[\u0080-\uFFFF]') {
|
|
131
|
-
$fixed = __cursorUtf8FromLatin1 $item
|
|
132
|
-
if ($null -eq $fixed) { return ,$Value }
|
|
133
|
-
$edits.Add(@{ Target = $current; Key = $i; Value = $fixed })
|
|
134
|
-
}
|
|
135
|
-
} elseif (__cursorIsRestContainer $item) {
|
|
136
|
-
$pending.Push(@{ Target = $current; Key = $i; Value = $item; Depth = $entry.Depth + 1 })
|
|
137
|
-
}
|
|
138
|
-
}
|
|
139
|
-
} elseif ($current -is [System.Xml.XmlNode]) {
|
|
140
|
-
foreach ($node in $current.SelectNodes('.//text() | .//@* | .//comment()')) {
|
|
141
|
-
if ($node.Value -cmatch '[\u0080-\uFFFF]') {
|
|
142
|
-
$fixed = __cursorUtf8FromLatin1 $node.Value
|
|
143
|
-
if ($null -eq $fixed) { return ,$Value }
|
|
144
|
-
$edits.Add(@{ Target = $node; Key = $null; Value = $fixed })
|
|
145
|
-
}
|
|
146
|
-
}
|
|
147
|
-
}
|
|
148
|
-
}
|
|
149
|
-
foreach ($edit in $edits) {
|
|
150
|
-
if ($null -eq $edit.Target) { $root = $edit.Value }
|
|
151
|
-
elseif ($null -eq $edit.Key) { $edit.Target.Value = $edit.Value }
|
|
152
|
-
else { $edit.Target[$edit.Key] = $edit.Value }
|
|
153
|
-
}
|
|
154
|
-
return ,$root
|
|
155
|
-
}
|
|
156
|
-
function global:__cursorFixRestResponse {
|
|
157
|
-
param([Parameter(ValueFromPipeline = $true)]$Response)
|
|
158
|
-
process {
|
|
159
|
-
Set-StrictMode -Off
|
|
160
|
-
$fixed = $Response
|
|
161
|
-
try {
|
|
162
|
-
if ($Response -is [string] -or (__cursorIsRestContainer $Response)) {
|
|
163
|
-
$text = __cursorRestOutputText $Response
|
|
164
|
-
$declared = ($Response -is [string] -or $Response -is [System.Xml.XmlNode]) -and (__cursorDeclaresOtherCharset $text)
|
|
165
|
-
if (-not $declared -and $null -ne (__cursorUtf8FromLatin1 $text)) { $fixed = __cursorFixRestValue $Response }
|
|
166
|
-
}
|
|
167
|
-
} catch { $fixed = $Response }
|
|
168
|
-
,$fixed
|
|
169
|
-
}
|
|
170
|
-
}
|
|
171
|
-
$__cursorWebProxyTemplate = @'
|
|
172
|
-
__BINDING__
|
|
173
|
-
param(
|
|
174
|
-
__PARAMS__
|
|
175
|
-
)
|
|
176
|
-
begin {
|
|
177
|
-
try {
|
|
178
|
-
$outBuffer = $null
|
|
179
|
-
if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { $PSBoundParameters['OutBuffer'] = 1 }
|
|
180
|
-
if ($PSBoundParameters.ContainsKey('SessionVariable') -and -not $PSBoundParameters.ContainsKey('WebSession')) {
|
|
181
|
-
$sessionName = [string]$PSBoundParameters['SessionVariable']
|
|
182
|
-
$webSession = New-Object Microsoft.PowerShell.Commands.WebRequestSession
|
|
183
|
-
if ($sessionName.Contains(':')) { $ExecutionContext.SessionState.PSVariable.Set($sessionName, $webSession) } else { Set-Variable -Name $sessionName -Value $webSession -Scope 1 }
|
|
184
|
-
[void]$PSBoundParameters.Remove('SessionVariable')
|
|
185
|
-
$PSBoundParameters['WebSession'] = $webSession
|
|
186
|
-
}
|
|
187
|
-
$wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Microsoft.PowerShell.Utility\__CMDLET__', [System.Management.Automation.CommandTypes]::Cmdlet)
|
|
188
|
-
$scriptCmd = { & $wrappedCmd @PSBoundParameters | __FILTER__ }
|
|
189
|
-
$steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)
|
|
190
|
-
$steppablePipeline.Begin($PSCmdlet)
|
|
191
|
-
} catch { $PSCmdlet.ThrowTerminatingError($_) }
|
|
192
|
-
}
|
|
193
|
-
process { try { $steppablePipeline.Process($_) } catch { $PSCmdlet.ThrowTerminatingError($_) } }
|
|
194
|
-
end { try { $steppablePipeline.End() } catch { $PSCmdlet.ThrowTerminatingError($_) } }
|
|
195
|
-
<#
|
|
196
|
-
.ForwardHelpTargetName Microsoft.PowerShell.Utility\__CMDLET__
|
|
197
|
-
.ForwardHelpCategory Cmdlet
|
|
198
|
-
#>
|
|
199
|
-
'@
|
|
200
|
-
foreach ($__cursorWebCmdletName in @('Invoke-WebRequest', 'Invoke-RestMethod')) {
|
|
201
|
-
$__cursorWebCmdlet = $ExecutionContext.InvokeCommand.GetCommand("Microsoft.PowerShell.Utility\$__cursorWebCmdletName", [System.Management.Automation.CommandTypes]::Cmdlet)
|
|
202
|
-
if (-not $__cursorWebCmdlet) { continue }
|
|
203
|
-
if (Test-Path -LiteralPath "Function:\$__cursorWebCmdletName") { continue }
|
|
204
|
-
$__cursorWebMetadata = New-Object System.Management.Automation.CommandMetadata $__cursorWebCmdlet
|
|
205
|
-
$__cursorWebFilter = if ($__cursorWebCmdletName -eq 'Invoke-WebRequest') { '__cursorFixWebResponse' } else { '__cursorFixRestResponse' }
|
|
206
|
-
$__cursorWebProxy = $__cursorWebProxyTemplate.Replace('__BINDING__', [System.Management.Automation.ProxyCommand]::GetCmdletBindingAttribute($__cursorWebMetadata)).Replace('__PARAMS__', [System.Management.Automation.ProxyCommand]::GetParamBlock($__cursorWebMetadata)).Replace('__CMDLET__', $__cursorWebCmdletName).Replace('__FILTER__', $__cursorWebFilter)
|
|
207
|
-
Set-Item -Path "Function:\global:$__cursorWebCmdletName" -Value ([scriptblock]::Create($__cursorWebProxy))
|
|
208
|
-
}
|
|
209
|
-
}
|
|
210
|
-
} catch { }
|
|
211
|
-
`;var fn=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const mn=(0,nn.v5)("shell_exec.powershell.phase_ms",{description:"Time in each phase of one stateful PowerShell command: process start to the wrapper's first statement, state restore, the command, the state dump to process exit, cleanup, and spawn to exit",labelNames:["phase","shell_kind","dump_mode"]});let gn;function wn(){const e=[process.platform,process.env.SHELL,process.env.PATH,process.env.SYSTEMROOT,process.cwd()].join("\0");if(gn?.key===e)return gn.executable;const t=function(){if("win32"!==process.platform){const e=process.env.SHELL;if(e?.includes("pwsh")||e?.includes("powershell"))return e}let e=S("pwsh",[]).cmd;if("pwsh"!==e)return e;if(e=S("powershell",[]).cmd,"powershell"!==e)return e;if("win32"===process.platform&&(e=f.join(process.env.SYSTEMROOT,"System32","WindowsPowerShell","v1.0","powershell.exe"),(0,m.existsSync)(e)))return e;throw new Error("Neither 'pwsh' (PowerShell Core) nor 'powershell' (Windows PowerShell) found in PATH")}();return gn={key:e,executable:t},t}function yn(e,t=process.platform){return"win32"!==t||f.win32.basename(e).toLowerCase().startsWith("pwsh")?"pwsh":"powershell51"}class vn{cwd;state;constructor(e,t){this.cwd=e,this.state=t}async getCwd(){return this.cwd}clone(e){return new vn(e??this.cwd,this.state)}async*execute(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(n,(0,fr.VI)(e.withName("PowerShellState.execute")),!1),s=r?.pipeStdin??!1,a=r?.workingDirectory??this.cwd,c=(0,mr.Jt)(),l=function(e,t=process.platform,r=process.env){const n={...r,...xr,...e?.env};return u(n),"win32"===t&&!0===e?.powershellUtf8ChildEnv&&(F(n),N(n)),i(n)}(r),d=A(l)?M(t):t,h=H.tmpdir(),p=f.join(h,`ps-state-out-${(0,W.randomUUID)()}.txt`),m="win32"===process.platform,g=((e,t,r,n,o)=>{const s=!0!==o?.perLineStateDump;return`${s?`$__cursorTimingStart = ${ln}`:""}\n${o?.utf8Console?un:""}\n${e}\n${hn}${o?.webRequestUtf8?pn:""}\n${o?.envInjection??""}\nSet-Location ${i=t,`'${i.replace(/['\u2018\u2019\u201A\u201B]/g,"$&$&")}'`}\n$env:NODE_DISABLE_COMPILE_CACHE = '1'\n$env:NODE_COMPILE_CACHE = $null${s?`\n$__cursorTimingRestored = ${ln}`:""}\n\n# PowerShell 5.1 does not treat \\" as an escaped quote, so cmd /c "rmdir /s /q \\"D:\\dir\\""\n# hands cmd a bare \\ (the drive root). Refuse double-quoted args that end in \\ and touch the next arg.\n${o?.parseAfterUtf8Switch?(e=>`# The command is parsed here, after the statements above ran, so a syntax error in it is\n# reported in the encoding they set and not in the console's start-up code page.\n$__cursorCommandText = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String('${Buffer.from(e,"utf8").toString("base64")}'))\n$__cursorParseErrors = $null\n$__cursorCommandAst = [System.Management.Automation.Language.Parser]::ParseInput($__cursorCommandText, [ref]$null, [ref]$__cursorParseErrors)\nif ($__cursorParseErrors.Count -gt 0) {\n foreach ($__cursorParseError in $__cursorParseErrors) {\n [Console]::Error.WriteLine($__cursorParseError.ToString())\n }\n exit 1\n}\n$__cursorCommand = $__cursorCommandAst.GetScriptBlock()`)(r):(e=>`$__cursorCommand = {\n${e}\n}`)(r)}\n$__cursorBrokenQuote = $__cursorCommand.Ast.Find({\n param($node)\n if ($node -isnot [System.Management.Automation.Language.CommandAst]) { return $false }\n $elements = $node.CommandElements\n for ($i = 0; $i -lt $elements.Count - 1; $i++) {\n $element = $elements[$i]\n if (($element -is [System.Management.Automation.Language.StringConstantExpressionAst] -or\n $element -is [System.Management.Automation.Language.ExpandableStringExpressionAst]) -and\n $element.StringConstantType -eq 'DoubleQuoted' -and\n $element.Value.EndsWith('\\') -and\n $elements[$i + 1].Extent.StartOffset -eq $element.Extent.EndOffset) {\n return $true\n }\n }\n return $false\n}, $true)\nif ($__cursorBrokenQuote) {\n [Console]::Error.WriteLine('Command refused: PowerShell does not treat \\" as an escaped quote, so a double-quoted string ends at \\" and the rest runs as separate arguments, near: ' + $__cursorBrokenQuote.Extent.Text)\n [Console]::Error.WriteLine('Quote the outer string with single quotes instead, or write a double quote inside a double-quoted string as \`".')\n exit 1\n}\n# Out-Default writes held-back table output before exit, dot-sourcing keeps the command's state for the dump\n. $__cursorCommand | Out-Default\n$COMMAND_EXIT_CODE = $LASTEXITCODE\n${s?`$__cursorTimingCommandDone = ${ln}\n\n${an}\nDump-PowerShellState -OutputFile "${n}" -Trailer ('${cn}{0} {1} {2} {3}' -f $__cursorTimingStart, $__cursorTimingRestored, $__cursorTimingCommandDone, $PSVersionTable.PSVersion.Major)`:`\n${sn}\nDump-PowerShellState -OutputFile "${n}"`}\n\nexit $COMMAND_EXIT_CODE\n`;var i})(this.state,a,d,p,{utf8Console:m&&!0===r?.powershellUtf8Console,parseAfterUtf8Switch:m&&!0===r?.powershellParseAfterUtf8Switch,envInjection:m&&!0===r?.powershellUtf8ChildEnv?B:"",webRequestUtf8:m&&!0===r?.powershellWebRequestUtf8,perLineStateDump:!0===r?.powershellPerLineStateDump}),w=f.join(h,`ps-script-${(0,W.randomUUID)()}.ps1`);await async function(e,t){await te.writeFile(e,"\ufeff"+t,{encoding:"utf8"})}(w,g);const y=["-ExecutionPolicy","Bypass"];s||y.push("-NonInteractive"),y.push("-File",w);const v=wn(),b=r?.sandboxWorkspaceRoot??a,S=(await wt(b,r?.sandboxPolicy)).policy,k="insecure_none"!==S.type?{...S,sandboxWorkspaceRoot:b}:S,_=Date.now();let C,E;const x=Rr(v,y,{env:l,stdio:[s?"pipe":"ignore","pipe","pipe"],cwd:a,detached:!m},k,r?.signal);x.on("spawn",(async()=>{try{await c.write({type:"stdin_ready",stdin:x.stdin??void 0,pid:x.pid,shell:yn(v)})}catch(e){}}));const P=kr({stdout:x.stdout,stderr:x.stderr,writable:c,bufferOutputEvents:r?.bufferOutputEvents,outputLimiterOptions:r?.outputLimiterOptions}),I=async()=>{try{const{state:e,timings:t}=function(e){const t=e.lastIndexOf(`\n${cn}`)+1;if(0===t)return{state:e};const r=e.slice(t+23).trim().split(" ").map(Number);if(4!==r.length||!r.every(Number.isFinite))return{state:e};const[n,o,s,i]=r;return{state:e.slice(0,t),timings:{startedAt:n,restoredAt:o,commandDoneAt:s,majorVersion:i}}}(await te.readFile(p,"utf8"));E=t;const{cwd:r,rest:n}=Hr(e);this.state=n,this.cwd=r.trim(),await(0,te.rm)(p).catch((()=>{}))}catch(e){}await(0,te.rm)(w,{recursive:!0,force:!0,maxRetries:5}).catch((e=>{console.warn(`[shell-exec] Could not remove PowerShell script ${w}`,e)}))};let R=null,T=null,$=null,D=!1;const O=async t=>{if(D)return;if(D=!0,$&&(clearTimeout($),$=null),(0,fr.HF)(o.ctx,"exit"),t)try{await P.waitForOutput()}catch(e){return await I(),void c.throw(e instanceof Error?e:new Error(String(e)))}await P.flush();try{await c.write({type:"exit",code:R,signal:T??void 0,data:"",aborted:r?.signal?.aborted??!1})}catch(e){}const n=Date.now();await I(),void 0!==C&&function(e,t){const r={shell_kind:(void 0!==t.script?t.script.majorVersion>=6:f.basename(t.executable).toLowerCase().startsWith("pwsh"))?"pwsh":"powershell51",dump_mode:t.perLineStateDump?"per_line":"single_write"},n=[["process",t.exitedAt-t.spawnedAt],["cleanup",t.cleanupMs]],o=t.script;if(void 0!==o){const e=[["start",o.startedAt-t.spawnedAt],["restore",o.restoredAt-o.startedAt],["command",o.commandDoneAt-o.restoredAt],["dump",t.exitedAt-o.commandDoneAt]];e.every((([,e])=>e>=0))&&n.push(...e)}for(const[t,o]of n)mn.histogram(e,o,{phase:t,...r})}(e,{executable:v,perLineStateDump:!0===r?.powershellPerLineStateDump,spawnedAt:_,exitedAt:C,cleanupMs:Date.now()-n,script:E}),c.close()};x.on("exit",((e,t)=>{C=Date.now(),R=e,T=t;const n=r?.closeTimeout??5e3;n>0&&($=setTimeout((()=>{console.warn(`[shell-exec] Close event did not fire within ${n}ms after exit. This may indicate a background process is holding file descriptors open. Proceeding anyway to prevent hang.`),O(!1)}),n))})),x.on("close",(async()=>{await O(!0)})),x.on("error",(e=>{var t;t=v,gn?.executable===t&&(gn=void 0),I().catch((()=>{})),c.throw(e)})),yield*c}catch(e){n.error=e,n.hasError=!0}finally{fn(n)}}}async function bn(){return new vn(process.cwd(),"")}var Sn=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function kn(e){const t=f.win32.parse(e).name.toLowerCase();return"powershell"===t||"pwsh"===t}function _n(e,t=process.platform){switch(f.win32.parse(e).name.toLowerCase()){case"pwsh":return"naive_pwsh";case"powershell":return"win32"===t?"naive_powershell51":"naive_pwsh";case"bash":return"naive_bash";case"zsh":return"naive_zsh";default:return"naive_other"}}class Cn{cwd;options;deps;constructor(e,t,r){this.cwd=e,this.options=t,this.deps=r}async getCwd(){return this.cwd}clone(e){return new Cn(e??this.cwd,this.options,this.deps)}async*execute(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(n,(0,fr.VI)(e.withName("NaiveTerminalExecutor.execute")),!1),s=(0,mr.Jt)(),a=r?.pipeStdin??!1,c=this.options?.shell||process.env.SHELL||"/bin/sh",l=r?.powershellUtf8Console??this.options?.powershellUtf8Console,u=r?.powershellUtf8ChildEnv??this.options?.powershellUtf8ChildEnv,d=function(e,t,r=process.platform,n=process.env){const o={...n,...xr,...t?.env};return"win32"!==r||!0!==t?.powershellUtf8ChildEnv&&kn(e)||(F(o),N(o)),i(o)}(c,{env:r?.env,powershellUtf8ChildEnv:u}),h=A(d)?M(t):t,p=function(e,t,r,n=process.platform){return"win32"===n&&kn(e)?`${!0===r?.powershellUtf8Console?un:""}${!0===r?.powershellUtf8ChildEnv?`${B}\n`:""}${t}`:t}(c,h,{powershellUtf8Console:l,powershellUtf8ChildEnv:u}),f=r?.workingDirectory??this.cwd,m=r?.sandboxWorkspaceRoot??f,g=this.deps?.resolveSandboxPolicyForWorkspace??wt,w=(await g(m,r?.sandboxPolicy)).policy,y="insecure_none"!==w.type?{...w,sandboxWorkspaceRoot:m}:w,v="win32"===process.platform,b=this.options?.powerShellSpares,S=void 0!==b&&!a&&"insecure_none"===y.type&&kn(c)?{shell:c,shellArgs:this.options?.shellArgs??[],cwd:f,env:d}:void 0,k=void 0!==S?await(b?.take(S)):void 0,_=this.deps?.spawnWithSignal??Rr,C=k??_(c,[...this.options?.shellArgs??[],"-c",p],{env:d,cwd:f,stdio:[a?"pipe":"ignore","pipe","pipe"],detached:!v},y,r?.signal),E=async()=>{try{await s.write({type:"stdin_ready",stdin:void 0===k?C.stdin??void 0:void 0,pid:C.pid,shell:_n(c)})}catch(e){}};void 0!==k?(r?.signal&&Tr(k,{detached:!v},r.signal),function(e,t){e.stdin?.on("error",(()=>{})),e.stdin?.end(Buffer.from(t,"utf8"))}(k,p),E()):C.on("spawn",E),void 0!==S&&b?.prestart(S);const x=(this.deps?.attachShellOutputStreams??kr)({stdout:C.stdout,stderr:C.stderr,writable:s,bufferOutputEvents:r?.bufferOutputEvents,outputLimiterOptions:r?.outputLimiterOptions});C.on("error",(e=>{s.throw(e)}));const P=new Promise((e=>{C.once("close",(()=>e()))})),I=r?.closeTimeout??250;C.on("exit",(async(e,t)=>{(0,fr.HF)(o.ctx,"exit");const n=r?.signal?.aborted??!1;if(await(0===I?P:async function(e,t){let r;const n=new Promise((e=>{r=setTimeout((()=>setImmediate(e)),t)}));try{await Promise.race([e,n])}finally{clearTimeout(r)}}(P,I)),await x.flush(),y.captureDenies)try{const e=await dr(C);e&&e.length>0&&await s.write({type:"sandbox_denies",events:e})}catch{}try{await s.write({type:"exit",code:e,signal:t??void 0,data:"",aborted:n}),s.close()}catch(e){s.close()}})),yield*s}catch(e){n.error=e,n.hasError=!0}finally{Sn(n)}}}const En="__CURSOR_ZSH_STATE_START__",xn="__CURSOR_ZSH_STATE_END__",Pn=' local tool\n for tool in base64 tr; do\n if ! builtin whence -p "$tool" >/dev/null 2>&1; then\n builtin print -ru2 -- "Shell state not saved: $tool is not on PATH"\n return 0\n fi\n done\n if ! command base64 </dev/null >/dev/null 2>&1; then\n builtin print -ru2 -- "Shell state not saved: the environment is too large to run commands"\n return 0\n fi\n',In=`#!/usr/bin/env zsh\n\n# Usage:\n# source dump_zsh_state.zsh\n# dump_zsh_state\n# Or execute directly (captures a subshell's state):\n# ./dump_zsh_state.zsh\n\n# Define a function so sourcing won't alter caller state; emulate locally inside\nfunction dump_zsh_state() {\n emulate -L zsh -o errreturn -o pipefail\n set -u\n\n\n # Helper to log timing, only if DUMP_ZSH_STATE_TIMING is set\n if [[ -n "\${DUMP_ZSH_STATE_TIMING:-}" ]]; then\n # Timing setup\n typeset start_time=\${EPOCHREALTIME}\n typeset step_start=\${EPOCHREALTIME}\n _log_timing() {\n typeset step_name="$1"\n typeset now=\${EPOCHREALTIME}\n typeset step_duration=$((now - step_start))\n typeset total_duration=$((now - start_time))\n builtin printf "[TIMING] %-20s: %6.3fs (total: %6.3fs)\n" "$step_name" "$step_duration" "$total_duration" >&2\n step_start=$now\n }\n else\n _log_timing() { :; }\n fi\n\n # Ensure parameter arrays are available\n builtin zmodload -F zsh/parameter p:parameters p:options p:functions p:aliases p:galiases p:saliases 2>/dev/null || true\n _log_timing "zmodload"\n\n # Helper to print a line to stdout\n _emit() {\n builtin print -r -- "$1"\n }\n\n # Helper to safely encode and emit unsafe values, then the line that replays them (one eval by default)\n _emit_encoded() {\n local content="$1"\n local var_name="$2"\n if [[ -n "$content" ]]; then\n # Builtin printf, not a here-document: no argument length limit, and no temp file\n builtin printf 'cursor_snap_%s=$(builtin printf %%s '"'"'%s'"'"' | command base64 -d)\n' "$var_name" "$(command base64 <<<"$content" | command tr -d '\n')"\n if [[ -n "\${3:-}" ]]; then\n builtin print -r -- "$3"\n else\n builtin printf 'builtin eval "$cursor_snap_%s"\n' "$var_name"\n fi\n fi\n }\n\n # Aliases replay after the functions, so a user function named alias would run in place of\n # each alias line. Only a line that starts an alias gets builtin: a quoted value can span\n # lines, and a continuation line can start with "alias ". awk reads bytes under LC_ALL=C, so a\n # value that is not valid UTF-8 does not make it warn. Without awk the lines stay as they are.\n _builtin_alias_lines() {\n [[ -n "$1" ]] || return 0\n builtin printf '%s\n' "$1" | LC_ALL=C command awk -v sq="'" '\n !q && /^alias / { $0 = "builtin " $0 }\n {\n print\n for (i = 1; i <= length($0); i++) {\n c = substr($0, i, 1)\n if (q == 1) { if (c == sq) q = 0 }\n else if (q == 2) { if (c == "\\\\") i++; else if (c == sq) q = 0 }\n else if (c == "\\\\") i++\n else if (c == "$" && substr($0, i + 1, 1) == sq) { q = 2; i++ }\n else if (c == sq) q = 1\n }\n }' 2>/dev/null ||\n builtin printf '%s\n' "$1"\n }\n\n _log_timing "init"\n\n${Pn}\n # Emit start marker at the very beginning of the output\n _emit "__CURSOR_ZSH_STATE_START__"\n\n # Header\n _emit "$PWD"\n\n _emit "# zsh state dump generated on $(command date +'%Y-%m-%d %H:%M:%S %z')"\n _log_timing "header"\n\n # Working directory\n _log_timing "working_dir"\n\n # Drop ELECTRON_RUN_AS_NODE by exact name so one command exporting it can't\n # bake it into the snapshot that every later command re-evals (IDE-2911:\n # Cypress boots as plain Node until a new chat). Exact unset rather than the\n # line-based grep below, which would also eat vars whose name or multiline\n # value merely contains the token. The shell exits right after the dump.\n builtin unset ELECTRON_RUN_AS_NODE 2>/dev/null || true\n\n # Environment variables (exported)\n # Filter out: proxy settings plus request/session-scoped vars that must not\n # leak across shell executions.\n # Under a non-UTF-8 locale zsh writes byte 0xa7 inside $'...' as M-', which\n # its own parser reads as the closing quote (zsh 5.9 Src/utils.c quotestring,\n # https://github.com/zsh-users/zsh/blob/zsh-5.9/Src/utils.c); the sed rewrites\n # that one escape to the § form so the restore eval can parse it. It runs\n # only on scalar $'...' lines: a plain-quoted value can hold the same four\n # characters literally, and there they must stay.\n local env_vars\n env_vars=$(builtin typeset -xp 2>/dev/null | command grep -viE '_proxy=|CURSOR_SANDBOX|SUDO_ASKPASS|CURSOR_ASKPASS|CURSOR_CONVERSATION_ID|CURSOR_REQUEST_ID|CURSOR_AGENT_STORE' | command sed "/^export[^=]*=[\\$]'/ s/\\\\\\\\M-'/\\\\\\\\xa7/g" || true)\n if [[ -n "\${__CURSOR_SANDBOX_OWNED_ENV:-}" ]]; then\n env_vars=$(builtin printf '%s\n' "$env_vars" | command grep -vE "^(export|declare|typeset)( -[a-zA-Z]+)* (\${__CURSOR_SANDBOX_OWNED_ENV// /|})=" || true)\n fi\n _emit_encoded "$env_vars" "ENV_VARS_B64"\n _log_timing "env_variables"\n\n # Options (replayable as setopt lines). Exclude the errreturn/nounset/pipefail this\n # function force-enables above, so they are not baked into the restored snapshot and\n # leaked onto every subsequent command (a stray pipefail makes a successful\n # 'cmd | head' report exit 141).\n local zsh_opts\n zsh_opts=$(setopt 2>/dev/null | command grep -vE '^(errreturn|nounset|pipefail)$' | command awk '{printf "builtin setopt %s 2>/dev/null || true\\n", $0}' || true)\n _emit_encoded "$zsh_opts" "ZSH_OPTS_B64"\n _log_timing "options"\n\n # Each function ends in a NUL and gets its own eval, since one eval of all is quadratic in size\n # and one bad definition would drop the rest. typeset +f lists names without zsh/parameter.\n local all_functions fn\n all_functions=$(\n for fn in \${(f)"$(builtin typeset +f)"}; do\n builtin typeset -f -- "$fn"\n builtin print -rn -- $'\\0'\n done 2>/dev/null || true\n )\n local replay_functions='for cursor_snap_fn in "\${(@0)cursor_snap_FUNCTIONS_B64}"; do builtin eval "$cursor_snap_fn" || builtin true; done'\n _emit_encoded "$all_functions" "FUNCTIONS_B64" "$replay_functions"\n _log_timing "functions"\n\n # Aliases (regular, global, and suffix)\n local alias_lines\n alias_lines=$({\n builtin alias -L 2>/dev/null || true\n builtin alias -gL 2>/dev/null || true\n builtin alias -sL 2>/dev/null || true\n })\n _builtin_alias_lines "$alias_lines" || true\n _log_timing "aliases"\n\n # Done\n _emit "# end of zsh state dump"\n _emit "__CURSOR_ZSH_STATE_END__"\n _log_timing "finalize"\n}\n`,Rn="__CURSOR_ZSH_STATE_LIGHT_VALID__",Tn="# end of zsh state dump (light)",An=`#!/usr/bin/env zsh\n\n# Usage:\n# source dump_zsh_state_light.zsh\n# dump_zsh_state_light\n# Or execute directly (captures a subshell's state):\n# ./dump_zsh_state_light.zsh\n\n# Lightweight version that skips function tracking for better performance\n\n# Define a function so sourcing won't alter caller state; emulate locally inside\nfunction dump_zsh_state_light() {\n emulate -L zsh -o errreturn -o pipefail\n set -u\n\n\n # Helper to log timing, only if DUMP_ZSH_STATE_TIMING is set\n if [[ -n "\${DUMP_ZSH_STATE_TIMING:-}" ]]; then\n # Timing setup\n typeset start_time=\${EPOCHREALTIME}\n typeset step_start=\${EPOCHREALTIME}\n _log_timing() {\n typeset step_name="$1"\n typeset now=\${EPOCHREALTIME}\n typeset step_duration=$((now - step_start))\n typeset total_duration=$((now - start_time))\n builtin printf "[TIMING] %-20s: %6.3fs (total: %6.3fs)\n" "$step_name" "$step_duration" "$total_duration" >&2\n step_start=$now\n }\n else\n _log_timing() { :; }\n fi\n\n # Ensure parameter arrays are available\n builtin zmodload -F zsh/parameter p:parameters p:options p:aliases p:galiases p:saliases 2>/dev/null || true\n _log_timing "zmodload"\n\n # Helper to print a line to stdout\n _emit() {\n builtin print -r -- "$1"\n }\n\n # Helper to safely encode and emit unsafe values\n _emit_encoded() {\n local content="$1"\n local var_name="$2"\n if [[ -n "$content" ]]; then\n # Builtin printf, not a here-document: no argument length limit, and no temp file\n builtin printf 'cursor_snap_%s=$(builtin printf %%s '"'"'%s'"'"' | command base64 -d)\n' "$var_name" "$(command base64 <<<"$content" | command tr -d '\n')"\n builtin printf 'eval "$cursor_snap_%s"\n' "$var_name"\n fi\n }\n\n _log_timing "init"\n\n${Pn}\n # Emit validity marker so we can detect if dump_zsh_state_light completed\n _emit "__CURSOR_ZSH_STATE_LIGHT_VALID__"\n\n # Header\n _emit "$PWD"\n\n _emit "# zsh state dump (light) generated on $(command date +'%Y-%m-%d %H:%M:%S %z')"\n _log_timing "header"\n\n # Working directory\n _log_timing "working_dir"\n\n # Drop ELECTRON_RUN_AS_NODE by exact name so one command exporting it can't\n # bake it into the snapshot that every later command re-evals (IDE-2911:\n # Cypress boots as plain Node until a new chat). Exact unset rather than the\n # line-based grep below, which would also eat vars whose name or multiline\n # value merely contains the token. The shell exits right after the dump.\n builtin unset ELECTRON_RUN_AS_NODE 2>/dev/null || true\n\n # Environment variables (exported)\n # Filter out: proxy settings plus request/session-scoped vars that must not\n # leak across shell executions.\n # Under a non-UTF-8 locale zsh writes byte 0xa7 inside $'...' as M-', which\n # its own parser reads as the closing quote (zsh 5.9 Src/utils.c quotestring,\n # https://github.com/zsh-users/zsh/blob/zsh-5.9/Src/utils.c); the sed rewrites\n # that one escape to the § form so the restore eval can parse it. It runs\n # only on scalar $'...' lines: a plain-quoted value can hold the same four\n # characters literally, and there they must stay.\n local env_vars\n env_vars=$(builtin typeset -xp 2>/dev/null | command grep -viE '_proxy=|CURSOR_SANDBOX|SUDO_ASKPASS|CURSOR_ASKPASS|CURSOR_CONVERSATION_ID|CURSOR_REQUEST_ID|CURSOR_AGENT_STORE' | command sed "/^export[^=]*=[\\$]'/ s/\\\\\\\\M-'/\\\\\\\\xa7/g" || true)\n if [[ -n "\${__CURSOR_SANDBOX_OWNED_ENV:-}" ]]; then\n env_vars=$(builtin printf '%s\n' "$env_vars" | command grep -vE "^(export|declare|typeset)( -[a-zA-Z]+)* (\${__CURSOR_SANDBOX_OWNED_ENV// /|})=" || true)\n fi\n _emit_encoded "$env_vars" "ENV_VARS_B64"\n _log_timing "env_variables"\n\n # Options (replayable as setopt lines). Exclude the errreturn/nounset/pipefail this\n # function force-enables above, so they are not baked into the restored snapshot and\n # leaked onto every subsequent command (a stray pipefail makes a successful\n # 'cmd | head' report exit 141).\n local zsh_opts\n zsh_opts=$(setopt 2>/dev/null | command grep -vE '^(errreturn|nounset|pipefail)$' | command awk '{printf "builtin setopt %s 2>/dev/null || true\\n", $0}' || true)\n _emit_encoded "$zsh_opts" "ZSH_OPTS_B64"\n _log_timing "options"\n\n # SKIP FUNCTIONS - this is the key difference for performance\n\n # Aliases (regular, global, and suffix)\n {\n builtin alias -L 2>/dev/null || true\n builtin alias -gL 2>/dev/null || true\n builtin alias -sL 2>/dev/null || true\n }\n _log_timing "aliases"\n\n # Done\n _emit "${Tn}"\n _log_timing "finalize"\n}\n`;var $n=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function Mn(){const e=process.env.SHELL;return e?.includes("zsh")?e:S("zsh",[]).cmd}class Dn{cwd;state;commandPipeUnreadable;constructor(e,t,r=!1){this.cwd=e,this.state=t,this.commandPipeUnreadable=r}async getCwd(){return this.cwd}clone(e){return new Dn(e??this.cwd,this.state,this.commandPipeUnreadable)}async*execute(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(n,(0,fr.VI)(e.withName("ZshLightState.execute")),!1),s=r?.pipeStdin??!1,i=(0,mr.Jt)(),a=r?.workingDirectory??this.cwd,c={...process.env,...xr,...r?.env};u(c);let l='builtin eval "$1"';s||(l+=" < /dev/null");const d=$(c),h=jr()&&!this.commandPipeUnreadable,p=["-c",(h?Nr:"")+"builtin export PATH=\"/usr/bin:/bin:/usr/sbin:/sbin${PATH:+:$PATH}\"; snap=$(command cat <&3); builtin unsetopt aliases 2>/dev/null; builtin unalias -m '*' 2>/dev/null || true; "+`${An} builtin eval "$snap"; { builtin unsetopt nounset 2>/dev/null || true; builtin eval "\${__CURSOR_SANDBOX_ENV_RESTORE:-}" 2>/dev/null; `+X+Y+`builtin export PWD="$(builtin pwd)"; builtin setopt aliases 2>/dev/null; ${d}${l}; }; COMMAND_EXIT_CODE=$?; dump_zsh_state_light >&4; builtin exit $COMMAND_EXIT_CODE`,gr,...h?[]:[t]],f=r?.sandboxWorkspaceRoot??a,m=(await wt(f,r?.sandboxPolicy)).policy,g="insecure_none"!==m.type?{...m,sandboxWorkspaceRoot:f}:m,w=Rr(Mn(),p,{env:c,stdio:[s?"pipe":"ignore","pipe","pipe","pipe","pipe",h?"pipe":"ignore"],cwd:a,detached:!0},g,r?.signal);let y="";w.on("spawn",(async()=>{try{await i.write({type:"stdin_ready",stdin:w.stdin??void 0,pid:w.pid,shell:"zsh_light"})}catch(e){}}));const v=kr({stdout:w.stdout,stderr:w.stderr,writable:i,bufferOutputEvents:r?.bufferOutputEvents,outputLimiterOptions:r?.outputLimiterOptions});w.on("error",(e=>{i.throw(e)}));let b=null,S=null,k=null,_=!1;const C=async e=>{if(!_){if(_=!0,k&&(clearTimeout(k),k=null),(0,fr.HF)(o.ctx,"exit"),e)try{await v.waitForOutput()}catch(e){return void i.throw(e instanceof Error?e:new Error(String(e)))}if(await v.flush(),h&&Lr(b,y)&&(this.commandPipeUnreadable=!0),!r?.signal?.aborted){const e=`${Rn}\n`;if(y.startsWith(e)){const t=y.slice(e.length),{cwd:r,rest:n}=Hr(t);r?.startsWith("/")&&(this.state=n,this.cwd=r)}}if(g.captureDenies)try{const e=await dr(w);e&&e.length>0&&await i.write({type:"sandbox_denies",events:e})}catch{}try{await i.write({type:"exit",code:b,signal:S??void 0,data:"",aborted:r?.signal?.aborted??!1}),i.close()}catch(e){i.close()}}};w.on("exit",((e,t)=>{b=e,S=t,Mr(w.pid,t,r?.signal?.aborted??!1);const n=r?.closeTimeout??5e3;n>0&&(k=setTimeout((()=>{console.warn(`[shell-exec] Close event did not fire within ${n}ms after exit. This may indicate a background process is holding file descriptors open. Proceeding anyway to prevent hang.`),C(!1).finally((()=>{Fr(w)}))}),n))})),w.on("close",(async()=>{await C(!0)}));const E=w.stdio[3],x=w.stdio[4],P=E instanceof pr.default.Writable?E:null,I=x instanceof pr.default.Readable?x:null;h&&Ur(w,t),Br(P,this.state),Wr(I,(e=>{y+=e})),yield*i}catch(e){n.error=e,n.hasError=!0}finally{$n(n)}}}async function On(e,t){const r={...process.env,...xr,...e?.env},n="__CURSOR_STATE_MARKER__",o=["-o","extendedglob",zr(e),`${An} builtin printf '${n}\\n'; dump_zsh_state_light`],s=Rr(Mn(),o,{env:r,stdio:["ignore","pipe","ignore"],detached:!0},{type:"insecure_none"},e?.signal);s.on("error",(e=>{console.warn(`[shell-exec] zsh-light state init spawn failed; falling back to empty state: ${e instanceof Error?e.message:String(e)}`)}));const{stdout:i}=await Dr(s,{shellName:"zsh-light",...t}),a=Gr(qr(i,n),Rn,Tn)??`${process.cwd()}\n`,{cwd:c,rest:l}=Hr(a);return new Dn(c,l)}var Fn=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function Nn(){const e=process.env.SHELL;return e?.includes("zsh")?e:S("zsh",[]).cmd}class Ln{cwd;state;commandPipeUnreadable;constructor(e,t,r=!1){this.cwd=e,this.state=t,this.commandPipeUnreadable=r}async getCwd(){return this.cwd}clone(e){return new Ln(e??this.cwd,this.state,this.commandPipeUnreadable)}async*execute(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(n,(0,fr.VI)(e.withName("ZshState.execute")),!1),s=r?.pipeStdin??!1,i=r?.keepBackgroundJobs??!1,a=(0,mr.Jt)(),c=r?.workingDirectory??this.cwd,l={...process.env,...xr,...r?.env};u(l);let d='builtin eval "$1"';i&&(d+=" 3<&- 4>&-"),s||(d+=" < /dev/null");const h=$(l),p=jr()&&!this.commandPipeUnreadable,f=["-c",(p?Nr:"")+"builtin export PATH=\"/usr/bin:/bin:/usr/sbin:/sbin${PATH:+:$PATH}\"; snap=$(command cat <&3); builtin unsetopt aliases 2>/dev/null; builtin unalias -m '*' 2>/dev/null || true; "+`${In} builtin eval "$snap"; { builtin unsetopt nounset 2>/dev/null || true; builtin eval "\${__CURSOR_SANDBOX_ENV_RESTORE:-}" 2>/dev/null; `+X+Y+`builtin export PWD="$(builtin pwd)"; builtin setopt aliases 2>/dev/null; ${h}${d}; }; COMMAND_EXIT_CODE=$?; dump_zsh_state >&4; builtin exit $COMMAND_EXIT_CODE`,gr,...p?[]:[t]],m=r?.sandboxWorkspaceRoot??c,g=(await wt(m,r?.sandboxPolicy)).policy,w="insecure_none"!==g.type?{...g,sandboxWorkspaceRoot:m}:g,y=Rr(Nn(),f,{env:l,stdio:[s?"pipe":"ignore","pipe","pipe","pipe","pipe",p?"pipe":"ignore"],cwd:c,detached:!0},w,r?.signal);let v="";y.on("spawn",(async()=>{try{await a.write({type:"stdin_ready",stdin:y.stdin??void 0,pid:y.pid,shell:"zsh"})}catch(e){}}));const b=kr({stdout:y.stdout,stderr:y.stderr,writable:a,bufferOutputEvents:r?.bufferOutputEvents,outputLimiterOptions:r?.outputLimiterOptions});y.on("error",(e=>{a.throw(e)}));let S=null,k=null,_=null,C=!1;const E=async e=>{if(!C){if(C=!0,_&&(clearTimeout(_),_=null),(0,fr.HF)(o.ctx,"exit"),e)try{await b.waitForOutput()}catch(e){return void a.throw(e instanceof Error?e:new Error(String(e)))}if(await b.flush(),p&&Lr(S,v)&&(this.commandPipeUnreadable=!0),!r?.signal?.aborted){const e=`${En}\n`,t=`${xn}\n`;if(v.startsWith(e)&&v.endsWith(t)){let t=v.slice(e.length);t=t.slice(0,-25);const{cwd:r,rest:n}=Hr(t);r?.startsWith("/")&&(this.state=n,this.cwd=r)}}if(w.captureDenies)try{const e=await dr(y);e&&e.length>0&&await a.write({type:"sandbox_denies",events:e})}catch{}try{await a.write({type:"exit",code:S,signal:k??void 0,data:"",aborted:r?.signal?.aborted??!1}),a.close()}catch(e){a.close()}}};y.on("exit",((e,t)=>{S=e,k=t,Mr(y.pid,t,r?.signal?.aborted??!1);const n=r?.closeTimeout??5e3;n>0&&(_=setTimeout((()=>{if(C)return;const e=`[shell-exec] Close event did not fire within ${n}ms after exit. This may indicate a background process is holding file descriptors open. `;i?console.warn(`${e}Leaving it running because keepBackgroundJobs is set.`):(console.warn(`${e}Killing detached process group.`),Ar(y.pid,"SIGKILL")),E(!1).finally((()=>{Fr(y)}))}),n))})),y.on("close",(async()=>{await E(!0)}));const x=y.stdio[3],P=y.stdio[4],I=x instanceof pr.default.Writable?x:null,R=P instanceof pr.default.Readable?P:null;p&&Ur(y,t),Br(I,this.state),Wr(R,(e=>{v+=e})),yield*a}catch(e){n.error=e,n.hasError=!0}finally{Fn(n)}}}async function jn(e,t){const r={...process.env,...xr,...e?.env},n="__CURSOR_STATE_MARKER__",o=["-o","extendedglob",zr(e),`${In} builtin printf '${n}\\n'; dump_zsh_state`],s=Rr(Nn(),o,{env:r,stdio:["ignore","pipe","ignore"],detached:!0},{type:"insecure_none"},e?.signal);s.on("error",(e=>{console.warn(`[shell-exec] zsh state init spawn failed; falling back to empty state: ${e instanceof Error?e.message:String(e)}`)}));const{stdout:i}=await Dr(s,{shellName:"zsh",...t}),a=Gr(qr(i,n),En,xn)??`${process.cwd()}\n`,{cwd:c,rest:l}=Hr(a);return new Ln(c,l)}function Un(e){try{return S(e,[]).cmd!==e}catch(e){return!1}}function Bn(){if("win32"!==process.platform)return;if(!process.env.MSYSTEM)return;const e=process.env.EXEPATH;if(e)return function(e){const t=e.replace(/[\\/]+$/,""),r=f.default.win32.basename(t).toLowerCase();return"bash.exe"===r?t:"bin"===r?f.default.win32.join(t,"bash.exe"):f.default.win32.join(t,"bin","bash.exe")}(e);const t=["C:\\Program Files\\Git\\bin\\bash.exe","C:\\Program Files (x86)\\Git\\bin\\bash.exe"];for(const e of t)try{if(S(e,[]).cmd===e)return e}catch{}return"C:\\Program Files\\Git\\bin\\bash.exe"}function Wn(e){if(e===Er.ZshLight)return Er.ZshLight;const t=e||process.env.SHELL||"",r="win32"===process.platform,n=r&&!e?Bn():void 0,o=void 0!==n||/git.*bash\.exe$/i.test(t)||/program.*git.*bin.*bash\.exe$/i.test(t),s=!r||o;return t.includes("zsh")?Er.Zsh:t.includes("bash")&&s?Er.Bash:t.includes("pwsh")||t.includes("powershell")?Er.PowerShell:n?Er.Bash:r&&(Un("pwsh")||Un("powershell"))?Er.PowerShell:Un("zsh")?Er.Zsh:Un("bash")&&s?Er.Bash:Un("pwsh")||Un("powershell")?Er.PowerShell:Er.Naive}function Hn(e,t){let r=e;if(!e?.userTerminalHint){const t=Bn();t&&(r={...e,userTerminalHint:t})}const n=Wn(r?.userTerminalHint??""),o=t?.initBashState??en,s=t?.initPowerShellState??bn,i=t?.initZshState??jn,a=t?.initZshLightState??On;switch(n){case Er.Zsh:return new rn((()=>i(r)));case Er.Bash:return new rn((()=>o(r)));case Er.PowerShell:return new rn((()=>s()));case Er.ZshLight:return new rn((()=>a(r)));default:{const e=t?.getPowerShellExecutable??wn;return function(e){const t="win32"===process.platform,r=e?.shell??(t?wn():void 0),n=process.cwd();return new Cn(n,{...e,shell:r})}({env:r?.env,shell:"win32"===process.platform?e():void 0})}}}const qn={perUser:{type:"insecure_none"}}},"../utils/dist/lru-cache.js"(e,t,r){r.d(t,{q:()=>ue});var n,o,s,i,a,c,l,u,d,h,p,f,m,g,w,y,v,b,S,k,_,C,E,x,P,I,R,T,A,$,M,D,O,F,N,L,j,U,B,W,H,q,z,G,V,K,J,Z,X,Q=function(e,t,r,n,o){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!o)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!o:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?o.call(e,r):o?o.value=r:t.set(e,r),r},Y=function(e,t,r,n){if("a"===r&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?n:"a"===r?n.call(e):n?n.value:t.get(e)};const ee="object"==typeof performance&&performance&&"function"==typeof performance.now?performance:Date,te=new Set,re="object"==typeof process&&process?process:{},ne=(e,t,r,n)=>{"function"==typeof re.emitWarning?re.emitWarning(e,t,r,n):console.error(`[${r}] ${t}: ${e}`)};let oe,se=globalThis.AbortController;if(void 0===se){oe=class{constructor(){this._onabort=[],this.aborted=!1}addEventListener(e,t){this._onabort.push(t)}},se=class{constructor(){this.signal=new oe,t()}abort(e){if(!this.signal.aborted){this.signal.reason=e,this.signal.aborted=!0;for(const t of this.signal._onabort)t(e);this.signal.onabort?.(e)}}};let e="1"!==re.env?.LRU_CACHE_IGNORE_AC_WARNING;const t=()=>{e&&(e=!1,ne("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",t))}}Symbol("type");const ie=e=>e&&e===Math.floor(e)&&e>0&&Number.isFinite(e),ae=e=>ie(e)?e<=256?Uint8Array:e<=65536?Uint16Array:e<=2**32?Uint32Array:e<=Number.MAX_SAFE_INTEGER?ce:null:null;class ce extends Array{constructor(e){super(e),this.fill(0)}}class le{static create(e){const t=ae(e);if(!t)return[];Q(n,n,!0,"f",o);const r=new n(e,t);return Q(n,n,!1,"f",o),r}constructor(e,t){if(!Y(n,n,"f",o))throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new t(e),this.length=0}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}}n=le,o={value:!1};class ue{get perf(){return Y(this,p,"f")}static unsafeExposeInternals(e){return{starts:Y(e,x,"f"),ttls:Y(e,P,"f"),sizes:Y(e,E,"f"),keyMap:Y(e,g,"f"),keyList:Y(e,w,"f"),valList:Y(e,y,"f"),next:Y(e,v,"f"),prev:Y(e,b,"f"),get head(){return Y(e,S,"f")},get tail(){return Y(e,k,"f")},free:Y(e,_,"f"),isBackgroundFetch:t=>Y(e,s,"m",G).call(e,t),backgroundFetch:(t,r,n,o)=>Y(e,s,"m",z).call(e,t,r,n,o),moveToTail:t=>Y(e,s,"m",K).call(e,t),indexes:t=>Y(e,s,"m",B).call(e,t),rindexes:t=>Y(e,s,"m",W).call(e,t),isStale:t=>Y(e,F,"f").call(e,t)}}get max(){return Y(this,i,"f")}get maxSize(){return Y(this,a,"f")}get calculatedSize(){return Y(this,m,"f")}get size(){return Y(this,f,"f")}get fetchMethod(){return Y(this,d,"f")}get memoMethod(){return Y(this,h,"f")}get dispose(){return Y(this,c,"f")}get onInsert(){return Y(this,l,"f")}get disposeAfter(){return Y(this,u,"f")}constructor(e){s.add(this),i.set(this,void 0),a.set(this,void 0),c.set(this,void 0),l.set(this,void 0),u.set(this,void 0),d.set(this,void 0),h.set(this,void 0),p.set(this,void 0),f.set(this,void 0),m.set(this,void 0),g.set(this,void 0),w.set(this,void 0),y.set(this,void 0),v.set(this,void 0),b.set(this,void 0),S.set(this,void 0),k.set(this,void 0),_.set(this,void 0),C.set(this,void 0),E.set(this,void 0),x.set(this,void 0),P.set(this,void 0),I.set(this,void 0),R.set(this,void 0),T.set(this,void 0),A.set(this,void 0),M.set(this,(()=>{})),D.set(this,(()=>{})),O.set(this,(()=>{})),F.set(this,(()=>!1)),L.set(this,(e=>{})),j.set(this,((e,t,r)=>{})),U.set(this,((e,t,r,n)=>{if(r||n)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0})),this[X]="LRUCache";const{max:t=0,ttl:r,ttlResolution:n=1,ttlAutopurge:o,updateAgeOnGet:B,updateAgeOnHas:W,allowStale:H,dispose:q,onInsert:z,disposeAfter:G,noDisposeOnSet:V,noUpdateTTL:K,maxSize:J=0,maxEntrySize:Z=0,sizeCalculation:re,fetchMethod:oe,memoMethod:se,noDeleteOnFetchRejection:ce,noDeleteOnStaleGet:de,allowStaleOnFetchRejection:he,allowStaleOnFetchAbort:pe,ignoreFetchAbort:fe,perf:me}=e;if(void 0!==me&&"function"!=typeof me?.now)throw new TypeError("perf option must have a now() method if specified");if(Q(this,p,me??ee,"f"),0!==t&&!ie(t))throw new TypeError("max option must be a nonnegative integer");const ge=t?ae(t):Array;if(!ge)throw new Error(`invalid max value: ${t}`);if(Q(this,i,t,"f"),Q(this,a,J,"f"),this.maxEntrySize=Z||Y(this,a,"f"),this.sizeCalculation=re,this.sizeCalculation){if(!Y(this,a,"f")&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if("function"!=typeof this.sizeCalculation)throw new TypeError("sizeCalculation set to non-function")}if(void 0!==se&&"function"!=typeof se)throw new TypeError("memoMethod must be a function if defined");if(Q(this,h,se,"f"),void 0!==oe&&"function"!=typeof oe)throw new TypeError("fetchMethod must be a function if specified");if(Q(this,d,oe,"f"),Q(this,R,!!oe,"f"),Q(this,g,new Map,"f"),Q(this,w,new Array(t).fill(void 0),"f"),Q(this,y,new Array(t).fill(void 0),"f"),Q(this,v,new ge(t),"f"),Q(this,b,new ge(t),"f"),Q(this,S,0,"f"),Q(this,k,0,"f"),Q(this,_,le.create(t),"f"),Q(this,f,0,"f"),Q(this,m,0,"f"),"function"==typeof q&&Q(this,c,q,"f"),"function"==typeof z&&Q(this,l,z,"f"),"function"==typeof G?(Q(this,u,G,"f"),Q(this,C,[],"f")):(Q(this,u,void 0,"f"),Q(this,C,void 0,"f")),Q(this,I,!!Y(this,c,"f"),"f"),Q(this,A,!!Y(this,l,"f"),"f"),Q(this,T,!!Y(this,u,"f"),"f"),this.noDisposeOnSet=!!V,this.noUpdateTTL=!!K,this.noDeleteOnFetchRejection=!!ce,this.allowStaleOnFetchRejection=!!he,this.allowStaleOnFetchAbort=!!pe,this.ignoreFetchAbort=!!fe,0!==this.maxEntrySize){if(0!==Y(this,a,"f")&&!ie(Y(this,a,"f")))throw new TypeError("maxSize must be a positive integer if specified");if(!ie(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");Y(this,s,"m",N).call(this)}if(this.allowStale=!!H,this.noDeleteOnStaleGet=!!de,this.updateAgeOnGet=!!B,this.updateAgeOnHas=!!W,this.ttlResolution=ie(n)||0===n?n:1,this.ttlAutopurge=!!o,this.ttl=r||0,this.ttl){if(!ie(this.ttl))throw new TypeError("ttl must be a positive integer if specified");Y(this,s,"m",$).call(this)}if(0===Y(this,i,"f")&&0===this.ttl&&0===Y(this,a,"f"))throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!Y(this,i,"f")&&!Y(this,a,"f")){const e="LRU_CACHE_UNBOUNDED";(e=>!te.has(e))(e)&&(te.add(e),ne("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",e,ue))}}getRemainingTTL(e){return Y(this,g,"f").has(e)?1/0:0}*entries(){for(const e of Y(this,s,"m",B).call(this))void 0===Y(this,y,"f")[e]||void 0===Y(this,w,"f")[e]||Y(this,s,"m",G).call(this,Y(this,y,"f")[e])||(yield[Y(this,w,"f")[e],Y(this,y,"f")[e]])}*rentries(){for(const e of Y(this,s,"m",W).call(this))void 0===Y(this,y,"f")[e]||void 0===Y(this,w,"f")[e]||Y(this,s,"m",G).call(this,Y(this,y,"f")[e])||(yield[Y(this,w,"f")[e],Y(this,y,"f")[e]])}*keys(){for(const e of Y(this,s,"m",B).call(this)){const t=Y(this,w,"f")[e];void 0===t||Y(this,s,"m",G).call(this,Y(this,y,"f")[e])||(yield t)}}*rkeys(){for(const e of Y(this,s,"m",W).call(this)){const t=Y(this,w,"f")[e];void 0===t||Y(this,s,"m",G).call(this,Y(this,y,"f")[e])||(yield t)}}*values(){for(const e of Y(this,s,"m",B).call(this))void 0===Y(this,y,"f")[e]||Y(this,s,"m",G).call(this,Y(this,y,"f")[e])||(yield Y(this,y,"f")[e])}*rvalues(){for(const e of Y(this,s,"m",W).call(this))void 0===Y(this,y,"f")[e]||Y(this,s,"m",G).call(this,Y(this,y,"f")[e])||(yield Y(this,y,"f")[e])}[(i=new WeakMap,a=new WeakMap,c=new WeakMap,l=new WeakMap,u=new WeakMap,d=new WeakMap,h=new WeakMap,p=new WeakMap,f=new WeakMap,m=new WeakMap,g=new WeakMap,w=new WeakMap,y=new WeakMap,v=new WeakMap,b=new WeakMap,S=new WeakMap,k=new WeakMap,_=new WeakMap,C=new WeakMap,E=new WeakMap,x=new WeakMap,P=new WeakMap,I=new WeakMap,R=new WeakMap,T=new WeakMap,A=new WeakMap,M=new WeakMap,D=new WeakMap,O=new WeakMap,F=new WeakMap,L=new WeakMap,j=new WeakMap,U=new WeakMap,s=new WeakSet,$=function(){const e=new ce(Y(this,i,"f")),t=new ce(Y(this,i,"f"));Q(this,P,e,"f"),Q(this,x,t,"f"),Q(this,O,((r,n,o=Y(this,p,"f").now())=>{if(t[r]=0!==n?o:0,e[r]=n,0!==n&&this.ttlAutopurge){const e=setTimeout((()=>{Y(this,F,"f").call(this,r)&&Y(this,s,"m",J).call(this,Y(this,w,"f")[r],"expire")}),n+1);e.unref&&e.unref()}}),"f"),Q(this,M,(r=>{t[r]=0!==e[r]?Y(this,p,"f").now():0}),"f"),Q(this,D,((o,s)=>{if(e[s]){const i=e[s],a=t[s];if(!i||!a)return;o.ttl=i,o.start=a,o.now=r||n();const c=o.now-a;o.remainingTTL=i-c}}),"f");let r=0;const n=()=>{const e=Y(this,p,"f").now();if(this.ttlResolution>0){r=e;const t=setTimeout((()=>{r=0}),this.ttlResolution);t.unref&&t.unref()}return e};this.getRemainingTTL=o=>{const s=Y(this,g,"f").get(o);if(void 0===s)return 0;const i=e[s],a=t[s];return i&&a?i-((r||n())-a):1/0},Q(this,F,(o=>{const s=t[o],i=e[o];return!!i&&!!s&&(r||n())-s>i}),"f")},N=function(){const e=new ce(Y(this,i,"f"));Q(this,m,0,"f"),Q(this,E,e,"f"),Q(this,L,(t=>{Q(this,m,Y(this,m,"f")-e[t],"f"),e[t]=0}),"f"),Q(this,U,((e,t,r,n)=>{if(Y(this,s,"m",G).call(this,t))return 0;if(!ie(r)){if(!n)throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");if("function"!=typeof n)throw new TypeError("sizeCalculation must be a function");if(r=n(t,e),!ie(r))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}return r}),"f"),Q(this,j,((t,r,n)=>{if(e[t]=r,Y(this,a,"f")){const r=Y(this,a,"f")-e[t];for(;Y(this,m,"f")>r;)Y(this,s,"m",q).call(this,!0)}Q(this,m,Y(this,m,"f")+e[t],"f"),n&&(n.entrySize=r,n.totalCalculatedSize=Y(this,m,"f"))}),"f")},B=function*({allowStale:e=this.allowStale}={}){if(Y(this,f,"f"))for(let t=Y(this,k,"f");Y(this,s,"m",H).call(this,t)&&(!e&&Y(this,F,"f").call(this,t)||(yield t),t!==Y(this,S,"f"));)t=Y(this,b,"f")[t]},W=function*({allowStale:e=this.allowStale}={}){if(Y(this,f,"f"))for(let t=Y(this,S,"f");Y(this,s,"m",H).call(this,t)&&(!e&&Y(this,F,"f").call(this,t)||(yield t),t!==Y(this,k,"f"));)t=Y(this,v,"f")[t]},H=function(e){return void 0!==e&&Y(this,g,"f").get(Y(this,w,"f")[e])===e},Symbol.iterator)](){return this.entries()}find(e,t={}){for(const r of Y(this,s,"m",B).call(this)){const n=Y(this,y,"f")[r],o=Y(this,s,"m",G).call(this,n)?n.__staleWhileFetching:n;if(void 0!==o&&e(o,Y(this,w,"f")[r],this))return this.get(Y(this,w,"f")[r],t)}}forEach(e,t=this){for(const r of Y(this,s,"m",B).call(this)){const n=Y(this,y,"f")[r],o=Y(this,s,"m",G).call(this,n)?n.__staleWhileFetching:n;void 0!==o&&e.call(t,o,Y(this,w,"f")[r],this)}}rforEach(e,t=this){for(const r of Y(this,s,"m",W).call(this)){const n=Y(this,y,"f")[r],o=Y(this,s,"m",G).call(this,n)?n.__staleWhileFetching:n;void 0!==o&&e.call(t,o,Y(this,w,"f")[r],this)}}purgeStale(){let e=!1;for(const t of Y(this,s,"m",W).call(this,{allowStale:!0}))Y(this,F,"f").call(this,t)&&(Y(this,s,"m",J).call(this,Y(this,w,"f")[t],"expire"),e=!0);return e}info(e){const t=Y(this,g,"f").get(e);if(void 0===t)return;const r=Y(this,y,"f")[t],n=Y(this,s,"m",G).call(this,r)?r.__staleWhileFetching:r;if(void 0===n)return;const o={value:n};if(Y(this,P,"f")&&Y(this,x,"f")){const e=Y(this,P,"f")[t],r=Y(this,x,"f")[t];if(e&&r){const t=e-(Y(this,p,"f").now()-r);o.ttl=t,o.start=Date.now()}}return Y(this,E,"f")&&(o.size=Y(this,E,"f")[t]),o}dump(){const e=[];for(const t of Y(this,s,"m",B).call(this,{allowStale:!0})){const r=Y(this,w,"f")[t],n=Y(this,y,"f")[t],o=Y(this,s,"m",G).call(this,n)?n.__staleWhileFetching:n;if(void 0===o||void 0===r)continue;const i={value:o};if(Y(this,P,"f")&&Y(this,x,"f")){i.ttl=Y(this,P,"f")[t];const e=Y(this,p,"f").now()-Y(this,x,"f")[t];i.start=Math.floor(Date.now()-e)}Y(this,E,"f")&&(i.size=Y(this,E,"f")[t]),e.unshift([r,i])}return e}load(e){this.clear();for(const[t,r]of e){if(r.start){const e=Date.now()-r.start;r.start=Y(this,p,"f").now()-e}this.set(t,r.value,r)}}set(e,t,r={}){var n;if(void 0===t)return this.delete(e),this;const{ttl:o=this.ttl,start:a,noDisposeOnSet:d=this.noDisposeOnSet,sizeCalculation:h=this.sizeCalculation,status:p}=r;let{noUpdateTTL:m=this.noUpdateTTL}=r;const S=Y(this,U,"f").call(this,e,t,r.size||0,h);if(this.maxEntrySize&&S>this.maxEntrySize)return p&&(p.set="miss",p.maxEntrySizeExceeded=!0),Y(this,s,"m",J).call(this,e,"set"),this;let E=0===Y(this,f,"f")?void 0:Y(this,g,"f").get(e);if(void 0===E)E=0===Y(this,f,"f")?Y(this,k,"f"):0!==Y(this,_,"f").length?Y(this,_,"f").pop():Y(this,f,"f")===Y(this,i,"f")?Y(this,s,"m",q).call(this,!1):Y(this,f,"f"),Y(this,w,"f")[E]=e,Y(this,y,"f")[E]=t,Y(this,g,"f").set(e,E),Y(this,v,"f")[Y(this,k,"f")]=E,Y(this,b,"f")[E]=Y(this,k,"f"),Q(this,k,E,"f"),Q(this,f,(n=Y(this,f,"f"),++n),"f"),Y(this,j,"f").call(this,E,S,p),p&&(p.set="add"),m=!1,Y(this,A,"f")&&Y(this,l,"f")?.call(this,t,e,"add");else{Y(this,s,"m",K).call(this,E);const r=Y(this,y,"f")[E];if(t!==r){if(Y(this,R,"f")&&Y(this,s,"m",G).call(this,r)){r.__abortController.abort(new Error("replaced"));const{__staleWhileFetching:t}=r;void 0===t||d||(Y(this,I,"f")&&Y(this,c,"f")?.call(this,t,e,"set"),Y(this,T,"f")&&Y(this,C,"f")?.push([t,e,"set"]))}else d||(Y(this,I,"f")&&Y(this,c,"f")?.call(this,r,e,"set"),Y(this,T,"f")&&Y(this,C,"f")?.push([r,e,"set"]));if(Y(this,L,"f").call(this,E),Y(this,j,"f").call(this,E,S,p),Y(this,y,"f")[E]=t,p){p.set="replace";const e=r&&Y(this,s,"m",G).call(this,r)?r.__staleWhileFetching:r;void 0!==e&&(p.oldValue=e)}}else p&&(p.set="update");Y(this,A,"f")&&this.onInsert?.(t,e,t===r?"update":"replace")}if(0===o||Y(this,P,"f")||Y(this,s,"m",$).call(this),Y(this,P,"f")&&(m||Y(this,O,"f").call(this,E,o,a),p&&Y(this,D,"f").call(this,p,E)),!d&&Y(this,T,"f")&&Y(this,C,"f")){const e=Y(this,C,"f");let t;for(;t=e?.shift();)Y(this,u,"f")?.call(this,...t)}return this}pop(){try{for(;Y(this,f,"f");){const e=Y(this,y,"f")[Y(this,S,"f")];if(Y(this,s,"m",q).call(this,!0),Y(this,s,"m",G).call(this,e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(void 0!==e)return e}return}finally{if(Y(this,T,"f")&&Y(this,C,"f")){const e=Y(this,C,"f");let t;for(;t=e?.shift();)Y(this,u,"f")?.call(this,...t)}}}has(e,t={}){const{updateAgeOnHas:r=this.updateAgeOnHas,status:n}=t,o=Y(this,g,"f").get(e);if(void 0!==o){const e=Y(this,y,"f")[o];if(Y(this,s,"m",G).call(this,e)&&void 0===e.__staleWhileFetching)return!1;if(!Y(this,F,"f").call(this,o))return r&&Y(this,M,"f").call(this,o),n&&(n.has="hit",Y(this,D,"f").call(this,n,o)),!0;n&&(n.has="stale",Y(this,D,"f").call(this,n,o))}else n&&(n.has="miss");return!1}peek(e,t={}){const{allowStale:r=this.allowStale}=t,n=Y(this,g,"f").get(e);if(void 0===n||!r&&Y(this,F,"f").call(this,n))return;const o=Y(this,y,"f")[n];return Y(this,s,"m",G).call(this,o)?o.__staleWhileFetching:o}async fetch(e,t={}){const{allowStale:r=this.allowStale,updateAgeOnGet:n=this.updateAgeOnGet,noDeleteOnStaleGet:o=this.noDeleteOnStaleGet,ttl:i=this.ttl,noDisposeOnSet:a=this.noDisposeOnSet,size:c=0,sizeCalculation:l=this.sizeCalculation,noUpdateTTL:u=this.noUpdateTTL,noDeleteOnFetchRejection:d=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:h=this.allowStaleOnFetchRejection,ignoreFetchAbort:p=this.ignoreFetchAbort,allowStaleOnFetchAbort:f=this.allowStaleOnFetchAbort,context:m,forceRefresh:w=!1,status:v,signal:b}=t;if(!Y(this,R,"f"))return v&&(v.fetch="get"),this.get(e,{allowStale:r,updateAgeOnGet:n,noDeleteOnStaleGet:o,status:v});const S={allowStale:r,updateAgeOnGet:n,noDeleteOnStaleGet:o,ttl:i,noDisposeOnSet:a,size:c,sizeCalculation:l,noUpdateTTL:u,noDeleteOnFetchRejection:d,allowStaleOnFetchRejection:h,allowStaleOnFetchAbort:f,ignoreFetchAbort:p,status:v,signal:b},k=Y(this,g,"f").get(e);if(void 0===k){v&&(v.fetch="miss");const t=Y(this,s,"m",z).call(this,e,k,S,m);return t.__returned=t}{const t=Y(this,y,"f")[k];if(Y(this,s,"m",G).call(this,t)){const e=r&&void 0!==t.__staleWhileFetching;return v&&(v.fetch="inflight",e&&(v.returnedStale=!0)),e?t.__staleWhileFetching:t.__returned=t}const o=Y(this,F,"f").call(this,k);if(!w&&!o)return v&&(v.fetch="hit"),Y(this,s,"m",K).call(this,k),n&&Y(this,M,"f").call(this,k),v&&Y(this,D,"f").call(this,v,k),t;const i=Y(this,s,"m",z).call(this,e,k,S,m),a=void 0!==i.__staleWhileFetching&&r;return v&&(v.fetch=o?"stale":"refresh",a&&o&&(v.returnedStale=!0)),a?i.__staleWhileFetching:i.__returned=i}}async forceFetch(e,t={}){const r=await this.fetch(e,t);if(void 0===r)throw new Error("fetch() returned undefined");return r}memo(e,t={}){const r=Y(this,h,"f");if(!r)throw new Error("no memoMethod provided to constructor");const{context:n,forceRefresh:o,...s}=t,i=this.get(e,s);if(!o&&void 0!==i)return i;const a=r(e,i,{options:s,context:n});return this.set(e,a,s),a}get(e,t={}){const{allowStale:r=this.allowStale,updateAgeOnGet:n=this.updateAgeOnGet,noDeleteOnStaleGet:o=this.noDeleteOnStaleGet,status:i}=t,a=Y(this,g,"f").get(e);if(void 0!==a){const t=Y(this,y,"f")[a],c=Y(this,s,"m",G).call(this,t);return i&&Y(this,D,"f").call(this,i,a),Y(this,F,"f").call(this,a)?(i&&(i.get="stale"),c?(i&&r&&void 0!==t.__staleWhileFetching&&(i.returnedStale=!0),r?t.__staleWhileFetching:void 0):(o||Y(this,s,"m",J).call(this,e,"expire"),i&&r&&(i.returnedStale=!0),r?t:void 0)):(i&&(i.get="hit"),c?t.__staleWhileFetching:(Y(this,s,"m",K).call(this,a),n&&Y(this,M,"f").call(this,a),t))}i&&(i.get="miss")}delete(e){return Y(this,s,"m",J).call(this,e,"delete")}clear(){Y(this,s,"m",Z).call(this,"delete")}}X=Symbol.toStringTag,q=function(e){var t;const r=Y(this,S,"f"),n=Y(this,w,"f")[r],o=Y(this,y,"f")[r];return Y(this,R,"f")&&Y(this,s,"m",G).call(this,o)?o.__abortController.abort(new Error("evicted")):(Y(this,I,"f")||Y(this,T,"f"))&&(Y(this,I,"f")&&Y(this,c,"f")?.call(this,o,n,"evict"),Y(this,T,"f")&&Y(this,C,"f")?.push([o,n,"evict"])),Y(this,L,"f").call(this,r),e&&(Y(this,w,"f")[r]=void 0,Y(this,y,"f")[r]=void 0,Y(this,_,"f").push(r)),1===Y(this,f,"f")?(Q(this,S,Q(this,k,0,"f"),"f"),Y(this,_,"f").length=0):Q(this,S,Y(this,v,"f")[r],"f"),Y(this,g,"f").delete(n),Q(this,f,(t=Y(this,f,"f"),--t),"f"),r},z=function(e,t,r,n){const o=void 0===t?void 0:Y(this,y,"f")[t];if(Y(this,s,"m",G).call(this,o))return o;const i=new se,{signal:a}=r;a?.addEventListener("abort",(()=>i.abort(a.reason)),{signal:i.signal});const c={signal:i.signal,options:r,context:n},l=(n,o=!1)=>{const{aborted:a}=i.signal,l=r.ignoreFetchAbort&&void 0!==n;if(r.status&&(a&&!o?(r.status.fetchAborted=!0,r.status.fetchError=i.signal.reason,l&&(r.status.fetchAbortIgnored=!0)):r.status.fetchResolved=!0),a&&!l&&!o)return u(i.signal.reason);const d=h,p=Y(this,y,"f")[t];return(p===h||l&&o&&void 0===p)&&(void 0===n?void 0!==d.__staleWhileFetching?Y(this,y,"f")[t]=d.__staleWhileFetching:Y(this,s,"m",J).call(this,e,"fetch"):(r.status&&(r.status.fetchUpdated=!0),this.set(e,n,c.options))),n},u=n=>{const{aborted:o}=i.signal,a=o&&r.allowStaleOnFetchAbort,c=a||r.allowStaleOnFetchRejection,l=c||r.noDeleteOnFetchRejection,u=h;if(Y(this,y,"f")[t]===h&&(l&&void 0!==u.__staleWhileFetching?a||(Y(this,y,"f")[t]=u.__staleWhileFetching):Y(this,s,"m",J).call(this,e,"fetch")),c)return r.status&&void 0!==u.__staleWhileFetching&&(r.status.returnedStale=!0),u.__staleWhileFetching;if(u.__returned===u)throw n};r.status&&(r.status.fetchDispatched=!0);const h=new Promise(((t,n)=>{const s=Y(this,d,"f")?.call(this,e,o,c);s&&s instanceof Promise&&s.then((e=>t(void 0===e?void 0:e)),n),i.signal.addEventListener("abort",(()=>{r.ignoreFetchAbort&&!r.allowStaleOnFetchAbort||(t(void 0),r.allowStaleOnFetchAbort&&(t=e=>l(e,!0)))}))})).then(l,(e=>(r.status&&(r.status.fetchRejected=!0,r.status.fetchError=e),u(e)))),p=Object.assign(h,{__abortController:i,__staleWhileFetching:o,__returned:void 0});return void 0===t?(this.set(e,p,{...c.options,status:void 0}),t=Y(this,g,"f").get(e)):Y(this,y,"f")[t]=p,p},G=function(e){if(!Y(this,R,"f"))return!1;const t=e;return!!t&&t instanceof Promise&&t.hasOwnProperty("__staleWhileFetching")&&t.__abortController instanceof se},V=function(e,t){Y(this,b,"f")[t]=e,Y(this,v,"f")[e]=t},K=function(e){e!==Y(this,k,"f")&&(e===Y(this,S,"f")?Q(this,S,Y(this,v,"f")[e],"f"):Y(this,s,"m",V).call(this,Y(this,b,"f")[e],Y(this,v,"f")[e]),Y(this,s,"m",V).call(this,Y(this,k,"f"),e),Q(this,k,e,"f"))},J=function(e,t){var r;let n=!1;if(0!==Y(this,f,"f")){const o=Y(this,g,"f").get(e);if(void 0!==o)if(n=!0,1===Y(this,f,"f"))Y(this,s,"m",Z).call(this,t);else{Y(this,L,"f").call(this,o);const n=Y(this,y,"f")[o];if(Y(this,s,"m",G).call(this,n)?n.__abortController.abort(new Error("deleted")):(Y(this,I,"f")||Y(this,T,"f"))&&(Y(this,I,"f")&&Y(this,c,"f")?.call(this,n,e,t),Y(this,T,"f")&&Y(this,C,"f")?.push([n,e,t])),Y(this,g,"f").delete(e),Y(this,w,"f")[o]=void 0,Y(this,y,"f")[o]=void 0,o===Y(this,k,"f"))Q(this,k,Y(this,b,"f")[o],"f");else if(o===Y(this,S,"f"))Q(this,S,Y(this,v,"f")[o],"f");else{const e=Y(this,b,"f")[o];Y(this,v,"f")[e]=Y(this,v,"f")[o];const t=Y(this,v,"f")[o];Y(this,b,"f")[t]=Y(this,b,"f")[o]}Q(this,f,(r=Y(this,f,"f"),--r),"f"),Y(this,_,"f").push(o)}}if(Y(this,T,"f")&&Y(this,C,"f")?.length){const e=Y(this,C,"f");let t;for(;t=e?.shift();)Y(this,u,"f")?.call(this,...t)}return n},Z=function(e){for(const t of Y(this,s,"m",W).call(this,{allowStale:!0})){const r=Y(this,y,"f")[t];if(Y(this,s,"m",G).call(this,r))r.__abortController.abort(new Error("deleted"));else{const n=Y(this,w,"f")[t];Y(this,I,"f")&&Y(this,c,"f")?.call(this,r,n,e),Y(this,T,"f")&&Y(this,C,"f")?.push([r,n,e])}}if(Y(this,g,"f").clear(),Y(this,y,"f").fill(void 0),Y(this,w,"f").fill(void 0),Y(this,P,"f")&&Y(this,x,"f")&&(Y(this,P,"f").fill(0),Y(this,x,"f").fill(0)),Y(this,E,"f")&&Y(this,E,"f").fill(0),Q(this,S,0,"f"),Q(this,k,0,"f"),Y(this,_,"f").length=0,Q(this,m,0,"f"),Q(this,f,0,"f"),Y(this,T,"f")&&Y(this,C,"f")){const e=Y(this,C,"f");let t;for(;t=e?.shift();)Y(this,u,"f")?.call(this,...t)}}},"../utils/dist/path-utils.js"(e,t,r){r.d(t,{BJ:()=>p,DN:()=>u,PS:()=>m,ZU:()=>d,fl:()=>g,jl:()=>a,o1:()=>l,oL:()=>f,yn:()=>c});var n=r("node:fs/promises"),o=r("node:os"),s=r("node:path"),i=r("node:url");function a(e){return e.replace(/^~(?=$|\/|\\)/,(0,o.homedir)())}function c(e,t){return void 0!==e&&("win32"===process.platform?(0,s.normalize)(e).toLowerCase()===(0,s.normalize)(t).toLowerCase():e===t)}function l(e,t){const r=a(function(e){if(!e.startsWith("file://"))return e;try{return(0,i.fileURLToPath)(e)}catch{return e}}(e));return t&&!(0,s.isAbsolute)(r)?(0,s.resolve)(t,r):(0,s.resolve)(r)}async function u(e,t){const r=l(e,t);let o=r;for(;;)try{const e=await(0,n.realpath)(o);return(0,s.resolve)(e,(0,s.relative)(o,r))}catch(e){if("ENOENT"!==(e instanceof Error&&"code"in e?e.code:void 0))return null;const t=(0,s.dirname)(o);if(t===o)return r;o=t}}function d({basePath:e,targetPath:t}){const r=(0,s.resolve)(e),n=(0,s.resolve)(e,t);return r===(0,s.parse)(r).root?(0,s.parse)(n).root===r&&(n===r||n.length>r.length):n===r||n.startsWith(r+s.sep)}function h(e,t){for(const r of t)if(d({basePath:r,targetPath:e}))return!0;return!1}function p(e,t){const r="win32"===process.platform||"darwin"===process.platform,n=r?e.toLowerCase():e,o=r?t.toLowerCase():t;if(n===o)return!0;const i=o.endsWith(s.sep)?o:o+s.sep;return n.startsWith(i)}function f(e){return e.replace(/\\/g,"/")}const m="You cannot search other worktrees for this repository, stay within your workspace paths.";function g(e){const{targetPath:t,workspacePaths:r,mainWorktreePath:n}=e;if(void 0===t)return!1;if(0===r.length)return!1;if(!r.every((e=>function(e){return f(e).includes(".cursor/worktrees")}(e))))return!1;if(h(t,r))return!1;const o=(0,s.isAbsolute)(t)?[(0,s.resolve)(t)]:r.map((e=>(0,s.resolve)(e,t))),i=r.map((e=>function(e){const t=f(e),r=t.indexOf("/.cursor/worktrees/");if(-1===r)return;const n=t.slice(r+19).split("/");if(n.length<2)return;const o=n[0]??"";return 0!==o.length?t.slice(0,r+19+o.length):void 0}(e))).filter((e=>void 0!==e));return!!(i.length>0&&o.some((e=>h(e,i))))||!(void 0===n||!o.some((e=>h(e,[n]))))}},"../utils/dist/safe-spawn-cwd.js"(e,t,r){r.d(t,{$Y:()=>U,$f:()=>I,A:()=>P,D1:()=>R,Gq:()=>D,Gw:()=>d,KX:()=>G,KZ:()=>j,N6:()=>w,Vn:()=>H,Zv:()=>m,fK:()=>q,iA:()=>F,kO:()=>A,mM:()=>T,qr:()=>$,wr:()=>V,wz:()=>W,yo:()=>M});var n=r("node:crypto?8af2"),o=r("node:fs"),s=r("node:fs/promises"),i=r("node:os"),a=r("node:path"),c=r("node:stream"),l=r("../utils/dist/promise-extras.js");const u="/cursor/stores",d="cursor-fuse-cwd",h="cursor-fuse-cwd:cd",p=Buffer.from(h);function f(e){return Buffer.from(Buffer.concat(e))}class m{constructor(){this.held=Buffer.alloc(0),this.released=!1,this.seen=0,this.prefix=Buffer.alloc(0)}get bytes(){return this.seen}get stdoutPrefix(){return this.prefix}get diverged(){return this.released}note(e){const t=Buffer.from(e);if(this.seen+=t.length,this.prefix.length<32){const e=Math.min(t.length,32-this.prefix.length);this.prefix=f([this.prefix,t.subarray(0,e)])}if(this.released)return t;const r=f([this.held,t]);if(!(r.length<=p.length&&p.subarray(0,r.length).equals(r)))return this.released=!0,this.held=Buffer.alloc(0),r;this.held=r}takeHeld(){if(0===this.held.length)return void(this.released=!0);const e=this.held;return this.held=Buffer.alloc(0),this.released=!0,e}}function g(e,{quietCd:t=!1,fallbackCd:r=!1}={}){const n=t?" 2>/dev/null":"";return`${r?`cd "$1"${n} || cd "$2"${n}`:`cd "$1"${n}`} || { ${e}; }; shift${r?" 2":""}; exec "$@"`}const w=g(`printf %s '${h}'; exit 79`),y=g("printf '%s\\n' \"The command did not run: the sandbox cannot enter $1. Re-run it with working_directory set to $(pwd) or another directory inside the workspace.\" >&2; exit 1",{quietCd:!0,fallbackCd:!0});let v,b,S=function(){try{return(0,o.readFileSync)("/proc/self/mountinfo","utf8")}catch{return}};function k(e){return e?.readMountinfo??S}function _(e,t){return"/"===t||e===t||e.startsWith(`${t}/`)}function C(e){return"fuse"===e||"fuseblk"===e||e.startsWith("fuse.")}function E(e){return v===e&&void 0!==b||(v=e,b=function(e){const t=[];for(const o of e.split("\n")){if(0===o.length)continue;const e=o.split(" ");if(e.length<10)continue;let s=-1;for(let t=6;t<e.length;t++)if("-"===e[t]){s=t;break}const i=e[4],a=-1===s?void 0:e[s+1];void 0!==i&&void 0!==a&&0!==a.length&&t.push({mountPoint:(n=i,r=n.replace(/\\([0-7]{3})/g,((e,t)=>String.fromCharCode(Number.parseInt(t,8)))),"/"===r?"/":r.replace(/\/+$/,"")),fstype:a})}var r,n;return t}(e)),b}function x(e,t){let r;for(const n of t)_(e,n.mountPoint)&&(void 0===r||n.mountPoint.length>=r.mountPoint.length)&&(r=n);return r}function P(e,t){const r=k(t)();if(void 0===r)return!1;const n=x(a.default.resolve(e),E(r));return void 0!==n&&C(n.fstype)}function I(e){const t=a.default.resolve(e);return t===u||t.startsWith(`${u}/`)}function R(e){const t=e?.processCwd??process.cwd();return"linux"===(e?.platform??process.platform)&&P(t,e)?e?.tmpdir??(0,i.tmpdir)():t}function T(e,t,r,n){const o=n?.platform??process.platform,s=r?.cwd;if("linux"!==o||void 0===s||r?.shell||!P(s,n))return{command:e,args:[...t],options:r,hopped:!1};const i=a.default.resolve(s),c=R({processCwd:n?.processCwd,tmpdir:n?.tmpdir,platform:o,readMountinfo:n?.readMountinfo});return{command:"/bin/sh",args:["-c",w,d,i,e,...t],options:{...r,cwd:c},hopped:!0,hopCwd:i}}function A(e,t,{directory:r,fallbackDirectory:n=r}){return{command:"/bin/sh",args:["-c",y,"cursor-sandbox-cwd",r,n,e,...t]}}function $(e=process.env){return"1"===e.CURSOR_SPAWN_CWD_HOP}const M="exec_daemon.spawn.cwd_hop",D="exec_daemon.spawn.cwd_hop_cd_failed";function O(e){return(0,n.createHash)("sha256").update(e,"utf8").digest("hex").slice(0,12)}function F(e){return{cwdKind:I(e)?"agent_store_fuse":"fuse",cwdHash:O(e)}}function N(e){return e.isDirectory()?"dir":e.isSymbolicLink()?"symlink":e.isFile()?"file":"other"}async function L(e,t,r){if(void 0===t)return"unchecked";if(t.some((t=>t.mountPoint===e)))return"mount_point";if(t.some((t=>C(t.fstype)&&_(e,t.mountPoint))))return"unchecked";const{root:n}=a.default.parse(e),o=e.slice(n.length).split(a.default.sep);let s=n;for(const[e,n]of o.entries()){s=a.default.join(s,n);const i=e===o.length-1;if(!i&&t.some((e=>e.mountPoint===s)))continue;let c;try{c=await(0,l.wj)(r(s),250)}catch(e){if(e instanceof l.MU)return"unchecked";const t="object"==typeof e&&null!==e&&"code"in e?e.code:void 0;return"ENOENT"===t||"ENOTDIR"===t?"missing":"unreadable"}if(i)return N(c);if(c.isSymbolicLink())return"symlink_ancestor"}return"unchecked"}async function j(e,t){const r=a.default.resolve(e),n=t?.lstat??s.lstat,o=k(t)(),i=void 0===o?void 0:E(o),c=new Map,l=e=>{let t=c.get(e);return void 0===t&&(t=n(e),c.set(e,t)),t},[u,d]=await Promise.all([L(r,i,l),L(a.default.dirname(r),i,l)]),h=void 0===i?void 0:x(r,i);return{cwdHash:O(r),cwdType:u,parentType:d,mountFsType:void 0===h?void 0:(p=h.fstype,"fuse.agent-store"===p?p:C(p)?"fuse_other":"overlay"===p||"ext4"===p||"tmpfs"===p?p:"other")};var p}function U(e,t=process.env){return $(t)&&void 0!==e&&P(e)}function B(e){return`working directory is not accessible: ${a.default.resolve(e)}`}function W(e){return U(e.cwd,e.env)&&79===e.exitCode&&18===e.stdoutBytes&&("string"==typeof(t=e.stdoutPrefix)?t===h:Buffer.from(t).equals(Buffer.from(h)));var t}function H(e){const t=new Error(B(e));return t.code="ENOENT",t}function q(e,t){return e instanceof Error&&"ENOENT"===e.code&&e.message===B(t)}function z(e){return"object"==typeof e&&null!==e&&"emit"in e&&"function"==typeof e.emit&&"on"in e&&"function"==typeof e.on&&"stdout"in e&&"stdin"in e}function G(e,t){if(function(e,t){if("object"!=typeof e||null===e||!("status"in e))return!1;const r=e.status,n="stdout"in e?e.stdout:void 0,o={status:"number"==typeof r||null===r?r:void 0,stdout:"string"==typeof n||n instanceof Uint8Array||null===n?n:void 0},s=function(e){if(null==e.stdout)return{bytes:0,prefix:Buffer.alloc(0)};const t="string"==typeof e.stdout?Buffer.from(e.stdout):f([e.stdout]);return{bytes:t.length,prefix:t.subarray(0,32)}}(o);return W({exitCode:"number"==typeof o.status?o.status:null,stdoutBytes:s.bytes,stdoutPrefix:s.prefix,cwd:t})}(e,t))throw H(t);throw e}function V(e,t){if(z(e))return function(e,t){const r=new m,n=new c.PassThrough;let o,s=!1;const i=e.stdout,a=e.emit.bind(e),l=e=>{if(e)r.takeHeld();else{const e=r.takeHeld();void 0===e||n.writableEnded||n.write(e)}n.writableEnded||n.end()},u=e=>{const t=e?.[0];return null===t||"number"==typeof t?t:null},d=e=>W({exitCode:u(e),stdoutBytes:r.bytes,stdoutPrefix:r.stdoutPrefix,cwd:t}),h=()=>(s=!0,l(!0),a("error",H(t))),p=()=>{void 0!==o&&79===u(o)&&(a("exit",...o),o=void 0)};i&&(i.on("data",(e=>{if(s)return;const t=r.note(e);if(void 0!==t)return n.write(t),void p();d(o)&&h()})),i.on("error",(e=>{n.destroy(e)})),Object.defineProperty(e,"stdout",{configurable:!0,enumerable:!0,get:()=>n})),e.emit=(e,...t)=>s?"exit"!==e&&"close"!==e&&a(e,...t):"exit"===e?(o=t,79!==u(t)?a(e,...t):d(t)?h():!(!r.diverged&&null!=i)&&(o=void 0,a(e,...t))):"close"===e?d(t)||d(o)?h():(l(!1),p(),a(e,...t)):a(e,...t)}(e,t),e;if("object"==typeof(r=e)&&null!==r&&!z(r)&&"onData"in r&&"function"==typeof r.onData&&"onExit"in r&&"function"==typeof r.onExit)return function(e,t){const r=new m,n=[],o=e.onData.bind(e),s=e.onExit.bind(e);e.onData=e=>(n.push(e),o((t=>{const n="string"==typeof t?Buffer.from(t):t,o=r.note(n);void 0!==o&&e("string"==typeof t?o.toString("utf8"):o)}))),e.onExit=e=>s((o=>{const s=r.takeHeld();if(W({exitCode:o.exitCode,stdoutBytes:r.bytes,stdoutPrefix:r.stdoutPrefix,cwd:t}))e(o);else{if(void 0!==s)for(const e of n)e(s);e(o)}}))}(e,t),e;var r;if(function(e){return"object"==typeof e&&null!==e&&"then"in e&&"function"==typeof e.then}(e)){const r=e.then((e=>e),(e=>G(e,t)));return r}return e}},"../utils/dist/test-resets.js"(e,t,r){r.d(t,{J:()=>o});const n="undefined"==typeof process||void 0===process.env.VITEST?void 0:globalThis.__cursorTestResets??=new Set;function o(e){n?.add(e)}},"../utils/dist/workload-spawn.js"(e,t,r){r.d(t,{D9:()=>u});var n=r("node:fs");function o(e){if(!("linux"!==process.platform||void 0===e||e<=0))try{(0,n.writeFileSync)(`/proc/${e}/oom_score_adj`,"0")}catch{}}var s=r("../utils/dist/safe-spawn-cwd.js");const i=/^\/sys\/fs\/cgroup\/[A-Za-z0-9_/.-]+$/,a=Object.freeze({kind:"direct"});function c({workloadCgroupDir:e,hopCwd:t}){const r=`echo $$ 2>/dev/null > '${e}/cgroup.procs'; echo 0 2>/dev/null > /proc/$$/oom_score_adj; `;return void 0!==t?r+s.N6:`${r}exec "$0" "$@"`}function l(e){try{return!!(0,n.statSync)(e).isDirectory()&&((0,n.accessSync)(`${e}/cgroup.procs`,n.constants.W_OK),!0)}catch{return!1}}const u=function(e,t=o){return function(r,n,o,...i){const a=i[0],l=(0,s.qr)()&&null!==(u=a)&&"object"==typeof u&&!Array.isArray(u)?(0,s.mM)(n,o,a):void 0;var u;let d,h=n,p=[...o],f=i;!0===l?.hopped&&void 0!==l.hopCwd?(f=function(e,t){return[t,...e.slice(1)]}(i,l.options),"armed"===e.kind?(h="/bin/sh",p=["-c",c({workloadCgroupDir:e.workloadCgroupDir,hopCwd:l.hopCwd}),s.Gw,l.hopCwd,n,...o]):(h=l.command,p=l.args)):"armed"===e.kind&&(h=e.executable,p=[...e.argumentPrefix,n,...o]);try{d=r(h,p,...f)}catch(e){throw!0===l?.hopped&&void 0!==l.hopCwd&&(0,s.KX)(e,l.hopCwd),e}return function(e,t){"object"==typeof e&&null!==e&&"pid"in e&&"number"==typeof e.pid?t(e.pid):"object"==typeof e&&null!==e&&"child"in e&&"object"==typeof e.child&&null!==e.child&&"pid"in e.child&&"number"==typeof e.child.pid&&t(e.child.pid)}(d,t),!0===l?.hopped&&void 0!==l.hopCwd?(0,s.wr)(d,l.hopCwd):d}}(function(e,t,r=l){return"linux"===e&&void 0!==t&&i.test(t)&&!t.includes("..")&&r(t)?Object.freeze({kind:"armed",workloadCgroupDir:t,executable:"/bin/sh",argumentPrefix:Object.freeze(["-c",c({workloadCgroupDir:t})])}):a}(process.platform,process.env.CURSOR_WORKLOAD_CGROUP))},"../utils/dist/writable-iterable.js"(e,t,r){r.d(t,{F8:()=>o,Jt:()=>s,W2:()=>n});class n extends Error{constructor(e){super(e),this.name="WriteIterableClosedError"}}class o{constructor(e,t){this.writable=e,this.map=t,this.closed=!1}async write(e){if(this.closed)throw new n("WritableIterable is closed");const t=this.map(e);await this.writable.write(t)}close(){this.closed||(this.closed=!0)}}function s(){const e=[];let t,r,o,s,i=!1;function a(n,o){i=!0,void 0!==o&&(s=o),c(o);let a=t;for(t=void 0,r=void 0;void 0!==a;){const e=a.next;a.reject(o??n),a=e}for(;e.length>0;){const t=e.shift();void 0!==o?t.reject(o):t.resolve({done:!0,value:void 0})}}function c(e){const t=o;void 0!==t&&(o=void 0,void 0!==e?t.reject(e):t.resolve())}return{write(a){if(i)return Promise.reject(s??new n("WritableIterable is closed"));const c=e.shift();return void 0!==c?(c.resolve({done:!1,value:a}),e.length>0?Promise.resolve():new Promise(((e,t)=>{o={value:a,resolve:e,reject:t}}))):new Promise(((e,n)=>{const o={value:a,resolve:e,reject:n};void 0===r?t=o:r.next=o,r=o}))},throw(e){i||a(e,e)},close(){i||a(new n("WritableIterable is closed"))},[Symbol.asyncIterator]:()=>({next(){c();const n=t;return void 0!==n?(t=n.next,n.next=void 0,void 0===t&&(r=void 0),o=n,Promise.resolve({done:!1,value:n.value})):i?void 0!==s?Promise.reject(s):Promise.resolve({done:!0,value:void 0}):new Promise(((t,r)=>{e.push({resolve:t,reject:r})}))},throw:e=>(a(e,e),Promise.resolve({done:!0,value:void 0})),return:()=>(a(new Error("Iterator was closed")),Promise.resolve({done:!0,value:void 0}))})}}}};
|