@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/144.js
ADDED
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
import{createRequire as e}from"node:module";const t=e(import.meta.url);export const __webpack_esm_id__=144;export const __webpack_esm_ids__=[144];export const __webpack_esm_modules__={"./src/agent/local-executor.ts"(e,t,r){r.d(t,{createLocalExecutor:()=>IW});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 R(e){return e instanceof P?"EXEC_BACKEND_UNAVAILABLE":e instanceof Error&&"AgentExecStreamStartTimeoutError"===e.name?"AGENT_EXEC_STREAM_START_TIMEOUT":void 0}class I{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:R(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 Re=(0,l.h)("@anysphere/agent-client:exec-checkpoint-gate"),Ie=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&&Ie.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(Rt.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(It.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+: )/,Rt=/^Proxy \S+ refused to tunnel to \S+: 407\b/,It=/^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(Tn),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(Tn);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"),Rr=new Set(["askQuestionInteractionQuery","switchModeRequestQuery","mcpAuthRequestQuery","connectScmRequestQuery"]);class Ir{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&&Rr.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 I(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,vn=(0,u.Pu)("agent_client.turn.retry",{description:"Turn attempts retried by the turn runner",labelNames:["attempt","reason","loop"]});function bn(e){return e<=1?"1":2===e?"2":e<=5?"3_5":"gt5"}function Sn(e){return!0===e.stall?"stall":!0===e.rateLimit?"rate_limit":e.countAsTransportError?"transport":e.countAsServerError?"server":!0===e.immediate?"speculative":"other"}const kn=new Set(["textDelta","thinkingDelta","thinkingCompleted","partialToolCall","toolCallDelta","toolCallStarted","toolCallCompleted","tokenDelta"]);function _n(e){const{message:t}=e;return("textDelta"!==t.case||void 0===t.value||!("isServerNotice"in t.value)||!0!==t.value.isServerNotice)&&kn.has(t.case??"")}async function Cn(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 En(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 xn(e){const{connectCode:t,connectCodeName:r,...n}=e;return void 0===r?n:{...n,connectCode:r}}async function Pn(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 Cn(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 Cn(u,o,void 0===d?void 0:e=>d({error:a,delayMs:u,waitEnded:e}))};let d,h,p,f,m,g,w=e.state,y=e.action,v=0,b=o,S=0,k=0,_=!1,C=0;const E=()=>{_&&(n.onConnectionStateChange?.({state:"connected"}),_=!1)},x=(e,t)=>()=>{e===v&&("progress"===t?m=!0:g=!0,E())},P=e=>({handleCheckpoint:async(t,n,o)=>{e===v&&(m=!0),await r.handleCheckpoint(t,n,o),e===v&&(d=n,h=o?.resumeEligibility??"eligible",E())},getLatestCheckpoint:()=>r.getLatestCheckpoint()});for(;;){if(t.canceled)throw a.toCancelledError(void 0,b);if(d=void 0,h=void 0,m=!1,g=!1,s.beginAttempt?.({attempt:v,originalRequestId:c}),v>0?(b=(0,ge.C)(),await(n.onRetryStarting?.(v,{actionCase:y.action.case,conversationState:w,isResume:"resumeAction"===y.action.case,attemptRequestId:b})),e.logging&&gn.info(t,`[${e.logging.tag}] Retrying attempt ${v}`,{attempt:v,actionCase:y.action.case,requestId:b,originalRequestId:c}),"resumeAction"===y.action.case&&(await(n.onRetryResuming?.({checkpointState:w,nextAttempt:v,reason:"resume_action"})),e.logging&&gn.info(t,`[${e.logging.tag}] Resuming from checkpoint`,{nextAttempt:v,reason:"resume_action"}))):(e.logging&&gn.info(t,`[${e.logging.tag}] Initial request`,{attempt:v,actionCase:y.action.case,requestId:b}),!0===e.notifyInitialResume&&"resumeAction"===y.action.case&&(await(n.onRetryResuming?.({checkpointState:w,nextAttempt:v,reason:"resume_action"})),e.logging&&gn.info(t,`[${e.logging.tag}] Resuming from checkpoint`,{nextAttempt:v,reason:"resume_action"}))),t.canceled)throw a.toCancelledError(void 0,b);try{return await s.runAttempt({state:w,action:y,checkpointHandler:P(v),attempt:v,attemptRequestId:b,notifyConnected:E,notifyApplicationProgress:x(v,"progress"),notifyApplicationActivity:x(v,"activity")}),E(),void(e.logging&&gn.info(t,`[${e.logging.tag}] Request successful`,{attempt:v,actionCase:y.action.case,requestId:b,originalRequestId:c}))}catch(r){if(!0===a.shortCircuit?.(r))throw a.toCancelledError(r,b);const o=!0===n.endlessRetries?.(),E=e.nowMs?.()??Date.now();(m||g)&&(p=void 0,f=void 0);const x=void 0===p?void 0:E-p,P=void 0===f?void 0:E-f;let T=s.classify(r,{attempt:v,attemptRequestId:b,originalRequestId:c,serverErrorRetries:S,transportErrorRetries:k,stallRetryElapsedMs:x,rateLimitRetryElapsedMs:P,endlessRetries:o});if("retry"===T.action){const n=!("resumeAction"===y.action.case&&w.pendingToolCalls.length>0)&&("resumeAction"===y.action.case||!0===e.noProgressGuardCountsReplays&&v>0);void 0!==d?C=0:n&&m&&(C++,C>=2&&(e.logging&&gn.warn(t,`[${e.logging.tag}] Resume attempts are streaming but not producing checkpoints; stopping automatic resume`,{noProgressResumeFailures:C,attempt:v,requestId:b,originalRequestId:c,errorName:r instanceof Error?r.name:typeof r}),T={action:"throw",error:new qe("Agent turn stopped after repeated resume attempts made no progress",{cause:r instanceof Error?r:void 0,requestId:b,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:T.transportFailureKind}))}const A={...void 0===T.transportFailureKind?{}:{transportFailureKind:T.transportFailureKind},...void 0===e.loop?{}:{loop:e.loop}},$=e.logging?.diagnostics?.(r);if(e.logging){const e="retry"===T.action?`RETRY (countAsServerError=${T.countAsServerError}, countAsTransportError=${T.countAsTransportError})`:`THROW ${T.error.kind}`;gn.warn(t,`[AGENT_ERROR_DIAGNOSTICS] requestId=${b} originalRequestId=${c} decision=${e}`,{decision:e,willRetry:"retry"===T.action,enableAgentRetries:n.enableAgentRetries??!1,endlessRetries:o,isRunningInTest:n.isRunningInTest??!1,serverErrorRetries:S,transportErrorRetries:k,attempt:v,requestId:b,originalRequestId:c,...A,...$})}if("throw"===T.action){if(0===v){const r={attempt:0,actionCase:y.action.case,error:T.error,requestId:b,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:b,originalRequestId:c})}}throw e.logging&&gn.warn(t,`[${e.logging.tag}] Error not retryable`,{...A,...$,attempt:v,actionCase:y.action.case,requestId:b,originalRequestId:c,errorName:T.error.name,...!0===e.logging.includeErrorObjects?{error:T.error}:{},serverErrorRetries:S,transportErrorRetries:k}),T.error}const M=v+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!==T.immediate&&(n.onConnectionStateChange?.({state:"reconnecting",attempt:M,trigger:{...A,...s.reconnectTrigger?.(r,T,{originalRequestId:c,failedAttemptRequestId:b,nextAttempt:M})??{originatingRequestId:c,attemptRequestId:b}}}),_=!0),T.countAsServerError&&S++,T.countAsTransportError&&k++,!0===T.stall?p??=E:p=void 0,!0===T.rateLimit?f??=E:f=void 0,v=M;try{vn.increment(t,1,{attempt:bn(M),reason:Sn(T),loop:e.loop??"nal"})}catch{}void 0!==d&&(I=d,En((R=w).turns,I.turns)&&En(R.rootPromptMessagesJson,I.rootPromptMessagesJson)||(l=wn),w=d,y=new i.QFf({action:{case:"resumeAction",value:new i.qKo}})),s.onRetryCommitted?.(),!0===T.immediate||!0===T.noBackoff&&void 0===T.retryAfterMs||await u(v,t.signal,o,T,r)}}var R,I}var Rn=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},In=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 Tn=(0,y.cF)(Symbol("agentStreamMetadata"),void 0),An=(0,l.h)("@anysphere/agent-client:abort"),$n=(0,l.h)("@anysphere/agent-client:retry"),Mn=(0,l.h)("@anysphere/agent-client:request-context-blob");async function Dn({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,Mn.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 On=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 Fn(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 Nn(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 Ln(e){return e instanceof Error?e.name:void 0}class jn{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:Ln(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=Ln(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 R={networkPhaseStartedAt:performance.now()};try{d.onNetworkPhaseStart?.()}catch(t){$n.warn(e,"onNetworkPhaseStart callback failed",{error:String(t)})}const I=Rn(h,(0,$.VI)(e.withName("networkPhase")),!1);e=I.ctx,await(0,$.MG)(I.span,(()=>Pn({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,...xn(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,notifyApplicationActivity:d})=>{const h=function(e,t,r){return{sendUpdate:async(n,o)=>{if(t===r())return e.sendUpdate(n,o);"toolCallCompleted"===o.message?.case&&$n.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,h,y,b,a,o,u,v,i,S,k,C,c,l,d,s,R)},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{In(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 C={stack:[],error:void 0,hasError:!1};try{const P=e;e=this.options.prepareAttemptContext?.(e,{attempt:S,attemptRequestId:f,originalRequestId:m,runOptions:p})??e;const R=Rn(C,(0,$.VI)(e.withName(_)),!1);R.span.setAttribute("agent.attempt",S),R.span.setAttribute("agent.request_id",f),R.span.setAttribute("agent.original_request_id",m),e=R.ctx,e=(0,$.Mf)(e,"agent.request_id",f),e=(e=(0,$.Mf)(e,"agent.original_request_id",m)).with(Tn,{requestId:f,rootParentRequestId:p.rootParentRequestId,modelDetails:n});const I=new Set(w.sources);let T=void 0!==w.abortReasonName||void 0!==w.abortReasonMessage;const M=(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);T||void 0===n||(T=!0,w.abortReasonName=n.abortReasonName,w.abortReasonMessage=n.abortReasonMessage),An.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;M("ctx_signal_abort",ue(t))}else e.signal.addEventListener("abort",(()=>{const t=e.signal.reason;M("ctx_signal_abort",ue(t))}),{once:!0});const[D,O]=e.withCancel();if(c.signal?.aborted){const e=c.signal?.reason;M("conversation_action_abort",ue(e)),O()}else c.signal?.addEventListener("abort",(()=>{const e=c.signal?.reason;M("conversation_action_abort",ue(e)),O()}),{once:!0});if(e.canceled||D.canceled){const t={ctxCanceled:e.canceled,softCancel:D.canceled};throw M("pre_run_cancel",t),new Ke("User aborted request")}const F=(0,$.VI)(e.withName("createControlledExecManager")),N=A.fromResources(s);F[Symbol.dispose]();const[L,j]=e.withCancel(),U=new Gt,{failThresholdMs:B,advisoryThresholdMs:W}=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 H;const q=Rn(C,new Vt(L,{thresholdMs:B,advisoryThresholdMs:W,loop:this.options.loop,transportMode:()=>H,onStall:e=>{M("stall_detector",{thresholdMs:B,advisoryThresholdMs:W}),j(e)},onStallCallback:p.onStall,handlerTracker:U}),!1);let z,G,V;const K=(0,ve.Jt)(),J=new h.F8(K,(e=>(q.reset("outbound_write",On(e)),e))),Z=Rn(C,(0,$.VI)(e.withName("writeInitialRequest")),!1);let X;const Q=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),Y=p.requestContextBlobTransportMode??"legacy",te=0===S&&"userMessageAction"===r.action.case&&0===t.turns.length,re="ref_only"===Y&&te?"dual":Y,[,ne]=await Promise.all([Dn({ctx:e,action:r,resources:s,blobStore:a,options:p,source:"run_request",transportMode:re,notifyBytes:0===S}),void 0===p.mintLlmGatewayCredential?Promise.resolve(void 0):Tr(p.mintLlmGatewayCredential,{signal:D.signal,isCanceled:()=>D.canceled,requestId:f})]),oe={action:r,headers:p.headers??{}},se=this.options.decorateAttempt?.(oe,p)??oe,ie=new i.Mpn({conversationState:t,action:se.action,modelDetails:n,requestedModel:p.requestedModel,clientLlmGatewayCredential:ne,mcpTools:Q,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(X=J.write(new de.KS({message:{case:"runRequest",value:ie}})),D.canceled){const t={ctxCanceled:e.canceled,softCancel:D.canceled};throw M("post_write_cancel",t),Z[Symbol.dispose](),new Ke("User aborted request")}const ae={...se.headers,"x-request-id":f,"x-original-request-id":m,...Me(p),...Oe()};z=(0,$.VI)(e.withName("handshakeEstablishment")),z.span.setAttribute("handshake.firstStreamOnClient",!this.hasStartedStream),this.hasStartedStream=!0;const ce=function(e){return e?.get(mn)}(e)?.startTransportRun(),pe=void 0===ce?z.ctx:function(e,t){return e.with(mn,t)}(z.ctx,ce),fe=0===S&&void 0!==p.onTtftBreakdown?k?.networkPhaseStartedAt:void 0;let ge;const ye=void 0===ce&&void 0===fe?K:(E=K,x=()=>{ge=performance.now(),ce?.markFirstRequestSent(ge)},{[Symbol.asyncIterator](){const e=E[Symbol.asyncIterator]();let t=!1;const r={next:()=>(t||(t=!0,x()),e.next())};return void 0!==e.return&&(r.return=t=>e.return(t)),void 0!==e.throw&&(r.throw=t=>e.throw(t)),r}}),be=this.client.run(pe,ye,{signal:L.signal,headers:ae,onHeader:e=>{H=e.get("x-cursor-agent-transport-mode")??void 0,p.onHeader?.(e)},onNetworkStarted:()=>{void 0===G&&(G=performance.now(),0===S&&(V=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)}}()))}}),ke=performance.now();let Ce;const xe=t=>{z&&(z.span.setAttribute("handshake.firstMessageHeartbeat",t),void 0!==G&&z.span.setAttribute("handshake.preNetworkMs",G-ke),z[Symbol.dispose](),z=void 0),y();const r=performance.now();Ce=r,p.onFirstMessage?.(r-ke),void 0!==G&&(p.onFirstMessageNetwork?.(r-G),void 0!==V&&(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:H,firstMessageNetworkMs:r-G,reading:V.stop()}),V=void 0))},Pe=()=>{b(),p.onFirstNonHeartbeatResponse?.(performance.now()-ke,S)},Ie=p.onTtftBreakdown?e=>{const t=performance.now(),r=void 0===fe||void 0===ge||"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:fe,transportRunCalledAt:ke,firstRequestTakenAt:ge,firstMessageAt:Ce??t,firstOutputAt:t,firstOutputAtEpochMs:Date.now()});p.onTtftBreakdown(void 0===r?e:{...e,transit:r},S)}:void 0,$e=!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){Re.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&&Re.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){Re.debug(e,"Held a tool call's exec for the checkpoint that names it",{toolCallId:t});try{n.onHeld?.(t)}catch(t){Re.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&&Re.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,be,{action:se.action,state:t},void 0===this.options.onExecHeldForCheckpoint?{}:{onHeld:this.options.onExecHeldForCheckpoint}):be,De=!0===this.options.execAfterCheckpointStored||!0===this.options.execCheckpointGate?new _e(void 0===this.options.onExecHeldForCheckpointStore?{}:{onExecHeld:this.options.onExecHeldForCheckpointStore}):void 0,{interactionStream:Fe,execStream:Ne,checkpointStream:Le,kvStream:je,done:Ue}=function(e,t,r,n,o,s,i,a,c,l){const u=(0,ve.Jt)(),d=(0,ve.Jt)(),h=(0,ve.Jt)(),p=(0,ve.Jt)();let f=!1,m=!1,g=!1;return{interactionStream:u,execStream:d,checkpointStream:h,kvStream:p,done:async function(){let w,y,v=!1,b=!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){$n.warn(e,"onTtftBreakdown callback failed",{error:String(t)})}}const t="interactionUpdate"===o.message.case&&"heartbeat"===o.message.value.message.case;if(f||(f=!0,n(t)),t)r.onServerSentHeartbeat(),r.reset("inbound_message","heartbeat");else{if(!m){m=!0;try{i?.()}catch(t){$n.warn(e,"onFirstNonHeartbeatMessage callback failed",{error:String(t)})}}if(!g&&"interactionUpdate"===o.message.case&&_n(o.message.value)){g=!0;try{l?.()}catch(t){$n.warn(e,"onFirstModelOutput callback failed",{error:String(t)})}}r.reset("inbound_message",On(o))}if("interactionUpdate"===o.message.case&&"turnEnded"===o.message.value.message.case&&(v=!0),"interactionUpdate"!==o.message.case&&"interactionQuery"!==o.message.case||await u.write(o.message).catch((()=>{})),"execServerMessage"!==o.message.case&&"execServerControlMessage"!==o.message.case||await d.write(o.message.value),"conversationCheckpointUpdate"===o.message.case){const e=v?"ineligible_terminal_turn":"eligible";"ineligible_terminal_turn"===e&&(b=!0);const t=c?.noteRouted(o.message.value);try{await h.write({checkpoint:o.message.value,metadata:{resumeEligibility:e},...void 0===t?{}:{onSettled:t}})}catch(e){throw t?.(),e}}"kvServerMessage"===o.message.case&&await p.write(o.message.value)}r.onStreamEnded()}catch(e){w=e}finally{if(y=w,v&&b&&void 0!==w&&!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)}(w)&&($n.debug(e,"Ignoring transport close after terminal agent stream",{caughtError:w instanceof Error?`${w.name}: ${w.message}`:String(w)}),r.onStreamEnded(),y=void 0),v||o?.aborted||s?.aborted){if(!v&&!o?.aborted){const t=`Stream ended without turnEnded, abort signals: signal.aborted=${o?.aborted}, parentSignal.aborted=${s?.aborted}; firstMessageFired=${f}`;$n.warn(e,t)}}else{const t="Stream ended without turnEnded — connection likely dropped mid-stream";void 0===w?($n.warn(e,t),y=new qe(t,{isTransport:!0})):w instanceof Error&&"[aborted] aborted"===w.message?($n.warn(e,`${t}; retrying caught [aborted] aborted error`),y=new qe(t,{cause:w,isTransport:!0})):$n.warn(e,`${t}; caught non-retriable stream error, rethrowing as-is`,{caughtError:Fn(w)})}u.close(),d.close(),h.close(),p.close()}if(void 0!==y)throw y}()}}(e,$e,q,xe,D.signal,e.signal,Pe,Ie,De,v);let Be;const We={handleCheckpoint:async(e,t,r)=>{await l.handleCheckpoint(e,t,r),Be=r?.resumeEligibility??"eligible"},getLatestCheckpoint:()=>l.getLatestCheckpoint()};Z[Symbol.dispose]();const ze=5e3;let Ve;const Je=()=>{Ve=setTimeout((()=>{J.write(new de.KS({message:{case:"clientHeartbeat",value:new de.kA}})).then((()=>q.onClientSentHeartbeat()),(()=>{})),Je()}),ze)},Ze=()=>{void 0!==Ve&&(clearTimeout(Ve),Ve=void 0)};Je();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 Ir(Fe,o,new h.F8(J,(e=>new de.KS({message:{case:"interactionResponse",value:e}}))),q);t={run:async e=>{await Promise.all([U.track("handleShellStream",Nn(e,a,o)),U.track("interactionController",c.run(e))])}}}else{const e=new Ir(Fe,o,new h.F8(J,(e=>new de.KS({message:{case:"interactionResponse",value:e}}))),q);t={run:async t=>{await U.track("interactionController",e.run(t))}}}void 0!==X&&await Promise.race([X,Ue.catch((()=>{}))]);const i=new h.F8(J,(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(Ne,i,N,De),S=new le(je,new h.F8(J,(e=>new de.KS({message:{case:"kvClientMessage",value:e}}))),a,{beforeGetBlob:async(e,t)=>a.persistForRemoteRead(e,t)}),k=new Se(Le,We,e);let _,C;const E={promise:new Promise(((e,t)=>{_=e,C=t})),resolve:_,reject:C};D.canceled?(E.resolve(),Fe.close()):D.signal.addEventListener("abort",(()=>{E.resolve(),Fe.close()}),{once:!0}),l.run(D).then(E.resolve).catch(E.reject);const x=Promise.allSettled([U.track("streamSplitter",Ue.finally((()=>{Ze(),c.close(),i.close()}))),U.track("execHandler",E.promise),t.run(e),U.track("checkpointController",k.run()),U.track("kvHandler",S.run(e)),U.track("conversationActionManager",c.run(e,{write:async t=>{await Dn({ctx:e,action:t,resources:s,blobStore:a,options:p,source:"queued_action"}),await J.write(new de.KS({message:{case:"conversationAction",value:t}}))}}))]);let R,I;const T={promise:new Promise(((e,t)=>{R=e,I=t})),resolve:R,reject:I};x.then(T.resolve).catch(T.reject),e.canceled?T.reject(new Ke("User aborted request")):e.signal.addEventListener("abort",(()=>T.reject(new Ke("User aborted request"))),{once:!0});const A=()=>{e.signal.aborted?j():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:Ue,lingerMs:p.softCancelLingerMs}).then((t=>{$n.info(e,"Soft-cancel transport linger finished",{outcome:t,requestId:f}),j()}))};D.canceled?(A(),T.reject(new Ke("User aborted request"))):D.signal.addEventListener("abort",(()=>{A(),T.reject(new Ke("User aborted request"))}),{once:!0});const $=await T.promise,M=$[0],O=$[1],F=$[3],L=e=>e.reason instanceof Error?`${e.reason.name}: ${e.reason.message}`:String(e.reason);if("rejected"===F.status)throw new Ge("Checkpoint persistence failed",{cause:F.reason instanceof Error?F.reason:void 0,requestId:f,displayInfo:{title:"Checkpoint persistence failed",detail:L(F),isRetryable:!1}});const B="ineligible_terminal_turn"===Be;if(B){const t={..."rejected"===M.status?{streamSplitter:L(M)}:{},..."rejected"===O.status?{execHandler:L(O)}:{}};Object.keys(t).length>0&&$n.debug(e,"Ignoring handler errors after terminal checkpoint",t)}if("rejected"===M.status&&!B)throw M.reason;if("rejected"===O.status&&!B)throw O.reason;D.canceled||await this.processUnprocessedMessages(P,c,We,n,o,s,a,u,p,f,m,g,w,q,y,v,b)}finally{Ze(),V?.stop(),V=void 0,z&&(z[Symbol.dispose](),z=void 0)}}catch(e){C.error=e,C.hasError=!0}finally{In(C)}var E,x}async processUnprocessedMessages(e,t,r,n,o,s,a,c,l,u,d,h,p,f,m,g,w){if(!t.hasUnprocessedMessages())return;const y=t.getUnprocessedUserMessages(),v=r.getLatestCheckpoint();if(!v||0===y.length)return;const b=y[0];t.markMessageAsProcessed(b),t.resetStream(),f[Symbol.dispose]();const S=r.getLatestCheckpoint();try{await this.runInternal(e,v,new i.QFf({action:{case:"userMessageAction",value:new i.Vtf({userMessage:b})}}),n,o,s,a,t,r,c,l,u,d,h,p,m,g,w,0,void 0,"agent.request.queuedMessage")}catch(e){throw S===r.getLatestCheckpoint()&&t.requeueMessage(b),e}}}const Un="cursor-ide-browser",Bn="cursor-dev-control",Wn="custom-user-tools",Hn=new Set(["cursor-app-control","cursor-backend-control","cursor-browser-extension",Un,Bn,Wn,"fsd","cursor-subscriptions","cursor-cloud","suggestions","Cursor Slack Tools","Cursor Automation Tools"]);function qn(e){return!Hn.has(e)}const zn=new Set([Bn,Un]);function Gn(e){if(void 0!==e&&0!==Object.keys(e).length)try{return JSON.stringify(e)}catch{return}}function Vn(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 Kn;function Jn(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"}(Kn||(Kn={}));const Xn=q("mcp-executor",(e=>new B(e,Z("mcpArgs"),X("mcpResult"))),((e,t)=>{t.register(new I(e,Y("mcpArgs"),Q("mcpResult")))})),Qn=q("list-mcp-resources-executor",(e=>new B(e,Z("listMcpResourcesExecArgs"),X("listMcpResourcesExecResult"))),((e,t)=>{t.register(new I(e,Y("listMcpResourcesExecArgs"),Q("listMcpResourcesExecResult")))})),Yn=q("read-mcp-resource-executor",(e=>new B(e,Z("readMcpResourceExecArgs"),X("readMcpResourceExecResult"))),((e,t)=>{t.register(new I(e,Y("readMcpResourceExecArgs"),Q("readMcpResourceExecResult")))})),eo=q("mcp-state-executor",(e=>new B(e,Z("mcpStateExecArgs"),X("mcpStateExecResult"))),((e,t)=>{t.register(new I(e,Y("mcpStateExecArgs"),Q("mcpStateExecResult")))}));var to=r("../proto/dist/generated/agent/v1/subagent_exec_pb.js");(0,y.cF)(Symbol("pendingSubagentReplay"),void 0);class ro extends Error{constructor(e,t){super(e),this.name="SubagentHostError",this.agentId=t?.agentId,this.cause=t?.cause}}const no=q("subagent-executor",(e=>new B(e,Z("subagentArgs"),X("subagentResult"))),((e,t)=>{t.register(new I(e,Y("subagentArgs"),Q("subagentResult")))})),oo=q("subagent-await-executor",(e=>new B(e,Z("subagentAwaitArgs"),X("subagentAwaitResult"))),((e,t)=>{t.register(new I(e,Y("subagentAwaitArgs"),Q("subagentAwaitResult")))})),so=q("force-background-subagent-executor",(e=>new B(e,Z("forceBackgroundSubagentArgs"),X("forceBackgroundSubagentResult"))),((e,t)=>{t.register(new I(e,Y("forceBackgroundSubagentArgs"),Q("forceBackgroundSubagentResult")))}));var io=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/status.js"),ao=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/span_kind.js");const co=(0,ye.createContextKey)(void 0,{description:"anysphere.callerContext"});function lo(e){return null!==e&&"object"==typeof e&&Symbol.asyncIterator in e}function uo(e){return e instanceof Error?e:new Error(String(e))}function ho(e,t,r){return{[Symbol.asyncIterator](){const n=e[Symbol.asyncIterator]();let o=!1;const s=e=>{o||(o=!0,e?(t?.recordException(uo(e)),t?.setStatus({code:io.s.ERROR,message:e instanceof Error?e.message:"Stream failed"})):t?.setStatus({code:io.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 po(...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 fo(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:ao.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=po(o,e))}const i=po(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(co,l),g={...c,headers:i,signal:p,contextValues:m},w=s.call(e,a,g);return lo(w)?ho(w,u,d):null!==(h=w)&&"object"==typeof h&&"then"in h&&"function"==typeof h.then?Promise.resolve(w).then((e=>lo(e)?ho(e,u,d):(u?.setStatus({code:io.s.OK}),u?.end(),d?.(),e))).catch((e=>{throw u?.recordException(uo(e)),u?.setStatus({code:io.s.ERROR,message:e instanceof Error?e.message:"RPC call failed"}),u?.end(),d?.(),e})):(u?.setStatus({code:io.s.OK}),u?.end(),d?.(),w)}catch(e){throw u?.recordException(uo(e)),u?.setStatus({code:io.s.ERROR,message:e instanceof Error?e.message:"RPC call failed"}),u?.end(),d?.(),e}var h}}})}var mo=r("node:crypto?8af2"),go=r("../utils/dist/workspace-paths.js");function wo(){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 yo(e){return(0,s.join)(wo(),(0,go.r_)(e))}var vo=r("node:fs/promises"),bo=r("../../node_modules/.pnpm/lru-cache@11.2.5/node_modules/lru-cache/dist/esm/index.js"),So=r("node:fs");const ko="local";function _o(e,t){return`${e}:task_progress:${t}`}function Co(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 Eo(e,t){e.hookApprovalRequirement=void 0!==t?new he.In(t):void 0}function xo(e){return e.hookApprovalRequirement}function Po(e){return e?.kind===he.b.FORCE_PROMPT}function Ro(e){return!(!e.skipApproval||e.smartModeClassifierAllowed&&Po(e.hookApprovalRequirement))}var Io=r("../proto/dist/generated/agent/v1/background_shell_exec_pb.js"),To=r("../shell-exec/dist/api/index.js"),Ao=r("./src/agent/native/tree-sitter.webpack.cjs"),$o=r("./src/agent/native/tree-sitter-bash.webpack.cjs");const Mo=function(e,t=console.warn){let r;return()=>{if(void 0!==r)return r;try{const t=e();t.setLanguage($o),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 Ao)),Do=new Set(["file_redirect","heredoc_redirect","herestring_redirect","heredoc","here_string","redirect","redirection"]),Oo=new Set(["<",">",">>",">|","<>","<&",">&","&>","&>>"]);function Fo(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=>Oo.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)Do.has(r.type)&&h(r,t)})(t),Do.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 No(e){return Fo(Mo(),e)}function Lo(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 jo(e,t){return t>0?t>=e.length?e.length:Math.trunc(t):0}function Uo(e,t){const r=jo(e,t);return Lo(e,r)?r-1:r}function Bo(e,t){const r=jo(e,t);return Lo(e,r)?r+1:r}function Wo(e,t){return t>0?e.length<=t?e:e.slice(0,Uo(e,t)):""}function Ho(e,t){return t>0?e.length<=t?e:e.slice(Bo(e,e.length-Math.trunc(t))):""}let qo,zo;function Go(e,t){qo??=new TextEncoder,zo??=new Uint8Array(65536);let r=0,n=0;for(;r<e.length&&n<t;){const o=Math.min(t-n,zo.length),s=e.slice(r,r+o),i=qo.encodeInto(s,zo.subarray(0,o));if(0===i.read)break;r+=i.read,n+=i.written}return{read:r,written:n}}var Vo=r("../../node_modules/.pnpm/re2js@1.2.2/node_modules/re2js/build/index.esm.js"),Ko=r("../utils/dist/path-utils.js");const Jo="path is empty or only whitespace",Zo=async e=>{const t=(0,Ko.o1)(e);try{return await(0,vo.realpath)(t)}catch{return t}},Xo=1048576,Qo=52428800;var Yo=r("../proto/dist/generated/agent/v1/sandbox_pb.js");function es(e){if(!e)return;let t;return"allow"===e.default?t=Yo.h1.ALLOW:"deny"===e.default&&(t=Yo.h1.DENY),new Yo.RB({version:e.version,defaultAction:t,deny:e.deny??[],allow:e.allow??[],logging:e.logging?(r=e.logging,new Yo.Qq({decisionLogPath:r.decisionLogPath,logFormat:r.logFormat})):void 0});var r}function ts(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 Yo.h1.ALLOW:t.default="allow";break;case Yo.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,To.T6)():(0,To.Po)())}function rs(e){switch(e){case"system":return Yo.Sz.SYSTEM;case"workspace":return Yo.Sz.WORKSPACE;default:return Yo.Sz.UNSPECIFIED}}function ns(e){const t=function(e){switch(e){case Yo.Sz.SYSTEM:return"system";case Yo.Sz.WORKSPACE:return"workspace";case Yo.Sz.UNSPECIFIED:default:return}}(e.readBoundary),r=e.additionalReadPaths??[];return{readBoundary:t,additionalReadPaths:"workspace"===t&&r.length>0?r:void 0,privateTmp:e.privateTmp}}function os(e){if(!e)return{type:"insecure_none"};switch(e.type){case Yo.vc.INSECURE_NONE:case Yo.vc.UNSPECIFIED:return{type:"insecure_none",allowlistEscalated:e.allowlistEscalated,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies};case Yo.vc.WORKSPACE_READWRITE:return{type:"workspace_readwrite",networkPolicy:ts(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,...ns(e)};case Yo.vc.WORKSPACE_READONLY:return{type:"workspace_readonly",networkPolicy:ts(e),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadonlyPaths:e.additionalReadonlyPaths,disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicyStrict:e.networkPolicyStrict,...ns(e)};default:return{type:"insecure_none"}}}function ss(e){if(e)return"insecure_none"===e.type?new Yo.Mw({type:Yo.vc.INSECURE_NONE,allowlistEscalated:e.allowlistEscalated,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies}):"workspace_readwrite"===e.type?new Yo.Mw({type:Yo.vc.WORKSPACE_READWRITE,networkAccess:(0,To.$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:es(e.networkPolicy),networkPolicyStrict:e.networkPolicyStrict,readBoundary:rs(e.readBoundary),additionalReadPaths:"workspace"===e.readBoundary?e.additionalReadPaths??[]:[],privateTmp:e.privateTmp}):"workspace_readonly"===e.type?new Yo.Mw({type:Yo.vc.WORKSPACE_READONLY,networkAccess:(0,To.$b)(e.networkPolicy),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadonlyPaths:e.additionalReadonlyPaths??[],disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicy:es(e.networkPolicy),networkPolicyStrict:e.networkPolicyStrict,readBoundary:rs(e.readBoundary),additionalReadPaths:"workspace"===e.readBoundary?e.additionalReadPaths??[]:[],privateTmp:e.privateTmp}):new Yo.Mw({type:Yo.vc.INSECURE_NONE})}function is(e){return" "===e||"\t"===e||"\n"===e||"\r"===e||" "===e||""===e||""===e||""===e||"\ufeff"===e}function as(e){let t="",r=!1;for(const n of e)is(n)?r=!0:(r&&t.length>0&&(t+=" "),r=!1,t+=n);return t}function cs(e){if(0===e.length)return!1;for(let t=0;t<e.length;t++)if("*"!==e[t])return!1;return!0}function ls(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()}}var us=r("../utils/dist/command-glob.js");function ds({command:e,parsingResult:t}){return[...new Set([e,...t.executableCommands.map((e=>e.fullText))])]}const hs={a:"",b:"\b",e:"",E:"",f:"\f",n:"\n",r:"\r",t:"\t",v:"\v","\\":"\\","'":"'",'"':'"',"?":"?"};function ps(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=hs[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 as(t)}function fs({rule:e,command:t}){const r=as(e).trim();return 0!==r.length&&(null!==function(e){const t=as(e).trim();if(0===t.length)return"Rule cannot be empty";if(t.length>512)return"Rule cannot exceed 512 characters";if(cs(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=ls(t);if(void 0!==r){const{executablePattern:e,argsPattern:t}=r;if(cs(e)&&(0===t.length||cs(t)))return"Rule cannot match every command; narrow the executable or argument pattern"}return null}(r)||[t.trim(),as(t).trim(),ps(t).trim()].some((e=>function(e,t){const r=ls(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((0,us.T)(e,s)&&(0,us.T)(n,i))return!0}return e.includes("*")?(0,us.T)(e,t):t===e||t.startsWith(`${e} `)}(r,e))))}function ms({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=>fs({rule:e,command:t}))))return e}function gs(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 ws({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=ms({matchForms:ds({command:e,parsingResult:t}),blockedCommands:r});return void 0===n?void 0:gs(n)}var ys=r("../utils/dist/test-resets.js");const vs="CURSOR_FORCED_SHELL_EGRESS_NETWORK_DEFAULT",bs="CURSOR_FORCED_SHELL_EGRESS_DEPENDENCY_DENY_DOMAINS",Ss=/\$\(|`|<\(|>\(/,ks=/[;&|]/;let _s,Cs,Es,xs;function Ps(){if(void 0===_s){const e=(process.env.CURSOR_FORCED_SHELL_EGRESS??"").trim().toLowerCase();_s=""!==e&&"0"!==e&&"false"!==e&&"off"!==e}return _s}function Rs(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 Is(e){return(process.env[e]??"").split(",").map((e=>e.trim())).filter((e=>e.length>0))}function Ts(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 As(){if(void 0===xs){const e=(process.env[vs]??"").trim().toLowerCase();let t="deny";"allow"===e||"deny"===e?t=e:""!==e&&console.error(`[forced-egress] ignoring invalid value in ${vs} (expected "allow" or "deny"); using "deny".`);const r=Is("CURSOR_FORCED_SHELL_EGRESS_DENY_DOMAINS"),n=(process.env[bs]??"").trim();let o=r;"none"===n.toLowerCase()?o=[]:""!==n&&(o=Is(bs)),xs={networkDefault:t,denyDomains:r,dependencyDenyDomains:o,allowDomains:Is("CURSOR_FORCED_SHELL_EGRESS_ALLOW_DOMAINS"),writablePaths:Ts("CURSOR_FORCED_SHELL_EGRESS_WRITABLE_PATHS")}}return xs}function $s(e,t,r={}){const n=[Rs(e),Rs(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 Ms(e,t){const r=function(){const e=As();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===Cs&&(Cs=$s("CURSOR_FORCED_SHELL_EGRESS_DEPENDENCY_REGEX","CURSOR_FORCED_SHELL_EGRESS_EXTRA_DEPENDENCY_REGEX",{anchorToExecutable:!0})),Cs);if(null===n)return r;const o=t?.executableCommands??[];if(t?.parsingFailed||0===o.length)return r;if(Ss.test(e))return r;const s=(void 0===Es&&(Es=$s("CURSOR_FORCED_SHELL_EGRESS_SOURCE_REGEX","CURSOR_FORCED_SHELL_EGRESS_EXTRA_SOURCE_REGEX")),Es);for(const e of o){const t=e.fullText?.trim()||e.name?.trim()||"";if(!t||s?.test(t)||ks.test(t))return r}return o.every((e=>n.test(e.fullText?.trim()||e.name?.trim()||"")))?function(){const e=As();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,ys.J)((function(){_s=void 0,Cs=void 0,Es=void 0,xs=void 0}));var Ds=r("../utils/dist/lru-cache.js");const Os=["Desktop","Documents","Downloads","Music","Movies","Pictures","Library",".Trash"],Fs="/Volumes";function Ns(e){const t=e.replace(/\/{2,}/g,"/");return t.length>1&&t.endsWith("/")?t.slice(0,-1):t}function Ls(e,t){if("darwin"!==t.platform)return[];const r=Ns(e),n=r.toLowerCase(),o=Ns(t.homeDirectory),s="/"===r?1:r.split("/").length;return[...Os.map((e=>`${o}/${e}`)),Fs].filter((e=>function(e,t){return e!==t&&e.startsWith(t.endsWith("/")?t:`${t}/`)}(e.toLowerCase(),n))).map((e=>{const t=e.split("/").slice(s).join("/");return`${"/"===r?"":r}/${t}`}))}var js=r("../utils/dist/safe-spawn-cwd.js"),Us=r("node:util");const Bs=8388608;var Ws=r("../../node_modules/.pnpm/iconv-lite@0.7.0/node_modules/iconv-lite/lib/index.js"),Hs=r("../../node_modules/.pnpm/jschardet@3.1.4/node_modules/jschardet/index.js");function qs(e){let t=1,r=0;for(;;){const n=e.indexOf("\n",r);if(-1===n)return t;t++,r=n+1}}const zs="utf8",Gs="utf8bom",Vs="latin1",Ks={"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 Js(e){return Ks[e]||e}function Zs(e){return e.startsWith("\ufeff")?e.slice(1):e}function Xs(e){const t=e.toLowerCase();return"latin-1"===t?Vs:"utf-8"===t?zs:"utf-8-bom"===t||"utf-8 bom"===t?Gs:t}function Qs(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 Ys=new Us.TextDecoder("utf-8",{fatal:!1}),ei=new Us.TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),ti="�";function ri(e){return Ys.decode(e)}function ni(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 oi(e,t=1/0){let r=0,n=0;for(;r<t;){const t=e.indexOf(ti,n);if(-1===t)break;r++,n=t+1}return r}function si(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 ii(e){return e<128?1:e<2048?2:e<65536?3:4}var ai;!function(e){e.CRLF="CRLF",e.LF="LF"}(ai||(ai={}));const ci=[".mp4",".webm",".mov",".avi",".mkv",".wmv",".flv",".m4v"],li=new Set(ci),ui=new Us.TextDecoder("utf-8",{fatal:!0}),di=new Us.TextDecoder("latin1"),hi=Buffer.from([239,187,191]),pi={utf16le:Buffer.from([255,254]),utf16be:Buffer.from([254,255]),utf32le:Buffer.from([255,254,0,0]),utf32be:Buffer.from([0,0,254,255])},fi=8192,mi="UTF-8",gi="windows-1252",wi=/[^\u0000-\u007f\ufffd]/u,yi=/(?:\p{Script=Cyrillic}\p{M}*){3,}/gu,vi=/(?:\p{Script=Greek}\p{M}*){3,}/gu,bi=/(?:\p{Script=Hebrew}\p{M}*){3,}/gu,Si=new Map([["windows-1251",yi],["ISO-8859-5",yi],["KOI8-R",yi],["x-mac-cyrillic",yi],["IBM866",yi],["IBM855",yi],["ISO-8859-7",vi],["windows-1253",vi],["windows-1255",bi],["ISO-8859-8",bi],["TIS-620",/(?:\p{Script=Thai}\p{M}*){3,}/gu]]),ki=/\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,_i=/[\p{L}\p{M}]+/gu,Ci=String.raw`[\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u00FF\u0152\u0153\u0160\u0161\u017D\u017E\u0178]`,Ei=new RegExp(`[A-Za-z]${Ci}{1,2}(?!${Ci})|^${Ci}{1,2}[A-Za-z]`,"u"),xi=new Map,Pi=new Set([".png",".jpg",".jpeg",".gif",".webp",".ico",".bmp",".pdf",".zip",".tar",".gz",".exe",".dll",".so",".dylib",".bin",...ci]),Ri=/\.(png|jpg|jpeg|gif|webp|ico|bmp)$/i,Ii=new Set([".ps1",".psm1",".psd1"]),Ti=/[^\u0000-\u007f]/u;function Ai(e){const t=e.toLowerCase(),r=t.lastIndexOf(".");return-1===r?"":t.substring(r)}function $i(e){const t=Ai(e);return li.has(t)}function Mi(e){const t=Ai(e);return{encoding:"binary",lineEnding:ai.LF,isBinaryFile:!0,isImageFile:Ri.test(t),isVideoFile:li.has(t)}}async function Di(e,t){return(await Oi(e,t)).text}async function Oi(e,t){const{stamp:r,buf:n}=await async function(e){const t=await(0,vo.open)(e,"r");try{return{stamp:await t.stat(),buf:await t.readFile()}}finally{await t.close()}}(e),o=ji(n);if(o.isBinaryFile)throw new Error("Binary file cannot be decoded as text");const s=Vi(e,r);let i;i=t||s||o.encoding;const{text:a,encoding:c}=Zi(n,i),l=Zs(a),u=c===zs&&Xi(n)?Gs:c;Ki(e,r,u);const d=function(e,t){if(t===Gs)return Xi(e);const r=pi[Js(Xs(t))];return void 0!==r&&e.subarray(0,r.length).equals(r)}(n,u);if(o.lineEnding===ai.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 Fi(e,t){if("binary"===t.encoding)return void Gi(e);let r;try{r=await(0,vo.stat)(e)}catch{return void Gi(e)}r.size===t.buffer.byteLength?Ki(e,r,t.encoding):Gi(e)}async function Ni(e,t,r,o){let s,i;try{s=r?await async function(e,t){try{return await Li(e)}catch{}const r=Ai(e);if(Pi.has(r))return Mi(e);try{return await async function(e){const t=new Map;let r=0;for await(const n of qi(e)){if(r>=100)break;try{const e=await Li(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:zi()}(t)}catch{return zi()}}(e,r):await Li(e)}catch{const t=Ai(e);s=Pi.has(t)?Mi(e):zi()}const a=()=>i??=async function(e){try{const t=await(0,vo.stat)(e);if(!t.isFile()||t.size>Bs)return;return await(0,vo.readFile)(e)}catch{return}}(e),c=Vi(e,await async function(e){try{return await(0,vo.stat)(e)}catch{return}}(e));let l;if(!s.isBinaryFile){let r;o?r=Xs(o):c?r=Xs(c):(r=Xs(s.encoding),r===Gs||Ws.encodingExists(Js(r))||(r=zs),r!==zs&&r!==Gs||(r=await async function(e,t){const r=await t();return void 0===r||(0,n.isUtf8)(r)?e:Ji(r).encoding===Vs?Vs:e}(r,a))),r===zs&&!o&&function(e,t){return"win32"===process.platform&&Ii.has(Ai(e))&&Ti.test(t)&&!t.startsWith("#!")}(e,t)&&(await async function(e){try{return await(0,vo.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=Gs);const i=r===Gs||r===zs&&!o&&await Qi(e,hi),u=pi[Js(r)];i?l=hi:u&&await Qi(e,u)&&(l=u),s={...s,encoding:i?Gs:r}}const u=qs(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=Zs(Zi(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=Qs(t),o=Qs(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===ai.CRLF?"\r\n":"\n"}):s.lineEnding===ai.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?Zs(t):t,p=s.encoding===Gs?zs:s.encoding,f=p===zs?await async function(e,t){if(!t.includes(ti))return;const r=await e();return void 0===r?void 0:function(e,t){if(!e.includes(ti)||(0,n.isUtf8)(t))return;const r=function(e){const t=[];let r=0;for(const n of ei.decode(e)){const o=n.codePointAt(0)??0;if(65533!==o){r+=ii(o);continue}const s=si(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(ti);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(ti,"utf8"));return Buffer.concat(s)}(t,r)}(a,h):void 0,m=f??Ws.encode(h,p,{defaultEncoding:zs});return{lines:u,buffer:l?Buffer.concat([l,m]):m,format:s}}async function Li(e){const t=ji((r=await Hi(e)).length===fi?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:$i(e)}:{...t,isVideoFile:!1}}function ji(e){if(0===e.length)return zi();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:Bi(Ws.decode(e.subarray(0,fi),Js(Xs(t)))),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1};if(!function(e){const t=Math.min(fi,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&&27!==t&&r++}return r/t*100<5}(e))return{encoding:"binary",lineEnding:ai.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:mi,lineEnding:Ui(e),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1};if(!(0,n.isUtf8)(e)&&(o=ri(e),s=e.length,ni(o)||1024*oi(o)<=s&&!wi.test(o)))return{encoding:mi,lineEnding:Ui(e),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1};const i=Hs.detect(e);let a=i.confidence>.7?i.encoding:"utf-8";"ascii"===a&&(a="utf-8");const c=Si.get(a);return void 0!==c&&(a=function(e,t,r){const n=Js(Xs(t));if(!Ws.encodingExists(n))return t;const o=Ws.decode(e,n);return ki.test(o)&&function(e,t,r){const n=t.match(r)?.length??0;let o=0;for(const[t]of Ws.decode(e,gi).matchAll(_i))Ei.test(t)&&o++;return o>n}(e,o,r)?gi:t}(e,a,c)),a!==gi||function(e,t){const r=Js(Xs(t));return!Ws.getDecoder(r).write(e).includes(ti)}(e,a)||(a="utf-8"),{encoding:a??"utf-8",lineEnding:Ui(e),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1}}function Ui(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 Wi(t,r)}function Bi(e){const t=e.match(/\n/g)?.length??0,r=e.match(/\r\n/g)?.length??0;return Wi(r,t-r)}function Wi(e,t){return 0===e&&0===t?ai.LF:e/(e+t)*100>=5?ai.CRLF:ai.LF}async function Hi(e){const t=await(0,vo.open)(e,"r");try{const e=Buffer.allocUnsafe(fi),{bytesRead:r}=await t.read(e,0,fi,0);return e.subarray(0,r)}finally{await t.close()}}async function*qi(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,vo.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*qi(r)):n.isFile()&&(yield r)}}catch(e){return}}function zi(){return{encoding:zs,lineEnding:"win32"===process.platform?ai.CRLF:ai.LF,isBinaryFile:!1,isImageFile:!1,isVideoFile:!1}}function Gi(e){xi.delete(e)}function Vi(e,t){const r=xi.get(e);if(void 0!==r)return void 0!==t&&r.size===t.size&&r.mtimeMs===t.mtimeMs?r.encoding:void xi.delete(e)}function Ki(e,t,r){if(xi.has(e)&&xi.delete(e),xi.set(e,{encoding:r,size:t.size,mtimeMs:t.mtimeMs}),xi.size<=100)return;const n=xi.keys().next().value;void 0!==n&&xi.delete(n)}function Ji(e){try{return{text:ui.decode(e),encoding:zs}}catch{const t=ri(e);return ni(t)?{text:t,encoding:zs}:{text:di.decode(e),encoding:Vs}}}function Zi(e,t){const r=Xs(t);if(r===zs||r===Gs||"ascii"===r){const t=Ji(e);return r===Gs&&t.encoding===zs?{text:t.text,encoding:Gs}:t}if(r===Vs)return{text:di.decode(e),encoding:Vs};try{const t=Js(r);if(Ws.encodingExists(t))return{text:Ws.decode(e,t),encoding:r}}catch{}return Ji(e)}function Xi(e){return e.length>=hi.length&&e[0]===hi[0]&&e[1]===hi[1]&&e[2]===hi[2]}async function Qi(e,t){try{return(await Hi(e)).subarray(0,t.length).equals(t)}catch{return!1}}var Yi=r("../../node_modules/.pnpm/ignore@7.0.5/node_modules/ignore/index.js");class ea{constructor({ttlMs:e,now:t=Date.now}){this.entries=new Map,this.nextSweepAtMs=0,this.ttlMs="function"==typeof e?e:ea.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 ta=r("node:string_decoder");const ra=new Map,na=new Map;let oa;function sa(e){return(0,mo.createHash)("sha256").update(e).digest("hex").slice(0,16)}async function ia(e){try{return await(0,vo.access)(e),!0}catch{return!1}}async function aa(e){const t=await(0,vo.stat)(e),r=ra.get(e);if(void 0!==r&&r.mtimeMs===t.mtimeMs&&r.size===t.size&&(r.ripgrepPath===e||await ia(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=ji(t);return r.isBinaryFile?ri(t):Zs(Zi(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(oa??=(0,vo.mkdtemp)((0,s.join)((0,o.tmpdir)(),"cursorignore-utf8-")).then((e=>(process.once("exit",(()=>{try{(0,So.rmSync)(e,{recursive:!0,force:!0})}catch{}})),e))),oa),n=(0,s.join)(r,`cursorignore-${sa(e)}-${sa(t)}.txt`);if(await ia(n))return n;const i=`${n}.${process.pid}.${Date.now()}.tmp`;return await(0,vo.writeFile)(i,t,"utf8"),await(0,vo.rename)(i,n),n}(e,r)}(e,await(0,vo.readFile)(e));return ra.set(e,{mtimeMs:t.mtimeMs,size:t.size,ripgrepPath:i}),i}function ca(e){return Promise.all(e.map((e=>async function(e){const t=na.get(e);if(void 0!==t)return t;const r=aa(e).catch((()=>e)).finally((()=>{na.delete(e)}));return na.set(e,r),r}(e))))}(0,ys.J)((function(){ra.clear(),na.clear()}));var la=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 ua(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 da(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 ca(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,To.spawnInSandbox)((0,To.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=ua(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 ta.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{la(r)}}(),didTimeout:w}}var ha=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 pa;function fa(e=process.env){if(void 0!==pa)return pa;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 ma({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 ga{constructor(e=()=>fa()){this.cache=new ea({ttlMs:e})}get size(){return this.cache.size}clear(){this.cache.clear()}delete(e){this.cache.delete(ma(e))}walk(e,t){const r=ma(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,ua(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{ha(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=da(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 wa=16777216,ya=new Set([32,9,10,13]),va="a path through /proc or /dev/fd",ba={kind:"none"},Sa={kind:"stop"};function ka(e,t){return{kind:"refused",refused:{name:e,reason:t}}}async function _a(e){const t=await async function(e){if(void 0===await(0,vo.lstat)(e).catch((()=>{})))return ba;if(await xa(Buffer.from(e)))return ka(".git",va);const t=await(0,vo.stat)(e).catch((()=>{}));if(void 0===t)return ba;if(!t.isFile())return Ca(e);const r=await Ta(e,{whole:1048576});if("not-regular"===r.kind)return ka(".git","not a regular file");if("bytes"!==r.kind)return Sa;const n=Buffer.from("gitdir: "),o=Da(r.bytes);if(!o.subarray(0,n.length).equals(n)||o.length<=n.length)return Sa;const i=Ma({dir:(0,s.dirname)(e),target:Oa(o.subarray(n.length))});if(await xa(i))return ka(".git",va);const a=await Ca(i);return"none"===a.kind?Sa:a}($a(e,".git").toString());return"none"!==t.kind?t:Ca(e)}async function Ca(e){const t=await async function(e){const t=await(0,vo.lstat)(e).catch((()=>{}));if(void 0===t||t.isDirectory())return ba;if(t.isSymbolicLink()){const t=await(0,vo.readlink)(e,{encoding:"buffer"}).catch((()=>{}));return"refs/"===t?.subarray(0,5).toString("latin1")?"valid":ba}if(!t.isFile())return ka("HEAD","not a regular file");const r=await Ta(e,{prefix:255});if("not-regular"===r.kind)return ka("HEAD","not a regular file");if("bytes"!==r.kind)return ba;const n=Oa(r.bytes.subarray(0,255)).toString("latin1");if(n.startsWith("ref:")){let e=4;for(;e<n.length&&ya.has(n.charCodeAt(e));)e++;return n.startsWith("refs/",e)?"valid":ba}return/^[0-9a-fA-F]{40}/.test(n)?"valid":ba}($a(e,"HEAD"));if("valid"!==t)return t;let r=e;const n=$a(e,"commondir");if(void 0!==await(0,vo.lstat)(n).catch((()=>{}))){if(await xa(n))return ka("commondir",va);const t=await Ta(n,{whole:wa});switch(t.kind){case"bytes":{if(0===t.bytes.length)return Sa;const n=Ma({dir:e,target:Oa(Da(t.bytes))});if(await xa(n))return ka("commondir",va);const o=await(0,vo.realpath)(n,{encoding:"buffer"}).catch((()=>{}));if(void 0===o)return ba;r=o;break}case"too-large":return ka("commondir","over the size cap");case"not-regular":return ka("commondir","not a regular file");case"directory":case"unreadable":return Sa;default:throw new Error(`unhandled read ${String(t)}`)}}for(const e of["objects","refs"]){const t=$a(r,e);if(await xa(t))return ka(e,va);if(!await Aa(t))return ba}return{kind:"repository",gitDir:e,commonDir:r}}async function Ea({gitDir:e,commonDir:t}){const r=[["HEAD",$a(e,"HEAD")],["config.worktree",$a(e,"config.worktree")],["config",$a(t,"config")],["info/exclude",$a($a(t,"info"),"exclude")]];for(const[e,t]of r){if(await xa(t))return{name:e,reason:va};const r=await(0,vo.stat)(t).catch((()=>{}));if(void 0!==r&&!r.isDirectory()&&!await Ia(r)){if(!r.isFile())return{name:e,reason:"not a regular file"};if(r.size>wa)return{name:e,reason:"over the size cap"}}}}async function xa(e){if("win32"===process.platform)return!1;const t=Pa(e.toString("latin1")).reverse();let r="/",n=0;for(let e=t.pop();void 0!==e;e=t.pop()){if(".."===e){r=(0,s.dirname)(r);continue}const o=(0,s.join)(r,e),i="darwin"===process.platform?o.toLowerCase():o;if(["/proc","/dev/fd"].some((e=>i===e||i.startsWith(`${e}/`))))return!0;const a=await(0,vo.readlink)(Buffer.from(o,"latin1"),{encoding:"buffer"}).catch((()=>{}));if(void 0===a){r=o;continue}if(++n>40)return!1;const c=a.toString("latin1");(0,s.isAbsolute)(c)&&(r="/"),t.push(...Pa(c).reverse())}return!1}function Pa(e){return e.split("/").filter((e=>""!==e&&"."!==e))}let Ra;async function Ia(e){if(!e.isCharacterDevice())return!1;Ra??=(0,vo.stat)("/dev/null").catch((()=>{}));const t=await Ra;return void 0!==t&&e.dev===t.dev&&e.ino===t.ino}async function Ta(e,t){const r=So.constants.O_RDONLY|(So.constants.O_NONBLOCK??0)|(So.constants.O_NOCTTY??0),n=await(0,vo.open)(e,r).catch((()=>{}));if(void 0===n)return{kind:"unreadable"};try{const e=await n.stat();if(e.isDirectory())return{kind:"directory"};if(!e.isFile())return{kind:"not-regular"};if("whole"in t&&e.size>t.whole)return{kind:"too-large"};const r="whole"in t?t.whole:t.prefix,o=Buffer.alloc(Math.min(r+1,e.size+1));let s=0;for(;s<o.length;){const{bytesRead:e}=await n.read(o,s,o.length-s,null);if(0===e)break;s+=e}return"whole"in t&&s>t.whole?{kind:"too-large"}:{kind:"bytes",bytes:o.subarray(0,s)}}catch{return{kind:"unreadable"}}finally{await n.close().catch((()=>{}))}}function Aa(e){return(0,vo.access)(e,So.constants.X_OK).then((()=>!0),(()=>!1))}function $a(e,t){const r=Buffer.isBuffer(e)?e:Buffer.from(e),n=r.toString("latin1").endsWith(s.sep)?"":s.sep;return Buffer.concat([r,Buffer.from(`${n}${t}`)])}function Ma({dir:e,target:t}){return(0,s.isAbsolute)(t.toString("latin1"))?t:Buffer.concat([$a(e,""),t])}function Da(e){let t=e.length;for(;t>0&&(10===e[t-1]||13===e[t-1]);)t--;return e.subarray(0,t)}function Oa(e){const t=e.indexOf(0);return-1===t?e:e.subarray(0,t)}const Fa=[{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 Na(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 La(e,t){const r=Na(t);return r?`${e}${r}`.toLowerCase():""}new Map(Fa.map((e=>[e.gitHost,e.apiHost]))),new Map(Fa.map((e=>[e.gitHost,e.gitCdnHost]))),new Map(Fa.map((e=>[e.gitHost,e.cloneKitS3Host]))),new Map(Fa.map((e=>[e.gitHost,e.rawUserContentHost]))),new Map(Fa.map((e=>[e.apiHost,e.gitHost]))),new Map(Fa.map((e=>[e.apiHost,e.internalHost])));const ja=new Map;function Ua(e){const t=ja.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 La(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 La(n.includes("@")?n.slice(n.lastIndexOf("@")+1):n,o)}}(e);return ja.size>=16384&&ja.clear(),ja.set(e,r),r}function Ba(e){return/^origin(-[a-z0-9]+)?\.cursor\.com$/i.test(e)}(function(e){const t=Fa.find((t=>t.stage===e));if(void 0===t)throw new Error(`unknown Origin stage: ${e}`);return t})("prod").gitHost;const Wa=new Map;function Ha(e){if(void 0===e)return;if(Wa.has(e))return Wa.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||!Ba(t.hostname))return;const r=Na(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 Wa.size>=16384&&Wa.clear(),Wa.set(e,t),t}function qa(e){return void 0!==function(e){const t=Ha(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 za=(0,l.h)("local-exec:git-root"),Ga=new WeakMap,Va=new Map;function Ka(e,t,r){return Ja(e,t,r).then((e=>"repository"===e.kind?e.root:null))}function Ja(e,t,r){const n=performance.now();let o=Ga.get(t);void 0===o&&(o=new Map,Ga.set(t,o));const s=o.get(r);if(void 0!==s&&Za(s,n))return s.result;for(const[e,t]of o)Za(t,n)||o.delete(e);const i=t.guardedRootLookup,a=void 0===i?{result:Ya(e,t,r,void 0),windowStart:n}:{result:Xa(e,t,r,i.timeoutMs),windowStart:void 0};return void 0===a.windowStart&&a.result.then((()=>{a.windowStart=performance.now()})),o.set(r,a),a.result}function Za(e,t){return void 0===e.windowStart||t-e.windowStart<5e3}async function Xa(e,t,r,n){const o=new AbortController,i=performance.now()+n,a=await(0,Dr.wj)(async function({ctx:e,gitExecutor:t,startPath:r,deadline:n,settled:o}){const i=await function(e){let t=Va.get(e);if(void 0===t){t=async function(e){const t=await(0,vo.realpath)(e).catch((()=>{}));if(void 0===t)return;const r=function(){const e=(process.env.GIT_DISCOVERY_ACROSS_FILESYSTEM??"").toLowerCase();return!["","0","false","no","off"].includes(e)}()?void 0:(await(0,vo.stat)(t).catch((()=>{})))?.dev;for(let e=t;;){const t=await _a(e);switch(t.kind){case"refused":return t.refused;case"stop":return;case"repository":return Ea(t);case"none":break;default:throw new Error(`unhandled probe ${String(t)}`)}const n=(0,s.dirname)(e);if(n===e||void 0!==r&&(await(0,vo.stat)(n).catch((()=>{})))?.dev!==r)return;e=n}}(e),Va.set(e,t);const r=()=>{Va.delete(e)};t.then(r,r)}return t}(r);if(o.aborted)return{kind:"unknown",reason:"timed-out"};if(void 0!==i)return za.warn(e,"findGitRoot: not starting git; its answer is unknown",{adminFile:i.name,reason:i.reason}),{kind:"unknown",reason:"refused"};const a=Math.ceil(n-performance.now());return a<=0?{kind:"unknown",reason:"timed-out"}:Ya(e,t,r,a)}({ctx:e,gitExecutor:t,startPath:r,deadline:i,settled:o.signal}),n).catch((t=>t instanceof Dr.MU?{kind:"unknown",reason:"timed-out"}:(za.warn(e,"findGitRoot: the admin file check failed; not starting git",{code:Qa(t)}),{kind:"unknown",reason:"refused"}))).finally((()=>{o.abort()}));return"unknown"===a.kind&&"timed-out"===a.reason&&za.warn(e,"findGitRoot: the lookup ran past its bound; its answer is unknown",{timeoutMs:n}),a}function Qa(e){return"object"==typeof e&&null!==e&&"code"in e&&"string"==typeof e.code?e.code:void 0}async function Ya(e,t,r,n){try{return{kind:"repository",root:(await t.exec(e,r,["rev-parse","--show-toplevel"],{...void 0===n?{}:{timeout:n},caller:"findGitRoot"})).stdout.trim()}}catch(e){return void 0!==n&&function(e){return"object"==typeof e&&null!==e&&"killed"in e&&!0===e.killed}(e)?{kind:"unknown",reason:"timed-out"}:{kind:"none"}}}async function ec(e,t,r){try{return(await t.exec(e,r,["config","--get","remote.origin.url"],{caller:"getGitRemoteUrl"})).stdout.trim()}catch{return}}function tc(e){const t=e.trim();if(""===t)return t;try{const e=new URL(t);return""===e.host?nc(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=rc.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)??nc(t)??t}}const rc=new Set(["ftp","file","http","https","ws","wss"]);function nc(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 oc=["**/node_modules/**","**/.git/**","**/.turbo/**","**/.next/**","**/.cache/**","**/.pnpm/**","**/.yarn/**","**/dist/**","**/build/**","**/out/**","**/target/**","**/.vscode/**","**/.idea/**","**/venv/**","**/__pycache__/**","**/logs/**","**/tmp/**","**/temp/**"];function sc(e,t){return Ls(e,t).map((t=>`/${s.posix.relative(e,t)}`))}var ic=r("../../node_modules/.pnpm/picomatch@4.0.5/node_modules/picomatch/index.js");function ac(e,t){return e.some((e=>{return"*"===e.url.trim()?(e.patterns??[]).some((e=>uc(e.pattern,t))):!((r=e.url).includes("://")||r.includes("github.com")||r.includes("gitlab.com")||r.includes("bitbucket.org")||r.includes("@"))&&uc(e.url,t);var r}))}function cc(e,t,r){return lc(e.url,t)&&(e.patterns??[]).some((e=>uc(e.pattern,r)))}function lc(e,t){return e.includes("*")?"*"===e.trim()||function(e,t){const r=e.trim();return!!uc(r,t)||!!r.startsWith("*/")&&uc(`**/${r.slice(2)}`,t)}(mc(e),mc(t)):mc(e)===mc(t)}function uc(e,t){const r=e.trim();return!("."!==t&&""!==t||"**"!==r&&"**/*"!==r)||function(e){const t=pc.get(e);if(void 0!==t)return t;let r;try{const t=ic(e,{dot:!0});r=r=>{try{return t(r)}catch{return e===r}}}catch{r=t=>e===t}return fc(pc,dc,e,r)}(r)(t)}const dc=2048,hc=new Map,pc=new Map;function fc(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 mc(e){const t=hc.get(e);if(void 0!==t)return t;const r=(function(e){const t=Ha(e);if(void 0!==t)return`${t.hostname}/git/${t.owner}/${t.name}`.toLowerCase()}(n=e)??Ua(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 fc(hc,2048,e,r)}function gc(e){if("object"==typeof e&&null!==e&&"code"in e){const t=e.code;if("string"==typeof t)return t}}function wc(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,ys.J)((function(){hc.clear(),pc.clear()}));const yc=[".gitignore",".cursorignore"];async function vc(e){if(!(0,s.isAbsolute)(e))return null;const t=await(0,Ko.DN)(e);return null===t?null:t}function bc(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 Sc{constructor(e,t,r,n={}){this.disposeRequested=!1,this.initIgnoreService=()=>Cc.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 kc=Math.min(8,Math.max(1,Math.floor(o.default.availableParallelism()/2)));class _c{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=Yi().add(t),this.instances.set(e,r)),r}delete(e){this.instances.delete(e)}clear(){this.instances.clear(),this.lookups=0}}class Cc{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 Ds.q({max:2e3}),this.cursorIgnoreCache=new Ds.q({max:2e3}),this.gitRootCache=new Ds.q({max:1e4}),this.gitRemoteUrlCache=new Ds.q({max:200}),this.hasGitDirCache=new Ds.q({max:1e3}),this.gitParsedIgnoreCache=new _c(1e4),this.cursorParsedIgnoreCache=new _c(1e4),this.ignoreMappingsHaveEntries=!1,this.directoryWalkPlacementCache=new Ds.q({max:1e4}),this.extraRootCursorIgnoreCache=new Ds.q({max:32}),this.extraGitRepoMappingCache=new Ds.q({max:32}),this.unwalkedFolders=o.flatMap((e=>Ls(e,s)))}static getRipwalkCache(){return Cc.ripwalkCache??=new ga,Cc.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,Ko.DN)(e)??(0,Ko.o1)(e)}static async init(e,t,r,n,s={platform:process.platform,homeDirectory:o.default.homedir()}){const i={...s,homeDirectory:await(0,Ko.DN)(s.homeDirectory)??s.homeDirectory},a=await(0,Dr.PH)(r,(async e=>{const t=await(0,Ko.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=>({root:r,lookup:await Ja(e,t,r)}))),d=u.map((({root:e,lookup:t})=>"none"===t.kind?null:"unknown"===t.kind||Ls(t.root,i).length>0?e:t.root)).filter((e=>null!==e)),h=u.filter((({lookup:e})=>"unknown"===e.kind)).map((({root:e})=>(0,Ko.o1)(e)));return d.length>0&&await Promise.all([Cc.initializeIgnoreMapping({rootDirectories:d,ignoreFileName:".gitignore",mapping:c,scanEnvironment:i,unknownRoots:h}),Cc.initializeIgnoreMapping({rootDirectories:a,ignoreFileName:".cursorignore",mapping:l,scanEnvironment:i,unknownRoots:h})]),new Cc(t,c,l,n,a,i)}static async preloadHierarchy(e,t,r,n){let o=(0,Ko.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 Cc.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,vo.access)(n,vo.default.constants.F_OK);const t=await Di(n),o=Cc.parseIgnoreRules(t);r[e]=o}catch(o){"ENOENT"===gc(o)||console.error(`Error reading ${t} file at ${n}:`,o),r[e]=[]}}static async initializeIgnoreMapping({rootDirectories:e,ignoreFileName:t,mapping:r,scanEnvironment:n,unknownRoots:o}){try{const i=Cc.deduplicateRootDirectories(e),a=await Cc.promiseQueue.enqueueList(i,(e=>Cc.findFilesWithRipgrep({rootDirectory:e,fileName:t,scanEnvironment:n,noIgnoreVcs:o.some((t=>(0,Ko.ZU)({basePath:e,targetPath:t})))}))),c=Array.from(a.values()).flat();await Promise.all(c.map((async e=>{try{const t=await Di(e),n=Cc.parseIgnoreRules(t),o=(0,s.dirname)(e);r[o]=n}catch(r){console.error(`Error processing ${t} file at ${e}:`,r)}})));const l=new Set;for(const e of i)await Cc.preloadHierarchy(e,t,r,l)}catch(e){console.error(`Error initializing ignore mapping for ${t}:`,e)}}static async findFilesWithRipgrep({rootDirectory:e,fileName:t,scanEnvironment:r,noIgnoreVcs:n}){const o=(0,y.q6)(),i=[],a={root:e,includeGlobs:yc.map((e=>`**/${e}`)),excludeGlobs:[...oc,...sc(e,r)],noIgnoreVcs:n,source:"ignore_scan"},c=Cc.getRipwalkCache().walk(o,a);for await(const r of c.lines)(0,s.basename)(r)===t&&i.push((0,s.join)(e,r));return i}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=Cc.parseIgnoreRules(await Di((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)=>Yi().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,Ko.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,Ko.ZU)({basePath:t,targetPath:e})))?"walked":"outside",this.directoryWalkPlacementCache.set(e,r),r}async populateHierarchyIfNeeded(e,t,r){let n=(0,s.dirname)((0,Ko.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 Cc.promiseQueue.enqueueList(o,(e=>Cc.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,Ko.ZU)({basePath:n,targetPath:e}))continue;const t=(0,s.relative)(n,e);if(""===t)continue;const i=r(n,o),a=(0,Ko.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,Ko.ZU)({basePath:t,targetPath:e}))continue;const o=(0,s.join)(e,".cursorignore");try{await(0,vo.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,js.$f)(t))continue;const e=await(0,Ko.DN)(t);if(null===e||".git"===(0,s.basename)(e)||this.rootDirectories.some((t=>(0,Ko.ZU)({basePath:t,targetPath:e})))||r.includes(e))continue;const n=await vo.default.stat(e).catch((e=>{if(void 0===gc(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={},o=void 0===this.gitExecutor.guardedRootLookup?void 0:await Ja((0,y.q6)(),this.gitExecutor,e);await Cc.initializeIgnoreMapping({rootDirectories:[e],ignoreFileName:".cursorignore",mapping:t,scanEnvironment:this.scanEnvironment,unknownRoots:"unknown"===o?.kind?[e]:[]}),r={mapping:t,expiresAt:n+fa()},this.extraRootCursorIgnoreCache.set(e,r)}for(const[e,n]of Object.entries(r.mapping))t[e]=bc(t[e],n)}for(const e of[...this.rootDirectories,...r]){const r=await this.getRepoBlockExcludeGlobs(e);0!==r.length&&(t[e]=bc(t[e],r))}return t}async getGitIgnoreMapping(){return{...this.gitIgnoreMapping}}static deduplicateRootDirectories(e){const t=[...e.map((e=>(0,Ko.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 Ds.q({max:1}),this.cursorIgnoreCache=new Ds.q({max:1}),this.gitRootCache=new Ds.q({max:1}),this.gitRemoteUrlCache=new Ds.q({max:1}),this.hasGitDirCache=new Ds.q({max:1}),this.directoryWalkPlacementCache=new Ds.q({max:1}),this.extraRootCursorIgnoreCache=new Ds.q({max:1}),this.extraGitRepoMappingCache=new Ds.q({max:1}),this.gitParsedIgnoreCache.clear(),this.cursorParsedIgnoreCache.clear(),this.gitRepoMappingPromise=void 0}async handleCursorIgnoreCreated(e){const t=(0,s.dirname)(e),r=await Di(e),n=Cc.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 Di(e),n=Cc.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,Ko.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,vo.access)((0,s.join)(e,".git"),vo.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,Ko.ZU)({basePath:await this.getCursorDataDir(),targetPath:e})&&function(e,t){return 0!==e.allowed.length&&!ac(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=>cc(e,o,s))))return!0;e.allowed.length>0&&!n&&(n=!0,r=e.allowed.some((e=>cc(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 ec((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,Ko.ZU)({basePath:r,targetPath:e})&&(void 0===t||r.length>t.length)&&(t=r);return void 0!==t?(0,Ko.oL)((0,s.relative)(t,e)):(0,Ko.oL)(e)}getCursorDataDir(){return this.cursorDataDirPromise??=(async()=>{const e=(0,s.join)(o.default.homedir(),".cursor");return await(0,Ko.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,Ko.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=>lc(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,Ko.o1)(t);try{await(0,vo.access)((0,s.join)(e,".git"),vo.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,vo.access)((0,s.join)(i,".git"),vo.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,...sc(e,this.scanEnvironment)],noIgnoreVcs:!0,source:"ignore_scan"},i=Cc.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 ec(o,this.gitExecutor,e);t.set(e,r)}catch{t.set(e,void 0)}}))),t}}async function Ec(e,t){let r=e;if(Ps()&&(r=Ms(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]=bc(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,To.s9)(r.additionalReadwritePaths,[...n.roots,...n.commonDirs]);return{...r,additionalReadwritePaths:e.length>0?e:void 0,ignoreMapping:o}}return{...r,ignoreMapping:o}}Cc.promiseQueue=new Dr.TJ({max:kc});var xc=r("../proto/dist/generated/agent/v1/mcp_exec_pb.js");const Pc="agent-tools",Rc=51380224;var Ic=r("../proto/dist/generated/agent/v1/utils_pb.js");const Tc=new Us.TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}),Ac=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]]),$c=new Set([194,195,226,239]),Mc=/\p{Lu}/u,Dc=new Set([" ","","«","»","‹","›","‘","’","“","”","•","–","—","…","™"]),Oc=new Set(["¿","¡"]),Fc=new Map([[215,new Set(["¹","²","³","¼","½","¾","°","±","€","¢","£","¤","¥"])],[216,new Set(["¹","²","³","¼","½","¾","°","±","€","¢","£","¤","¥"])],[197,new Set(["¹","²","³"])],[205,Oc],[209,Oc],[211,Oc],[218,Oc],[220,Oc]]),Nc=new Set(["ƒ","Š","Œ","Ž","š","œ","ž","Ÿ"]),Lc=/[\p{Cc}\p{Cn}\p{Cs}\p{Co}]/u;function jc(e){if(void 0===e)return;const t=e.charCodeAt(0);return t>=128&&t<=191?t:Ac.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=jc(e[t+r]);if(void 0===n)return;o[r]=n}const s=e[t+1];if($c.has(r)){if(195===r&&Dc.has(s)&&t>0&&Mc.test(e[t-1]))return}else{if(Dc.has(s))return;if(!0===Fc.get(r)?.has(s))return;if(3===n&&Nc.has(s)&&Dc.has(e[t+2]))return}let i;try{i=Tc.decode(o)}catch{return}return Lc.test(i)?void 0:{index:t,text:e.slice(t,t+n),repaired:i}}function Bc(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 Wc=`[\\u00c2-\\u00f0][\\u0080-\\u00bf${[...Ac.keys()].join("")}]`,Hc=new RegExp(Wc),qc=/\p{L}/u;function zc(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||!Ac.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||!Mc.test(e[t.index-1]))return!0;const n=t.index+t.text.length;return n<e.length&&qc.test(e[n])}const Vc=["mojibake","replacement_chars"];function Kc(e){return e<=1?"1":e<6?"2-5":"6+"}function Jc(e){return e<=0?"0":Kc(e)}function Zc(e,t,r){if(void 0===e)return"new";if(t>0)return"damaged";const n=rl(r);return"utf8"!==n&&"utf8_bom"!==n?"other_encoding":"intact"}function Xc(e,t){return e<=t?"existing_only":"new_damage"}function Qc(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(Bc(t,1).length>0)return!0;t=""}t+=n.repaired,r=n.index+n.text.length}return Bc(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 Yc(e){return{detector:e,outcome:"clean",afterCount:0,beforeCount:0}}function el(e,t,r){const n=Bc(r,1e3);if(0===n.length)return Yc("mojibake");const o=void 0===e?[]:Bc(e,Math.max(n.length,6));return{detector:"mojibake",outcome:Xc(n.length,o.length),file:Zc(e,o.length,t),afterCount:n.length,beforeCount:o.length,pattern:Qc(n,o)}}function tl(e,t,r){const n=oi(r);if(0===n)return Yc("replacement_chars");const o=void 0===e?0:oi(e);return{detector:"replacement_chars",outcome:Xc(n,o),file:Zc(e,o,t),afterCount:n,beforeCount:o}}function rl(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 nl=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 ol(e){const t=(0,s.extname)(e).slice(1).toLowerCase();return""===t?"none":nl.get(t)??"other"}const sl=new Map([[1252,"1252"],[1250,"1250"],[1251,"1251"],[874,"874"],[932,"932"],[936,"936"],[949,"949"],[950,"950"],[65001,"65001"]]);function il(e){if("string"==typeof e)return e;const t=void 0===e.acp?void 0:sl.get(e.acp);return void 0===t?"other":e.oemcp===e.acp?t:`${t}_split`}function al(e,t){if("clean"===e.outcome)return{detector:e.detector,outcome:"clean",file:"unclassified"};const r={outcome:e.outcome,file:e.file,ext:ol(t.path),encoding:rl(t.encoding),code_page:il(t.pages),run_count:Kc(e.afterCount),delta:(n=e.afterCount-e.beforeCount,n<0?"neg":Jc(n)),before_count:Jc(e.beforeCount)};var n;return"mojibake"===e.detector?{detector:"mojibake",pattern:e.pattern,...r}:{detector:"replacement_chars",...r}}class cl{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+oi(t,6-r))}labels(e,t){const r=il(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:Jc(o),branch:e[t],stream:t,code_page:r})}return n}}const ll=/[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/,ul=Object.getOwnPropertyDescriptor(String.prototype,"isWellFormed")?.value;const dl=["replacement","lone_surrogate","mojibake_high","mojibake_medium","utf16","c1","clean"],hl=/\0[^\0]\0/,pl=/[\u0080-\u009f]/,fl=new RegExp(`[\\u0080-\\u009f]|${Wc}`),ml="\\u0000",gl=/\\u(?:[dD][89a-fA-F]|0000)/,wl=/\\u[dD](?:([89abAB])|[c-fC-F])[0-9a-fA-F]{2}/g,yl=/\\u[dD][c-fC-F][0-9a-fA-F]{2}/y;function vl(e,t){let r=0;for(;r<t&&92===e.charCodeAt(t-1-r);)r++;return r%2==0}function bl(e,t){return 92!==e.charCodeAt(t)?1:117===e.charCodeAt(t+1)?6:2}function Sl(e,t={}){const r=n.Buffer.byteLength(e,"utf8")===e.length;if(!r&&e.includes("�"))return"replacement";const o=!0===t.jsonEscaped&&gl.test(e);if(!r&&function(e){return"function"!=typeof ul?function(e){return ll.test(e)}(e):!0!==Reflect.apply(ul,e,[])}(e)||o&&function(e){wl.lastIndex=0;for(let t=wl.exec(e);null!==t;t=wl.exec(e))if(vl(e,t.index)){if(void 0===t[1])return!0;if(yl.lastIndex=t.index+6,!yl.test(e))return!0;wl.lastIndex=t.index+12}return!1}(e))return"lone_surrogate";if(function(e,t){return!(!e.includes("\0")||!hl.test(e))||t&&function(e){for(let t=e.indexOf(ml);-1!==t;t=e.indexOf(ml,t+6)){if(!vl(e,t))continue;const r=t+6;if(!(r>=e.length||e.startsWith(ml,r))&&e.startsWith(ml,r+bl(e,r)))return!0}return!1}(e)}(e,o))return"utf16";if(r)return"clean";if(!fl.test(e))return"clean";const s=function(e){if(!Hc.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?zc(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":pl.test(e)?"c1":"clean"}const kl=/^v?(\d{1,9})\.(\d{1,9})(?:\.\d{1,9})?(?:[-+][0-9A-Za-z.+-]*)?$/,_l=["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}]})),Cl=_l[0].major,El=_l[0].minor;function xl(e){if(null==e)return"unknown";const t=e.trim();if(0===t.length||t.length>128)return"unknown";const r=kl.exec(t);if(null===r)return"unknown";const n=Number(r[1]),o=Number(r[2]);if(n!==Cl)return"other";const s=_l.find((e=>e.minor===o));return void 0!==s?s.bucket:o<El?"older":"newer"}const Pl=(0,l.h)("local-exec:encoding-slices");function Rl(e,t){if(void 0===e)return!1;try{const{enabled:r}=e;return"function"==typeof r?r(t):r}catch{return!1}}function Il(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 Tl(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 Al{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=Tl(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 $l=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"})),Ml=(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"]}),Dl=dl[0],Ol=new Map(dl.map(((e,t)=>[e,t])));function Fl(e){return Ol.get(e)??dl.length}class Nl{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===Dl}noteText(e){if(0===e.length)return;const t=e.length>this.remaining?Wo(e,this.remaining):e;this.remaining-=Math.max(t.length,1);const r=Sl(t);Fl(r)<Fl(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 Ll{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 jl(e,t,r,n){const o={layer:r.layer,kind:n,origin:Il(n,r.evidence??"unseen",!0===r.partial),source:r.source??r.layer,version_bucket:xl(e.clientVersion)};void 0!==r.codePageLookup&&(o.code_page_lookup=r.codePageLookup),void 0!==r.shellKind&&(o.shell_kind=r.shellKind),Ml.increment(t,1,o)}function Ul(e,t){Pl.warn(e,"encoding slice was not counted (result unaffected)",{error:t instanceof Error?t.name:"unknown"})}function Bl(e,t,r,n){if(void 0!==e&&Rl(e,t))try{const o=new Nl;o.note(n),jl(e,t,r,o.kind())}catch(e){Ul(t,e)}}function Wl(e,t,r,n){if(void 0!==e&&Rl(e,t))try{jl(e,t,r,n)}catch(e){Ul(t,e)}}class Hl{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 ql(e,t,r,n){return void 0===t?e:{execute:async(o,s,i)=>{const a=await e.execute(o,s,i);if(Rl(t,o))try{n(a)&&Bl(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 zl{constructor(){this.text={stdout:new Nl,stderr:new Nl},this.bytes={stdout:new Al,stderr:new Al},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":$l.get(e)??"unknown"}(e)}record(e,t,r,n){for(const o of["stdout","stderr"])this.produced[o]&&Wl(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"),Vl=r("../utils/dist/workload-spawn.js");const Kl=(0,l.h)("local-exec:shell-output-encoding"),Jl=(0,Us.promisify)(Gl.execFile),Zl=/^\s*OEMCP\s+REG_\w+\s+(\d+)\s*$/m,Xl=/^\s*ACP\s+REG_\w+\s+(\d+)\s*$/m;function Ql(e,t){const r=t.exec(e);return null===r?void 0:Number(r[1])}const Yl="㐀-䶿一-鿿豈-",eu=" -〿㈀-㏿︰--",tu="‐-※←-⇿─-◿★☆",ru="-ヿ",nu=new Map([["cp932",{script:new RegExp(`[${Yl}${eu}${tu}${ru}]`),doubleByte:!0}],["cp936",{script:new RegExp(`[${Yl}${eu}${tu}${ru}-ㄯ]`),doubleByte:!0}],["cp949",{script:new RegExp(`[${Yl}${eu}${tu}${ru}-가-]`),doubleByte:!0}],["cp950",{script:new RegExp(`[${Yl}${eu}${tu}-ㄯ]`),doubleByte:!0}],["cp874",{script:new RegExp("[-]"),doubleByte:!1}]]);const ou=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,Vl.D9)(Jl,"\\\\.\\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=Ql(t,Zl),o=Ql(t,Xl);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 Ws.encodingExists(t)?t:void 0}(t);return void 0!==n&&nu.has(n)?n:void 0}(i),r=i,s=!0,n=void 0,o=void 0===i.oemcp&&void 0===i.acp?"unparsed":"answered",Kl.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),Kl.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),su=Buffer.alloc(0),iu=/[\u0080-\uffff]/;function au(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 cu(){const e=new ta.StringDecoder("utf8");return{write:t=>e.write(t),end:()=>e.end()}}function lu(e,t){return Ws.decode(t,e,{stripBOM:!1})}const uu=/[\xe0-\xef][\x80-\xbf]\?/;const du=10,hu=Buffer.alloc(0),pu=new Set([7,8,9,10,11,12,13,27]);function fu(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&&!pu.has(r))return!1}return!0}function mu(e,t,r=0,n){if("utf8"===t){const t=e.indexOf(du);return-1===t?-1:t+1}const[o,s]="utf16le"===t?[du,0]:[0,du];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 gu(e){const t=new ta.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 wu={encoding:"utf8",skip:0};function yu(e){const t=e();let r="utf8";const n={};let o=!1;const s=()=>"utf8"===r?t:n[r]??=gu(r),i=e=>("utf8"!==r&&e.length>0&&(o=!0),e);let a,c=!0,l=hu,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?wu:void 0;const r=0===e[0]?"utf16be":0===e[1]?"utf16le":void 0;if(void 0===r)return wu;const n=mu(e,r);if(-1!==n)return fu(e,r,n)?{encoding:r,skip:0}:wu;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)&&fu(e,r,o)?{encoding:r,skip:0}:wu}const o={encoding:r,skip:0},s=e.indexOf(0),i=e.indexOf(du);if(-1!==s&&(-1===i||s<i)){const n=s-s%2+2;return n>e.length?t?o:void 0:fu(e,r,n)?o:wu}if(-1===i)return t?wu:void 0;if("utf16le"===r&&i%2==0){if(i+1>=e.length)return t?wu:void 0;if(0===e[i+1])return o}return wu},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]===du,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=hu}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(du),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]===du&&(l=Buffer.of(du),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=mu(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):gu(t.encoding).write(n)},end(){const e=m(hu,!0)+i(s().end());return c=!0,l=hu,u=!1,d=0,a=void 0,e},branch:()=>!0===t.usedCodePage?.()?"code_page":o?"utf16":"utf8"}}var vu=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},bu=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 Su=(0,l.h)("local-exec:shell-core"),ku=(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"]}),_u="win32"===process.platform,Cu=["CURSOR_CONVERSATION_ID","CURSOR_REQUEST_ID","CURSOR_AGENT_STORE_FILES_DIR","CURSOR_AGENT_STORE_SHARED_PATHS"];function Eu(e){return`'${e.replace(/'/g,"'\\''")}'`}async function xu(e){try{return(await(0,vo.stat)(e)).isDirectory()}catch(e){const t=gc(e);if("ENOENT"===t||"ENOTDIR"===t)return!1;throw e}}const Pu=["eval-cursorbench","cursorbench","sand-eval","eval-harness"];function Ru(e){return Pu.some((t=>e.includes(t)))?(0,mo.createHash)("sha256").update(e).digest("hex"):e}function Iu(e,t){return e[t]??process.env[t]}const Tu=/^[A-Za-z_][A-Za-z0-9_]*$/,Au=/CURSOR_SANDBOX/i;function $u(e){return Tu.test(e)&&!Au.test(e)}function Mu(e){return"function"==typeof e?e():e}function Du(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 Fu extends Error{constructor(e){super(`working directory does not exist: ${e}; the command did not run`),this.name="WorkingDirectoryMissingError"}}class Nu{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{vu(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,Ko.o1)(a,this.workspacePath);if(!((0,js.$f)(c)&&(0,js.A)(c)||await xu(c)||await async function(e,t,r){const n=[t?.teamAdmin,t?.perRepo,t?.perUser].map((e=>"insecure_none"===e?.type?void 0:e?.privateTmp)).find((e=>void 0!==e));if("linux"!==process.platform||!0!==n||void 0===r||!(0,Ko.ZU)({basePath:"/tmp",targetPath:e}))return!1;const o=(0,To.W1)(r);return void 0!==o&&await xu(s.default.join(o,"tmp",s.default.relative("/tmp",e)))}(c,t.sandboxPolicy,this.workspacePath))){if(c!==(0,Ko.o1)(await i.getCwd(),this.workspacePath))throw new Fu(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,go.sh)(t.conversationId)),t.requestId&&(w.CURSOR_REQUEST_ID=t.requestId),this.projectDir&&(w.AGENT_TRANSCRIPTS=s.default.join(this.projectDir,go.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&&$u(e)&&(w[e]=t);const b=w.CURSOR_REQUEST_ID;void 0!==b&&(w.CURSOR_REQUEST_ID=Ru(b)),function(e,t){const r=Cu,n=Object.keys(t).filter((e=>$u(e)&&!r.includes(e))),o=`builtin unset ${[...Cu,...n].join(" ")} 2>/dev/null || true`,s=[];for(const t of Cu){const r=Iu(e,t);void 0!==r&&s.push(`builtin export ${t}=${Eu(r)}`)}for(const e of n){const r=t[e];void 0!==r&&s.push(`builtin export ${e}=${Eu(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=Ru(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=Iu(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[]}}(Iu(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=Du(i.additionalReadonlyPaths,a):i.additionalReadwritePaths=Du(i.additionalReadwritePaths,a));for(const e of n)e.readOnly||"workspace_readwrite"!==i.type?i.additionalReadonlyPaths=Du(i.additionalReadonlyPaths,e.path):i.additionalReadwritePaths=Du(i.additionalReadwritePaths,e.path);return{...e,perUser:i}}(t.sandboxPolicy,w),k=(0,To.CG)(S??To.BM);let _,C,E,x;S&&(yield{type:"start",sandboxed:"workspace_readonly"===k||"workspace_readwrite"===k}),t.askpassConfig&&!_u&&(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??ou,R=(this.options.outputFallbackEncoding??(()=>P.current()))(),I=()=>function(e){if(void 0===e)return cu();const t=nu.get(e);return void 0!==t&&Ws.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=iu.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&&uu.test(a.toString("latin1")),o=t.test(i[i.length-1])}},isUtf8Text:()=>s,reset(){n=!1,o=!1,s=!1}}}(t);let s=su,i=0,a="utf8",c=!1;const l=()=>{a="utf8",o.reset(),i=0},u=(t,n)=>{const s=n?au(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=lu(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=lu(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=iu.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=su,"utf8"===a){const e=t.subarray(0,t.length-au(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?au(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=su;const t=0===e.length?"":"utf8"===a?e.toString("utf8"):u(e,!1).text;return l(),t},usedCodePage:()=>c}}(e,t):cu()}(R),T={stdout:yu(I),stderr:yu(I)},A=new cl,M=Rl(this.options.encodingSlices,e)?new zl: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()))ku.increment(e,1,r);M?.record(this.options.encodingSlices,e,t,P.lastOutcome())}catch(t){Su.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:Mu(this.options.powershellUtf8Console),powershellUtf8ChildEnv:Mu(this.options.powershellUtf8ChildEnv),powershellParseAfterUtf8Switch:Mu(this.options.powershellParseAfterUtf8Switch),powershellWebRequestUtf8:Mu(this.options.powershellWebRequestUtf8),powershellPerLineStateDump:Mu(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+_<=Xo,f=void 0!==l&&!0!==l.truncated&&l.size+_<=Rc;"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+_>Rc)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,Pc);l.path=s.default.join(e,`${(0,mo.randomUUID)()}.txt`);try{await(0,vo.mkdir)(e,{recursive:!0}),l.file=(0,So.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:To.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+=qs(e)-1}const e=await new Promise((e=>l.file.end(e)));u??=e??void 0,u?await(0,vo.rm)(l.path,{force:!0}):t=new Ic.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"===gc(t)&&(0,js.$f)(c))try{Su.warn(e,"shell failed with ENOENT in an agent store working directory",{...await(0,js.KZ)(c)})}catch{}throw t}finally{O()}}catch(e){r.error=e,r.hasError=!0}finally{bu(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 Lu{constructor(e,t){this.innerExecutor=e,this.shellManager=t}async*execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{vu(r,(0,$.VI)(e.withName("ManagedShellCoreExecutor.execute")),!1),Su.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{bu(r)}}async getCwd(e){return this.innerExecutor.getCwd(e)}getWorkspacePath(){return this.innerExecutor.getWorkspacePath()}}class ju{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 Uu(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(gs(e.pattern));case"unsafeResolution":return t.onPermissionDenied(e.message);default:{const t=e;throw new Error(`Unhandled block reason type: ${JSON.stringify(t)}`)}}}function Bu(e){switch(e.type){case"userRejected":return e.reason;case"unsafeResolution":return e.message;case"adminCommandDenylist":return gs(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 Wu(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:Bu(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 qu=(0,l.h)("local-exec:background-shell");function zu(e,t,r){return new Io.Lt({result:Wu(e,t,r)})}class Gu{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 Vu(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 Ku(e){e().catch((()=>{}))}class Ju{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=Vo.L3.compile(e.config.pattern,Vo.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=Uo(e,n+t);o<=n&&(o=Bo(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=Ho(r,1024)}finish(){this.finished||(this.finished=!0,this.flushPendingBatch("finish"),this.clearFlushTimer(),0===this.matchedOccurrences&&this.recordWatchOutcome("silent",{silent_ms:Qu(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:Qu(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=_o(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:`${Wo(i,500)}...`),detail:o,outputPath:this.args.outputPath,reason:"task_progress"}})}emitLimitReachedNotification(){this.emittedNotifications+=1;const e=this.args.config.pattern,t=_o(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&&qu.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 Zu{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 Ju({shellId:t,outputPath:i,config:o,conversationId:r??ko,toolCallId:n,registry:this.backgroundWorkRegistry,ctx:e})}catch(r){return void(void 0!==e&&qu.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 Xu{async spawn(e,t){const r=new AbortController,n=new Gu(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 To.SandboxUnsupportedError||e instanceof Fu)throw e}return Ku((()=>Vu(n,o))),n}async adopt(e){const t=new Gu(e.shellId,e.abortController);return t.stdin=e.stdin,t.pid=e.pid,Ku((()=>Vu(t,e.eventIterator))),t}}function Qu(e){return Math.round(performance.now()-e)}function Yu(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`}function ed(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: ${Yu(e.cwd)}\n`,n+=`command: ${Yu(e.command)}\n`,void 0!==e.title&&e.title.trim().length>0&&(n+=`title: ${Yu(e.title)}\n`),n+=`status: ${r}\n`,n+=`started_at: ${e.startedAt}\n`,n+=`running_for_ms: ${t}\n`,n+="---\n",n}function td(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 rd{constructor(e,t){this.innerFactory=e,this.projectDir=t}async spawn(e,t){const r=s.join(this.projectDir,"terminals");await(0,vo.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=Qu(g),r=ed({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=Qu(g),n=ed({pid:e,cwd:t.workingDirectory,command:t.command,title:t.description,status:y,startedAt:m,runningForMs:r});await(0,vo.writeFile)(_,n,"utf8"),l=setInterval((()=>{E()}),5e3)},R=async()=>{a||(a=await So.promises.open(_,"r+")),c||(c=await So.promises.open(_,"a"))},I=async(e,t)=>{if(!v){if(v=!0,x(),p||await P(),await R(),void 0!==t){const e=Qu(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 R()),await S(r.data);else if("stderr"===r.type)p||(await P(),await R()),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 I(r.aborted?"aborted":0===r.code?"succeeded":"failed",`exit_code: ${r.code??"unknown"}`);else{u=!0,p||(await P(r.pid),await R());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 R(),await S(td("stderr"));else d=!0,p||await P(),await R(),await S(td("stdout"));yield r}if(!v){const e=i.signal?.aborted??!1;await I(e?"aborted":"failed")}}catch(e){const t=i.signal?.aborted??!1,r=Yu(e instanceof Error?e.message:"Unknown error");if(await I(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,vo.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=Qu(i),l=ed({pid:e.pid,cwd:e.workingDirectory,command:e.command,title:e.description,status:a,startedAt:o,runningForMs:c})+(e.initialOutput??"");await(0,vo.writeFile)(r,l,"utf8");const u=await So.promises.open(r,"r+");let d;try{d=await So.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=Qu(i),r=ed({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=Qu(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(td("stderr"))):(f=!0,await k(td("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 nd{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:Co(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??ko,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:Qu(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 od{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 sd{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 od(s,i):s,l=o??function(e){const t=new Xu;return new rd(t,e)}(n),u=new Zu(l,n,c);this.backgroundShellManager=new nd(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?os(t.sandboxPolicy):void 0,s=t.workingDirectory||await this.coreExecutor.getCwd(t.conversationId),i=(0,Ko.o1)(s),a=new he.HO(No(n).structured),c=ws({command:n,parsingResult:a,blockedCommands:t.adminCommandDenylist});if(void 0!==c)return new Io.Lt({result:{case:"rejected",value:new he.pZ({command:n,workingDirectory:i,reason:c})}});let l;if(qu.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}),Ro(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 qu.info(e,"Background shell: invariant blocked command",{toolCallId:t.toolCallId,blockReasonType:r.reason.type,skipApproval:t.skipApproval}),zu(n,i,r.reason);l=r.policy??o,qu.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:xo(t)},o);if("block"===r.kind)return qu.info(e,"Background shell: approval gate blocked command",{toolCallId:t.toolCallId,blockReasonType:r.reason.type,hasSmartModeApproval:void 0!==t.smartModeApproval,skipApproval:t.skipApproval}),zu(n,i,r.reason);l=r.policy,qu.info(e,"Background shell: approval gate allowed command",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,effectivePolicyType:l.type})}l=await Ec(l,{command:n,workingDirectory:i,parsingResult:a,permissionsService:this.permissionsService,ignoreService:this.ignoreService});try{const r=this.backgroundShellManager.generateShellId(),o=l?{perUser: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 Io.Lt({result:{case:"success",value:new Io.Po({shellId:r,command:n,workingDirectory:i,pid:a.pid})}})}catch(r){if(r instanceof To.SandboxUnsupportedError){const o=l?.type??"unknown";return qu.debug(e,"Background shell: sandbox policy unsupported on this host",{toolCallId:t.toolCallId,policyType:o,reason:r.reason}),new Io.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 Io.Lt({result:{case:"error",value:new Io.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 id=r("node:async_hooks");r("../../node_modules/.pnpm/minimatch@10.2.5/node_modules/minimatch/dist/esm/index.js");function ad(e){return e instanceof Error?e.message:String(e)}function cd(e){return"Failed to read skill file: "+ad(e)}function ld(e){return"Invalid skill frontmatter: "+ad(e)}function ud(e,t){return e||t?void 0:"Description is required"}new Set(["EACCES","EPERM","ENOENT","ENOTDIR","EISDIR","ELOOP","ENAMETOOLONG"]);const dd=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function hd(e){return e.toLocaleString("en-US")}var pd=r("node:url");const fd={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"},md=e=>"string"==typeof e,gd=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),wd=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),yd=(e,t=[])=>({isValid:e,errors:t});function vd(e,t,r){void 0===e||md(e)||r.push(`${t} must be a string if provided`)}const bd=e=>{const t=[];if(!gd(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)"),yd(!1,t);const r=e.type;return"prompt"===r?((e,t)=>{md(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&&(md(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)=>{md(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(md(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),yd(0===t.length,t)},Sd=(e,t)=>{const r=[];if(!Array.isArray(e))return r.push(`${t} must be an array of hook scripts`),yd(!1,r);for(let n=0;n<e.length;n++){const o=bd(e[n]);o.isValid||r.push(`${t}[${n}]: ${o.errors.join(", ")}`)}return yd(0===r.length,r)},kd=e=>{const t=[];if(!gd(e))return t.push("Hooks config must be an object"),yd(!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"),!gd(e.hooks))return t.push("Config hooks must be an object"),yd(!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(fd),n=e.hooks;for(const[e,o]of Object.entries(n))if(r.includes(e)){if(void 0!==o){const r=Sd(o,e);r.isValid||t.push(...r.errors)}}else t.push(`Unknown hook type: ${e}. Valid types are: ${r.join(", ")}`);return yd(0===t.length,t)},_d={PreToolUse:fd.preToolUse,PermissionRequest:null,PostToolUse:fd.postToolUse,UserPromptSubmit:fd.beforeSubmitPrompt,Stop:fd.stop,SubagentStop:fd.subagentStop,SessionStart:fd.sessionStart,SessionEnd:fd.sessionEnd,PreCompact:fd.preCompact,Notification:null},Cd=Object.fromEntries(Object.entries(_d).filter((e=>Ed(e[0])&&null!==e[1])).map((([e,t])=>[t,e])));function Ed(e){return Object.prototype.hasOwnProperty.call(_d,e)}const xd={Bash:"Shell",Read:"Read",Write:"Write",Edit:"Write",Glob:null,Grep:"Grep",WebFetch:"WebFetch",WebSearch:"WebSearch",Task:"Task"},Pd=["Glob"],Rd=["Notification","PermissionRequest"],Id=/^[A-Za-z0-9_./:=+-]+$/,Td=/^=|^-.*\./,Ad=/\$\{(?:CLAUDE_PROJECT_DIR|CURSOR_PROJECT_DIR|CLAUDE_PLUGIN_ROOT|CURSOR_PLUGIN_ROOT)\}/g,$d=/^[^\p{Cc}$`"]*$/u,Md=/\\(?:[$`"\\]|$)/;function Dd(e){return`'${e.replace(/'/g,"'\\''")}'`}function Od(e){if(Id.test(e)&&!Td.test(e))return e;const t=e.replace(Ad,"");if((t!==e||e.includes("'"))&&$d.test(t)&&!Md.test(e))return`"${e}"`;const r=[];let n=0;for(const t of e.matchAll(Ad))t.index>n&&r.push(Dd(e.slice(n,t.index))),r.push(`"${t[0]}"`),n=t.index+t[0].length;return(n<e.length||0===r.length)&&r.push(Dd(e.slice(n))),r.join("")}const Fd={warn:()=>{},info:()=>{}};function Nd(e,t,r=Fd){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 Ld(e,t,r=Fd){const n=[];let o;if("PreToolUse"===t||"PostToolUse"===t){const t=function(e,t=Fd){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=xd[t];null!==r?void 0!==r?n.includes(r)||n.push(r):n.push(t):Pd.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=Nd(t,o,r);e&&n.push(e)}return n}function jd(e,t=Fd){const r={};for(const[n,o]of Object.entries(e)){if(!Ed(n)){t.warn(`Unknown Claude Code event "${n}", skipping`);continue}if(Rd.includes(n)){t.warn(`Claude Code event "${n}" is not supported in Cursor and will be ignored`);continue}const e=_d[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=Ld(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 Ud=r("../../node_modules/.pnpm/gray-matter@4.0.3/node_modules/gray-matter/index.js");const Bd=()=>({});function Wd(e,t){return Ud(e,{...t,engines:{...t?.engines,js:Bd,javascript:Bd}})}function Hd(e,t,r){return Ud.stringify({content:e,data:{}},t,r)}function qd(e){return e.replace(/\\/g,"/").replace(/\/+$/,"")||"/"}function zd(e,t){if(Object.hasOwn(e,t))return e[t]}function Gd(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?qd(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===zd(i,e))continue;let r;void 0!==a&&(r=t.find((t=>!("project"!==t.scope&&"local"!==t.scope||!t.projectPath)&&(qd(t.projectPath)===a&&!0===zd(i,e))))),r||!0!==zd(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 Vd=r("../../node_modules/.pnpm/js-yaml@4.3.1/node_modules/js-yaml/dist/js-yaml.mjs");const Kd=je.enum(["canvas"]),Jd=je.array(Kd).transform((e=>[...new Set(e)].sort())),Zd=new Set(["https://agent-plugins.org/schemas/1.0.0/plugin.schema.json","https://agent-plugins.org/schemas/1.0.0/mcp.schema.json"]),Xd=/^v?(\d+\.\d+(?:\.\d+)?)$/;function Qd(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 Yd(e){let t;try{t=new URL(e).pathname.split("/")}catch{t=e.split("/")}for(const e of t){const t=Xd.exec(e);if(null!==t)return t[1]}}function eh(e){return void 0===e?{kind:"absent"}:Zd.has(e)?{kind:"supported",id:e,version:Yd(e)??e}:{kind:"unsupported",id:e}}const th=10485760,rh=/^[a-z0-9]([a-z0-9.-]*[a-z0-9])?$/,nh=[".cursor-plugin/plugin.json",".claude-plugin/plugin.json","plugin.json"],oh=[".cursor-plugin",".claude-plugin"],sh=[".cursor-plugin/marketplace.json",".claude-plugin/marketplace.json"],ih=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()}),ah=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()}),ch=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()}),lh=je.union([je.string(),ih,ah,ch]),uh=/^(\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?|never)$/,dh='Must be a semver version (X.Y.Z) or "never"',hh=je.object({cursor:je.string().regex(uh,dh).optional(),sand:je.string().regex(uh,dh).optional(),sandMobile:je.string().regex(uh,dh).optional()}),ph=je.object({name:je.string().min(1,"Author name is required"),email:je.string().email().optional()}),fh=je.enum(["string","number","integer","boolean","object","array","null"]),mh=je.union([fh,je.array(fh).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 gh(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 wh=je.lazy((()=>je.object({type:mh.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(),wh).optional(),required:je.array(je.string()).optional(),additionalProperties:je.union([je.boolean(),wh]).optional(),items:je.union([wh,je.array(wh)]).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(gh)));function yh(e){const t=wh.superRefine(((e,t)=>{Sh(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?kh(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 vh=je.unknown().superRefine(((e,t)=>{const r=yh(e);if(!r.success)for(const e of r.error.issues)t.addIssue({code:"custom",message:e.message,path:e.path})})).transform((e=>{if(!kh(e))throw new Error('Plugin variable schema must declare type "object"');return e})),bh=(je.object({name:je.string().min(1).transform((e=>e.toLowerCase())).refine((e=>rh.test(e)),"Name must be kebab-case (lowercase alphanumeric with hyphens and periods)"),displayName:je.string().optional(),source:lh,description:je.string().optional(),version:je.string().optional(),author:ph.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:Jd.optional(),logo:je.string().optional(),category:je.string().optional(),tags:je.array(je.string()).optional(),minClientVersions:hh.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:vh.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(rh,"Name must be kebab-case (lowercase alphanumeric with hyphens and periods)"),displayName:je.string().optional(),description:je.string().optional(),version:je.string().optional(),author:ph.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:Jd.optional(),minClientVersions:hh.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:vh.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 Sh(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function kh(e){return Sh(e)&&"object"===e.type}function _h(e){return e.trim().toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")}function Ch(e,t){if(Sh(e)&&"string"==typeof e.name){const t=_h(e.name);if(t.length>0)return t}return function(e){const t=void 0!==e.repoName?_h(e.repoName):"";return t.length>0?t:`cursor-marketplace-${e.fallbackId??(0,mo.randomUUID)()}`}(t)}function Eh(e){if(Sh(e)&&Sh(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 xh(e){return"string"==typeof e?e:void 0}function Ph(e){if(!Array.isArray(e))return;const t=e.filter((e=>"string"==typeof e));return t.length>0?t:void 0}function Rh(e){return"string"==typeof e?e:Ph(e)}function Ih(e){if(!Sh(e)||!Sh(e.metadata))return;const t={description:xh(e.metadata.description),version:xh(e.metadata.version),pluginRoot:xh(e.metadata.pluginRoot)};return void 0!==t.description||void 0!==t.version||void 0!==t.pluginRoot?t:void 0}function Th(e){if(!Sh(e))return;const t=xh(e.name);if(void 0===t||0===t.length)return;const r=xh(e.email);return{name:t,...void 0!==r?{email:r}:{}}}function Ah(e){if("string"==typeof e||Sh(e))return e;if(Array.isArray(e)){const t=e.filter((e=>"string"==typeof e||Sh(e)));return t.length>0?t:void 0}}function $h(e){if("string"==typeof e||Sh(e))return e}function Mh(e){if(void 0===e)return;const t=yh(e);return t.success?t.data:void 0}function Dh(e,t={}){if(e.length>th)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(!Sh(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(!Sh(e))return{skippedEntry:{index:t,error:`Plugin entry at index ${t} is not an object`}};const r="string"==typeof(n=e.source)?n:Sh(n)?"github"===n.source&&"string"==typeof n.repo&&n.repo.length>0?{source:"github",repo:n.repo,ref:xh(n.ref),sha:xh(n.sha)}:("url"===n.source||void 0===n.source)&&"string"==typeof n.url&&n.url.length>0?{source:"url",url:n.url,ref:xh(n.ref),sha:xh(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:xh(n.ref),sha:xh(n.sha)}:"string"==typeof n.repo&&n.repo.length>0?{source:"github",repo:n.repo,ref:xh(n.ref),sha:xh(n.sha)}:void 0:void 0;var n;if(void 0===r){const r=xh(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?_h(e.name):"")||function(e){if("string"==typeof e){const t=_h((0,s.basename)(e));return t.length>0?t:void 0}if("github"===e.source){const t=_h(e.repo.split("/").at(-1)??"");return t.length>0?t:void 0}if("git-subdir"===e.source){const t=_h((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=_h((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=Jd.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=hh.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:xh(e.displayName),source:r,description:xh(e.description),version:xh(e.version),author:Th(e.author),publisher:xh(e.publisher),homepage:xh(e.homepage),repository:xh(e.repository),license:xh(e.license),keywords:Ph(e.keywords),logo:xh(e.logo),category:xh(e.category),tags:Ph(e.tags),strict:"boolean"!=typeof e.strict||e.strict,commands:Rh(e.commands),agents:Rh(e.agents),skills:Rh(e.skills),rules:Rh(e.rules),hooks:$h(e.hooks),variables:Mh(e.variables),mcpServers:Ah(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:Ch(r,t),owner:Eh(r),description:xh(r.description),plugins:n,metadata:Ih(r),skippedPluginEntries:o}}}function Oh(e){if(e.length>th)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=eh(Qd(t)),n=bh.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 Fh(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 Nh(e){return!e.includes("..")&&!(0,s.isAbsolute)(e)&&!e.includes("://")}var Lh=r("../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/main.js");const jh=/\$\{(?:env:([A-Za-z_][A-Za-z0-9_]*)|([^:}]+)(?::-([^}]*))?)\}/g,Uh=/\$%7B([^%/?#]+?)%7D/gi;function Bh(e,t){return Wh(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 Wh(e,t){if("string"==typeof e)return function(e,t){return e.replace(Uh,"${$1}").replace(jh,((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=>Wh(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]=Wh(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 qh={log:()=>{},increment:()=>{},distribution:()=>{},captureException:()=>{}},zh=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()}),Gh=je.object({mcpServers:je.record(je.string(),zh).optional()}),Vh=[".mcp.json","mcp.json"],Kh=new Set(["author","owner","source","metadata"].map((e=>e.toLowerCase())));function Jh(e,t){if(!function(e){return Kh.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 Zh(e){return"object"==typeof e&&null!==e&&("command"in e||"url"in e)}function Xh(e){const t=void 0!==e&&e.length>0?e.replace(/\/+$/,""):void 0;return Vh.map((e=>void 0!==t?`${t}/${e}`:e))}function Qh(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 Bh(e,r);const o=new Map(Object.keys(n??{}).map((e=>[e.toLowerCase(),e])));return Bh(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 Yh(e,t,r){try{const n=(0,Lh.qg)(e),o=Qd(n);if(void 0!==o){const e=r?.log??qh;"unsupported"===eh(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=Yd(e),n=Yd(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=Gh.safeParse(n),i=!0===r?.skipExpansion;if(s.success&&s.data.mcpServers&&Object.keys(s.data.mcpServers).length>0)return i?s.data:Qh(s.data,t,r);const a={};for(const[e,t]of Object.entries(n))"mcpServers"!==e&&!Jh(e,t)&&Zh(t)&&(a[e]=t);if(Object.keys(a).length>0){const e=Gh.safeParse({mcpServers:a});if(e.success)return i?e.data:Qh(e.data,t,r)}return null}catch{return null}}function ep(e,t,r){for(const[n,o]of Object.entries(t))e.mcpServers[n]=o,e.mcpServerSourcePaths[n]=r}async function tp(e,t,r,n={}){const o=n.toSourcePath??(e=>e),s=n.installPathForExpansion??"",i=n.fallbackFileNames??Vh,a=n.manifestPrecedence??"override",c={},l={};for(const t of i){const r=await e(t);if(null===r)continue;const i=Yh(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(!Nh(i))return;const a=await t(i);if(null===a)return;const c=Yh(a,o,r.parserOptions);c?.mcpServers&&Object.keys(c.mcpServers).length>0&&ep(s,c.mcpServers,n(i))},a=e=>{const t=Yh(JSON.stringify(e),o,r.parserOptions);t?.mcpServers&&Object.keys(t.mcpServers).length>0&&ep(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 rp=new Set(["CREDENTIAL","CREDENTIALS","KEY","PASSPHRASE","PASSWORD","SECRET","TOKEN"]);function np(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=>rp.has(e)))}const op=/\$\{(?:env:([A-Z][A-Z0-9_]*)|([A-Z][A-Z0-9_]*)(?::-([^}]*))?)\}/g,sp=new Set(["CURSOR_PLUGIN_ROOT","CLAUDE_PLUGIN_ROOT"]),ip=new Set(["api","aws","db","dd","gcp","http","https","id","mcp","ssl","tls","uri","url"]);function ap(e){return e.split("_").filter((e=>e.length>0)).map((e=>{const t=e.toLowerCase();return ip.has(t)?e.toUpperCase():e.charAt(0).toUpperCase()+t.slice(1)})).join(" ")}function cp(e,t){if("string"!=typeof e){if(Array.isArray(e))for(const r of e)cp(r,t);else if(null!==e&&"object"==typeof e)for(const r of Object.values(e))cp(r,t)}else for(const[,r,n,o]of e.matchAll(op)){const e=r??n;if(void 0===e||sp.has(e)||t.has(e))continue;const s=void 0===r?`\${${e}}`:`\${env:${e}}`;t.set(e,{reference:s,defaultValue:o})}}function lp(e){if(void 0===e?.mcpServers)return;const t=new Map;if(cp(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:ap(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.`,...np(e)?{writeOnly:!0}:{}}}return{type:"object",properties:r}}const up=[".md",".mdc",".markdown"],dp=[...up,".txt"],hp=/^---\s*\n([\s\S]*?)\n---/;function pp(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function fp(e){return e.trim().toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9.-]/g,"")}function mp(e){const t=e.match(hp);if(!t)return{};try{const e=Vd.Ay.load(t[1],{schema:Vd.Ay.JSON_SCHEMA});if(!pp(e))return{};const r=pp(e.metadata)?e.metadata:void 0,n=gp(e.environments??r?.environments);return{disabledEnvironments:gp(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 gp(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 wp(e){return fp((0,s.basename)(e).replace(/\.(md|mdc|markdown|txt)$/i,""))}function yp(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 vp{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=Vh.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,up):s.has("skills")?this.discoverSkills(`${r}skills`):Promise.resolve([]),void 0!==n?.agents?this.discoverFromManifestPaths(r,n.agents,!1,up):s.has("agents")?this.discoverMarkdownComponents(`${r}agents`,up):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,dp):s.has("commands")?this.discoverMarkdownComponents(`${r}commands`,dp):Promise.resolve([]),void 0!==n?.rules?this.discoverFromManifestPaths(r,n.rules,!1,up):s.has("rules")?this.discoverMarkdownComponents(`${r}rules`,up):Promise.resolve([]),this.discoverMcpServers(r,n?.mcpServers,i)]);return{skills:yp(c?[c,...l]:l),agents:yp(u),hooks:d,commands:yp(h),rules:yp(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 pp(r)&&pp(r.hooks)?Object.keys(r.hooks).map((t=>({name:fp(t),path:e,description:`Hook: ${t}`}))):[]}catch{return[]}}async discoverHooksFromManifest(e,t){if("string"==typeof t){if(!Nh(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:fp(e),path:"manifest",description:`Hook: ${e}`})))}async discoverFromManifestPaths(e,t,r=!1,n=up){if("string"==typeof t){if(!Nh(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(!Nh(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=wp(t.endsWith("SKILL.md")?t.slice(0,-8).replace(/\/$/,""):t);const{content:n}=await this.fetcher.fetchFile(e),s=mp(n);if(r=s.name??r,r){const t={disabledEnvironments:s.disabledEnvironments,environments:s.environments,name:fp(r),path:e};void 0!==s.description&&(t.description=s.description),o.push(t)}}else{if(!await this.fetcher.fileExists(t))continue;let e=wp(t);const{content:r}=await this.fetcher.fetchFile(t),n=mp(r);e=n.name??e;const s=n.description;if(e){const r={name:fp(e),path:t};void 0!==s&&(r.description=s),o.push(r)}}}catch{}return o}async discoverMarkdownComponents(e,t=up,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=wp(e.name);const{content:r}=await this.fetcher.fetchFile(e.path),n=mp(r);t=n.name?fp(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=fp((0,s.basename)(e.replace(/[\\/]+$/,"")));const{content:n}=await this.fetcher.fetchFile(t),o=mp(n);if(r=o.name?fp(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=mp(r),o=n.name?fp(n.name):fp(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=>tp(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:fp(e),path:i.mcpServerSourcePaths?.[e]??"manifest"}))),variables:lp(a??i),configs:l}}}var bp=r("node:stream"),Sp=r("node:stream/promises"),kp=r("node:zlib");function _p(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 Cp(e){return e.replace(/[^a-zA-Z0-9._-]/g,"_")}var Ep=r("../../node_modules/.pnpm/tar@7.5.21/node_modules/tar/dist/esm/index.min.js");const xp=".cache-complete";function Pp(e){return Cp(e)}function Rp(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 Ip(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?Pp(t.version):void 0)}class Tp{constructor(e,t){const r=e??process.env.HOME??"";this.cacheRoot=t?.cacheRoot??(0,s.join)(r,".cursor","plugins/cache")}getCacheDir(e){return Ip(this.cacheRoot,e)}async isCached(e){const t=this.getCacheDir(e);try{const e=Rp({parent:t,name:xp});return(await(0,vo.stat)(e)).isFile()}catch{return!1}}async extractToCache(e){const t=this.getCacheDir(e);await(0,vo.mkdir)(t,{recursive:!0});const r=bp.Readable.from(e.tarball);return await(0,Sp.pipeline)(r,(0,kp.createGunzip)(),(0,Ep.o6)({cwd:t,strip:1})),await this.markCacheComplete(e),t}async listCachedVersions(e){const t=Ip(this.cacheRoot,e);try{return(await(0,vo.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,vo.rm)(t,{recursive:!0,force:!0})}catch{}}async removeAllVersions(e){const t=Ip(this.cacheRoot,e);await(0,vo.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=>Pp(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,vo.writeFile)(Rp({parent:t,name:xp}),"")}}class Ap extends Error{constructor(e,t){super(`Invalid Claude Code plugin identifier "${t}": ${e}`),this.raw=t,this.name="CCPluginIdentifierError"}}function $p(e){const t=e.trim();if(!t)throw new Ap("Empty identifier",e);const r=/^[a-zA-Z0-9_-]+$/,n=t.indexOf("@");if(n!==t.lastIndexOf("@"))throw new Ap("Plugin identifier cannot contain multiple @ symbols",e);if(-1===n){if(!r.test(t))throw new Ap("Plugin name must contain only alphanumeric characters, dashes, and underscores",e);if(t.length>100)throw new Ap("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 Ap("Missing plugin name before @",e);if(!s)throw new Ap("Missing source after @",e);if(!r.test(o))throw new Ap("Plugin name must contain only alphanumeric characters, dashes, and underscores",e);if(o.length>100)throw new Ap("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 Ap("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 Ap("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 Ap("Missing Git URL after 'url:'",e);try{new URL(t)}catch{throw new Ap("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 Ap("Missing marketplace name",e);if(!r.test(a))throw new Ap("Marketplace name must contain only alphanumeric characters, dashes, and underscores",e);return{name:o,sourceType:"marketplace",marketplace:a,version:c,raw:e}}function Mp(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 Dp(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 Fp(e){switch(e.source){case"cursor-first-party":case"cursor-third-party":return e.sourceInfo.pluginDbId;default:return}}function Np(e){switch(e.source){case"cursor-first-party":case"cursor-third-party":return e.sourceInfo.marketplaceDbId;default:return}}function Lp(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function jp(e){return!!Lp(e)&&(void 0===e.enabledPlugins||Lp(e.enabledPlugins))}function Up(e){return JSON.parse(e)}function Bp(e){const t=e??process.env.HOME??"";return(0,s.join)(t,".claude")}async function Wp(e){const t={enabledPlugins:{}};let r=!1;const n=(0,s.join)(e,".claude","settings.json");try{const e=Up(await(0,vo.readFile)(n,"utf-8"));jp(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=Up(await(0,vo.readFile)(o,"utf-8"));jp(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 qp(e){try{return(await(0,vo.lstat)(e)).isSymbolicLink()}catch{return!1}}async function zp(e){if(await qp(e))throw new Error(`Refusing to read symlink: ${e}`);return(0,vo.readFile)(e,"utf-8")}async function Gp(e){if((await(0,vo.stat)(e)).size>10485760)throw new Error(`File ${e} exceeds maximum size of 10485760 bytes`)}function Vp(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 Kp({installPath:e,logo:t}){const r=t?.trim();if(r&&!(0,s.isAbsolute)(r)&&!r.includes("://"))try{const t=await(0,vo.realpath)(e),n=Hp(t,r),o=await(0,vo.realpath)(n);if(Hp(t,o),!(await(0,vo.stat)(o)).isFile())return;return await Gp(o),(0,pd.pathToFileURL)(o).href}catch{return}}function Jp(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 Zp(e){return void 0!==e.version||void 0!==e.homepage||void 0!==e.repository}function Xp(e,t){return Jp({version:e.version??t?.version,homepage:e.homepage??t?.homepage,repository:e.repository??t?.repository})}async function Qp(e,t,r){let n;for(const o of nh){const i=(0,s.join)(e,o);let a;try{if(await qp(i))continue;if(!(await(0,vo.stat)(i)).isFile())continue;await Gp(i),a=await zp(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 Kp({installPath:e,logo:l.logo}),S=Jp(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&&!Zp(S))continue;if(!g&&!C){n=n?{...n,fields:Xp(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=Xp(S,n?.fields);return{manifestFilePath:i,...g&&{manifestOptions:{commands:u,agents:d,skills:h,rules:p,hooks:f,mcpServers:m}},...(C||Zp(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 Yp(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,vo.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,vo.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,vo.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,vo.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 Gp(i);const l=await(0,vo.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,vo.stat)(n)).isFile()}catch{return!1}}}}(e),n=new vp(r),o=await n.discoverComponents({manifest:t}),[i,a,c,l]=await Promise.all([ef(r,o.skills,e),rf(r,o.agents,e),nf(r,o.commands,e),tf(r,o.rules,e)]);return{skills:i,agents:a,commands:c,rules:l}}async function ef(e,t,r){const n=[];for(const o of t)try{const{content:t}=await e.fetchFile(o.path),s=sf({content:Hh(t,r),relativePath:o.path});s&&n.push(s)}catch{}return n}async function tf(e,t,r){const n=[];for(const o of t)try{const{content:t}=await e.fetchFile(o.path),s=sf({content:Hh(t,r),relativePath:o.path});s&&n.push({...s,name:o.name})}catch{}return n}async function rf(e,t,r){const n=[];for(const o of t)try{const{content:t}=await e.fetchFile(o.path),s=af({content:Hh(t,r),relativePath:o.path});s&&n.push(s)}catch{}return n}async function nf(e,t,r){const n=[];for(const o of t)try{const{content:t}=await e.fetchFile(o.path),s=cf({content:Hh(t,r),relativePath:o.path});s&&n.push(s)}catch{}return n}function of(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 sf({content:e,relativePath:t}){try{const r=Wd(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=gp(r.data.environments??r.data.metadata?.environments),u=gp(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:of(r.data.globs),alwaysApply:!0===r.data.alwaysApply,content:e,environments:l,disabledEnvironments:u}}catch{return null}}function af({content:e,relativePath:t}){try{const n=Wd(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 cf({content:e,relativePath:t}){try{const r=Wd(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 lf(e){if(void 0!==e)return{configuredVariables:e.configuredVariables}}async function uf(e,t,r){const n=r??lf(t);return async function(e,t={}){const r=t.toSourcePath??(e=>e);let n,o,s;for(const t of nh){const i=await e(t);if(null===i)continue;let a;try{a=JSON.parse(i)}catch{continue}s=Qd(a);const c=Oh(i);if(c.success){void 0!==c.data.mcpServers&&(n=c.data.mcpServers,o=r(t));break}}return tp(e,n,o,void 0===s?t:{...t,parserOptions:{...t.parserOptions,pluginSchemaId:s}})}(function(e){return async t=>{if(!Nh(t))return null;const r=(0,s.join)(e,t);try{return await qp(r)?null:(await(0,vo.stat)(r)).isFile()?(await Gp(r),await zp(r)):null}catch{return null}}}(e),{fallbackFileNames:Xh(),manifestPrecedence:"override",toSourcePath:t=>(0,s.join)(e,t),installPathForExpansion:e,parserOptions:n})}async function df(e,t,r){const n=await uf(e,void 0,{log:r});if(n)return n;for(const n of sh){const o=(0,s.join)(e,n);try{if(!(await(0,vo.stat)(o)).isFile())continue;const n=await(0,vo.readFile)(o,"utf-8"),i=JSON.parse(n);if(!ff(i)||!Array.isArray(i.plugins))continue;const a=i.plugins.filter(mf),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(!Nh(n))continue;const o=(0,s.join)(e,n);try{await Gp(o);const t=Yh(await zp(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 hf=new Set(Object.values(fd));function pf(e){return hf.has(e)}function ff(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function mf(e){return!(!ff(e)||"string"!=typeof e.name)&&(void 0===e.mcpServers||Array.isArray(e.mcpServers)&&e.mcpServers.every((e=>"string"==typeof e)))}function gf(e,t){const r={};for(const[n,o]of Object.entries(e.hooks))Array.isArray(o)&&pf(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 wf(e,t,r,n,o){if("object"==typeof n){const s=yf(n,t,r);return s&&"config"in s?{config:gf(s.config,e),...void 0!==o&&{sourcePath:o}}:s}let i,a,c;if("string"==typeof n){const t=n.replace(/^\.\//,"");if(!Nh(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 qp(i))return;if(!(await(0,vo.stat)(i)).isFile())return}catch{return}try{await Gp(i),a=await(0,vo.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=yf(c,t,r);return l&&"config"in l?{config:gf(l.config,e),sourcePath:i}:l}function yf(e,t,r){const n=function(e){if(!wd(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(wd(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=kd(e);return r.isValid&&kd(e).isValid?{config:e}:{error:{source:"claude-plugin",message:`Plugin ${t} hooks: ${r.errors.join("; ")}`}}}if("claude-code"===n){if(!(ff(o=e)&&ff(o.hooks)&&Object.keys(o.hooks).length>0))return;const n=jd(e.hooks,{warn:e=>r.log("warn",`Plugin ${t} hooks: ${e}`),info:e=>r.log("info",`Plugin ${t} hooks: ${e}`)}),s=kd(n);return s.isValid?{config:n}:{error:{source:"claude-plugin",message:`Plugin ${t} hooks: ${s.errors.join("; ")}`}}}var o}async function vf(e,t,r,n){const o=n?.log??qh,s=await Qp(e,t,o),i={...lf(r)??(n?.configuredVariables?{configuredVariables:n.configuredVariables}:void 0),log:o},[a,c,l]=await Promise.all([Yp(e,s?.manifestOptions),uf(e,r,i),wf(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 bf(e,t,r){const n=r?.log??qh,o=await Qp(e,t.raw,n),[s,i,a]=await Promise.all([Yp(e,o?.manifestOptions),df(e,t,n),wf(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 Sf(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 vf(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 kf(e,t,r={}){const n=r.log??qh,o=performance.now(),i=await async function(e){const t=Bp(e),r=(0,s.join)(t,"plugins","installed_plugins.json");try{const e=Up(await(0,vo.readFile)(r,"utf-8"));return Lp(n=e)&&Lp(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=Bp(e),r=(0,s.join)(t,"settings.json");try{const e=Up(await(0,vo.readFile)(r,"utf-8"));return jp(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 Gd(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=Gd(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 Wp(e)})),{max:8})),u=[],d=r.onError;for(const{pluginId:e,installPath:t}of l)try{const r=performance.now(),o=$p(e),s=await bf(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($p(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 _f(e){const t=e.log??qh,r=performance.now(),{client:n,userId:o,teamId:s,onCursorError:i,pruneOldVersions:a,pluginFilter:c,onPluginsListed:l}=e,u=[],d=e.cacheManager??new Tp(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,vo.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,vo.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 Sf(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:Vp(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 Cf(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 Ef(e){return Cf(e)??`path:${e.installPath}`}function xf(e,t={}){return{...e,model:t.stripModel?void 0:e.model,tools:t.stripTools?void 0:e.tools}}function Pf(e,t){const r=[];for(const o of e){const e=Mp(o.identifier),i=`plugin:${e}`,a=Dp(o.identifier),c=Op(o.identifier),l=Fp(o.identifier),u=Np(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 Rf=r("../proto/dist/generated/agent/v1/agent_skills_pb.js");const If=(0,Us.debuglog)("agent-skills-catalog-cache");function Tf(e){return(0,mo.createHash)("sha256").update(JSON.stringify({v:1,...e})).digest("hex")}async function Af(e){try{return(await(0,vo.stat)(e)).mtimeMs}catch{return}}function $f(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}const Mf=[".kits","cursor-pages"],Df={configDir:".cursor",subdir:"skills-cursor",thirdParty:!1,builtin:!0},Of=[{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},Df],Ff=(new Set(Of.map((e=>e.configDir))),new Set(["imagegen","openai-docs","opneai-docs","plugin-creator","skill-creator","skill-installer"]));function Nf(e){return e.replace(/\\/g,"/").split("/").filter(Boolean)}function Lf(e){const t=Nf(e);if(function(e){const t=e.findIndex(((t,r)=>function(e,t){return Of.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&&Ff.has(o)}function jf(e){return{dirPath:(0,s.join)(e,Df.configDir,Df.subdir),scope:"builtin",source:"builtin"}}const Uf="canvas";function Bf(e,t){return{dirPath:(0,s.join)(jf(e).dirPath,...Mf),scope:"builtin",source:"builtin"}}function Wf(e,t){const r=e.replace(/\\/g,"/"),n=t.replace(/\\/g,"/").replace(/\/+$/,"");if(r.startsWith(`${n}/`))return Nf(r.slice(n.length+1))}function Hf(e,t){const r=Wf(e,t);return void 0!==r&&!r.some((e=>e.startsWith(".")))}function qf(e){return Of.filter((t=>!t.builtin&&(e||!t.thirdParty)))}function zf(e,t){return qf(t).map((t=>({dirPath:(0,s.join)(e,t.configDir,t.subdir),scope:"project",source:"workspace"})))}function Gf(e,t){return qf(t).map((t=>({dirPath:(0,s.join)(e,t.configDir,t.subdir),scope:"user",source:"user"})))}var Vf=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 Kf(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}const Jf=Of.map((({configDir:e,subdir:t,thirdParty:r})=>({pattern:new RegExp(`[/\\\\]${Kf(e)}[/\\\\]${Kf(t)}[/\\\\]`,"i"),requiresThirdParty:r}))),Zf=/[/\\]\.cursor[/\\]rules[/\\]/i,Xf=[{pattern:/[/\\]\.cursor[/\\]agents[/\\]/i,requiresThirdParty:!1},{pattern:/[/\\]\.claude[/\\]agents[/\\]/i,requiresThirdParty:!0}],Qf=new Set(["AGENTS.md","CLAUDE.md","CLAUDE.local.md"]);function Yf(e,t){const r=e.replace(/\\/g,"/"),n=(0,s.basename)(r);if(Qf.has(n))return"AGENTS.md"===n||t&&("CLAUDE.md"===n||"CLAUDE.local.md"===n)?"markdown":void 0;if(Zf.test(r)&&n.endsWith(".mdc"))return"rules";if("SKILL.md"===n)for(const{pattern:e,requiresThirdParty:n}of Jf)if(e.test(r)){if(n&&!t)continue;return"skills"}if(n.endsWith(".md"))for(const{pattern:e,requiresThirdParty:n}of Xf)if(e.test(r)){if(n&&!t)continue;return"agents"}}class em{constructor(e,t,r,n){this.root=e,this.gitExecutor=t,this.userHomeDirectory=r,this.getThirdPartyExtensibilityEnabled=n}static getRipwalkCache(){return em.ripwalkCache??=new ga,em.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||Ls(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 Ka(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:oc,followSymlinks:!0,source:"nested_extensibility"},u={rules:[],skills:[],markdown:[],agents:[]},d=em.getRipwalkCache();try{const e=d.walk(r.ctx,l);try{for await(const t of e.lines){const e=Yf(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{Vf(t)}}buildIncludeGlobs(e){const t=["*/**/.cursor/**","*/**/.agents/**","*/**/AGENTS.md"];return e&&t.push("*/**/.claude/**","*/**/.codex/**","*/**/.grok/**","*/**/CLAUDE.md","*/**/CLAUDE.local.md"),t}}const tm=new Set(["node_modules","__pycache__","dist","build"]);async function rm({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,vo.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,vo.realpath)(n);if(!l(e))continue;if(a.has(e))continue;a.add(e)}catch{continue}const d=await(0,vo.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,vo.stat)(r);a=e.isDirectory(),l=e.isFile()}catch{continue}if(a){if((u=e.name).startsWith(".")||tm.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 nm={agentStoreSkillsDirs:[],userHomeDirectory:""};function om(e){const t=e.replace(/\\/g,"/");return t.endsWith("/")?t.slice(0,-1):t}function sm(e,t){const r=om(t.userHomeDirectory),n=e.replace(/\\/g,"/");if(r.length>0)for(const e of t.agentStoreSkillsDirs){const t=om(e);if(t.length>0&&n.startsWith(`${t}/`))return{key:`${r}::skills/${n.slice(t.length+1)}`,inAgentStore:!0}}return{key:im(e),inAgentStore:!1}}function im(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 am(e,t){const r=new Map,n=[];for(const o of e){const{key:e,inAgentStore:s}=sm(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 cm=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},lm=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 um=(0,l.h)("local-exec:cursor-rules");function dm(e){return"/"===e||"\\"===e}function hm(e){return e.split(/[\\/]+/).filter((e=>e.length>0)).length}async function pm(e){return await rm({rootDir:e,includeFile:e=>"SKILL.md"===e})}async function fm(e){let t;try{t=await Di(e)}catch(t){return{skillFilePath:e,error:cd(t)}}try{return{skillFilePath:e,content:t,parsed:Wd(t)}}catch(t){return{skillFilePath:e,error:ld(t)}}}async function mm(e){const t=await Zo(e);return{...await fm(e),realSkillFilePath:t}}function gm(e){return vm(e.data?.environments??e.data?.metadata?.environments)??[]}function wm(e){return vm(e.data?.["disabled-environments"]??e.data?.metadata?.disabledEnvironments)??[]}function ym(e){return vm(e.data?.metadata?.scopedTo??e.data?.["metadata.scopedTo"])??[]}function vm(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 bm(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 Sm(e){return Wo(e,1536)}function km(e){return!0===e.data?.alwaysApply}function _m(e){return!0===e.data?.["disable-model-invocation"]}function Cm({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 ${hd(s.length)} characters; the limit is 64. Rename the skill's folder.`),dd.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 ${hd(i)} characters; the limit is ${hd(1024)}.`);const a=Math.round(n.length/4);return a>5e3&&o.push(`Body is about ${hd(a)} tokens; the recommended limit is ${hd(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(km(r))return new Gr.DX({fullPath:e,content:t,frontmatter:n,type:new Gr.f5({type:{case:"global",value:new Gr.i9}}),environments:gm(r),disabledEnvironments:wm(r),scopedTo:ym(r),warnings:o});const s="string"==typeof r.data?.description?Sm(r.data.description):void 0,i=ud(s,_m(r));return i?new Gr.DX({fullPath:e,parseError:i,frontmatter:n,scopedTo:ym(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:gm(r),disabledEnvironments:wm(r),scopedTo:ym(r),warnings:o})}function Em({skillFilePath:e,content:t,parsed:r}){const n="string"==typeof r.data?.description?Sm(r.data.description):"",o=of(r.data?.paths??r.data?.globs),s=_m(r);return new Rf.N({fullPath:e,content:t,description:n,globs:o??[],parseError:ud(n,s),environments:gm(r),disabledEnvironments:wm(r),scopedTo:ym(r),disableModelInvocation:s})}function xm({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 Rf.N({fullPath:e,parseError:t})}({skillFilePath:r,errorMessage:n}))}function Pm(e,t,r,n){if("error"in t)return e.realSkillFilePathsByFullPath.set(t.skillFilePath,t.realSkillFilePath),void xm({rules:e.rules,agentSkills:e.agentSkills,skillFilePath:t.skillFilePath,errorMessage:t.error});bm(t.parsed,r,n)||(e.realSkillFilePathsByFullPath.set(t.skillFilePath,t.realSkillFilePath),e.rules.push(Cm(t)),km(t.parsed)||e.agentSkills.push(Em(t)))}const Rm=(0,Us.debuglog)("cursor-rules-service");function Im(){return{rules:[],agentSkills:[],realSkillFilePathsByFullPath:new Map}}function Tm(e){return t=>(Rm("%s: %O",e,t),Im())}function Am(e,t){return Tf({kind:"agent-store",surface:e,roots:[...t].sort()})}function $m(e,t){const r=t.replace(/\\/g,"/").replace(/\/+$/,"");return""!==r&&e.replace(/\\/g,"/").startsWith(`${r}/`)}function Mm(e){let t;if(!0===e.frontmatter.alwaysApply)t={case:"global",value:new Gr.i9};else{const r=of(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:Sm(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 Dm{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=cm(t,(0,$.VI)(e.withName("MergedCursorRulesService.getAllCursorRules")),!1),n=this.cursorRulesServices.map((e=>e.getAllCursorRules(r.ctx).catch((e=>((0,Us.debuglog)("Failed to load cursor rules from service:",e),[])))));return am((await Promise.all(n)).flat(),this.getAgentStoreSkillsContext())}catch(e){t.error=e,t.hasError=!0}finally{lm(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()}),Dm.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()}}Dm.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 em(r,t,(0,o.homedir)(),i),this.ignoreService=c??new Sc(t,void 0,[this.rootDirectory]);const u=performance.now();if(this._rules=this.load(e,l).then((t=>{try{um.info(e,"LocalCursorRulesService load completed",{durationMs:Math.round(performance.now()-u),ruleCount:t.length})}catch{}return t})).catch((e=>((0,Us.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=cm(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{lm(t)}}))}}reload(e){this._rules=this.load(e).catch((e=>((0,Us.debuglog)("Failed to load cursor rules:",e),[])));for(const e of this.onChangeCallbacks)e()}static getRipwalkCache(){return Om.ripwalkCache??=new ga,Om.ripwalkCache}reloadAtPath(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=cm(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,Us.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{lm(r)}}isRuleMarkdownFile(e){return Kr(e)}async readRulesAtPath(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=cm(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 Ka(n.ctx,this.gitExecutor,e)||e,r=await this.loadCursorRulesRule(n.ctx,t);return r?[r]:[]}if(o.endsWith(".mdc"))return await Fm(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{lm(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=cm(r,(0,$.VI)(e.withName("LocalCursorRulesService.load")),!1);this.loadTraceId=n.span.spanContext().traceId;const o=(0,s.resolve)(this.rootDirectory),i=await Ka(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,vo.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=hm(e.dir)-hm(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)&&(dm(r.at(-1))||dm(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{lm(r)}}async loadCursorRulesRule(e,t){const r={stack:[],error:void 0,hasError:!1};try{cm(r,(0,$.VI)(e.withName("LocalCursorRulesService.loadCursorrules")),!1);try{const e=(0,s.join)(t,".cursorrules");if((await(0,vo.stat)(e)).isFile())return{filename:".cursorrules",path:e,frontmatter:{alwaysApply:!0},body:await Di(e)}}catch{}return null}catch(e){r.error=e,r.hasError=!0}finally{lm(r)}}async getAllCursorRules(e){const t={stack:[],error:void 0,hasError:!1};try{return cm(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{lm(t)}}toCursorRule(e){return Mm({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=cm(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{lm(r)}}async loadRulesFromMarkdownFile(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{cm(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,vo.stat)(e)).isFile()){const t=Jr({content:await Di(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{lm(n)}}async isCursorIgnored(e){try{const t=await vc((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=cm(r,(0,$.VI)(e.withName("LocalCursorRulesService.parseNestedRuleFiles")),!1),o=(await Promise.all(t.map((async e=>{try{const t=Xr(await Di(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{lm(r)}}async parseNestedMarkdownFiles(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=cm(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{lm(r)}}async loadRulesFromDirectory(e,t){return await async function(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=cm(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 Fm(r))}}catch{}return o.span.setAttribute("rules",i.length),i}catch(e){n.error=e,n.hasError=!0}finally{lm(n)}}(e,t,Om.getRipwalkCache())}async dirIsDirectory(e,t){const r={stack:[],error:void 0,hasError:!1};try{cm(r,(0,$.VI)(e.withName("LocalCursorRulesService.dirIsDirectory")),!1);try{return(await(0,vo.stat)(t)).isDirectory()}catch{return!1}}catch(e){r.error=e,r.hasError=!0}finally{lm(r)}}}async function Fm(e){try{const t=Xr(await Di(e));if(t)return[{filename:(0,s.basename)(e,".mdc"),path:e,frontmatter:t.frontmatter,rawFrontmatter:t.rawFrontmatter,body:t.body}]}catch{}return[]}class Nm{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=jf(r).dirPath,this.canvasKitSkillRootDir=void 0===h?void 0:Bf(r).dirPath,this.workspaceCatalogKey=Tf({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 em(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{um.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,Tm("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(!$f(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]))&&$f(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 Af(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=>Rf.N.fromJson(e,{ignoreUnknownFields:!0}))).filter((e=>r(e.fullPath))),realSkillFilePathsByFullPath:t}}catch(e){return void If("snapshot failed to decode: %O",e)}}(t)}catch(e){return void Rm("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 Af(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=>{Rm("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 zf(r,e))t.add(n.dirPath)}for(const r of Gf(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=Wf(e,t);return void 0!==r&&2===r.length&&r[0]===Uf&&"SKILL.md"===r[1]}(e,this.builtinSkillRootDir))return!0}return Lf(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=cm(t,(0,$.VI)(r.withName("AgentSkillsCursorRulesService.fileWatcher.subscribe")),!1);this.reloadAtPath(n.ctx,e)}catch(e){t.error=e,t.hasError=!0}finally{lm(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(Tm("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=cm(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=>$m(i,e))))return void(this.reloadRequestedDuringSeed=!0);if(this.getAgentStoreSkillRoots().some((e=>$m(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,vo.stat)(i)}catch{return r}return await this.loadAll(n.ctx)}let s;try{s=await(0,vo.realpath)(i)}catch{return await this.loadAll(n.ctx)}if(s!==o)return await this.loadAll(n.ctx);try{return Pm(r,{...await async function(e){const t=await Di(e);return{skillFilePath:e,content:t,parsed:Wd(t)}}(i),realSkillFilePath:s},this.surface,this.getEnabledSkills()),r}catch{return await this.loadAll(n.ctx)}})().catch(Tm("Failed to load Agent Skills at path"));this._loaded=c,this.notifyChanged()}catch(e){r.error=e,r.hasError=!0}finally{lm(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(Am(this.surface,e),r))}),(e=>{Rm("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(Am(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=Im(),r=(await Promise.all(e.map((e=>pm(e))))).flat().filter((e=>!Lf(e))),n=await Promise.all(r.map((e=>mm(e)))),o=new Set;for(const e of n)o.has(e.realSkillFilePath)||(o.add(e.realSkillFilePath),Pm(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=cm(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=>{Rm("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 pm(e)).filter((e=>!this.isIgnoredSkillPath(e)));return Promise.all(t.map((e=>mm(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),xm({rules:o,agentSkills:s,skillFilePath:t.skillFilePath,errorMessage:t.error});else{if(bm(t.parsed,this.surface,this.getEnabledSkills()))continue;i.set(t.skillFilePath,t.realSkillFilePath),o.push(Cm(t)),km(t.parsed)||s.push(Em(t))}const d=(await a).flatMap((e=>e?.skills??[])).filter((e=>!Lf(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=>mm(e))));for(const e of f)if("error"in e)i.set(e.skillFilePath,e.realSkillFilePath),xm({rules:o,agentSkills:s,skillFilePath:e.skillFilePath,errorMessage:e.error});else{if(bm(e.parsed,this.surface,this.getEnabledSkills()))continue;i.set(e.skillFilePath,e.realSkillFilePath),o.push(Cm(e)),km(e.parsed)||s.push(Em(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{lm(r)}}}function Lm(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:Sm(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 jm{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{um.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,Us.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=>(um.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=cm(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 Pf(e,(e=>e.skills))}(e),a=function(e){return Pf(e,(e=>e.rules))}(e);for(const e of[...r,...a])o.push(Lm(e));for(const t of e){const e=`plugin:${Mp(t.identifier)}`,r=Dp(t.identifier),n=Op(t.identifier),o=Fp(t.identifier),a=Np(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===Wd(c.content).data?.["disable-model-invocation"]}catch{}i.push(new Rf.N({fullPath:(0,s.join)(t.installPath,c.path),content:c.content,description:Sm(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{lm(r)}}}var Um=r("../proto/dist/generated/agent/v1/subagents_pb.js");const Bm=(0,Us.debuglog)("local-subagents");class Wm{async getAllSubagents(){return[]}async reload(){return[]}}function Hm(e){return"true"===(e??"").trim().toLowerCase()}function qm(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()?Um.b$.READONLY:Um.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 zm(e){const t=(0,s.extname)(e).toLowerCase();return".md"===t||".mdc"===t||".markdown"===t}function Gm(e){return(0,s.basename)(e,(0,s.extname)(e)).replace(/[\s_]+/g,"-")}async function Vm(e,t){return await rm({rootDir:e,includeFile:zm,containmentRootDir:t})}class Km{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=>(Bm("Failed to load subagents: %o",e),[])))}async getAllSubagents(){return this.subagents}async reload(){return this.subagents=this.load().catch((e=>(Bm("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 Vm(r,this.allowExternalAgentSymlinks?void 0:this.workspacePath);for(const r of e){const e=(0,s.basename)(r);try{if(!(await(0,vo.stat)(r)).isFile())continue}catch(e){Bm("Skipping subagent file %s due to stat error: %o",r,e);continue}try{const o=qm(await Di(r));if(!o)continue;t.push(new Um.zz({fullPath:r,name:o.name||Gm(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){Bm("Failed to parse subagent file %s: %o",r,e)}}}return t}}const Jm=new Set(["claude-code-tutor"]);class Zm{constructor(e){this.subagentsServices=e}async getAllSubagents(){const e=await Promise.all(this.subagentsServices.map((e=>e.getAllSubagents().catch((e=>(Bm("Failed to load subagents from merged service: %o",e),[])))))),t=new Map;for(const r of e)for(const e of r)Jm.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 Xm{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&&(Bm("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=Dp(n.identifier),o=Op(n.identifier),i=Fp(n.identifier),a=Np(n.identifier);for(const c of n.agents){const l=xf(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?Um.b$.READONLY:Um.b$.DEFAULT;t.push(new Um.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 Qm{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 Ym(e,t){return`${e}:${(0,mo.createHash)("sha256").update(t.toBinary()).digest("hex")}`}function eg(e){return new bo.q({max:e?.max??10,ttl:e?.ttl})}function tg(e,t,r=eg(t)){return{async execute(t,n,o){if(!o?.execId)return e.execute(t,n,o);const s=Ym(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 rg=r("../proto/dist/generated/agent/v1/computer_use_tool_pb.js");r("node:readline"),Error;var ng=r("node:timers/promises");const og=Gl.execFile;function sg(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,Vl.D9)(og,e,t.map(String),{...s,encoding:"utf8"},((e,t)=>{e?o(e):n(t)}))}))}rg.w3.UNSPECIFIED,rg.w3.LEFT,rg.w3.MIDDLE,rg.w3.RIGHT,rg.w3.BACK,rg.w3.FORWARD,rg.Dh.UNSPECIFIED,rg.Dh.UP,rg.Dh.DOWN,rg.Dh.LEFT,rg.Dh.RIGHT;const ig=(0,Us.promisify)(Gl.execFile);function ag(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 cg(e){const{stdout:t}=await(0,Vl.D9)(ig,"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:ag(r.width,r.height),resolutionString:`${r.width}x${r.height}`}}rg.w3.UNSPECIFIED,rg.w3.LEFT,rg.w3.MIDDLE,rg.w3.RIGHT,rg.w3.BACK,rg.w3.FORWARD,rg.Dh.UNSPECIFIED,rg.Dh.UP,rg.Dh.DOWN,rg.Dh.LEFT,rg.Dh.RIGHT;const lg={pattern:"[\\w-]{1,64}",next:e=>e},ug={pattern:"[0-9a-f-]{36}",next:()=>mo.randomUUID()},dg={pattern:"webp",next:()=>"webp"},hg={native:[ug,dg],agent:[lg,ug,dg],legacyNative:[ug,{pattern:"png",next:()=>"png"}]};new RegExp(`^(?:${Object.values(hg).map((e=>e.map((e=>e.pattern)).join("\\."))).join("|")})$`),new RegExp(`^${lg.pattern}$`),rg.Z8.NATIVE_X11,rg.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 pg=r("../proto/dist/runtime/compact.js");pg.HL;var fg=(0,pg.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 mg{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 gg={left_ptr:fg.ARROW,arrow:fg.ARROW,default:fg.ARROW,top_left_arrow:fg.ARROW,hand:fg.POINTER,hand1:fg.POINTER,hand2:fg.POINTER,pointer:fg.POINTER,pointing_hand:fg.POINTER,xterm:fg.TEXT,ibeam:fg.TEXT,text:fg.TEXT,watch:fg.WAIT,wait:fg.WAIT,progress:fg.WAIT,left_ptr_watch:fg.WAIT,crosshair:fg.CROSSHAIR,cross:fg.CROSSHAIR,tcross:fg.CROSSHAIR,move:fg.MOVE,fleur:fg.MOVE,size_all:fg.MOVE,sb_v_double_arrow:fg.RESIZE_NS,v_double_arrow:fg.RESIZE_NS,ns_resize:fg.RESIZE_NS,row_resize:fg.RESIZE_NS,top_side:fg.RESIZE_NS,bottom_side:fg.RESIZE_NS,sb_h_double_arrow:fg.RESIZE_EW,h_double_arrow:fg.RESIZE_EW,ew_resize:fg.RESIZE_EW,col_resize:fg.RESIZE_EW,left_side:fg.RESIZE_EW,right_side:fg.RESIZE_EW,top_left_corner:fg.RESIZE_NWSE,bottom_right_corner:fg.RESIZE_NWSE,nwse_resize:fg.RESIZE_NWSE,size_fdiag:fg.RESIZE_NWSE,top_right_corner:fg.RESIZE_NESW,bottom_left_corner:fg.RESIZE_NESW,nesw_resize:fg.RESIZE_NESW,size_bdiag:fg.RESIZE_NESW,not_allowed:fg.NOT_ALLOWED,no_drop:fg.NOT_ALLOWED,forbidden:fg.NOT_ALLOWED,circle:fg.NOT_ALLOWED,grab:fg.GRAB,openhand:fg.GRAB,grabbing:fg.GRABBING,closedhand:fg.GRABBING};class wg{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 mg(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=fg.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 sg("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 sg("xdotool",["getmouselocation","--shell"],{env:this.env})).match(/CURSOR=(\S+)/i);if(e){const t=e[1].toLowerCase();return gg[t]??fg.ARROW}try{const e=await sg("xprop",["-root","_XSERVER_CURSOR"],{env:this.env,timeoutMs:500});for(const[t,r]of Object.entries(gg))if(e.toLowerCase().includes(t))return r}catch{}return fg.ARROW}catch{return fg.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 yg=r("node:net");function vg(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 bg extends Error{constructor(e){super(e),this.name="MacRPCProtocolError"}}const Sg=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(),kg=je.object({data:je.string(),mimeType:je.string().min(1)}).strip(),_g=je.object({message:je.string(),screenshot:kg.optional(),screenshotBefore:kg.optional(),structuredContent:je.unknown().optional(),isError:je.boolean()}).strip(),Cg=je.object({accessibilityTrusted:je.boolean(),screenRecordingGranted:je.boolean()}).strip(),Eg=je.union([je.object({id:je.number().int(),result:_g,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:Cg,result:je.never().optional(),ok:je.never().optional(),error:je.never().optional(),errorCode:je.never().optional(),sessionId:je.never().optional()}).strip()]);function xg(e,t){try{return JSON.parse(e)}catch{throw new bg(`local-cua ${t} is not valid JSON`)}}const Pg={responseMaxBytes:33554432,parseServiceState(e){const t=Sg.safeParse(xg(e,"service state")),r=t.success?t.data.rpcSocketPath??t.data.appControlSocketPath:void 0;if(!t.success||void 0===r)throw new bg("local-cua service state is malformed");return{...t.data,rpcSocketPath:r}},parseResponse({line:e,expectedID:t}){const r=Eg.safeParse(xg(e.toString("utf8"),"RPC response"));if(!r.success)throw new bg("local-cua RPC response is malformed");if(void 0!==r.data.id&&null!==r.data.id&&r.data.id!==t)throw new bg("local-cua RPC response ID did not match");return r.data}};class Rg extends Error{constructor(e,t){super(e),this.name="MacComputerUseRPCError",this.code=t?.code,this.userFacing=!0===t?.userFacing,this.tool=t?.tool}}function Ig(e){return"object"==typeof e&&null!==e&&"code"in e&&"string"==typeof e.code?e.code:e instanceof Error?vg(e.message)?e.name:e.message.length>0?`${e.name}: ${e.message}`:e.name:"unknown"}const Tg=new Map([["co.anysphere.cursor-computer-use","cursor-computer-use"],["co.anysphere.cursor-computer-use.dev","cursor-computer-use-dev"]]),Ag=/^[A-Za-z0-9][A-Za-z0-9._-]*$/;class $g{constructor(e){this.mode=e}static isInstalled(){if((0,So.existsSync)($g.serviceExecutablePath()))return!0;let e;try{e=Pg.parseServiceState((0,So.readFileSync)($g.serviceStatePath(),"utf8"))}catch{return!1}return void 0===e.pid||$g.isProcessAlive(e.pid)}static async runningHelperPid(){const e=await $g.readServiceState(),t=e?.pid;return void 0!==t&&$g.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!==$g.protocolMajor&&void 0!==e.pid&&!$g.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;$g.throwIfAborted(e.signal);const t=(0,mo.randomUUID)(),r=await this.sendWithRelaunchRetry(e,(()=>({id:$g.requestID,method:"control/start",requestID:t,mode:this.mode})),"control/start");if(void 0!==r.error)throw $g.rpcError(r);if(void 0===r.sessionId)throw new Rg("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 $g.readServiceState();if(void 0===e)return;const r=await $g.sendOnce($g.socketPathFrom(e),{id:$g.requestID,method:"control/release",requestID:(0,mo.randomUUID)(),mode:this.mode,sessionId:t},$g.defaultCallTimeoutMs);if(void 0!==r.error)throw $g.rpcError(r)}catch(t){$g.logger.warn(e,"local-cua control release failed",{error:Ig(t)})}}}async callTool(e,t,r){$g.throwIfAborted(e.signal);const n=$g.defaultCallTimeoutMs,o=await this.sendWithRelaunchRetry(e,(()=>{const e=Date.now()/1e3,o=this.activeSessionId;return{id:$g.requestID,method:"tools/call",requestID:(0,mo.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 $g.rpcError(o,t);const s=o.result;if(void 0===s)throw new Rg(`local-cua tool ${t} returned no result`,{tool:t});if(s.isError){const e=s.message.trim();throw new Rg(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=$g.defaultCallTimeoutMs,o=await this.ensureSocketPath(e);$g.throwIfAborted(e.signal);try{return await $g.sendOnce(o,t(),n,e.signal)}catch(o){if(!$g.isPreDeliveryConnectionError(o))throw o;$g.logger.warn(e,"local-cua callTool failed; relaunching and retrying",{tool:r,error:$g.spawnErrorCode(o)});const s=await this.ensureSocketPath(e,!0);return $g.throwIfAborted(e.signal),void 0!==this.activeSessionId&&(this.activeSessionId=void 0,await this.startControl(e)),await $g.sendOnce(s,t(),n,e.signal)}}static rpcError(e,t){return new Rg(e.error,{code:e.errorCode,userFacing:!0,tool:t})}async ensureSocketPath(e,t=!1){if($g.throwIfAborted(e.signal),!t){const e=await $g.readServiceState();if(e&&!$g.isExitedIncompatibleHelper(e))return $g.socketPathFrom(e)}await this.launchAndWait(e);const r=await $g.readServiceState();if(!r)throw new Rg("local-cua sidecar did not publish service.json after launch");return $g.socketPathFrom(r)}static setLaunchGuard(e){$g.launchGuard=e}async launchAndWait(e){const t=$g.serviceAppPath(),r=$g.launchGuard,n=()=>this.launchAppAndWait(e,t);await(void 0===r?n():r(t,n,e.signal))}async launchAppAndWait(e,t){$g.logger.info(e,"launching local-cua sidecar",$g.sidecarLaunchLogFields(t)),"1"===process.env[$g.directLaunchEnv]?await $g.spawnSidecarProcess(e,$g.serviceExecutablePath(),[],{detached:!0}):await $g.spawnSidecarProcess(e,"/usr/bin/open",["-g",t]);const r=Date.now()+$g.launchReadyTimeoutMs;for(;Date.now()<r;){$g.throwIfAborted(e.signal);const t=await $g.readServiceState();if(t&&!$g.isExitedIncompatibleHelper(t)){const r=$g.socketPathFrom(t);try{if("ok"in await $g.sendOnce(r,{id:$g.requestID,method:"ping"},2e3,e.signal))return}catch{}}await(0,Dr.cb)($g.launchPollIntervalMs)}throw new Rg("local-cua sidecar did not become ready in time")}static isPreDeliveryConnectionError(e){const t=Ig(e);return"ENOENT"===t||"ECONNREFUSED"===t}static serviceStatePath(){return s.join($g.helperIdentity().appSupportDirectory,"service.json")}static serviceAppPath(){const e=process.env[$g.serviceAppOverrideEnv];return e&&e.length>0?e:s.join(o.homedir(),...$g.sharedInstallRelativePath,`${$g.serviceAppBundleName}.app`)}static helperIdentity(){const e=$g.serviceAppPath(),t=process.env[$g.appSupportOverrideEnv],r=`${e}\0${t??""}`,n=$g.identityCache;if(n?.key===r)return n.identity;const i=function(e){let t;try{t=(0,So.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&&Ag.test(r.trim())?r.trim():void 0};return{executableName:r("CFBundleExecutable"),bundleIdentifier:r("CFBundleIdentifier")}}(e),a=s.join(e,"Contents","MacOS",i.executableName??$g.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:Tg.get(i.bundleIdentifier))??$g.appSupportFolder)};return(0,So.existsSync)(a)&&($g.identityCache={key:r,identity:c}),c}static sidecarLaunchLogFields(e){const t=`${$g.serviceAppBundleName}.app`;return{appName:s.basename(e)===t?t:"custom",appPathHash:(0,mo.createHash)("sha256").update(e).digest("hex"),usingOverride:Boolean(process.env[$g.serviceAppOverrideEnv])}}static spawnErrorCode(e){return Ig(e)}static socketError(e){const t=Ig(e);return new Rg(`local-cua RPC connection failed: ${t}`,{code:t})}static serviceExecutablePath(){return $g.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 Rg(`local-cua sidecar launch failed: ${$g.spawnErrorCode(e)}`))};i.once("error",a),i.once("spawn",(()=>{i.removeListener("error",a),i.on("error",(t=>{$g.logger.warn(e,"local-cua sidecar process error after launch",{error:$g.spawnErrorCode(t)})})),i.unref(),o()}))}))}static async readServiceState(){try{const e=await(0,vo.readFile)($g.serviceStatePath(),"utf8");return Pg.parseServiceState(e)}catch(e){if(e instanceof Error&&"code"in e&&"ENOENT"===e.code)return;if(e instanceof bg)return;throw new Rg("local-cua service state could not be read")}}static socketPathFrom(e){if(void 0!==e.protocolMajor&&e.protocolMajor!==$g.protocolMajor)throw new Rg(`The running Cursor Computer Use speaks protocol ${e.protocolMajor}, and this Cursor CLI speaks protocol ${$g.protocolMajor}. Update the Cursor CLI.`,{userFacing:!0});return e.rpcSocketPath}static abortError(e){return e.reason instanceof Error?e.reason:new Rg("local-cua RPC aborted")}static throwIfAborted(e){if(e.aborted)throw $g.abortError(e)}static sendOnce(e,t,r,n){return n?.aborted?Promise.reject($g.abortError(n)):new Promise(((o,s)=>{let i=!1,a=[],c=0,l=!1;const u=(0,yg.createConnection)({path:e}),d=e=>{i||(i=!0,clearTimeout(p),n?.removeEventListener("abort",h),u.destroy(),e())},h=()=>{d((()=>s(void 0===n?new Rg("local-cua RPC aborted"):$g.abortError(n))))},p=setTimeout((()=>{d((()=>s(new Rg(`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($g.socketError(e))))}))})),u.on("data",(e=>{const t=e.indexOf(10),r=c+(t<0?e.length:t);if(r>Pg.responseMaxBytes)return void d((()=>s(new Rg("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=Pg.parseResponse({line:n,expectedID:$g.requestID});d((()=>o(e)))}catch(e){d((()=>s(e)))}})),u.on("error",(e=>{d(l?()=>s(new Rg("local-cua RPC connection failed after request delivery")):()=>s($g.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 Rg(e))))})))}))}}let Mg;function Dg(){if(void 0===Mg){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 Mg===e&&(Mg=void 0),t}));Mg=e}return Mg}$g.logger=(0,l.h)("local-cua:rpc"),$g.serviceAppBundleName="Cursor Computer Use",$g.appSupportFolder="cursor-computer-use",$g.productionExecutableName="CUCursorService",$g.sharedInstallRelativePath=[".cursor","computer-use-sidecar"],$g.appSupportOverrideEnv="CUA_APP_SUPPORT_DIR",$g.serviceAppOverrideEnv="CUA_SERVICE_APP",$g.directLaunchEnv="CUA_DIRECT_LAUNCH",$g.protocolMajor=1,$g.defaultCallTimeoutMs=45e3,$g.launchReadyTimeoutMs=8e3,$g.launchPollIntervalMs=200,$g.requestID=1;var Og=r("node:module");const Fg="mac-webp-runtime.cjs";function Ng(e){return"function"==typeof e}function Lg(e){return"object"==typeof e&&null!==e&&"getFileName"in e&&"function"==typeof e.getFileName}function jg(){const e=(new Error).stack;return Array.isArray(e)?e.filter(Lg):[]}let Ug,Bg;function Wg(){return Ug??=(()=>{const e=Error.prepareStackTrace;try{Error.prepareStackTrace=(e,t)=>t;const e=jg()[0]?.getFileName();return function(){const e=Og;if("createRequire"in e&&Ng(e.createRequire))return e.createRequire;if("default"in e&&"object"==typeof e.default&&null!==e.default&&"createRequire"in e.default&&Ng(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}})(),Ug}function Hg(){const e=globalThis.__MAC_WEBP_IMPORT__;return"function"==typeof e?t=>Promise.resolve(e(t)):(Bg??=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 jg()){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,pd.fileURLToPath)(n):n);r((0,s.join)(t,Fg)),r((0,s.join)(t,"..","..","src","computer-use",Fg))}var n;"string"==typeof process.argv[1]&&process.argv[1].length>0&&r((0,s.join)((0,s.dirname)(process.argv[1]),Fg)),r((0,s.join)(process.cwd(),"src","computer-use",Fg)),r((0,s.join)(process.cwd(),"computer-use",Fg));try{const e=(0,s.dirname)(Wg().resolve("@anysphere/local-exec/package.json"));r((0,s.join)(e,"src","computer-use",Fg)),r((0,s.join)(e,"dist","computer-use",Fg))}catch{}for(const t of e)try{const e=Wg()(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")}(),Bg)}function qg(...e){return t=["@jsquash","webp",...e].join("/"),Wg().resolve(t);var t}async function zg(...e){var t;return await(t=(0,pd.pathToFileURL)(qg(...e)).href,Hg()(t))}const Gg=e=>{let t;return()=>{if(void 0===t){const r=e();r.catch((()=>{t===r&&(t=void 0)})),t=r}return t}},Vg=(Gg((async()=>{const e=await zg("decode.js");return await e.init({wasmBinary:await So.promises.readFile(qg("codec","dec","webp_dec.wasm"))}),e})),Gg((async()=>{const[e,t,r]=await Promise.all([zg("utils.js"),zg("meta.js"),zg("codec","enc","webp_enc.js")]);return{module:await e.initEmscriptenModule(r.default,void 0,{wasmBinary:await So.promises.readFile(qg("codec","enc","webp_enc.wasm"))}),defaultOptions:t.defaultOptions}}))),Kg="image/png",Jg={async normalize(e){if(e.mimeType!==Kg)throw new Error(`Mac screenshot must be ${Kg}, received ${e.mimeType}`);const t=await Dg(),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 Vg(),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}},Zg={userFacing:function(e){if(e instanceof Rg&&e.userFacing&&e.message.trim().length>0&&!vg(e.message))return e.message.trim()},isCaptureBlocked:function(e){return e instanceof Rg&&("computer_use_screenshot"===e.tool||"permission_required"===e.code)}},Xg=new Set(["keys"]),Qg=new Set(["matched","mismatch","unchecked"]),Yg=new Set(["no_text","password","control_keys","too_long","unreadable","moved","chromium","gecko"]),ew=new Set(["matched"]),tw=new Set(["too_long"]),rw=new Set(["watched","fell_back","unavailable","over_budget"]);class nw{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??Zg,this.reportTyping=!0===o}async execute(){const e=this.actions.some((e=>nw.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:nw.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:nw.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:nw.mouseButtonName(t.value.button),action:"down"}));break;case"mouseUp":this.recordActuation(await this.sidecar.mouseButton(this.ctx,{button:nw.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:nw.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===rg.EB.DOWN||t.value.stroke===rg.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 rg.ks({result:{case:"success",value:new rg.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=nw.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=nw.cursorFromResult(e)??nw.coordinateFromPoint(t)??this.cursor}recordTyping(e){if(!this.reportTyping)return;const t=e.message.trim();""!==t&&this.typingNotes.push(t);const r=nw.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",Qg),a=o("unchecked",Yg),c=void 0!==n.get("unchecked")&&null!==n.get("unchecked"),l=void 0!==i&&ew.has(i)&&!c||"unchecked"===i&&void 0!==a&&tw.has(a);return new rg.qA({method:o("method",Xg)??"",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",rw)})}async errorResult(e){let t;if(nw.logger.error(this.ctx,"local-cua execute failed",void 0,{error:Ig(e)}),!this.errors.isCaptureBlocked(e))try{const e=await this.sidecar.screenshot(this.ctx);t=(await this.normalizeScreenshot(e.screenshot,"error")).data}catch(e){nw.logger.warn(this.ctx,"local-cua error screenshot capture failed",{error:Ig(e)})}const r=this.errors.userFacing(e);return new rg.ks({result:{case:"error",value:new rg.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 rg.ks({result:{case:"error",value:new rg.Jb({error:"Screenshot unavailable",actionCount:this.actionCount,durationMs:Date.now()-this.startTime,log:e})}})}abortedResult(){return new rg.ks({result:{case:"error",value:new rg.Jb({error:"Computer use aborted",actionCount:this.actionCount,durationMs:Date.now()-this.startTime,log:this.log(),typing:this.typing})}})}static mouseButtonName(e){return nw.mouseButtonNames[e]??"left"}static scrollDirectionName(e){return nw.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 Jg.normalize(e),failed:!1}}catch(r){const n=Ig(r);return nw.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 rg.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 rg.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()}))}}nw.logger=(0,l.h)("local-cua:actions"),nw.mouseButtonNames={[rg.w3.UNSPECIFIED]:"left",[rg.w3.LEFT]:"left",[rg.w3.RIGHT]:"right",[rg.w3.MIDDLE]:"middle",[rg.w3.BACK]:"left",[rg.w3.FORWARD]:"left"},nw.scrollDirectionNames={[rg.Dh.UNSPECIFIED]:"down",[rg.Dh.UP]:"up",[rg.Dh.DOWN]:"down",[rg.Dh.LEFT]:"left",[rg.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 ow,sw=r("../proto/dist/generated/agent/v1/delete_exec_pb.js");function iw({encoding:e,bom:t,lineEnding:r}){return{encoding:e,bom:t,lineEnding:r}}class aw{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,vo.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 Ni(e,t,r,n);await(0,vo.writeFile)(e,o),await Fi(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"}(ow||(ow={}));var cw=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 lw{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 sw.Pi({result:{case:"error",value:new sw.GU({path:n,error:Jo})}});const o=(0,Ko.o1)(n,this.workspacePath),i=await this.permissionsService.shouldBlockWrite(e,o,"");if(i){const e=await Uu(i,{onNeedsApproval:async(e,t)=>null,onUserRejected:e=>new sw.Pi({result:{case:"rejected",value:new sw.iq({path:o,reason:e||""})}}),onPermissionDenied:(e,t)=>new sw.Pi({result:{case:"permissionDenied",value:new sw.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,vo.realpath)((0,s.dirname)(e)).catch((()=>{}));if(void 0===r)return e;if(void 0!==t){const n=await(0,vo.realpath)(t).catch((()=>{}));if(void 0!==n&&(0,Ko.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:ow.Delete,details:{path:a},toolCallId:t.toolCallId});if(!c.approved)return new sw.Pi({result:{case:"rejected",value:new sw.iq({path:o,reason:c.reason||""})}});let l;try{l=await(0,vo.stat)(o)}catch(e){return"ENOENT"===gc(e)?new sw.Pi({result:{case:"fileNotFound",value:new sw.n0({path:o})}}):new sw.Pi({result:{case:"error",value:new sw.GU({path:o,error:wc(e)})}})}if(!l.isFile()){const e=l.isDirectory()?"directory":"other";return new sw.Pi({result:{case:"notFile",value:new sw.LX({path:o,actualType:e})}})}const u=l.size;let d,h;if(u<=Qo)try{const e=await Oi(o);d=e.text,h=iw(e)}catch{}const p=d??"",f=await(0,vo.realpath)(o).catch((()=>o)),m=await(0,vo.stat)(o).catch((()=>{}));if(m?.dev!==l.dev||m.ino!==l.ino)return new sw.Pi({result:{case:"error",value:new sw.GU({path:o,error:"File changed while deleting; nothing was removed"})}});e.signal.throwIfAborted();try{await(0,vo.unlink)(o),this.agentFileViews?.recordDelete(o)}catch(e){return"EACCES"===gc(e)?new sw.Pi({result:{case:"permissionDenied",value:new sw.QG({path:o,clientVisibleError:"Permission denied"})}}):"EBUSY"===gc(e)?new sw.Pi({result:{case:"fileBusy",value:new sw.vX({path:o})}}):new sw.Pi({result:{case:"error",value:new sw.GU({path:o,error:wc(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 sw.Pi({result:{case:"success",value:new sw.fl({path:o,deletedFile:o,fileSize:BigInt(u),prevContent:p})}})}catch(e){r.error=e,r.hasError=!0}finally{cw(r)}}}class uw{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===Wn));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:Wn,serverName:Wn,instructions:`User-defined tools for this session (server "${Wn}"). 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 dw extends uw{constructor(e,t){super(e,t),this.observableInner=e}onDidChange(e){return this.observableInner.onDidChange(e)}}var hw=r("../proto/dist/generated/agent/v1/fetch_exec_pb.js"),pw=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 fw=/;\s*charset\s*=\s*"?([^";\s]+)/i;class mw{constructor(e){this.encodingSlices=e?.encodingSlices}async readText(e,t){if(!Rl(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=fw.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{Bl(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 hw.uN({result:{case:"success",value:new hw.Uk({url:n,content:r,statusCode:t.status,contentType:o})}})}catch(e){return new hw.uN({result:{case:"error",value:new hw.fk({url:n,error:wc(e)})}})}}catch(e){r.error=e,r.hasError=!0}finally{pw(r)}}}const gw=[["safe.bareRepository","explicit"]],ww=[["core.fsmonitor","false"],["core.hooksPath",o.devNull],["core.attributesFile",o.devNull]],yw=[["core.quotePath","false"]];function vw(e){const t="allow-hooks"===e?ww.filter((([e])=>"core.hooksPath"!==e)):ww;return[...gw,...t]}const bw=(0,Us.promisify)(Gl.execFile),Sw=new Set(["-c","-C","--git-dir","--work-tree","--namespace","--super-prefix","--config-env","--attr-source"]),kw=new Set(["diff","show","blame","log","whatchanged"]);function _w(e){for(let t=0;t<e.length;t++){const r=e[t];if(Sw.has(r))t++;else if(!r.startsWith("-"))return t}return-1}function Cw(e){const t=_w(e);return-1===t?void 0:e[t]}function Ew(e){const t=_w(e);if(-1===t||!kw.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 xw(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,[...vw(e.repoConfigExecution??"block"),...yw])}({command:Cw(e),optionsEnv:t})}async function Pw(e,t,r){const{env:n,encoding:o="utf8",...s}=r??{},i=Ew(t),a=await bw(e,i,{...s,encoding:o,env:xw(i,n)});return{stdout:a.stdout,stderr:a.stderr}}class Rw extends Error{constructor(e,t){super(`git did not run: repository config refused (${e})`),this.name="GitRepoConfigRefusedError",this.reason=e,this.exitCode=t}}const Iw=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]]]),Tw=["recurse-submodules","submodule","remerge-diff","diff-merges","alternate-refs"],Aw=/^[A-Za-z0-9][A-Za-z0-9_-]*$/,$w=/^filter\.(.*)\.(?:clean|smudge|process)$/s,Mw=new Set(["system","global","command"]),Dw={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 Ow(e){return e.flatMap((([e,t])=>["-c",`${e}=${t}`]))}const Fw=Ow([...vw("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 Nw(e){const t=e?.timeout??0,r=Number.isFinite(t)&&t>0?Math.min(t,2147483647):6e4;return performance.now()+r}function Lw(e,t=2147483647){return Math.max(1,Math.ceil(Math.min(t,e-performance.now())))}function jw(){const e=new Map;return{async exec(t,r,n){const o=Nw(n);return Pw("git",await Uw(e,t,r,o),{cwd:t,env:Dw,windowsHide:!0,killSignal:"SIGTERM",timeout:Lw(o)})},async run(t,r,n){const o=Nw(n);return function(e,t,r,n){return new Promise(((o,s)=>{const i=function(e,t,r){const{env:n,...o}=r??{},s=Ew(t);return(0,Gl.spawn)("git",s,{...o,env:xw(s,n)})}(0,t,{cwd:e,env:Dw,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"})))}),Lw(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 Uw(e,t,r,o),o,n?.input)}}}async function Uw(e,t,r,n){const{prefix:o,tail:s,readsConfig:i}=function(e){const t=Ew(e),r=_w(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=Iw.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=[...Tw,..."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),...Fw],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 Pw("git",[...t,"config","--list","--show-scope","--includes","-z"],{cwd:e,env:Dw,windowsHide:!0,killSignal:"SIGTERM",timeout:Lw(r,1e4),maxBuffer:16777216})).stdout}catch(e){throw function(e){if(!(e instanceof Error))return new Rw("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 Rw("timed-out");const t="code"in e&&"number"==typeof e.code?e.code:void 0;return new Rw("read-failed",t)}(e)}if(performance.now()>=r)throw new Rw("timed-out");return function(e){if(""===e)return[];const t=e.split("\0");if(""!==t.pop()||t.length%2!=0)throw new Rw("read-failed");const r=new Set;for(let e=0;e<t.length;e+=2){if(Mw.has(t[e]))continue;const n=t[e+1].split("\n",1)[0],o=$w.exec(n)?.[1];if(void 0!==o){if(!Aw.test(o))throw new Rw("unpinnable");r.add(o)}else(n.startsWith("lfs.extension.")||"lfs.storage"===n)&&r.add("lfs")}return[...r].sort().flatMap((e=>Ow([[`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 Bw(e,t,r){return jw().exec(e,t,r)}var Ww=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 Hw{constructor(e={}){void 0!==e.guardedRootLookup&&(this.guardedRootLookup=e.guardedRootLookup)}async exec(e,t,r,n){return qw(e,t,r,n,Bw)}forRequest(){const e=jw();return{exec:(t,r,n,o)=>qw(t,r,n,o,((t,r,n)=>e.exec(t,r,n))),...void 0===this.guardedRootLookup?{}:{guardedRootLookup:this.guardedRootLookup}}}}async function qw(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{Ww(s)}}var zw=r("../proto/dist/generated/agent/v1/grep_exec_pb.js");class Gw{constructor(){this.lineEnd=0,this.nextStart=0}}function Vw(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 Kw(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 Jw=-(2**31),Zw=2**31-1;function Xw(e){return Number.isNaN(e)?0:e<Jw?Jw:e>Zw?Zw:e}function Qw(e){if("number"==typeof e&&Number.isFinite(e)&&!(e<0))return Xw(Math.trunc(e))}function Yw(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 ey(e,t){const r=Yw(t),n=(0,s.join)(e,"mcps",r,"tools");let o;try{o=await(0,vo.readdir)(n)}catch(e){if("ENOENT"===gc(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,vo.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 ty=(0,l.h)("local-exec:mcp-disk-freshness-on-access"),ry="/mcps/",ny=(0,u.Pu)("mcp.discovery_freshness.check",{description:"MCP discovery surface freshness comparison outcome against canonical live tools",labelNames:["surface","outcome"]}),oy=(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"]}),sy=(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"]}),iy=(0,u.v5)("mcp.discovery_freshness.symmetric_difference",{description:"Total symmetric difference between canonical live tools and the observed discovery surface",labelNames:["surface"]}),ay=new Map;function cy(e){const t=e.replace(/\\/g,"/");return t.endsWith("/mcps")?`${t}/`:t}async function ly({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 ty.warn(e,"mcp_disk_state_read_failed",{error_type:t instanceof Error?t.name:typeof t})}const a=i.servers.find((e=>Yw(e.serverIdentifier)===n));if(void 0===a)return;let c;try{c=await o(r,a.serverIdentifier)}catch(t){return void ty.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"};ny.increment(e,1,{...l,outcome:c}),oy.histogram(e,i.length,l),sy.histogram(e,a.length,l),iy.histogram(e,i.length+a.length,l),"mismatch"===c&&ty.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 uy(e,t,r,n=ey){if(void 0===r||(void 0===(o=r)||!cy(o).includes(ry)))return;var o;const s=function(e){const t=cy(e),r=t.indexOf(ry);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=ay.get(i);void 0!==l&&clearTimeout(l);const u=e,d=setTimeout((()=>{ay.delete(i),(async()=>{if(c){const e=await t.getState(u);for(const r of e.servers){const o=Yw(r.serverIdentifier);await ly({ctx:u,mcpStateAccessor:t,projectDir:s.projectDir,sanitizedServerFolder:o,readDiskCatalog:n,state:e})}}else void 0!==a&&await ly({ctx:u,mcpStateAccessor:t,projectDir:s.projectDir,sanitizedServerFolder:a,readDiskCatalog:n})})().catch((e=>{ty.warn(u,"mcp_disk_discovery_freshness_schedule_failed",{error_type:e instanceof Error?e.name:typeof e})}))}),2e3);ay.set(i,d)}async function dy(e){try{return(await(0,vo.stat)(e,{bigint:!0})).mtimeNs}catch{return}}function hy(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 py(e,t,r=dy){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:hy(n,o,s.sep).map((({item:e})=>e)),statTimedOut:!1}}var fy=r("../proto/dist/generated/agent/v1/read_exec_pb.js");const my=Buffer.from([137,80,78,71,13,10,26,10]),gy=Buffer.from([0,0,0,0,73,69,78,68,174,66,96,130]),wy=e=>{if(e.length<my.length+25+gy.length||!e.subarray(0,my.length).equals(my)||13!==e.readUInt32BE(8)||"IHDR"!==e.toString("ascii",12,16)||!(e=>e.subarray(e.length-gy.length).equals(gy)||(e=>{let t=my.length+25;for(;t+gy.length<=e.length;){const r=e.readUInt32BE(t);if(r>e.length-t-gy.length)return!1;if("IEND"===e.toString("ascii",t+4,t+8))return e.subarray(t,t+gy.length).equals(gy);t+=gy.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)}},yy=e=>1===e||e>=208&&e<=216,vy=e=>192===e||193===e||194===e,by=e=>e>=195&&e<=207&&196!==e&&200!==e&&204!==e,Sy=e=>0===e||e>=208&&e<=215,ky=(e,t)=>{let r=e.indexOf(255,t);for(;-1!==r&&r+1<e.length;){const t=e[r+1];if(255!==t){if(!Sy(t))return r;r=e.indexOf(255,r+2)}else r+=1}},_y=e=>(e=>{const t=wy(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(yy(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=ky(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(yy(r)){t+=2;continue}if(218===r||217===r||by(r))return;const n=e.readUInt16BE(t+2);if(n<2)return;if(vy(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),Cy=(e,t)=>({width:Math.max(e?.width??0,t.width),height:Math.max(e?.height??0,t.height)}),Ey=(e,t)=>{for(;t<e.length&&0!==e[t];)t+=1+e[t];return t+1},xy=e=>{const t=e.toString("latin1",0,6);return e.subarray(0,my.length).equals(my)?"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},Py={0:1,2:3,4:2,6:4},Ry=async({data:e,width:t,height:r})=>{const n=Iy(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=bp.Readable.from(n.idat).pipe((0,kp.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;Ty({filter:d,row:u,previous:l,bytesPerPixel:n.channels}),Ay({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||$y({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},Iy=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=Py[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}},Ty=({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}`)}}},Ay=({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]]++}},$y=({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)},My={0:1,2:3,3:1,4:2,6:4},Dy=[1,2,4,8,16],Oy=[[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]],Fy=async e=>{const t=Ny(e);if(void 0===t)return;const r=Ly(t);let n=0;const o=bp.Readable.from(t.idat).pipe((0,kp.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=My[i[9]];if(void 0===e||!Dy.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}},Ly=({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?Oy.reduce(((r,[n,s,i,a])=>r+o(Math.ceil((e-n)/i),Math.ceil((t-s)/a))),0):o(e,t)};const jy=()=>{throw new Error("webp codec not registered: registerWebpCodec() must be called by a Node server before decoding/encoding webp")},Uy=e=>e.length>=12&&"RIFF"===e.toString("ascii",0,4)&&"WEBP"===e.toString("ascii",8,12),By=e=>{if(!Uy(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)}}},Wy=e=>jy().decode(e);async function Hy(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);_y(e.data);return e.resizeWithoutBudget(e.data)}const qy=[{width:1280,height:800},{width:1456,height:840}],zy=e=>void 0!==e&&qy.some((t=>t.width===e.width&&t.height===e.height)),Gy=1048576,Vy=e=>{const t=e.buffer;return t instanceof ArrayBuffer?new Uint8Array(t,e.byteOffset,e.byteLength):Uint8Array.from(e)};function Ky(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 Jy=(e,t,r=1024)=>Ky(e,t,r),Zy=(e,t)=>zy({width:e,height:t})?{width:e,height:t,needsResize:!1}:Ky(e,t),Xy=(e,t,r)=>{e.resize({w:t,h:r})};function Qy(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 Yy=(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:Qy(((e,t)=>{switch(t){case"png":return(e=>{let t,r=my.length;for(;r+16<=e.length;)"IHDR"===e.toString("ascii",r+4,r+8)&&(t=Cy(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 Cy(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=Ey(e,n+2);else{if(33!==e[n]||255!==e[n+1])break;r=11===e[n+2]?Ey(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))}},ev=e=>{const{width:t,height:r}=Jy(e.width,e.height,1280);return{width:t,height:r}},tv=async(e,t)=>{let{width:r,height:n}=e,o=await t({width:r,height:n});for(;o.length>Gy&&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:Vy(o),mimeType:"image/webp",reencoded:!0}},rv=async(e,t)=>{const r=(await Dg()).fromBitmap({data:Buffer.from(e.data),width:e.width,height:e.height});return tv(t,(async e=>(r.bitmap.width===e.width&&r.bitmap.height===e.height||Xy(r,e.width,e.height),(e=>jy().encode(e))({data:r.bitmap.data,width:r.bitmap.width,height:r.bitmap.height}))))};let nv;const ov=async(e,t)=>{if(void 0!==t?.pngByteBudgetBytes){const{pngByteBudgetBytes:r,...n}=t,o=_y(e);return"image/png"===o?.mimeType&&zy(o)&&await Fy(e),Hy({data:e,budgetBytes:r,maxImageBytes:Gy,fitImage:Zy,resizeWithoutBudget:e=>ov(e,n)})}const r=await(async(e,t)=>{const r=Uy(e);if(r&&!0===t?.preserveWebpDimensions)return;const n=r?void 0:_y(e),o=r?By(e):n;if(void 0===o||!zy(o))return;const s=nv;if(void 0!==n&&void 0!==s&&!zy(await s.readOrientedDimensions(e)))return;const i="image/png"===n?.mimeType;if(i&&await Fy(e),e.length<=Gy)return{data:Vy(e),mimeType:n?.mimeType??"image/webp"};const a=s?.resizeWebp;if(void 0!==a)return tv(o,(t=>a({data:e,...t})))})(e,t);if(void 0!==r)return r;if(Uy(e))return(async(e,t)=>{const r=By(e);if(!0===t?.preserveWebpDimensions&&void 0!==r)return{data:Vy(e),mimeType:"image/webp"};if(void 0!==r&&!Jy(r.width,r.height,1280).needsResize&&e.length<=Gy)return{data:Vy(e),mimeType:"image/webp"};if("passthrough"===t?.webpWithoutCodec)return{data:Vy(e),mimeType:"image/webp"};Qy(r);const n=undefined;if(void 0!==n)return tv(ev(r),(t=>n({data:e,...t})));const o=await Wy(e);return rv(o,ev(o))})(e,t);const n=_y(e);if(void 0!==n&&e.length<=Gy&&!Jy(n.width,n.height).needsResize)return{data:Vy(e),mimeType:n.mimeType};const o=xy(e);void 0!==o&&Yy(e,o);const s=void 0===n?void 0:Jy(n.width,n.height),i="image/png"===n?.mimeType&&!0===s?.needsResize?await Ry({data:e,width:s.width,height:s.height}).catch((()=>{})):void 0;void 0===i&&"png"===o&&await Fy(e);const a=await Dg(),c=void 0===i?await a.read(e):a.fromBitmap(i),l=(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"}})(c),u=!0===t?.convertUnsupportedModelFormatsToPng&&"image/png"!==l&&"image/jpeg"!==l?"image/png":l,{width:d,height:h,needsResize:p}=Jy(c.width,c.height);if(void 0===i&&!p&&e.length<=Gy&&u===l)return{data:Vy(e),mimeType:l};let f=d,m=h;p&&Xy(c,f,m);let g=await c.getBuffer(u);for(;g.length>Gy&&f>8&&m>8;)f=Math.max(8,Math.round(.8*f)),m=Math.max(8,Math.round(.8*m)),Xy(c,f,m),g=await c.getBuffer(u);return{data:Vy(g),mimeType:u,reencoded:!0}},sv=async e=>{const t=Buffer.from(e.buffer,e.byteOffset,e.byteLength),r=xy(t);let n;if(Uy(t))return{kind:"unchecked"};if(void 0===r)return{kind:"unchecked"};{Yy(t,r);const e=await Dg();n=async()=>("png"===r&&await Fy(t),e.read(t))}try{return await n(),{kind:"decodes"}}catch(e){return{kind:"undecodable",reason:e instanceof Error?e.message:String(e)}}},iv=BigInt(0),av=BigInt(8),cv=BigInt(16),lv=BigInt(65535);function uv(e){const t=e.trim().toLowerCase();return t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t}function dv(e){const t=e.split(".");if(4!==t.length)return;let r=iv;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<<av|BigInt(t)}return{version:4,value:r}}function hv(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=dv(n);if(!o)return;t.push(Number(o.value>>cv&lv)),t.push(Number(o.value&lv))}else{if(!/^[0-9a-f]{1,4}$/i.test(n))return;t.push(Number.parseInt(n,16))}}return t}function pv(e){return dv(e)??function(e){const t=uv(e);if(0===t.length||t.includes(":::"))return;const r=t.indexOf("::");if(-1===r){const e=hv(t);if(!e||8!==e.length)return;return{version:6,value:e.reduce(((e,t)=>e<<cv|BigInt(t)),iv)}}if(-1!==t.indexOf("::",r+1))return;const n=t.slice(0,r),o=t.slice(r+2),s=hv(n),i=hv(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<<cv|BigInt(t)),iv)}}(e)}function fv(e,t){const r=uv(e),n=uv(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=pv(t.slice(0,r)),o=pv(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 mv(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=>fv(e,t)))}(r.hostname,t)}var gv=r("../constants/dist/commercial-cursor-hosts.js");new Set([1,2]);const wv="cursor/requiresConfirmation",yv="https://grok.com/connectors-oauth-exchange-code/",vv="https://x.com/i/connectors/oauth_callback",bv="https://chat.x.com/connectors/oauth_callback",Sv="https://lite.x.com/i/connectors/oauth_callback",kv={provider:"google-workspace",clientRegistration:"static",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!0,authorizationParams:{access_type:"offline",prompt:"select_account consent"}},_v={provider:"x-money",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0,registeredAppRedirectUris:[yv,vv]},Cv="x-cursor-auth";function Ev(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 xv="https://mcp.shop.com",Pv={provider:"grok-connectors",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,scopes:["grok-plugins:access","offline_access"]},Rv=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/}]]),Iv=new Map([["gmailmcp.googleapis.com",{...kv,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",{...kv,scopes:["https://www.googleapis.com/auth/drive.readonly","https://www.googleapis.com/auth/drive.file"]}],["calendarmcp.googleapis.com",{...kv,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",{...kv,scopes:["https://www.googleapis.com/auth/documents"]}],["sheetsmcp.googleapis.com",{...kv,scopes:["https://www.googleapis.com/auth/spreadsheets"]}],["slidesmcp.googleapis.com",{...kv,scopes:["https://www.googleapis.com/auth/presentations"]}],["bigquery.googleapis.com",{...kv,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",_v],["mcp.money-staging.x.com",_v],["mcp.money.x.com",_v],["connectors-gateway.grok.gcp.mouseion.dev",Pv],["connectors-gateway.grok.com",Pv],["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:xv}}],["api.elections.kalshi.com",{provider:"kalshi",clientRegistration:"dynamic",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!0}],["mcp.squarespace.com",{provider:"squarespace",clientRegistration:"dynamic",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!0}]]),Tv=[".databricks.com",".azuredatabricks.net"];const Av=/^\/sncapps\/mcp-server\/mcp\/[^/]+$/,$v={provider:"databricks",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,requiresHostedCallback:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0,scopes:["ai-gateway","offline_access"],pinsScopesOverConfiguredScopes:!0},Mv={provider:"servicenow",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,unauthenticatedEndpointBlocked:!0,backendOnlyTokenExchange:!0,ownMcpJsonClientMayExchange:!0};function Dv(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("."))&&Tv.some((e=>t.endsWith(e)&&t.length>e.length))}(e.hostname)&&"/ai-gateway/mcp-services/system.ai.genie_one_mcp"===e.pathname.replace(/\/+$/,"")}(t)?$v:function(e){return"https:"===e.protocol&&""===e.port&&""===e.username&&""===e.password&&Av.test(e.pathname.replace(/\/+$/,""))}(t)?Mv:(r=t.hostname,Iv.get(r.toLowerCase()));var r}function Ov(e){return e.endsWith("/")?e:`${e}/`}async function Fv(e,t){if(void 0===t)return;const r=new URL(e),n=new URL(t);if(r.origin!==n.origin||!Ov(r.pathname).startsWith(Ov(n.pathname)))throw new Error(`Protected resource ${t} does not match expected ${r.href} (or origin)`);return n}const Nv=/^\/shops\/[A-Za-z0-9-]+\/mcp$/;function Lv(e){if(void 0!==e)try{return new URL(e)}catch{return}}async function jv(e,t){if(void 0===t)return;const r=new URL(e),n=Lv(t);if(void 0===n||n.origin!==r.origin||n.pathname!==r.pathname&&!Nv.test(n.pathname))throw new Error(`Protected resource ${t} does not match expected ${r.href} (or origin)`);return n}function Uv(e){const t=Lv(e);return void 0===t?void 0:Rv.get(t.hostname.toLowerCase())}const Bv=new Set([...Iv].filter((([,e])=>"google-workspace"===e.provider)).map((([e])=>e))),Wv="https://www.cursor.com/bot/mcp/oauth/callback",Hv={portal:"https://www.cursor.com/agents/mcp/oauth/callback",grokBotBounce:Wv},qv="tailnet_";new Set([`${qv}waiting_for_approval`,`${qv}tailnet_locked`,`${qv}joining`]);const zv="grokbot://mcp/oauth/callback",Gv="http://localhost:8787/callback",Vv="gb";function Kv(e){const t=new URL(Gv);return t.port=String(e),t.toString()}function Jv(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 Zv(e){const t=e.redirectUrl??Gv;if(!0!==e.loopbackIpv4||!Jv(t))return t;const r=new URL(t);return r.hostname="127.0.0.1",r.toString()}function Xv(e,t=Hv){const r=new Set,n=void 0!==e&&Jv(e);return e&&!n&&r.add(e),r.add(t.portal),e===zv&&r.add(t.grokBotBounce),r.add(Gv),e&&n&&r.add(e),Array.from(r)}function Qv(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 Yv(e){if(void 0===e)return{};const t={};"string"==typeof e.title&&e.title.length>0&&(t.title=Wo(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?.[wv]}(e)&&(t[wv]=!0),0===Object.keys(t).length?{}:{annotationsJson:JSON.stringify(t)}}new Map([[Vv,zv],["gw",yv],["gd",Gv],["xa",vv],["xc",bv],["xl",Sv],...[18787,28787,31787].map((e=>[`gd${e}`,Kv(e)]))]),new Map([[zv,Vv],[Wv,Vv],[yv,"gw"],[vv,"xa"],[bv,"xc"],[Sv,"xl"]]),Zv({loopbackIpv4:!0});var eb=r("../mcp-core/dist/transport/mcp-url-utils.js");function tb(e){return e.trim().toLowerCase()}const rb="<no-mcp-tool-allowed>";function nb({mode:e,tools:t}){const r=(t??[]).map(tb).filter((e=>e.length>0)),n=void 0===e?void 0:tb(e);return"all"===n?{mode:"all"}:"reads"===n?{mode:"reads"}:r.length>0?{mode:"custom",tools:r}:{mode:"all"}}function ob(e,t){switch(e.mode){case"all":return!0;case"custom":return function(e,t){const r=tb(e);return 0!==r.length&&r!==rb&&t.some((e=>tb(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 sb(e,t){switch(t.mode){case"all":return[`${e}:*`];case"custom":return t.tools.filter((e=>tb(e)!==rb)).map((t=>`${e}:${t}`));case"reads":return[];default:return t}}const ib=new Set(["ash","bash","csh","dash","fish","ksh","powershell","pwsh","sh","tcsh","zsh","cmd"]);function ab(e){return e.trim().split(/\s+/).filter(Boolean)}function cb(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 ab(t)[0]}(e);if(!t)return!1;const r=t.replace(/^["']|["']$/g,"").replaceAll("\\","/").split("/"),n=(r[r.length-1]??"").replace(/\.exe$/i,"").toLowerCase();return ib.has(n)}function lb(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 ub(e,t){return e.commandName.localeCompare(t.commandName)}function db(e){return e.split(" ")[0]??e}function hb(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=ab(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(ub);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=lb(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&&lb(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(db(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(db(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(db(e.id))}}if(0===o.length)return{defaultSelectedOptionIds:n,hasClassifierSuggestions:!1};const i=n.filter((e=>!s.has(db(e))));return{defaultSelectedOptionIds:[...new Set([...i,...o])],hasClassifierSuggestions:!0}}(e,t).defaultSelectedOptionIds}const pb=["com.todesktop.230313mzl4w4u92","co.anysphere.cursor","com.anysphere.molten-glass"],fb=["cursor","molten glass"];function mb(e){return pb.some((t=>e===t||e.startsWith(`${t}.`)))}const gb=[{bundleId:"com.apple.scripteditor2",name:"Script Editor"},{bundleId:"com.apple.automator",name:"Automator"},{bundleId:"com.apple.shortcuts",name:"Shortcuts"}],wb=[{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"},...gb,{bundleId:pb[0],name:"Cursor"}];function yb(e){const t=e.toLowerCase(),r=(0,s.basename)(e,".app").toLowerCase(),n=wb.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}:mb(t)?{bundleId:t,name:"Cursor"}:[t,r].some((e=>fb.some((t=>e===t||e.startsWith(`${t} `)))))?{bundleId:pb[0],name:"Cursor"}:void 0}const vb=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 bb(e){return vb.has(e.toLowerCase())}function Sb(e){return`app/${e}`}function kb(e){return"object"==typeof e&&null!==e}function _b(e){return Eb.includes(e)}function Cb(e){if(!kb(e))return;const{appArg:t,appSelectorArgs:r,capturesScreen:n}=e;if("boolean"==typeof n){if(void 0!==r){if(void 0!==t||!kb(r))return;const e={};for(const[t,n]of Object.entries(r)){if(!_b(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 Eb=["pid","bundleId","path","appName"],xb=/^[+-]?\d+$/;var Pb=r("../../node_modules/.pnpm/diff@8.0.3/node_modules/diff/libesm/patch/create.js");const Rb=".cursor/worktrees",Ib=".grok/build-desktop/worktrees",Tb="win32"===process.platform||"darwin"===process.platform,Ab=new Map;function $b(e,t){if(!(0,Ko.BJ)(t,e))return;const r=(Tb?(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 Mb(e,t){const r=$b(e,t);if(void 0!==r)return r;const n=function(e){if(Ab.has(e))return Ab.get(e);const t=[];let r,n=e;for(;;)try{const e=So.realpathSync.native(n);r=0===t.length?e:(0,s.join)(e,...t);break}catch(e){const r=gc(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 Ab.size>=64&&Ab.clear(),Ab.set(e,r),r}(e);var o,i;return void 0!==n&&(o=n,i=e,Tb?o.toLowerCase()!==i.toLowerCase():o!==i)?$b(n,t):void 0}function Db(e){const t=e?.trim();return t&&".cursor"!==t?[".cursor",t]:[".cursor"]}function Ob(e,t){const r=(0,o.homedir)();return Db(t?.dataFolderName).some((t=>void 0!==Mb((0,s.join)(r,t,"projects"),e)))}function Fb(e){const t=(0,o.homedir)();return[Rb,Ib].some((r=>void 0!==Mb((0,s.join)(t,...r.split("/")),e)))}function Nb(e,t,r){const n=function(e,t){const r=(0,o.homedir)();for(const n of Db(t?.dataFolderName)){const t=Mb((0,s.join)(r,n,"projects"),e);if(void 0!==t&&t.length>=2)return t[1]}}(e,r);return void 0!==n&&(Tb?t.some((e=>e.toLowerCase()===n.toLowerCase())):t.includes(n))}function Lb(e,t,r){const n=Mb(e,t);if(void 0===n)return!1;const o=n[0];return Tb?r.some((e=>e.toLowerCase()===o.toLowerCase())):r.includes(o)}const jb=/[\s"'`=/\\:;()[\]{},&|<>]/,Ub="win32"===process.platform||"darwin"===process.platform;async function Bb(e,t,r,n){const o=Vb(await Gb((0,s.join)(e,"gitdir")),"");if(void 0===o)return;const i=(0,s.resolve)(e,o);if(".git"!==(0,s.basename)(i)||(0,js.$f)(i))return;const a=(0,s.dirname)(i);if(r&&Fb(a))return;const c=await Kb(i);if(void 0===c)return;const l=(0,s.dirname)(c);if(r&&Fb(l))return;if(void 0!==n&&(u=Zb(a,l)?[l]:[a,l],d=n.command,!(void 0!==(h=n.realWorkingDirectory)&&u.some((e=>(0,Ko.BJ)(h,e)))||void 0!==d&&u.some((e=>{const t=(0,s.basename)(e);return t.length>0&&function(e,t){const r=Ub?e.toLowerCase():e,n=Ub?t.toLowerCase():t;let o=0;for(;;){const e=r.indexOf(n,o);if(-1===e)return!1;const t=0===e||jb.test(r[e-1]),s=e+n.length,i=s===r.length||jb.test(r[s]);if(t&&i)return!0;o=e+1}}(d,t)})))))return;var u,d,h;const p=await zb(i,c);return void 0!==p&&Zb(p.commonDir,t)?l:void 0}async function Wb(e,t){const r=await(0,vo.readdir)(e).catch(Jb);return void 0===r?[]:r.sort().slice(0,t)}function Hb(e,t){return t.some((t=>(0,Ko.BJ)(t,e)))}async function qb(e){for(let t=e;;t=(0,s.dirname)(t)){if((0,js.$f)(t))return;const e=(0,s.join)(t,".git"),r=await(0,vo.lstat)(e).catch(Jb);if(r?.isFile())return(await zb(e))?.commonDir;if(r?.isDirectory())return e;if(void 0!==r||(0,s.dirname)(t)===t)return}}async function zb(e,t){const r=Vb(await Gb(e),"gitdir: ");if(void 0===r)return;const n=await Kb((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=Vb(await Gb((0,s.join)(n,"commondir")),"");if(void 0===i)return;const a=await Kb((0,s.resolve)(n,i));if(void 0===a||!Zb(a,o))return;const c=Vb(await Gb((0,s.join)(n,"gitdir")),"");if(void 0===c)return;const[l,u]=await Promise.all([Kb((0,s.resolve)(n,c)),t??Kb(e)]);return void 0!==l&&void 0!==u&&Zb(l,u)?{commonDir:o,realDotGit:u}:void 0}async function Gb(e){const t=await(0,vo.lstat)(e).catch(Jb);if(void 0!==t&&t.isFile()&&!(t.size>4096))return(0,vo.readFile)(e,"utf8").catch(Jb)}function Vb(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 Kb(e){if(!(0,js.$f)(e))return(0,vo.realpath)(e).catch(Jb)}function Jb(e){const t=gc(e);if(void 0===t||t.startsWith("ERR_"))throw e}function Zb(e,t){return Ub?e.toLowerCase()===t.toLowerCase():e===t}function Xb(e,t,r){return{resolvedPath:e,originalPath:t,resolution:r}}function Qb(e){const t=gc(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:wc(e)}}}async function Yb(e,t){const r=(0,Ko.o1)(e,t);try{return Xb(await(0,vo.realpath)(r),r,{status:"resolved"})}catch(e){if("ENOENT"!==gc(e))return Xb(r,r,Qb(e));try{if((await(0,vo.lstat)(r)).isSymbolicLink()){let e=null;try{e=await(0,vo.readlink)(r)}catch{}return Xb(r,r,{status:"danglingSymlink",symlinkTarget:e})}try{return Xb(await(0,vo.realpath)(r),r,{status:"resolved"})}catch(e){if("ENOENT"!==gc(e))return Xb(r,r,Qb(e))}return Xb(r,r,{status:"unknownError",errno:"ENOENT",message:"realpath returned ENOENT but lstat found a non-symlink entry"})}catch(e){return"ENOENT"===gc(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,vo.realpath)(t);return Xb((0,s.join)(n,...r),e,{status:"newFile"})}catch(t){if("ENOENT"!==gc(t))return Xb(e,e,Qb(t))}r.unshift((0,s.basename)(t)),t=(0,s.dirname)(t)}return Xb(e,e,{status:"newFile"})}(r):Xb(r,r,Qb(e))}}}function eS(e){return"resolved"===e.status||"newFile"===e.status}function tS(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 rS({realAbsolutePath:e,setting:t,resolvedWorkspaceRoots:r,resolvedAllowFolders:n,resolvedAllowGlobs:o}){return!("workspace"!==t.boundary||nS(e,r)||nS(e,n)||sS(e,t.allowPaths)||sS(e,o))}function nS(e,t){return t.some((t=>(0,Ko.BJ)(e,t)))}function oS(e){return e.flatMap((e=>{const t=(0,Ko.jl)(e.trim());return!t.includes("*")&&(0,s.isAbsolute)(t)?[(0,s.resolve)(t)]:[]}))}function sS(e,t){const r="win32"===process.platform?Ko.oL:e=>e,n=r(e);return t.some((e=>{const t=(0,Ko.jl)(e.trim());return!(!t.includes("*")&&(0,s.isAbsolute)(t))&&(0,us.T)(r(t),n)}))}const iS={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 aS(e){const t=[];let r=!0,n=!1,o=e;for(;;){const e=iS[s.posix.basename(o.name)];if(void 0===e)return{command:o,wrapperForms:t,allowlistable:r,readsArguments:n};const i=cS(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||!pS(a))return{command:o,wrapperForms:t,allowlistable:!1,readsArguments:n};(o.name.includes("/")||o.args.slice(0,i).some((t=>lS(t,e)||uS(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 cS(e,t){let r=0;for(;r<e.length;){const n=e[r];if(lS(n,t))break;if(void 0===n||!pS(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=dS(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(hS))return"unreadable";for(r=n;r<e.length&&lS(e[r],t);)r++;return r<e.length?r:"none"}function lS(e,t){return!0===t.assignments&&/^[A-Za-z_][A-Za-z0-9_]*=/.test(e?.value??"")}function uS(e,t){return(t.directoryOptions??[]).some((t=>t.startsWith("--")?e===t||e.startsWith(`${t}=`):/^-[^-]/.test(e)&&e.includes(t.slice(1))))}function dS(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 hS(e){return"raw_string"===e.type||!/[$`]/.test(e.value)&&("string"===e.type||!/[*?[]|\{[^}]*(,|\.\.)/.test(e.value))}function pS(e){return("word"===e.type||"number"===e.type)&&!/[$`]/.test(e.value)}const fS=/(?<![\w-])(?:rm|rmdir|rd|del|erase|ri|remove-item)(?![\w-])/i,mS=/\s(?:-[dfiv]*r[dfiv]*|--recursive|-recurse|-recurs|-recur|-recu|-rec|-re)(?![\w-])/i;function gS(e,t,r){const n=t.exec(e);return null!==n&&r.test(e.slice(n.index+n[0].length))}var wS=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},yS=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 vS=(0,l.h)("permissions-service"),bS=(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"]}),SS=(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"]}),kS="Your team's MCP rules could not be checked for this MCP server, so this MCP tool can't run right now",_S=/[\p{Cc}\p{Bidi_Control}\p{Cs}]/gu,CS=/^[\p{M}\p{Cf}\p{Default_Ignorable_Code_Point}\s]+/u,ES=/[^\p{M}\p{Cf}\p{Default_Ignorable_Code_Point}\s\u2800]/u;function xS(e,t){for(const r of[e?.title,t?.title]){if("string"!=typeof r)continue;const e=Wo(r,1024).replace(_S," ").replace(/\s+/g," ").replace(CS,"").trim(),t=Wo(e,256).trimEnd();if(ES.test(t))return t}}function PS(e,t){return{toolTitle:xS(e,t),destructiveHint:"boolean"==typeof t?.destructiveHint?t.destructiveHint:void 0}}function RS(e){return Promise.all(e.map((async e=>{const t=await Yb(e);return eS(t.resolution)?t.resolvedPath:(0,Ko.o1)(e)})))}function IS(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 TS(e){return[...new Set(e)]}function AS(){return{fdTargets:new Map([[0,"original-stdin"],[1,"original-stdout"],[2,"original-stderr"]])}}function $S({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 MS(e){return">"===e||">>"===e||">|"===e||"&>"===e||"&>>"===e}function DS(e){return"<"!==e.operator&&"<&"!==e.operator}function OS(e){if(void 0===e||e.trim()!==e)return;const t=Number(e);return Number.isInteger(t)&&t>=0?t:void 0}function FS(e){return"<<"===e.operator&&"heredoc_redirect"===e.targetNodeType&&1===e.destinationFds.length&&0===Number(e.destinationFds[0])&&void 0!==e.targetText}function NS(e,t){return!(/^=|[~*?[{(#^`]/.test(e)||"\\"!==t.sep&&e.includes("\\"))}function LS(e){return"word"===e.type||"number"===e.type?NS(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 jS({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(LS);return t?[...r,void 0]:r}const US=new Set(["cd","chdir","pushd"]),BS=new Set(["popd","eval","source",".","trap","set-location","sl","push-location","pop-location"]);function WS(e){const t=e.replace(/["'\\]/g,"");return t.slice(t.lastIndexOf("/")+1).toLowerCase()}function HS(e,t){return new he.Pv({name:e,args:t,fullText:[e,...t.map((e=>e.value))].join(" ")})}function qS(e){let t=e;for(;;){const e=WS(t.name);if("command"===e){const e=HS("command",t.args),r=aS(e).command;if(r!==e){t=r;continue}const n=t.args[0]?.value;return void 0===n||"-v"===n||"-V"===n?t:"unreadable"}if("builtin"!==e)return t;const r="--"===t.args[0]?.value?t.args.slice(1):t.args,[n,...o]=r;if(void 0===n)return t;const s=LS(n);if(void 0===s||s.startsWith("-"))return"unreadable";t=HS(s,o)}}function zS(e,t){return!(!t.isAbsolute(e)||"/"!==t.sep&&/^[\\/]$/.test(t.parse(e).root))}async function GS({parsingResult:e,workingDirectory:t,resolvePathForPermissions:r,pathModule:n}){const o=[t];for(const t of e.executableCommands.map(aS)){const e=qS(t.command);if("unreadable"===e)return;const i=WS(e.name),a=e.args;if(BS.has(i)||/^cd\.\./.test(s=i)||/^[a-z]:$/.test(s))return;if(!US.has(i))continue;const c=1===a.length&&void 0!==a[0]?LS(a[0]):void 0;if(void 0===c||!zS(c,n))return;const l=await r(c);if(!eS(l.resolution))return;o.push(l.resolvedPath)}var s;return o}async function VS({targetText:e,workingDirectory:t,workingDirectories:r,...n}){const o=zS(e,n.pathModule)?[t]:r;if(void 0===o)return;let s;for(const t of o)if(s=await KS({...n,targetText:e,workingDirectory:t}),void 0===s)return;return s}async function KS({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(!eS(a.resolution))return;const c=[];for(const e of r){const t=await o(e);eS(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,To.OK)(e,r).catch((()=>!0)))return!0;return!1}({targetPath:a.resolvedPath,rootPaths:c,pathModule:s})?void 0:c.some((e=>$S({basePath:e,targetPath:a.resolvedPath,pathModule:s})))?"workspace-file":n&&!(0,To.dA)(a.originalPath)&&ak(a.resolvedPath,i)?"tmp-file":void 0}async function JS({parsingResult:e,workingDirectory:t,rootDirectories:r,allowTmpRedirects:n}){const i=await GS({parsingResult:e,workingDirectory:t,resolvePathForPermissions:Yb,pathModule:s});for(const a of e.executableCommands.map(aS).flatMap(jS))if("/dev/null"!==a&&(void 0===a||!await VS({targetText:a,workingDirectory:t,workingDirectories:i,rootDirectories:r,allowTmpRedirects:n,resolvePathForPermissions:Yb,pathModule:s,tempPathOptions:{platform:process.platform,env:process.env,pathModule:s,homeDirectory:(0,o.homedir)()}})))return!1;return!0}function ZS(e){return TS(e.map((e=>e.trim())).filter(Boolean))}function XS(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 QS(e,t){const r=t.trim();return!!r&&e.some((e=>e===r||e.startsWith(`${r} `)))}function YS(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 ek(e,t={}){return{type:e,...t}}function tk(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 rk(...e){return e.filter((e=>void 0!==e)).join(" • ")}function nk(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 ok(e,t){if("workspace"===e&&void 0!==t)return t}const sk={workspace:0,system:1};function ik(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 ak(e,{platform:t,env:r,pathModule:n,homeDirectory:o}){if((0,To.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||!$S({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 ck(e,t){if("insecure_none"===t.type)return!0;if("insecure_none"===e.type)return!1;const r=(0,To.$b)(e.networkPolicy),n=(0,To.$b)(t.networkPolicy);if(r&&!n)return!1;const o=(0,To._B)(e.networkPolicy),s=(0,To._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!(sk[i]>sk[a])}function lk(e){return{wrapperForms:e.flatMap((e=>e.wrapperForms)),allowlistable:e.every((e=>e.allowlistable)),readsArguments:e.some((e=>e.readsArguments))}}function uk(e){return[...e.wrapperForms,e.command.fullText.trim()].filter(Boolean)}class dk{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&&ck(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||!ck(this.requestedPolicy,e)||(this.state="allowlisted")}deny(){this.state="denied"}isRunnable(){return"preapproved"===this.state||"allowlisted"===this.state}}function hk(e){return e?.type??"undefined"}const pk=["skills","skills-cursor","rules","plugins"],fk=["assets","agent-notes","agent-tools","swarm-agents"];async function mk(e,t,r){return e.shouldBlockFileRead?.(t,r)??e.shouldBlockRead(t,r)}function gk(e){const t=e.lastIndexOf("::mcpScope:");return-1===t?e:e.slice(0,t)}function wk({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 yk=/^\s*Read\s*\((.*)\)\s*$/,vk=/^\s*Write\s*\((.*)\)\s*$/;class bk{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&&rS({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:nk(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 RS([...oS(e),...(0,To.r5)()])}async resolvedReadAllowGlobs(e){const t=function(e){return e.flatMap((e=>{const t=(0,Ko.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 RS(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,go.r_)(e)))),...pk.map((e=>(0,s.join)(t,e)))],n=this.rootDirectories.flatMap((e=>(0,To.W1)(e)??[]));return RS([...this.rootDirectories,...r,...n,...void 0===this.projectDir?[]:[this.projectDir]])}async shouldBlockReadInternal(e,{cursorIgnoreChecked:t=!1},r){const n=(0,Ko.o1)(e),o=await vc(n);if(null===o)return{type:"unsafeResolution",message:IS("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&&!Fb(o)&&!Ob(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(nS(e,n))return!1;const[o,s]=await Promise.all([this.resolvedReadAllowFolders(r.allowPaths),this.resolvedReadAllowGlobs(r.allowPaths)]);return!!rS({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 Yb(this.projectDir);return!!eS(r.resolution)&&Lb(r.resolvedPath,e,t)}async isFreelyWritableOutsideWorkspace(e,t){return function(e){return ak(e,{platform:process.platform,env:process.env,pathModule:s,homeDirectory:(0,o.homedir)()})}(e)||Nb(e,fk,{dataFolderName:t})||await this.isProjectDirInternalPath(e,fk)}async shouldBlockWrite(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{wS(n,(0,$.VI)(e.withName("InteractivePermissionsService.shouldBlockWrite")),!1).ctx;const i=await Yb(t);if(!eS(i.resolution))return{type:"unsafeResolution",message:tS(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,To.dA)(i.originalPath)||(0,To.dA)(a))return{type:"permissionsConfig"};const d=await this.getPermissions();if(!Fb(c)&&!Ob(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 Di(a),e=!1}catch{e=!0}if(e)t=r;else{const e=e=>e.endsWith("\n")?e:`${e}\n`,{hunks:o}=(0,Pb.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 Yb(e);if(eS(t.resolution)){if((0,Ko.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,js.$f)(o))return;const e=(0,s.join)(o,".git"),i=await(0,vo.lstat)(e).catch(Jb);if(i?.isFile()){const s=await zb(e);if(void 0!==s){const{commonDir:e}=s;if(Hb(o,t))return;if(t.some((t=>(0,Ko.BJ)(e,t))))return{root:o,commonDir:e};if(!await(r.isUntrustedExternalGitDir?.(e))&&(await(n??=Promise.all(t.map((e=>qb(e)))),n)).some((t=>void 0!==t&&Zb(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,To.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{yS(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 vc(t.workingDirectory);if(null===o){if(!0!==t.skipUnsafeWorkingDirectoryBlock)return{kind:"block",reason:{type:"unsafeResolution",message:IS("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(vS.info(e,"Shell permissions: evaluating shell command",{toolCallId:r.toolCallId,approvalMode:a,userConfiguredPolicyType:hk(l),requestedPolicyType:hk(n),effectiveRequestedPolicyType:hk(n??l),smartAllowlistEnabled:!0===i.smartAllowlistEnabled,hasSmartModeApprovalReason:void 0!==r.smartModeApprovalReason,hasSmartModeApprovalRequestId:void 0!==r.smartModeApprovalRequestId,hookForcesPrompt:Po(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 vS.info(e,"Shell permissions: prompting for empty allowlist",{toolCallId:r.toolCallId,approvalMode:a,userConfiguredPolicyType:hk(l),requestedPolicyType:hk(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(aS),b=w?w.map(YS):v.map((e=>e.command)),S=void 0!==w?w.map(XS):b.map((e=>[e.fullText.trim()].filter(Boolean))),k=void 0!==g?g.commands.map(XS):v.map(uk);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,To.$b)(l.networkPolicy)&&"insecure_none"!==n.type&&!(0,To._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,To.XX)(e.readBoundary,t.readBoundary),n="workspace"===r?(0,To.wG)(ok(e.readBoundary,e.additionalReadPaths),ok(t.readBoundary,t.additionalReadPaths)):void 0;return{...e,readBoundary:r,additionalReadPaths:n}}({requestedPolicy:n,userConfiguredPolicy:l}),p&&vS.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=[],R=[];const I=ZS(i.smartAllowlistDenylist??[]);if(I.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&&I.some((e=>QS(r,e)))){const r=t[e];r&&P.push(r)}}P.length>0&&(vS.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)));vS.info(e,"Smart allowlist: checking commands against lists",{commandCount:t.length,allowlistCount:r.length,commandBlocklistCount:I.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=ZS(s.flatMap((e=>function(e){const t=e.name.trim();if(!t)return[];if(cb(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),ZS(o)}(e)))),R=s.map((e=>e.suggestedAllowlistEntry)).filter((e=>"string"==typeof e)).filter((e=>x.includes(e))),x.length>0){const e=hb(x,R),t=e.length>0?e.join(", "):x.join(", ");E.push(`Not in allowlist: ${t}`)}_=o&&0===P.length,_&&vS.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=lk(v),$=b.map(((e,t)=>new dk(e,n,T,S[t],y?A:v[t])));if((0===b.length||h&&!y)&&!c){vS.info(e,"Shell permissions: prompting after parser miss",{toolCallId:r.toolCallId,approvalMode:a,requestedPolicyType:hk(n),userConfiguredPolicyType:hk(l),isSmartAllowlistActive:y,parsingFailed:h,parserCommandCount:b.length,hasSmartModeApprovalReason:void 0!==f,hasSmartModeApprovalRequestId:void 0!==m});const o={type:ow.Shell,toolCallId:r.toolCallId,details:{command:t,workingDirectory:r.workingDirectory,timeout:r.timeout,reason:rk(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 vS.info(e,"Shell permissions: blocked by readonly mode"),{kind:"block",reason:{type:"permissionsConfig",isReadonly:!0}};const j=Po(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&&fS.test(r)||gS(r,fS,mS)||gS(r,/(?<![\w-])(?:rmdir|rd|del|erase)(?![\w-])/i,/\/s(?![\w-])/i)||gS(r,/(?<![\w-])find(?![\w-])/i,/\s-delete\b/i))return!0;e||=gS(r,/(?<![\w-])(?:get-childitem|gci|ls|dir)(?![\w-])/i,mS)}}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&&vS.info(e,"Shell permissions: all commands allowed by sandbox policy");const t=await this.applyServerAndAdminPolicies(W);return vS.info(e,"Shell permissions: auto-approved shell command",{toolCallId:r.toolCallId,approvalMode:a,requestedPolicyType:hk(n),userConfiguredPolicyType:hk(l),autoApprovalPolicyType:hk(W),mergedPolicyType:hk(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=hb(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(", ");vS.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=rk(...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&&R.length>0?R: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));vS.info(e,"Shell permissions: requesting shell approval",{toolCallId:r.toolCallId,approvalMode:a,requestedPolicyType:hk(n),userConfiguredPolicyType:hk(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:ow.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(aS),d=l?c.commands.map(YS):u.map((e=>e.command));if(0===d.length)return!1;const h=l?c.commands.map(XS):d.map((e=>[e.fullText.trim()].filter(Boolean))),p=void 0!==c?c.commands.map(XS):u.map(uk),f={type:"insecure_none"},m=lk(u),g=d.map(((e,t)=>new dk(e,f,void 0,h[t],l?m:u[t])));if(await this.hasHardDeny(n,g))return!1;const w=ZS(o.smartAllowlistDenylist??[]);if(w.length>0)for(const e of p)if(e&&0!==e.length&&w.some((t=>QS(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,t),u=await this.resolveTeamAdminLayer(n);if("unavailable"===u){const{policy:e}=await(0,To.resolveSandboxPolicyForWorkspace)(t,{perUser:c,perRepo:l});return function(e){return"insecure_none"===e.type?e:{...e,networkPolicy:(0,To.Po)(),readBoundary:"workspace",additionalReadPaths:[]}}(e)}const d=void 0===u?void 0:ek(c.type,u),h=(0,To._B)(e.networkPolicy)&&!tk(d?.networkPolicy),{policy:p}=await(0,To.resolveSandboxPolicyForWorkspace)(t,{perUser:c,perRepo:l,teamAdmin:d});return h?{...p,networkPolicy:(0,To.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=await this.foldPerUserFilePolicy(a,n),l=await this.loadPerRepoFilePolicy(c,t);if("workspace"===(l?.readBoundary??c.readBoundary))return}const a=[];for(const e of this.rootDirectories){if((0,js.$f)(e))continue;const t=await Yb(e);eS(t.resolution)&&!Fb(t.resolvedPath)&&a.push(t.resolvedPath)}if(0===a.length)return;let c;if(!(0,js.$f)(t.workingDirectory)){const e=await Yb(t.workingDirectory);eS(e.resolution)&&(c=e.resolvedPath)}return async function(e,t={}){if(0===e.length)return;const r=await Promise.all(e.map((e=>qb(e)))),n=[];for(const o of r)void 0===o||n.some((e=>Zb(e,o)))||!e.some((e=>(0,Ko.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 Wb((0,s.join)(r,"worktrees"),256),c=await(0,Dr.PH)(n,(e=>Bb((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=>Zb(e,r)))||e.some((e=>(0,Ko.BJ)(r,e)))||Hb(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,To.tv)(t,(0,o.homedir)());if(!r||"insecure_none"===r.type)return e;let n=(0,To.fZ)(r.networkPolicy,e.networkPolicy);n&&void 0!==e.networkPolicy?.default&&(n={...n,default:e.networkPolicy.default});const s=(0,To.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,privateTmp:r.privateTmp??e.privateTmp};if("workspace_readwrite"===e.type&&"workspace_readwrite"===r.type){const t=(0,To.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,To._B)(e.networkPolicy))return e;const r={default:"deny",allow:TS(t.allowlist)};return{...e,networkPolicy:(0,To.fZ)(e.networkPolicy,r)}}async loadPerRepoFilePolicy(e,t){const r=await(0,To.tv)((0,s.join)(t,".cursor","sandbox.json"),t);if(r){if("1"===process.env[gv.K4]){const n=(0,To.fB)({perUser:e,perRepo:r},t).perRepo;return"insecure_none"===n?.type?void 0:n}if("insecure_none"!==r.type)return r.type!==e.type?ek(e.type,{networkPolicy:r.networkPolicy,additionalReadonlyPaths:r.additionalReadonlyPaths,..."additionalReadwritePaths"in r?{additionalReadwritePaths:r.additionalReadwritePaths}:{},disableTmpWrite:r.disableTmpWrite,networkPolicyStrict:r.networkPolicyStrict,readBoundary:r.readBoundary,additionalReadPaths:r.additionalReadPaths,privateTmp:r.privateTmp}):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:TS(i.allowlist)}:{},...i.denylist.length>0?{deny:TS(i.denylist)}:{}}:void 0:(0,To.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,To._B)(e.networkPolicy))return;const{teamAdminPolicy:t}=await this.getPermissions(),r=await this.resolveTeamAdminLayer(t);return function(e){if(tk(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,To.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=Yb,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=await GS({parsingResult:e,workingDirectory:t,resolvePathForPermissions:i,pathModule:a}),h=AS();for(const e of l){if(FS(e))continue;const o=u?AS():h,{operator:s,targetText:l}=e,f=e.destinationFds;if(">&"===s){const e=OS(l),t=void 0===e?void 0:o.fdTargets.get(e);if("original-stdout"!==(p=t)&&"original-stderr"!==p&&"dev-null"!==p&&"workspace-file"!==p&&"tmp-file"!==p){for(const e of f)o.fdTargets.set(e,"unsafe");return!1}for(const e of f)o.fdTargets.set(e,t);continue}if("<&"===s){const e=OS(l),t=void 0===e?void 0:o.fdTargets.get(e);if("dev-null"!==t){for(const e of f)o.fdTargets.set(e,"unsafe");return!1}for(const e of f)o.fdTargets.set(e,t);continue}if("/dev/null"===l){for(const e of f)o.fdTargets.set(e,"dev-null");continue}if(!MS(s)||void 0===l||"word"===e.targetNodeType&&!NS(l,a)){for(const e of f)o.fdTargets.set(e,"unsafe");return!1}const m=await VS({targetText:l,workingDirectory:t,workingDirectories:d,rootDirectories:r,allowTmpRedirects:n,resolvePathForPermissions:i,pathModule:a,tempPathOptions:c});if(!m){for(const e of f)o.fdTargets.set(e,"unsafe");return!1}for(const e of f)o.fdTargets.set(e,m)}var p;return!0}({parsingResult:e,workingDirectory:t,rootDirectories:this.rootDirectories,allowTmpRedirects:r}),l=await JS({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(DS))}({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:ow.Shell,toolCallId:t.toolCallId,details:{command:e,workingDirectory:t.workingDirectory,timeout:t.timeout,reason:rk(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 JS({parsingResult:t,workingDirectory:e.workingDirectory,rootDirectories:this.rootDirectories,allowTmpRedirects:!0})?[]:this.generateAllowlistPatterns(t.executableCommands.map(aS))}async getAdminCommandDenylistBlock(e,t){const r=(await this.teamSettingsService.getAdminCommandDenylist()).rules;if(0===r.length)return;const n=ms({matchForms:t.parsingResult?ds({command:t.command,parsingResult:t.parsingResult}):[t.command],blockedCommands:r});return void 0!==n?(vS.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!==ik(e)}isPathEntry(e,t){return new RegExp(`^\\s*${e}\\s*\\(`).test(t)}matchesShell(e,t){const r=ik(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&&!cb(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?yk:vk}(e));if(r)return(r[1]??"").trim()}compileReadDenyMatcher(e){try{const t=this.pathEntryRawPattern("Read",e);if(void 0===t)return()=>!1;const r=(0,us.b)((0,Ko.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,Ko.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(0,us.T)(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{wS(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:Qv(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=wk({server:gk(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,...PS(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,...PS(r,l),providerIdentifier:a,args:c,canAllowlist:_,allowlistEntry:b,computerUseApp:S}}}catch(e){o.error=e,o.hasError=!0}finally{yS(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 SS.increment(e,1,{reason:"outside_limit"}),"Your team's admin limits this MCP tool";case"settings_unavailable":return SS.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 SS.increment(e,1,{reason:"unknown_server"}),kS;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 ob(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(gk(e.serverIdentifier||e.providerIdentifier),t);if(!1===n)return{kind:"notComputerUse"};const o=await async function(e,t){const r=Cb(e.meta?.["cursor/computerUseScope"])??Cb(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])=>_b(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&&xb.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?yb(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&&xb.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:yb(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 mb(t)?"Computer Use doesn't control Cursor itself, including its approval cards. Ask the user to do it instead.":gb.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.":wb.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=bb(o.app.bundleId)?void 0:wk({server:r.serverId,tool:Sb(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=gk(e);return!0===this.computerUse?.providerIdentifiers.has(t)}async isComputerUseDisabledByAdminFor(e){const t=this.computerUseAdminPolicy;return t?.providerIdentifiers.has(gk(e))?await t.isDisabledByAdmin():!!this.isComputerUseServer(e)&&!0===await(this.teamSettingsService.isComputerUseDisabledByAdmin?.())}allowComputerUseAppForSession({bundleId:e}){const t=void 0===this.computerUse||bb(e)?void 0:wk({server:this.computerUse.serverId,tool:Sb(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??Qv(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=gk(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}){bS.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&&fv(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&&ob(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 Sk=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 kk=65536,_k=1048576,Ck=(0,l.h)("LocalReadExecutor"),Ek=async(e,t,r,n)=>{const o=setTimeout((()=>{Ck.warn(e,`[watchdog, LocalReadExecutor] ${t} still not completed after ${r}ms`)}),r);try{return await n()}finally{clearTimeout(o)}};function xk(e){return BigInt(Math.min(e,4294967295))}async function Pk(e,t){if(0===t)return(0,vo.readFile)(e);if(t>2147483647)throw new RangeError(`File size (${t}) is greater than 2 GiB`);const r=await(0,vo.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 Rk(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 Ik(e){return e>=32&&e<=126||9===e||10===e||13===e}function Tk(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&&Ik(t)&&r++,0===t&&Ik(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 Ak=Buffer.from("\n---\n");function $k(e,t){const r=e.length;if(r<2*Ak.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(Ak,r-Ak.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+Ak.length,r-4).toString("utf-8"))?o:r}const Mk=[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 Dk(e){return new fy.sV({result:{case:"invalidFile",value:new fy.cW({path:e,reason:"File content is binary data, not text"})}})}function Ok(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=Fk(s,e),c=Fk(i,e);return{applied:!0,start:a,end:Math.max(a,c)}}function Fk(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 Nk(e){return-1===e.indexOf("\r\n")?e:e.replaceAll("\r\n","\n")}function Lk(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 jk(e,t,r){const n=Lk((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 Uk(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=Nk(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=Wo(c,o)),{text:c,truncated:l}}function Bk(e,t,r,n){if(t>=r)return{text:"",truncated:!1};const o=Math.min(r,t+2*n+1);let s=Nk(e.slice(t,o));const i=s.length>n||o<r;return s.length>n&&(s=Wo(s,n)),s.length<e.length&&(s=o_(s)),{text:s,truncated:i}}function Wk(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+Wo(t,n),truncated:!0}:{text:e.text+t,truncated:e.truncated}}function Hk(e,t){if(e.truncated)return e;const r=Wk(e,t);return{text:r.text,truncated:r.truncated}}function qk(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=Wk(n,"\n")),n=Wk(n,o.text),o.truncated&&(n={text:n.text,truncated:!0})})),n}function zk(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 Gk(e){return void 0===e.maxChars||void 0!==e.offset||void 0!==e.limit?Bs:Math.min(Bs,e.maxChars+2)}function Vk(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 Kk extends Error{constructor(){super("Invalid UTF-8 while streaming read"),this.name="InvalidUtf8Error"}}function Jk(e){for(let t=1;t<=Math.min(3,e.length);t++){const r=e[e.length-t]??0;if(128!=(192&r))return Zk(r)>t?t:0}return 0}function Zk(e){return e>=240?4:e>=224?3:e>=192?2:1}class Xk{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 Kk}validate(e){let t=e;if(this.carry.length>0){const r=Zk(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 Kk;t=e.subarray(r)}const r=Jk(t);if(!(0,n.isUtf8)(t.subarray(0,t.length-r)))throw new Kk;this.carry=Buffer.from(t.subarray(t.length-r))}}function Qk(e,t){const r=function({file:e,stats:t,format:r},n){return zk(n??Vi(e,t)??r.encoding)}(e,t),n=function(e){const t=zk(e);return"utf8bom"===t?"utf8":t}(r);return"utf8"===n?{kind:"strictUtf8",cacheEncoding:"utf8"}:Ws.encodingExists(n)?{kind:"iconv",decoderEncoding:n,cacheEncoding:r}:{kind:"strictUtf8",cacheEncoding:"utf8"}}function Yk(e){const t=Rk(e),r=$k(e,t);return"utf-8"!==Tk(e.subarray(t,r))?"other_encoding":function(e){if((0,n.isUtf8)(e))return"utf8_valid";const t=Tl(e);return t>0&&(0,n.isUtf8)(e.subarray(0,e.length-t))?"utf8_cut":"utf8_invalid"}(e)}async function e_(e,t){const r=t>0?Math.min(t,_k):_k,o=await Pk(e,r);return o.length===t&&(0,n.isUtf8)(o)||ni(new Us.TextDecoder("utf-8",{fatal:!1}).decode(o,{stream:o.length===_k&&o.length!==t}))?{kind:"lossyUtf8",cacheEncoding:"utf8"}:{kind:"iconv",decoderEncoding:"latin1",cacheEncoding:"latin1"}}async function t_(e){const t=await(0,vo.stat)(e),r=await Li(e);if(r.isBinaryFile)return;const n=Qk({file:e,stats:t,format:r},void 0);if("iconv"===n.kind)return n.decoderEncoding;const o=await e_(e,t.size);return"iconv"===o.kind?o.decoderEncoding:void 0}async function r_(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,R=[],I=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>=Bs,q=()=>v||w&&g>=Bs,z=(e,t)=>{if(H())return;const r=k.length>0?1:0;let n=Bs-C;if(r>0){if(n<=0)return void(E=!0);n--}const o=e.text.length>n?{line:{text:Wo(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=Bs-g;if(r>0){if(n<=0)return void(w=!0);n--}const o=e.text.length>n?{line:{text:Wo(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=R[I];void 0!==e&&(A-=e.line.text.length+1),R[I]=void 0,I=(I+1)%R.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===R.length){const e=new Array(Math.min(h,Math.max(16,2*R.length)));for(let t=0;t<T;t++)e[t]=R[(I+t)%R.length];R=e,I=0}R[(I+T)%R.length]=e,T++})({line:e,hasNewline:t}),A+=e.text.length+1;T>1&&A>Bs;)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-Jk(e));return Q=new Xk(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 Us.TextDecoder("utf-8",{fatal:"strictUtf8"===r.kind,ignoreBOM:!0}),i=(0,So.createReadStream)(t,{highWaterMark:kk,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 Kk;throw e}return}const i=(0,So.createReadStream)(t,{highWaterMark:kk,signal:e.signal,...s}).pipe(Ws.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=Hk(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=Hk(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&&Ki(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)+kk,ae=e=>e.text.length>ie?{text:Wo(e.text,ie),truncated:!0}:e,ce=()=>qk({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=R[(I+e)%R.length];void 0!==r&&t.push(r)}let r={text:"",truncated:$};return r=qk(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(qk({text:"",truncated:E||se},k,re));return{content:le.text,totalLines:F,truncated:le.truncated,rangeApplied:!0}}class n_{constructor(e,t,r){this.permissionsService=e,this.workspacePath=t,this.terminalReads=new Ll,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 fy.sV({result:{case:"error",value:new fy.F_({path:o,error:Jo})}});const i=(0,Ko.o1)(o,this.workspacePath),a=await Ek(e,"permissionsService.shouldBlockFileRead",3e3,(()=>mk(this.permissionsService,i)));if(a){const r=await Ek(e,"resolveFileReadBlock",3e3,(()=>async function(e,t){return await Uu(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:ow.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 fy.sV({result:{case:"rejected",value:new fy.f4({path:i,reason:r.reason??""})}});if("denied"===r.kind)return new fy.sV({result:{case:"permissionDenied",value:new fy.lW({path:i})}})}void 0!==this.mcpStateAccessor&&uy(e,this.mcpStateAccessor,i);try{const r=await Ek(e,"stat",3e3,(()=>(0,vo.stat)(i)));if(r.isDirectory())return new fy.sV({result:{case:"invalidFile",value:new fy.cW({path:i,reason:"Path is a directory, not a file"})}});if(!r.isFile())return new fy.sV({result:{case:"invalidFile",value:new fy.cW({path:i,reason:"Path is neither a file nor a directory"})}});const o=function(e){return null!==function(e){const t=_p(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=_p(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 Ek(e,"getFormatForFile",3e3,(()=>Li(i))),l=c.isImageFile,u=function(e){return".pdf"===(0,s.extname)(e).toLowerCase()}(i),d=$i(i);if(l){const t=await Ek(e,"prepareImageForModel",3e3,(async()=>(async e=>{let t;try{t=await ov(e)}catch(t){const r=await sv(e);if("undecodable"===r.kind)return r;throw t}if(!0===t.reencoded)return{kind:"image",image:t};const r=await sv(t.data);return"undecodable"===r.kind?r:{kind:"image",image:t}})(await(0,vo.readFile)(i))));return"undecodable"===t.kind?new fy.sV({result:{case:"invalidFile",value:new fy.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 fy.sV({result:{case:"success",value:new fy.mE({path:i,output:{case:"data",value:t.image.data},totalLines:0,fileSize:xk(r.size),truncated:!1})}})}if(u){const t=await Ek(e,"readPdfBinary",3e3,(()=>(0,vo.readFile)(i)));return new fy.sV({result:{case:"success",value:new fy.mE({path:i,output:{case:"data",value:t},totalLines:0,fileSize:xk(r.size),truncated:!1})}})}if(c.isBinaryFile&&d){if(void 0!==t.maxVideoBytes&&r.size>t.maxVideoBytes)return new fy.sV({result:{case:"success",value:new fy.mE({path:i,totalLines:0,fileSize:xk(r.size),truncated:!0})}});const n=await Ek(e,"readBinaryFile",3e3,(()=>(0,vo.readFile)(i)));return new fy.sV({result:{case:"success",value:new fy.mE({path:i,output:{case:"data",value:n},totalLines:0,fileSize:xk(r.size),truncated:!1})}})}if(c.isBinaryFile)return Dk(i);{const n=this.useStreamingRead,o=!n||await Ek(e,"useStreamingRead",3e3,(()=>n()));if(o||r.size>Bs){const n=await Ek(e,"readTextStreaming",7e3,(()=>async function(e,t,r,n){const o=Qk(t,r.encodingHint);try{return{...await r_(e,t,r,o,n),decoder:o.kind}}catch(o){if(o instanceof Kk){const o=await e_(t.file,t.stats.size);return{...await r_(e,t,r,o,n),decoder:o.kind}}throw o}}(e,{file:i,stats:r,format:c},t,o))),s=Vk(n.content,n.truncated,t);return Rl(this.encodingSlices,e)&&this.recordStreamedRead(e,i,r.size,n,s),new fy.sV({result:{case:"success",value:new fy.mE({path:i,output:{case:"content",value:s},totalLines:n.totalLines,fileSize:xk(r.size),truncated:n.truncated,rangeApplied:n.rangeApplied})}})}const s=await Ek(e,"readText",3e3,(()=>Di(i,t.encodingHint))),a=await Ek(e,"countLines",3e3,(()=>qs(s))),l=function(e,t,r){const n=Ok(t,""===e,r);return n.applied?n.start>=n.end?{content:"",rangeApplied:!0}:{content:jk(e,n.start,n.end),rangeApplied:!0}:{content:e,rangeApplied:!1}}(s,a,t);let u=l.content,d=!1;const h=Gk(t);return u.length>h&&(u=Vk(u.substring(0,h),!0,t),d=!0),u.length<s.length&&(u=o_(u)),Bl(this.encodingSlices,e,{layer:"exec_read"},u),new fy.sV({result:{case:"success",value:new fy.mE({path:i,output:{case:"content",value:u},totalLines:a,fileSize:xk(r.size),truncated:d,rangeApplied:l.rangeApplied})}})}}catch(e){const t=gc(e);return"ENOENT"===t?new fy.sV({result:{case:"fileNotFound",value:new fy.Ko({path:i})}}):"EACCES"===t||"EPERM"===t?new fy.sV({result:{case:"permissionDenied",value:new fy.lW({path:i})}}):new fy.sV({result:{case:"error",value:new fy.F_({path:i,error:e instanceof Error?e.message:"Unknown error occurred"})}})}}catch(e){r.error=e,r.hasError=!0}finally{Sk(r)}var n}async recordStreamedRead(e,t,r,o,s){try{const i=function(e){try{const t=new Nl;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 Pk(e,t),!(0,n.isAscii)(r)&&(0,n.isUtf8)(r)?"utf8_as_other":"other_encoding"}catch{return"other_encoding"}var r}(t,r)),Wl(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 Ek(e,"readTerminalFile",3e3,(()=>Pk(t,r.size)));if(o&&(i=s,Mk.some((e=>function(e,t){return e.length>=t.length&&e.subarray(0,t.length).equals(t)}(i,e)))))return Dk(t);var i;const a=function(e,t,r=8388608){if(0===e.length)return{content:"",totalLines:1,rangeApplied:!1,truncated:!1};const n=Rk(e),o=$k(e,n);if("utf-8"!==Tk(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=Ok(o,n,t);if(!s.applied){const t=Bk(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=Lk((t=>e.indexOf("\n",t)),e.length,(t=>e.charCodeAt(t-1)),s.start,s.end,!0),a=Bk(e,i.from,i.to,r);return{content:a.text,totalLines:o,rangeApplied:!0,truncated:a.truncated}}(function(e){const t=Rk(e),r=t>0?e.subarray(0,t).toString("utf-8"):"",n=$k(e,t),o=n<e.length?e.subarray(n).toString("utf-8"):"",s=e.subarray(t,n),i=Tk(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=Ok(s,o,r);if(!i.applied){if(o)return{content:"",totalLines:s,rangeApplied:!1,truncated:!1};const r=Uk(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=Lk((t=>e.indexOf(10,t)),e.length,(t=>e[t-1]??0),i.start,i.end,!0),c=Uk(e,a.from,a.to,t,n);return{content:c.text,totalLines:s,rangeApplied:!0,truncated:c.truncated}}(e,s,t,r)}(s,n,Gk(n)),c=Vk(a.content,a.truncated,n);return Rl(this.encodingSlices,e)&&(o||this.terminalReads.firstRead(n.toolCallId,t))&&Bl(this.encodingSlices,e,{layer:o?"exec_read":"exec_terminal_context",evidence:Yk(s),partial:a.rangeApplied||a.truncated},c),new fy.sV({result:{case:"success",value:new fy.mE({path:t,output:{case:"content",value:c},totalLines:a.totalLines,fileSize:xk(r.size),truncated:a.truncated,rangeApplied:a.rangeApplied})}})}}function o_(e){return Buffer.from(e,"utf16le").toString("utf16le")}var 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},i_=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 a_(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 c_(e){return`Path '${e}' is neither a file nor a directory`}async function l_(e){const t=await(0,vo.stat)(e).catch((()=>{}));return void 0!==t&&!t.isFile()&&!t.isDirectory()}function u_(e,t,r){const n=function(e,t){let r;for(const n of t)(0,Ko.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 d_ extends Error{}function h_(e){const t=new AbortController,r=setTimeout((()=>t.abort()),e);return{signal:t.signal,clear:()=>clearTimeout(r)}}function p_(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 f_(e){switch(e){case"content":return new zw.vD({result:{case:"content",value:new zw.Zp({ripgrepTruncated:!0})}});case"files_with_matches":return new zw.vD({result:{case:"files",value:new zw.T7({ripgrepTruncated:!0})}});case"count":return new zw.vD({result:{case:"count",value:new zw.xA({ripgrepTruncated:!0})}});default:throw new Error(`Unknown output mode: ${String(e)}`)}}function m_(e){return"success"===e.result.case&&Object.values(e.result.value.workspaceResults).some((e=>!0===e.result.value?.clientTruncated))}function g_(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 w_(e){return/^(utf-?16|ucs-?2)/i.test(e)}const y_=(0,l.h)("local-exec/grep"),v_=(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"]}),b_=(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"]}),S_=(0,u.v5)("local_exec.grep.rg.spawn_ms",{description:"Time to start the ripgrep process for one Grep or Glob search",labelNames:["sandboxed"]}),k_=(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 __(e){return e instanceof Error&&e.message.includes("ENOENT")&&e.message.includes("spawn")}function C_(e){try{return(0,So.existsSync)(e)}catch{return"check_failed"}}function E_(e){if("object"==typeof e&&null!==e&&"errno"in e){const t=e.errno;if("number"==typeof t)return t}}function x_(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 P_(e,t,r,n){return{...I_(e),...n,cwd:t,cwdExists:C_(t),errorMessage:wc(r),errorCode:gc(r),errno:E_(r),syscall:x_(r,"syscall"),errorPath:x_(r,"path")}}function R_(e){return new Error(`Path does not exist: ${e}`)}function I_(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,So.existsSync)(e)}catch(e){t.rgPathExists=!1,t.rgPathExistsError=e instanceof Error?e.message:String(e)}try{const r=(0,So.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,So.existsSync)(r),t.parentDirExists&&(t.parentDirContents=(0,So.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,So.existsSync)(n),t.grandparentDirExists&&(t.grandparentDirContents=(0,So.readdirSync)(n).slice(0,50))}catch(e){t.grandparentDirError=e instanceof Error?e.message:String(e)}if(t.rgPathExists)try{const r=(0,So.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,So.existsSync)(n)}catch{t.asarExists="check_failed"}const i=r.concat(o);try{if(t.asarUnpackedDirExists=(0,So.existsSync)(i),t.asarUnpackedDirExists){const r=(0,s.dirname)((0,s.dirname)(e));t.ripgrepPkgDirExists=(0,So.existsSync)(r)}}catch{t.asarUnpackedDirExists="check_failed"}}}return t}class T_{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,Ko.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,Ko.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,Ko.BJ)(t,e)))?void 0:[...new Set(r.map((({target:e})=>e)))]}searchTarget(e,t){if(!t.path)return".";const r=(0,Ko.o1)(t.path,this.singleWorkspacePath??e);return(0,Ko.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 ca(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,vo.stat)(e)).isFile())return;const{encoding:t}=await Li(e);return w_(t)?t.toLowerCase():void 0}catch{return}}((0,Ko.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,Ko.o1)(s.file,t),i=await vc(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 py(t,(e=>(0,Ko.o1)(n(e),r)));return s.statTimedOut&&(y_.info(e,"newest_first.stat_timeout_fallback",{toolCallId:o.toolCallId,execId:o.execId,outputMode:o.outputMode,fileCount:t.length}),b_.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,T_.CLIENT_LIMIT_LINES)}async runFilesMode(e,t,r,n,o,s,i){const a={stack:[],error:void 0,hasError:!1};try{const d=s_(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?T_.HARD_MAX_OUTPUT_LINES:T_.CLIENT_LIMIT_LINES,u=T_.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 Gw;let s=0,i=0,a=0;for(;Vw(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&&Vw(c,a,o);)l.push(c.slice(a,o.lineEnd)),a=o.nextStart;return{files:l,totalFiles:Xw(s),clientTruncated:s>t,ripgrepTruncated:s>=r}}(c,l,u)),m=f.totalFiles>T_.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 zw.T7({files:w,totalFiles:Xw(f.totalFiles-y),clientTruncated:m,ripgrepTruncated:f.ripgrepTruncated||p.timedOut||p.stdoutByteCapped});return{result:new zw.vD({result:{case:"files",value:v}}),timedOut:p.timedOut}}catch(e){a.error=e,a.hasError=!0}finally{i_(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=s_(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?T_.HARD_MAX_OUTPUT_LINES:T_.CLIENT_LIMIT_LINES,u=T_.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 Gw;let i=0;for(;Vw(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:Xw(a),totalMatches:Xw(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 zw.xA({counts:g.map((e=>new zw.sS({file:e.file,count:Xw(e.count)}))),totalFiles:Xw(f.totalFiles-y),totalMatches:Xw(f.totalMatches-v),clientTruncated:f.totalFiles>T_.CLIENT_LIMIT_LINES,ripgrepTruncated:f.ripgrepTruncated||p.timedOut||p.stdoutByteCapped});return{result:new zw.vD({result:{case:"count",value:b}}),timedOut:p.timedOut}}catch(e){a.error=e,a.hasError=!0}finally{i_(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=s_(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=T_.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 s_(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 Gw;let a=0,c=0,l=0,u=0;for(;Vw(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:Xw(l),totalMatchedLines:Xw(a),totalFiles:Xw(s.size),clientTruncated:c>=t,ripgrepTruncated:l>=r}}(e,t,r)}catch(e){o.error=e,o.hasError=!0}finally{i_(o)}}(p,T_.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 zw.Zp({matches:C.map((e=>new zw.uI({file:e.file,matches:e.matches.map((e=>new zw.dx({lineNumber:e.lineNumber,content:e.content,isContextLine:e.isContextLine})))}))),totalLines:Xw(m-k),totalMatchedLines:Xw(g-_),clientTruncated:w,ripgrepTruncated:y||h.timedOut||h.stdoutByteCapped});return{result:new zw.vD({result:{case:"content",value:E}}),timedOut:h.timedOut}}catch(e){a.error=e,a.hasError=!0}finally{i_(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=s_(s,(0,$.VI)(e.withName("LocalGrepExecutor.decodeLinesAsRead")),!1),c=function(e,t){const r=[],o=new Gw;let s=0,i=0,a=e.indexOf("�");for(;-1!==a&&Vw(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=Kw(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()+T_.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)(t_((0,Ko.o1)(l[h],r)),e,"encoding detection timed out")}catch(e){if(e instanceof Dr.MU)break;continue}void 0===t||w_(t)||u.set(l[h],t)}return h<l.length&&y_.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),Ws.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{i_(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 y_.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){y_.info(e,"ripgrep.deadline_reached",{toolCallId:t.toolCallId,execId:t.execId,outputMode:t.outputMode,...r}),v_.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(T_.INDEXED_GREP_CONTEXT_TIMEOUT_MS),i={phase:"provider"},a=performance.now();try{return await(0,Dr.wj)(this.grepProvider.executeIndexedGrep(o,t,r,i),T_.INDEXED_GREP_TIMEOUT_MS,`Indexed grep timed out after ${T_.INDEXED_GREP_TIMEOUT_MS/1e3}s`)}catch(t){if(t instanceof Dr.MU)return s(t),void y_.debug(e,"indexed_grep.timeout_fallback",{...n,totalMs:Math.round(performance.now()-a),...i});throw t}finally{s()}}static ripgrepTimeoutError(){return new d_(`Timed out after ${T_.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??T_.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(T_.ripgrepTimeoutError());let f;const m="insecure_none"===s.type?"false":"true",g=performance.now();let w=g;try{const e=s;f=(0,To.spawnInSandbox)((0,To.Ko)(),r,{cwd:t},e),w=performance.now(),0}catch(r){if(p(),__(r)){const n=(0,To.Ko)();if(y_.error(e,"rg_diagnostics.spawn_throw",void 0,P_(n,t,r,i)),!1===C_(t))return u(R_(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=g_(y,!0,this.stdoutDecodes.get(i));""===e.stdout?u(T_.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(),__(r)){const n=(0,To.Ko)();if(y_.error(e,"rg_diagnostics.spawn_enoent",void 0,P_(n,t,r,i)),!1===C_(t))return void u(R_(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=g_(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}),S_.histogram(e,w-g,{sandboxed:m}),C||_||o.aborted||e.signal.aborted||0!==t&&1!==t||k_.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 vc(t[0]);return null===r?{error:a_(e)}:await this.ignoreService.isCursorIgnored(r)?{error:`Path '${e}' is filtered out by .cursorignore`}:await l_(t[0])?{error:c_(e)}:{resolvedTarget:r}}async execute(e,t,r){if(!Rl(this.encodingSlices,e))return this.search(e,t,r,void 0);const n=new Hl,o=await this.search(e,t,r,n);return"success"===o.result.case&&Bl(this.encodingSlices,e,{layer:"exec_grep",evidence:n.evidence(),partial:m_(o)},o),o}async search(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{const a=s_(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=os(t.sandboxPolicy),p=this.grepProvider.getWorktreeGuardInfo?.(c);if((0,Ko.fl)({targetPath:t.path,workspacePaths:c,mainWorktreePath:p?.mainWorktreePath}))return new zw.Ud({result:{case:"error",value:new zw.ts({error:Ko.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 zw.Ud({result:{case:"error",value:new zw.ts({error:r.error})}});void 0!==this.mcpStateAccessor&&uy(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,Ko.BJ)(s,o))continue;const i=await vc(s);if(null!==i)if(await this.ignoreService.isCursorIgnored(i))r=!0;else{if(await l_(s))return new zw.Ud({result:{case:"error",value:new zw.ts({error:c_(m.path)})}});t.push(n),void 0!==this.mcpStateAccessor&&uy(e,this.mcpStateAccessor,i)}}if(0===t.length){const e=r?`Path '${m.path}' is filtered out by .cursorignore`:a_(m.path);return new zw.Ud({result:{case:"error",value:new zw.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?h_(T_.MAIN_TIMEOUT_MS):void 0;let n=0,o=!1;try{for(const s of g){if(!0===t?.signal.aborted){r[s]=f_(u),n++,o=!0;continue}if(!1===C_(s))return new zw.Ud({result:{case:"error",value:new zw.ts({error:`Path does not exist: ${s}`})}});const i=t??h_(T_.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 d_))throw t;if(r[s]=f_(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(p_));if(this.reportDeadlineReached(a.ctx,d,{streaming:e,folderCount:g.length,stoppedFolderCount:n,outcome:t?"failed":"partial"}),t)throw T_.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=>u_(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 zw.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 zw.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 zw.vD({result:{case:"count",value:s}});break}default:n[t]=o}}return n}(r,g),i=new zw._0({pattern:m.pattern,path:void 0!==m.path&&this.isRootIndependentSearchPath(m.path)?(0,Ko.o1)(m.path):m.path,outputMode:u,workspaceResults:o});return new zw.Ud({result:{case:"success",value:i}})}catch(e){if(m.path){const e=(0,Ko.o1)(m.path,this.singleWorkspacePath);try{await(0,vo.stat)(e)}catch(t){return new zw.Ud({result:{case:"error",value:new zw.ts({error:`Path does not exist: ${e}`})}})}}return new zw.Ud({result:{case:"error",value:new zw.ts({error:e instanceof Error?e.message:String(e)})}})}}catch(e){o.error=e,o.hasError=!0}finally{i_(o)}var i}}T_.MAIN_TIMEOUT_MS=25e3,T_.INDEXED_GREP_TIMEOUT_MS=25e3,T_.INDEXED_GREP_CONTEXT_TIMEOUT_MS=T_.INDEXED_GREP_TIMEOUT_MS+100,T_.HARD_MAX_OUTPUT_LINES=1e4,T_.CLIENT_LIMIT_LINES=2e3,T_.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 A_=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()}),A_.extend({memory:je.object({anon_bytes:je.number()}).nullish().catch(null)});const $_=je.number().int().nonnegative(),M_=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(M_)}),je.object({type:je.literal("summary"),files_searched:$_,more:je.boolean(),stop_reason:je.string().nullable(),skipped:je.object({over_size:$_,size_unknown:$_,budget_exhausted:$_,fetch_failed:$_,unreadable:$_})}),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 D_=r("../proto/dist/generated/agent/v1/ls_exec_pb.js"),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},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});class N_{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{O_(r,(0,$.VI)(e.withName("LocalLsExecutor.execute")),!1).ctx;const n=(0,Ko.o1)(t.path,this.workspacePath);try{let r;try{r=await(0,vo.stat)(n)}catch(e){return"ENOENT"===gc(e)?function(e){const t=_p(e,"terminals");return null!==t&&0===t.remainingPath.length}(n)?new D_.fv({result:{case:"error",value:new D_.uj({path:n,error:"No active terminals."})}}):new D_.fv({result:{case:"error",value:new D_.uj({path:n,error:`Path does not exist: ${n}`})}}):new D_.fv({result:{case:"error",value:new D_.uj({path:n,error:wc(e)})}})}if(!r.isDirectory())return new D_.fv({result:{case:"error",value:new D_.uj({path:n,error:`Path is not a directory: ${n}`})}});const o=os(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 D_.fv({result:{case:"timeout",value:new D_.ze({directoryTreeRoot:a})}}):new D_.fv({result:{case:"success",value:new D_.PC({directoryTreeRoot:a})}})}catch(e){return new D_.fv({result:{case:"error",value:new D_.uj({path:n,error:e instanceof Error?e.message:"Unknown error occurred"})}})}}catch(e){r.error=e,r.hasError=!0}finally{F_(r)}}async getDirectoryTree(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{return O_(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{F_(o)}}async buildTreeFromRipgrepStream(e,t,r,n,o){const i={stack:[],error:void 0,hasError:!1};try{O_(i,(0,$.VI)(e.withName("LocalLsExecutor.buildTreeFromRipgrepStream")),!1);const a=(0,s.resolve)(t),c=new D_.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}=da(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 vc(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{F_(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 D_.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]=Xw(e.fullSubtreeExtensionCounts[i]+1),e.numFiles??=0,e.numFiles=Xw(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 D_.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 L_ extends Error{constructor(e,t){super(`Tool ${e} not found, available tools: ${t.join(", ")}`),this.toolName=e,this.availableTools=t,this.name="McpToolNotFoundError"}}function j_(e){if(e instanceof L_)return!0;if(!(e instanceof Error)||"McpToolNotFoundError"!==e.name)return!1;const t=e;return"string"==typeof t.toolName&&Array.isArray(t.availableTools)}function U_(e){return!0===e.url?.startsWith("mcp-provider://")}function B_(e){const t=e?.trim();return void 0===t||0===t.length?void 0:t}function W_(e){const t=e?.trim();return void 0===t||0===t.length?void 0:t}function H_(e,t){return(t??[]).some((t=>{const r=B_(t.command),n=W_(t.serverUrl);if(void 0===r&&void 0===n)return!1;const o=void 0===r||void 0!==e.command&&(0,eb.mD)(r,e.command),s=void 0===n||void 0!==e.url&&(0,eb.eA)(n,e.url);return o&&s}))}function q_(e,t){if(U_(e))return!1;const r=t?.rules??[];return r.length>0&&H_(e,r)}var z_=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 G_ extends Error{constructor(e){super(`MCP server "${e}" is disabled`),this.name="McpServerDisabledError"}}class V_ extends Error{constructor(e){super(`MCP server "${e}" has not been approved`),this.serverName=e,this.name="McpServerNotApprovedError"}}class K_ extends Error{constructor(e,t){super(`MCP server "${e}" is overridden by ${t}`),this.serverName=e,this.overridingConfigPath=t,this.name="McpServerOverriddenError"}}class J_{constructor(e){this.disabledService=e}async load(e,t,r,n,o){if(await this.disabledService.isServerDisabled(t))throw new G_(t);return await o(e,r)}}class Z_{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 V_(t);return await o(e,r)}catch(e){s.error=e,s.hasError=!0}finally{z_(s)}}}class X_{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,mo.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,vo.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,vo.mkdir)(s.default.dirname(this.approvalsPath),{recursive:!0}),await(0,vo.writeFile)(this.approvalsPath,JSON.stringify(e,null,2))}async saveApprovals(e){await this.saveApprovalsToFile(e),this.approvalsPromise=Promise.resolve(e)}}const Q_=["https://api.cursor.com","https://api2.cursor.sh"],Y_=["CURSOR_API_BASE_URL","CURSOR_BACKEND_URL"],eC=/^MCP server ".+" is blocked by \S/u;function tC(e){if(void 0!==e&&""!==e)try{return new URL(e).origin}catch{return}}function rC(e,t=process.env){if(void 0===e)return!1;let r;try{r=new URL(e)}catch{return!1}if("/v1/agent/mcp"!==r.pathname.replace(/\/+$/,"")&&!r.pathname.startsWith("/internal/agent-serve/agent-sdk-mcp-relay/"))return!1;const n=new Set(Q_);for(const e of Y_){const r=tC(t[e]);void 0!==r&&n.add(r)}return n.has(r.origin)}function nC(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function oC(e,t){if("string"!=typeof e)return;const r=e.trim();return""===r||r.length>t||/\p{Cc}/u.test(r)?void 0:r}function sC(e){if(!Array.isArray(e))return;const t=[];for(const r of e.slice(0,200)){const e=oC(r,200);void 0!==e&&t.push(e)}return t}function iC(e,t){const r=t.slice(0,20).join(", "),n=t.length-20;return n>0?` ${e}: ${r}, and ${n} more.`:` ${e}: ${r}.`}var aC=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},cC=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 lC{async load(e,t,r,n,o){const s=o(e,r);return new dC(e,t,s,r)}}function uC(e){let t;return e.then((e=>{t=e})).catch((()=>{})),t}class dC{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=aC(t,(0,$.VI)(e.withName("CachedMcpClient.getTools")),!1);r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("cacheTraceId",this.clientPromiseTraceId??"undefined");const n=uC(this.toolsPromise);return void 0!==n?n:await this.toolsPromise}catch(e){t.error=e,t.hasError=!0}finally{cC(t)}}async callTool(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{const i=aC(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{cC(s)}}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{const r=aC(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{cC(t)}}async getClient(e){const t={stack:[],error:void 0,hasError:!1};try{const r=aC(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{cC(t)}}async listResources(e){const t={stack:[],error:void 0,hasError:!1};try{const r=aC(t,(0,$.VI)(e.withName("CachedMcpClient.listResources")),!1);r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("cacheTraceId",this.clientPromiseTraceId??"undefined");const n=uC(this.resourcesPromise);return void 0!==n?{resources:n}:{resources:await this.resourcesPromise}}catch(e){t.error=e,t.hasError=!0}finally{cC(t)}}async readResource(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=aC(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{cC(r)}}async listPrompts(e){const t={stack:[],error:void 0,hasError:!1};try{const r=aC(t,(0,$.VI)(e.withName("CachedMcpClient.listPrompts")),!1);r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("cacheTraceId",this.clientPromiseTraceId??"undefined");const n=uC(this.promptsPromise);return void 0!==n?n:await this.promptsPromise}catch(e){t.error=e,t.hasError=!0}finally{cC(t)}}async getPrompt(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=aC(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{cC(n)}}async getState(e){const t={stack:[],error:void 0,hasError:!1};try{const r=aC(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{cC(t)}}async getAllowlistInUse(){try{await this.toolsPromise;const e=await this.clientPromise;return await(e?.getAllowlistInUse?.())}catch{return}}async getAllowlistRefusal(){if(void 0!==this.config&&"url"in this.config&&rC(this.config.url))try{return void await this.toolsPromise}catch(e){return function(e){const t=e instanceof Error?e.message:"string"==typeof e?e:void 0;if(void 0===t)return;const r=t.indexOf("{");if(-1===r)return;let n;try{n=JSON.parse(t.slice(r))}catch{return}if(!nC(n))return;const o=oC(n.error,700);return void 0!==o&&eC.test(o)?o:void 0}(e)}}async close(){try{const e=await this.clientPromise;await(e?.close?.())}catch{}}}function hC(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function pC(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 fC(e){return e?` (${pC(e,"")})`:""}function mC(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=mC(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=mC(n);if(void 0===e)return;r[t]=e}return r}function gC(e){const t=mC(e);if(null!=t&&"object"==typeof t&&!Array.isArray(t))return t}const wC=new TextDecoder("utf-8",{fatal:!0});function yC(e){return"string"==typeof e?e.split(";")[0]?.trim().toLowerCase()??"":""}function vC(e,t){const r=Buffer.from(t,"base64"),n=function(e){try{const t=wC.decode(e);return t.includes("\0")?void 0:t}catch{return}}(r)??(function(e){const t=yC(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: ${pC(e.uri,"unknown")} (${o}, ${r.byteLength} bytes). The file is not text, so its contents are not included.]`,binary:!0}}const bC=new Set(["image/png","image/jpeg","image/jpg","image/gif","image/webp"]);function SC(e){return"string"==typeof e.text&&e.text.length>0?e.text:void 0}function kC(e){if(!hC(e))return;const t=e.resource;return hC(t)&&void 0===SC(t)&&"string"==typeof t.blob&&bC.has(yC(t.mimeType))?t.blob:void 0}function _C(e){const t=e,r=t.resource;if(hC(r)){const e=SC(r);return void 0!==e?e:"string"==typeof r.blob?vC(r,r.blob).text:`Resource: ${pC(r.uri,"unknown")}${fC(r.name)}`}return t.uri?`Resource: ${pC(t.uri,"unknown")}${fC(t.name)}`:`Unsupported content type "${e.type}": ${JSON.stringify(e)}`}function CC(e){const t=gC(e);if(void 0!==t&&0!==Object.keys(t).length)try{return Buffer.byteLength(JSON.stringify(t))<=262144?t:void 0}catch{return}}var EC=r("zod/v4-mini");const xC=EC.object({CLIENT_ID:EC.string(),CLIENT_SECRET:EC.optional(EC.string()),scopes:EC.optional(EC.array(EC.string()))}),PC=EC.strictObject({caBundle:EC.string().check(EC.trim(),EC.minLength(1),EC.maxLength(131072))}),RC=EC.object({type:EC.optional(EC.literal("stdio")),command:EC.string(),args:EC.optional(EC.array(EC.string())),env:EC.optional(EC.record(EC.string(),EC.string())),envFile:EC.optional(EC.string()),cwd:EC.optional(EC.string()),enabledTools:EC.optional(EC.array(EC.string())),startupTimeoutSec:EC.catch(EC.optional(EC.number().check(EC.positive())),void 0)}),IC=EC.object({type:EC.optional(EC.enum(["http","sse"])),url:EC.string(),headers:EC.optional(EC.record(EC.string(),EC.string())),auth:EC.optional(xC),tls:EC.optional(PC),placement:EC.optional(EC.enum(["server","client"])),enabledTools:EC.optional(EC.array(EC.string()))}),TC=EC.union([RC,IC]),AC=EC.object({mcpServers:EC.record(EC.string(),TC)});Error;const $C=/\$\{(?:env:([A-Za-z_][A-Za-z0-9_]*)|([^:}]+)(?::-([^}]*))?)\}/g;function MC(e,t){if("string"==typeof e)return function(e,t){return e.replace($C,((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=>MC(e,t)));if(null!==e&&"object"==typeof e){const r={};for(const[n,o]of Object.entries(e))r[n]=MC(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 DC(e){const t=Object.entries(e);return{jsonKeyOf:new Map(t.map((([e,t])=>[t,e]))),tomlKeyOf:new Map(t)}}const OC=DC({CLIENT_ID:"client_id",CLIENT_SECRET:"client_secret",scopes:"scopes"}),FC=DC({caBundle:"ca_bundle"}),NC=DC({type:"type",command:"command",args:"args",env:"env",envFile:"env_file",cwd:"cwd",enabledTools:"enabled_tools",startupTimeoutSec:"startup_timeout_sec"}),LC=DC({type:"type",url:"url",headers:"http_headers",auth:"auth",tls:"tls",placement:"placement",enabledTools:"enabled_tools"}),jC=(new Map([["auth",{keys:OC,unknownKeyIsError:!1}],["tls",{keys:FC,unknownKeyIsError:!0}]]),"enabled");new Set([...NC.jsonKeyOf.keys(),...LC.jsonKeyOf.keys(),jC]);Symbol("disabled");const UC=(0,l.h)("McpConfig");async function BC(e,t=e=>process.env[e]){try{const r=await(0,vo.readFile)(e,"utf8"),n=MC((0,Lh.qg)(r),t);return AC.parse(n)}catch{return{mcpServers:{}}}}async function WC(e,t=e=>process.env[e]){const r={config:{mcpServers:{}},diagnostics:[]};return r}async function HC(e,t=e=>process.env[e]){const{config:r,diagnostics:n}=await WC(0,t);return n.length>0&&UC.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 qC=["enterprise","project","user","env"];function zC(e){return"project"===e||"env"===e}const GC=["0.0.0.0/0","::/0"];function VC(e){const t=(e??[]).filter((e=>e.trim().length>0)),r=t.flatMap((e=>{const t=(0,eb.bi)(e);return void 0===t?[]:[t]}));return{hasInvalidEntries:r.length!==t.length,entries:r}}function KC(e){const t=!0===e.enabled,r=VC(e.mcpNetworkDenylist),n="deny_all"===e.mcpNetworkMode||r.entries.includes("*")||r.hasInvalidEntries,o=t?function(e){if("allow_all"===e.mcpNetworkMode)return[...GC];const t=VC(e.mcpNetworkAllowlist);if("allowlist"===e.mcpNetworkMode)return t.entries.includes("*")?[...GC]:t.entries;if(!function(e){return(e.mcpNetworkAllowlist??[]).some((e=>e.trim().length>0))}(e))return[...GC];const r=(0,eb.b6)(e);return r.includes("*")?[...GC]:r}(e):[],s=t?n?["*"]:r.entries:[];return JSON.stringify({enabled:t,mode:e.mcpNetworkMode,allow:n?[]:o,deny:s})}class JC 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 ZC=new Set(["invalid_auth","not_authed","account_inactive","token_revoked","token_expired"]);class XC extends Error{constructor(){super("Your organization admin only allows Slack workspaces your company manages. Connect your company Slack workspace instead."),this.name="SlackWorkspaceNotManagedError"}}class QC 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 YC(e){return URL.canParse(e)&&"mcp.slack.com"===new URL(e).hostname.toLowerCase()}function eE(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&&ZC.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(!YC(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 QC;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 QC;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 XC;return e(i,a)}}function tE(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)&&uE(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=oE(e,n),s=cE(o,t,r);return Object.is(s,o)?[]:[[n,s]]})),a=Object.getOwnPropertyDescriptor(e,"cause"),c=void 0===a?void 0:oE(e,"cause"),l=cE(c,t,r),u=e instanceof AggregateError?oE(e,"errors"):void 0,d=function(e,t,r){if(!Array.isArray(e))return e;const n=e.map((e=>cE(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])=>nE(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(iE(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[sE];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=pE(e);return void 0!==g&&pE(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 rE(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 nE(e,t,r){const n=Object.getOwnPropertyDescriptor(e,t);return!0===n?.writable&&Reflect.defineProperty(e,t,{...n,value:r})}function oE(e,t){try{const r=Object.getOwnPropertyDescriptor(e,t);return void 0===r?.get?r?.value:r.get.call(e)}catch{return}}const sE=Symbol.for("nodejs.util.inspect.custom");function iE(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 aE(e,t,r,n){if("string"==typeof e)return t(e);if("object"!=typeof e||null===e)return e;if(e instanceof Error)return tE(e,t,n);if(Array.isArray(e)){if(r>=4)return;return e.slice(0,64).map((e=>aE(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:aE(a,t,r,n),writable:!0,enumerable:!0,configurable:!0})}catch{}return o}(e,t,r+1,n)}function cE(e,t,r){if(e instanceof Error)return tE(e,t,r);try{return uE(e,t)?aE(e,t,1,r):e}catch{return}}const lE=4096;function uE(e,t){const r=new Set,n=[e];for(let o=0;n.length>0;o++){if(o>=lE||n.length>lE)return dE(e,t);const s=n.pop();if("string"==typeof s){if(t(s)!==s)return!0}else if((hE(s)||s instanceof Error)&&!r.has(s)){r.add(s),s instanceof Error&&(n.push(oE(s,"message"),oE(s,"stack"),oE(s,"cause")),s instanceof AggregateError&&n.push(oE(s,"errors")));for(const e of Object.keys(s))n.push(oE(s,e))}}return!1}function dE(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,oE(n,e)]))),message:oE(n,"message"),stack:oE(n,"stack"),cause:oE(n,"cause"),...n instanceof AggregateError?{errors:oE(n,"errors")}:{}}):t);var n}))}catch{return!0}return void 0!==n&&t(n)!==n}function hE(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 pE(e){try{return"string"==typeof e.name?e.name:void 0}catch{return}}const fE=/spt_[A-Za-z0-9_]{6,}/g,mE=/[A-Z0-9]/;function gE(e){return function(e){return e.replace(fE,(e=>function(e){return e.slice(4).split("_").some((e=>e.length>=8&&mE.test(e)))}(e)?"[redacted Link shared payment token]":e))}(e)}var wE=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 yE=new Set([429,502,503,504]);function vE(e){return"object"==typeof e&&null!==e}function bE(e){const t=vE(e)?e.code:void 0,r=(e instanceof Error||vE(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&&yE.has(o)&&!yE.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 SE=8192;function kE(e){return void 0===e?"unknown":"url"in e&&e.url.length>0?void 0!==Ev(e.url)?"rest_mcp":"streamable_http":"command"in e?"stdio":"unknown"}new Set(["ENOENT","EACCES","ENOTDIR","EPERM"]);const _E=/\$\{[^}]*\}/;function CE(e){if(void 0!==function(e){if(void 0===e)return;const t=e.trim();return 0!==t.length&&_E.test(t)?t:void 0}(e))return;const t=e?.trim();return t&&t.length>0?t:void 0}const EE=new Map;async function xE(e,t=fetch){if(void 0===Ev(e))return;const r=new URL(e),n=`${r.origin}/.well-known/oauth-protected-resource${r.pathname.replace(/\/+$/,"")}`,o=EE.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 EE.set(n,{metadata:s,expiresAtMs:Date.now()+3e5}),s}(0,ys.J)((function(){EE.clear()}));const PE={info:()=>{},warn:()=>{},error:()=>{},debug:()=>{}};function RE(e){return PE}const IE=/^[\x21\x23-\x5B\x5D-\x7E]+$/,TE=["invalid_request","invalid_token","insufficient_scope"];function AE(e){return TE.some((t=>t===e))}function $E(e){const t=new Set;for(const r of e)r.length<=200&&IE.test(r)&&t.add(r);return[...t]}const ME=/[!#$%&'*+.^_`|~0-9A-Za-z-]+/y,DE=/"((?:[^"\\]|\\.)*)"?/y,OE=/[^\s,]*/y;function FE(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(ME);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(DE)?.[1]??"").replace(/\\(.)/g,"$1"):o(OE)?.[0]??"";if((void 0===r||"bearer"===r)&&s[0].toLowerCase()===t)return i}}const NE={stepUpScopes:[],signInMissing:[]};function LE(e){return Array.isArray(e)?e.filter((e=>"string"==typeof e&&e.length>0)):void 0}function jE(e){if("object"!=typeof e||null===e||Array.isArray(e))return NE;const t=LE("grantedScopes"in e?e.grantedScopes:void 0),r=LE("requestedScopes"in e?e.requestedScopes:void 0);return{...void 0!==t?{grantedScopes:t}:{},stepUpScopes:LE("stepUpScopes"in e?e.stepUpScopes:void 0)??[],signInMissing:LE("signInMissing"in e?e.signInMissing:void 0)??[],...void 0!==r?{requestedScopes:r}:{}}}function UE(e){return(e??"").split(/\s+/).filter((e=>e.length>0))}function BE(e,t){return e.filter((e=>!t.has(e)))}function WE(e){const t=Uv(e.serverUrl),r=e.connectorName??t?.displayName??e.accountKey,n=RE(e.accountKey);let o;const s=async()=>jE(await e.readRecord()),i=async t=>{if(void 0!==t.grantedScopes)return t.grantedScopes;const r=UE(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=FE(t,"error")?.toLowerCase(),n=FE(t,"resource_metadata");return{error:void 0===r||""===r?"none":AE(r)?r:"other",scopes:$E((FE(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 Bv.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 $E(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:UE(t.searchParams.get("scope"))})}}},async recordTokens(t,{isRefresh:r}){const n=await e.readRecord();if(void 0===n)return;const o=jE(n),s=UE(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=BE(o.requestedScopes,c);await e.writeRecord({grantedScopes:i,stepUpScopes:BE(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}=jE(e);return t.length>0?{stepUpScopes:t,signInMissing:[]}:void 0}(await e.readRecord()):void 0)}}}function HE(e){const t=Uv(e.serverUrl);for(const r of e.scopes){const e=t?.stepUpScopes[r]?.action;if(void 0!==e)return e}return e.toolTitle}function qE(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:HE(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 zE extends Error{constructor(e,t,r){super(qE({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 qE({kind:this.decision.kind,serverUrl:this.serverUrl,connectorName:this.connectorName,scopes:this.decision.scopes,toolTitle:e??this.decision.toolName})}}function GE(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 VE(e){return e instanceof Error&&/does not support dynamic client registration/i.test(e.message)}Error,Error;const KE=new Set(["UnauthorizedError","InvalidGrantError","InvalidTokenError","InvalidClientError","UnauthorizedClientError"]),JE=new Set(["invalid_grant","invalid_token","invalid_client","unauthorized_client"]),ZE=[/\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 XE=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/types.js");const QE="2026-07-28",YE=-32022,ex="io.modelcontextprotocol/protocolVersion",tx="io.modelcontextprotocol/clientCapabilities",rx="io.modelcontextprotocol/clientInfo",nx="io.modelcontextprotocol/serverInfo",ox={name:"cursor",version:"1.0.0"},sx=new Map;function ix(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function ax(e){const t=new URL(String(e));return t.hash="",t.href}function cx(e,t){const r=sx.get(e);return!(void 0===r||r<=t()&&(sx.delete(e),1))}function lx(e,t){try{return ax(e)===t}catch{return!1}}function ux(e){return(e.headers.get("content-type")??"").toLowerCase().includes("application/json")}const dx=new Set(["events/subscribe","events/unsubscribe","events/poll","events/stream"]);function hx(e,t,r,n,o=t.message){const s=new Headers(e?.headers);if(s.set("mcp-protocol-version",QE),s.set("mcp-method",r),s.delete("mcp-session-id"),!t.isRequest&&o===t.message)return{...e,headers:s};const i=ix(o.params)?o.params:{},a=ix(i._meta)?i._meta:{},c=function(e,t){const r="tools/call"===e||"prompts/get"===e||dx.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,[ex]:QE,[tx]:n.capabilities,[rx]:n.clientInfo}}});return{...e,headers:s,body:l}}function px(e){return new Response(JSON.stringify({jsonrpc:"2.0",...e}),{status:200,headers:{"content-type":"application/json"}})}function fx(e,t){const r=ax(t.serverUrl),n=t.now??Date.now;let o={capabilities:{},clientInfo:{...ox}},s=!1;const i=()=>s||cx(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,hx(a,t,"server/discover",o,c)),d=await async function(e,t,r){if(!e.ok||!ux(e))return e;let n;try{n=await e.clone().json()}catch{return e}if(!ix(n)||!ix(n.result))return e;const o=n.result,s=o.supportedVersions;if(!Array.isArray(s)||!s.includes(QE))return px({id:t,error:{code:YE,message:"Unsupported protocol version",data:{requested:QE,supported:s??[]}}});const i=ix(o._meta)?o._meta:{},a=ix(i[nx])?i[nx]:{name:new URL(r).hostname,version:"unknown"};return px({id:t,result:{protocolVersion:XE.aE,capabilities:ix(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){sx.set(e,t()+6e5)}(r,n)),d}return e(i,hx(a,t,c,o))};return async(t,c)=>{const l=function(e,t,r){if("POST"!==(t?.method??"GET").toUpperCase()||"string"!=typeof t?.body||!lx(e,r))return;let n;try{n=JSON.parse(t.body)}catch{return}if(!ix(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()&&lx(e,r)}(t,c,r)&&i()?new Response(null,{status:405}):e(t,c);if(l.isRequest&&"initialize"===l.method){const e=ix(l.message.params)?l.message.params:{};o={capabilities:ix(e.capabilities)?e.capabilities:{},clientInfo:ix(e.clientInfo)?e.clientInfo:o.clientInfo}}const u=l.isRequest&&"initialize"===l.method;if(u?cx(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||!ux(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(!ix(r)||!ix(r.error))return!1;const n=r.error;if(n.code!==YE||!ix(n.data))return!1;const o=n.data.supported;return Array.isArray(o)&&o.includes(QE)}(d)){const e=await a(l,t,c);return s?e:d}return d}}function mx(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()===Cv));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()!==Cv))),cursorAuthHeaderValue:n[1],cursorAuthOrigin:o}}function gx(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(Cv,i),r(n,{...o,headers:a,redirect:"manual"})}}class wx{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 yx=r("crypto");function vx(e){const t={};for(const[r,n]of Object.entries(e))void 0!==n&&(t[r]=n);return t}function bx(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 Sx(e,t){return bx(e,t)}function kx(e){if(e)return(0,yx.createHash)("sha256").update(e).digest("hex").slice(0,12)}function _x(e){if(e&&0!==e.length)return kx(JSON.stringify([...e].sort()))}function Cx(e){return{clientIdHash:kx(e?.client_id),hasClientSecret:(e?.client_secret??"").length>0,redirectUrisHash:_x(e?.redirect_uris),redirectUriCount:e?.redirect_uris?.length??0}}function Ex(e){return"object"==typeof e&&null!==e}function xx(e,t){let r=e;for(const e of t){if(!Ex(r)||!(e in r))return;r=r[e]}return r}function Px(e,t){for(const r of t){const t=xx(e,r.split("."));if("string"==typeof t)return t}}function Rx(e){if(!e||"object"!=typeof e)return;const t=e.errorCode;return"string"==typeof t?t:void 0}function Ix(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 Tx=e=>e;function Ax(e,t){if(e instanceof Error){const r=e.message;return r&&r!==e.name?Lx(t(r)):void 0}if("string"==typeof e||"number"==typeof e||"boolean"==typeof e){const r=String(e);return r?Lx(t(r)):void 0}}function $x(e){if(e&&"object"==typeof e)return Ex(e)?e.cause:void 0}function Mx(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(Lx(t(String(o)))):Ex(o)&&"string"==typeof o.message&&n.push(Lx(t(o.message)));break}{const e=Ax(o,t);n.push(e?`${o.name}: ${e}`:o.name),o=$x(o)}}return n.length>1?n.join(" > "):void 0}const Dx="[REDACTED]",Ox=/(^|_|-)(token|secret|password|assertion|authorization|verifier|challenge|code)(_|-|$)/i;function Fx(e){return e.replace(/(authorization[^:=\r\n]{0,32}[:=]\s*["']?)(?:[A-Za-z][\w.~+/-]*[ \t]+)?[^"',\s&}]+/gi,`$1${Dx}`).replace(/((?:access_token|refresh_token|id_token|client_secret|code|password|assertion|token|secret)[^:=\r\n]{0,32}[:=]\s*["']?)([^"',\s&}]+)/gi,`$1${Dx}`).replace(/(\bBearer\s+)([A-Za-z0-9\-._~+/]+=*)/gi,`$1${Dx}`)}function Nx(e,t=256){return e.length>t?`${e.slice(0,Math.max(0,t-3))}...`:e}function Lx(e,t){return Nx(Fx(e),t?.maxLength)}function jx(e,t=Tx){if("string"==typeof e)return Nx(Fx(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")||Ox.test(t)}(e)?Dx:"string"==typeof r?Fx(t(r)):r));if(!r)return;return Nx(r)}catch{return}}function Ux(e,t=Tx){const r=$x(e),n=e instanceof Error?e.name:null!=e?typeof e:void 0,o=r instanceof Error?r.name:void 0,s=Ax(r,t),i=Ax(e,t)??s,a=Px(e,["code","cause.code"]),c=Rx(e)??Rx(r)??Px(e,["errorCode","error","cause.errorCode","cause.error","body.error","response.body.error"]),l=void 0===c?void 0:Lx(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=xx(e,t.split("."));if("number"==typeof r&&Number.isFinite(r))return r}}(e)??Ix(i)??Ix(s),d=jx(xx(e,["response","body"])??xx(e,["body"])??xx(e,["data"])??xx(e,["cause","body"])??xx(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 vx({errorName:n,errorMessage:i,errorType:null!=e?typeof e:void 0,httpStatus:u,oauthErrorCode:l,errorResponseSummary:d,networkClassification:h,causeName:o,causeMessage:s,causeChain:Mx(e,t),sdkErrorKind:p})}const Bx={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 Wx(e){const t=e.message??Bx[e.event],r={event:e.event,cursorMcp:{oauth:vx({...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 Hx=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]))),qx=4096;function zx(e){return"object"==typeof e&&null!==e&&"url"in e&&"string"==typeof e.url}function Gx(e){return"string"==typeof e?e:e instanceof URL?e.toString():e.url}function Vx(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Kx(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(Vx(e)){const t={};for(const[r,n]of Object.entries(e)){if("string"!=typeof n)return;t[r]=n}return t}}function Jx(e,t){const r=new Headers(Kx(zx(e)?e.headers:void 0));return new Headers(Kx(t?.headers)).forEach(((e,t)=>{r.set(t,e)})),r}function Zx(e){const t=[];return e.forEach(((e,r)=>{t.push(r)})),t.sort()}function Xx(e){if(null===e)return null;const t=Number.parseInt(e,10);return Number.isNaN(t)?null:t}function Qx(e,t){if(null==e)return{kind:"none",bytes:0,contentLength:Xx(t.get("content-length"))};if("string"==typeof e){const r=(new TextEncoder).encode(e).length;return{kind:"text",bytes:r,contentLength:Xx(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:Xx(t.get("content-length"))??n}}return e instanceof Blob?{kind:"blob",bytes:e.size,contentLength:Xx(t.get("content-length"))??e.size}:e instanceof ArrayBuffer||ArrayBuffer.isView(e)?{kind:"binary",bytes:e.byteLength,contentLength:Xx(t.get("content-length"))??e.byteLength}:"object"==typeof e&&null!==e&&("getReader"in e||Symbol.asyncIterator in e)?{kind:"stream",bytes:null,contentLength:Xx(t.get("content-length"))}:{kind:"unknown",bytes:null,contentLength:Xx(t.get("content-length"))}}function Yx(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 eP(e){const{input:t,init:r}=e,n=bx(Gx(t)),o=Jx(t,r),s=Zx(o),i=o.get("content-type"),a=kx(o.get("mcp-session-id")??void 0),c=function(e){if(!e)return null;const t=e.trim().split(/\s+/,1)[0]??"";return Hx.get(t.toLowerCase())??"unrecognized"}(o.get("authorization"));return{method:(r?.method??(zx(t)?t.method:void 0)??"GET").toUpperCase(),url:n,headers:{names:s,count:s.length},contentType:i,body:Qx(r?.body,o),sessionIdHash:a??null,authorizationScheme:c}}function tP(e,t){const r=Zx(e.headers),n=Xx(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:kx(e.headers.get("mcp-session-id")??void 0)??null,wwwAuthenticateHash:kx(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:rP(e.headers,"retry-after"),slackRateLimitType:rP(e.headers,"x-slack-ratelimit-type")}}function rP(e,t){return e.get(t)?.slice(0,64)??null}function nP(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 oP(e,t){const r=eP({input:e,init:t});if(void 0!==Yx(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 sP=e=>e,iP="REDACTED_SESSION_ID",aP=/\b00D[A-Za-z0-9]{12,15}![A-Za-z0-9._]{20,512}/g;async function cP(e,t,r){try{const n=r(await e.clone().text());return n.length>t?n.slice(0,t):n}catch{return}}async function lP(e){if(!oP(e.input,e.init))return;const t=await cP(e.response,qx,e.redact);if(void 0!==t)try{return jx(JSON.parse(t))}catch{return Lx(t,{maxLength:qx})}}async function uP(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 cP(t,qx,r);if(void 0===o)return;return function(e){if("/mcp"!==(t=bx(Gx(e.input)).path)&&!0!==t?.endsWith("/mcp"))return Lx(e.rawText,{maxLength:qx});var t;try{const t=JSON.parse(e.rawText);return Vx(t)?function(e){const t=e.error;if("string"==typeof t)return JSON.stringify({error:t});if("object"!=typeof t||null===t)return;if(!Vx(t))return;const r=t,n="number"==typeof r.code||"string"==typeof r.code?r.code:void 0,o="string"==typeof r.message?Lx(r.message,{maxLength:qx}):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 lP({input:e.input,response:e.response,init:e.init,redact:e.redact}):void 0}}function dP(e,t,r){try{e()}catch{t.warn?.("MCP HTTP exchange logging failed",{event:"mcp_http_exchange_logging_failure",phase:r})}}function hP(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=>hP(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,hP(n,t,r+1)])))}function pP(e,t){const r=e=>{const r=hP(e,t,0);return Vx(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 fP(e){const{fetch:t,logSuccessfulExchanges:r=!0,redactLogText:n}=e,o=void 0===n?e.logger:pP(e.logger,n);return async(s,i)=>{const a=Date.now(),c="function"==typeof e.metadata?e.metadata(s):e.metadata,l=!0===e.redactEchoedSessionId?function(e,t,r){const n=Jx(e,t).get("mcp-session-id")?.trim()??"";return e=>{const t=n.length>=8?e.split(n).join(iP):e;return r(t.replace(aP,iP))}}(s,i,n??sP):n??sP;try{const e=await t(s,i),{responseErrorSummary:n,oauthTokenErrorBodySummary:u}=e.ok?{}:await uP({input:s,init:i,response:e,redact:l});return!r&&e.ok||dP((()=>{!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=eP({input:t,init:r}),l=Yx(c.contentType,r?.body);return{event:"mcp_http_exchange",outcome:n.ok?"success":"http_error",durationMs:o,cursorMcp:{transport:{...s,request:c,response:tP(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")&&!oP(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:n,oauthTokenErrorBodySummary:u})}),o,"success"),e}catch(t){const r=function(e){if(!Ex(e))return;const t=Ex(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}(t),{responseErrorSummary:u,oauthTokenErrorBodySummary:d}=r?await uP({input:s,init:i,response:r,redact:l}):{};throw dP((()=>{!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=Ux(n,e.redactLogText),u=eP({input:t,init:r}),d=Yx(u.contentType,r?.body);return{event:"mcp_http_exchange",outcome:"error",durationMs:o,cursorMcp:{transport:{...s,request:u,response:void 0!==i?tP(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:nP(l)}}}}(e))}({logger:o,input:s,init:i,error:t,durationMs:Date.now()-a,metadata:c,responseFromError:r,responseErrorSummary:u,oauthTokenErrorBodySummary:d,redactLogText:!0===e.redactEchoedSessionId?l:n})}),o,"failure"),t}}}function mP(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 gP(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 wP(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 yP=["PYTHONIOENCODING","PYTHONUTF8","PYTHONLEGACYWINDOWSSTDIO"],vP=[".exe",".cmd",".bat"],bP=/^pythonw?(?:\d+(?:\.\d+)*t?)?$/,SP=new Set(["py","pyw"]),kP=new Set(["--cache-dir","--color","--allow-insecure-host","--directory","--project","--config-file"]),_P=new Set;function CP(e){return yP.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 EP(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 xP(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 vP)if(t.endsWith(e))return t.slice(0,-e.length);return t}(e);if(bP.test(r)||SP.has(r)||"uvx"===r)return!0;if("uv"===r){const e=EP(t,kP);return"run"===e?.value||"tool"===e?.value&&"run"===EP(e.rest,kP)?.value}return"pipx"===r&&"run"===EP(t,_P)?.value}(n,o)?CP(i)||CP(r)?i:{...i,PYTHONIOENCODING:"utf-8:surrogateescape"}:i}async function PP(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 RP=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js"),IP=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/sse.js"),TP=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.js"),AP=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js");var $P=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js");function MP(e){return`${typeof e}:${String(e)}`}function DP(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(MP(e.id),r)}else if("notifications/cancelled"===e.method){const n=e.params?.requestId;if("string"!=typeof n&&"number"!=typeof n)return;const o=MP(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=MP(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 OP(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,mo.createHash)("sha256").update(JSON.stringify([e.url,t,e.accessToken??null])).digest("hex")}class FP{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,XE.vo)(e)&&(0,XE.eK)(e)){const t={jsonrpc:"2.0",id:e.id,result:this.initializeResult};queueMicrotask((()=>this.onmessage?.(t)))}else(0,XE.wU)(e)||await this.inner.send(e,t)}}const NP=je.object({tools:je.array(je.unknown()),nextCursor:je.unknown().optional(),_meta:je.unknown().optional()}),LP={typeFilled:0,toolDropped:0,outputStripped:0};function jP(e){if(zP(e))return"string"==typeof e.name?e.name:void 0}function UP(e){return BP(e.issues.filter((e=>"outputSchema"===e.path[0])))}function BP(e){return e.map((e=>`${e.path.map(String).join(".")}: ${e.message}`))}function WP(e){if(!zP(e))return e;const t={...e};return delete t.outputSchema,t}function HP(e){return zP(e)&&!("type"in e)}function qP(e,t){return{...e,inputSchema:{type:"object",...t}}}function zP(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var GP=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/ajv-provider.js");const VP=new class{constructor({maxSchemasPerCompiler:e=2048,createCompiler:t=()=>new GP.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,mo.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 KP{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>=SE}append(e){const t=SE-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}=Go(e,Math.trunc(t));return r>=e.length?e:e.slice(0,r)}(e,t);this.captured+=r,this.capturedBytes=r.length<e.length?SE:this.capturedBytes+function(e){return Go(e,1/0).written}(r)}}const JP=new WeakMap;var ZP=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},XP=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 QP=(0,l.h)("McpSdkClient"),YP=(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 eR(e,t,r){try{YP.increment(e,1,function(e){const t=e.httpStatus??(void 0!==e.error?function(e){if(!e||"object"!=typeof e)return;const t=bE(e);if(void 0!==t)return t;const r=vE(e)?e.cause:void 0;return r&&"object"==typeof r?bE(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:kE(t),...r}))}catch{}}const tR=(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 rR(e){return void 0===e?"unknown":"url"in e?"http":"stdio"}const nR=["authorization_code","refresh_token"],oR=["code"];class sR{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=Lv(e);return void 0!==r&&function(e){return"https:"===e.protocol&&e.hostname===new URL(xv).hostname}(r)?async()=>{}:void 0!==r&&function(e){return"https:"===e.protocol&&"setup.shopify.com"===e.hostname&&""===e.port&&"/mcp"===e.pathname}(r)?jv:Fv}(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,mo.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=Dv(e);return!0!==n?.pinsScopesOverConfiguredScopes?void 0!==t&&t.length>0||void 0===r?t:Uv(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=Dv(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 iR(e){const{serverName:t,config:n,tokenStorage:o}=e,s=await xE(n.url,e.fetchImpl),i=Zv({loopbackIpv4:s?.loopbackIpv4,redirectUrl:e.authRedirectUrl}),a=function(e,t){const r=CE(e?.CLIENT_ID);if(void 0!==r)return{client_id:r,...e?.CLIENT_SECRET?{client_secret:e.CLIENT_SECRET}:{},redirect_uris:Xv(t),grant_types:[...nR],response_types:[...oR],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 sR({identifier:t,redirectUrl:i,serverUrl:n.url,restMcpProviderMetadata:s,gtmMcpMatch:e.gtmMcpMatch??{gtmApiOrigin:void 0},clientMetadata:{redirect_uris:Xv(i),token_endpoint_auth_method:"none",grant_types:[...nR],response_types:[...oR],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:WE({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 aR=new Set;let cR=!1;function lR(){for(const e of aR)try{process.kill(e,"SIGKILL")}catch{}}function uR(e){return VE(e)?new RP.D_:e}function dR(e,t){return fx(e??globalThis.fetch.bind(globalThis),{serverUrl:t})}function hR(e,t,r){const n=mx(e,t),o=r??(globalThis.fetch?globalThis.fetch.bind(globalThis):void 0),s=void 0!==n.cursorAuthHeaderValue&&void 0!==n.cursorAuthOrigin&&void 0!==o?gx((()=>n.cursorAuthHeaderValue),n.cursorAuthOrigin,o):o;return{transportHeaders:n.headers,baseFetch:s}}class pR{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 wx,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}})();Wx({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 $P.K({name:"Cursor",version:"1.0.0"},{capabilities:t,jsonSchemaValidator:VP})}setupElicitationHandler(){this.client.setRequestHandler(XE.$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??Gv;const f=await iR({serverName:e,config:t,tokenStorage:r,authRedirectUrl:o,fetchImpl:s,gtmMcpMatch:c,isScopePinGateEnabled:l,scopeChallengeStepUp:u}),m=f.tokens(),g=mx(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?gx((()=>g.cursorAuthHeaderValue),g.cursorAuthOrigin,v):v,S=e=>void 0===b||void 0===i?b:fP({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,RP.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:GE(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){RE(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 zE(n,o.serverUrl,o.scopeStepUp.connectorName)});var o},C=pR.createClient(h),E=e=>e instanceof RP.D_||function(e){if(null===e||"object"!=typeof e)return!1;const t=e.name;if("string"==typeof t&&KE.has(t))return!0;const r=e.errorCode;return!("string"!=typeof r||!JE.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&&ZE.some((e=>e.test(n)))}(e)}(e)||VE(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,RP.j2)(f,{serverUrl:p.toString(),authorizationCode:t,...void 0!==r?{resourceMetadataUrl:r}:{},...void 0!==b?{fetchFn:b}:{}}),a&&Wx({logger:a,event:"mcp_oauth_callback_completion",metadata:{identifier:e,...Sx(p.toString()),...mP(f.tokens(),{expiresInIsFresh:!0})}})},P=r=>{const n=f.lastRedirectUrl?.toString?.()??"",o=new pR(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},R=async r=>{const n=new IP.A(p,{authProvider:y,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...w??{}}},fetch:_(S("sse"))});try{return await C.connect(n),new pR(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&&Wx({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),...Sx(p.toString()),...Ux(t,i?.redactLogText)}}),P();if(void 0!==r&&gP(t)&&t instanceof IP._)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 R();const I=new AP.j(p,{authProvider:y,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...w??{}}},fetch:_(dR(S("streamableHttp"),p))});try{await C.connect(I);const r=function(e,t=Date.now){return cx(ax(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:OP({url:t.url,headers:n,accessToken:f.tokens()?.access_token})}}(C,I);return new pR(e,C,{initialState:{kind:"ready"},authProvider:f,authCodeExchange:x,sessionId:I.sessionId,protocolVersion:I.protocolVersion,...void 0===r?{}:{sessionlessInitialize:r},config:t,oauthLifecycleLogger:a,redactLogText:i?.redactLogText})}catch(t){if(E(t))return a&&Wx({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),...Sx(p.toString()),...Ux(t,i?.redactLogText)}}),P(I.sessionId);if(gP(t))return R(t);throw t}}static async fromStreamableHttpWithoutOAuth(e,t,r){const n=pR.createClient(),o=new AP.j(new URL(t.url),{requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...t.headers}},fetch:r});return await n.connect(o),new pR(e,n,{initialState:{kind:"ready"},sessionId:o.sessionId,protocolVersion:o.protocolVersion,config:t})}static async fromCachedSession(e,t,r,n,o,s=Gv,i,a,c,l,u){const d=new URL(t.url),h=await iR({serverName:e,config:t,tokenStorage:n,authRedirectUrl:s,fetchImpl:i,gtmMcpMatch:l,isScopePinGateEnabled:u}),{transportHeaders:p,baseFetch:f}=hR(t.url,o,i),m=new AP.j(d,{authProvider:h,sessionId:r.sessionId,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...p??{}}},fetch:void 0!==f&&void 0!==a?fP({fetch:f,logger:a.logger,metadata:{...a.metadata,transportType:"streamableHttp"},redactLogText:a.redactLogText}):f});m.setProtocolVersion(r.protocolVersion);const g=function(e){return e._requestMessageId=(0,mo.randomInt)(1048576,2146435072),e}(pR.createClient());return await g.connect(m),new pR(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=Gv,i,a,c,l){const u=await iR({serverName:e,config:t,tokenStorage:n,authRedirectUrl:s,fetchImpl:i,gtmMcpMatch:a,isScopePinGateEnabled:c});if(OP({url:t.url,headers:o,accessToken:u.tokens()?.access_token})!==r.credentialFingerprint)return;const{transportHeaders:d,baseFetch:h}=hR(t.url,o,i),p=new AP.j(new URL(t.url),{authProvider:u,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...d??{}}},fetch:h}),f=pR.createClient();return await f.connect(new FP(p,r.result)),new pR(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 AP.j&&await e.resumeStream("")}static async fromCommand(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{ZP(s,(0,$.VI)(e.withName("McpSdkClient.fromCommand")),!1);const l=(c=o?.spawn,void 0!==c||"linux"!==process.platform?c:(e,t,r)=>(0,Vl.D9)(Gl.spawn,e,t,r)),u=r.args??[],d=new TP.oQ({command:r.command,args:u,env:wP(xP({command:r.command,args:u,env:n})),cwd:r.cwd,stderr:"pipe",...l&&{spawn:l}}),h=function(e){const t=new KP;let r=null===e;return null!==e&&(e.on("data",(e=>{t.full||t.push(e)})),e.once("end",(()=>{t.end(),r=!0}))),{read:()=>Lx(t.text.replace(/\s+/g," ").trim(),{maxLength:SE}),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=pR.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,aR.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,aR.add(i),cR||(cR=!0,process.on("exit",lR)));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}`,JP.set(r,t),r}(e,h.read())}finally{w=!1,void 0!==b&&clearTimeout(b)}return new pR(t,p,{initialState:{kind:"ready"},config:r,stdioServer:void 0!==m,serverSignals:DP(d)})}catch(e){s.error=e,s.hasError=!0}finally{XP(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 AP.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 AP.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=ZP(t,(0,$.VI)(e.withName("McpSdkClient.getTools")),!1);if(r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("mcp.transport",rR(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()=>{let e;const t=await PP({fetchPage:async t=>{o++;const n=await async function(e,t,r){try{const r=await e.listTools({cursor:t});return{tools:r.tools,nextCursor:r.nextCursor,meta:r._meta,...LP}}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}},NP),o=[];let s=0,i=0,a=0;for(const e of n.tools){let t=e;if(zP(e)){const r=e.inputSchema;HP(r)&&(t=qP(e,r),s++)}let n=XE.Dn.safeParse(t);if(!n.success&&(c=n.error).issues.some((e=>"outputSchema"===e.path[0]))){const o=XE.Dn.safeParse(WP(t));o.success&&(a++,r(jP(e),UP(n.error),"output_stripped"),n=o)}n.success?o.push(n.data):(i++,r(jP(e),BP(n.error.issues),"dropped"))}var c;return{tools:o,nextCursor:"string"==typeof n.nextCursor?n.nextCursor:void 0,meta:n._meta,typeFilled:s,toolDropped:i,outputStripped:a}}(this.client,t,((e,t,n)=>{(function(e,t,r){const n=JSON.stringify([e,t,r]);if(mR.has(n))return mR.delete(n),mR.add(n),!1;if(mR.add(n),mR.size>256){const e=mR.keys().next().value;void 0!==e&&mR.delete(e)}return!0})(n,this.serverName,e??"")&&QP.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+=n.typeFilled,gR(r.ctx,"type_filled",n.typeFilled),gR(r.ctx,"tool_dropped",n.toolDropped),gR(r.ctx,"output_stripped",n.outputStripped),e??=function(e){if(!nC(e))return;const t=e.mcpAllowlist;if(!nC(t)||"string"!=typeof t.list)return;const r=oC(t.name,200),n=oC(t.reason,200);if(void 0===r||void 0===n)return;const o={list:"local"===t.list||"cloud"===t.list?t.list:"other",name:r,reason:n},s=sC(t.allowedServerNames)??sC(t.allowedServers);void 0!==s&&(o.allowedServers=s);const i=sC(t.blockedServers);return void 0!==i&&(o.blockedServers=i),o}(n.meta),n},itemsOf:e=>e.tools,nextCursorOf:e=>e.nextCursor});return this._allowlistInUse=this.reportsCursorMcpAllowlist()?e:void 0,t.map((e=>({...e,inputSchema:mC(e.inputSchema),outputSchema:void 0===e.outputSchema?void 0:mC(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=uR(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 RP.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",{...Ux(t,this._redactLogText)}),this._stateEnteredAtMs=Date.now()}throw t}}catch(e){t.error=e,t.hasError=!0}finally{XP(t)}}async getAllowlistInUse(){return this._allowlistInUse}reportsCursorMcpAllowlist(){return void 0!==this.config&&"url"in this.config&&rC(this.config.url)}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=XE.O4.MethodNotFound;if(t instanceof XE.Nh&&t.code===n&&void 0===this.client.getServerCapabilities()?.tools)return void this.noteToolListSuccess();if(t instanceof RP.D_||!this.toolListAttemptIsCurrent(r))return;const o=function(e){if(e instanceof XE.Nh)return{descriptor:`McpError ${e.code}`,errorClass:"McpError",jsonRpcCode:e.code};if(e instanceof AP.b||e instanceof IP._){const t=e instanceof AP.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&&QP.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=ZP(s,(0,$.VI)(e.withName("McpSdkClient.callTool")),!1);a.span.setAttribute("toolName",t),a.span.setAttribute("serverName",this.serverName),a.span.setAttribute("mcp.transport",rR(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=ZP(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{XP(e)}}if("requires_authentication"===this.stateValue.kind)throw new RP.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=ZP(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),eR(e,this.config,{isError:!0===c.isError}),{content:c.content,isError:!0===c.isError,structuredContent:(i=c.structuredContent,gC(i)),_meta:CC(c._meta)}}catch(e){n.error=e,n.hasError=!0}finally{XP(n)}}catch(t){const r=uR(t);r instanceof zE?(eR(e,this.config,{error:r,httpStatus:r.decision.status}),function(e,t){try{tR.increment(e,1,{decision:t.decision.kind,dropped:String(t.decision.dropped.length>0)})}catch{}}(e,r)):eR(e,this.config,{error:r});const n=r instanceof zE&&"offer"===r.decision.kind&&void 0!==this._authProvider?.lastRedirectUrl&&this._authProvider.lastRedirectUrl!==u;if((r instanceof RP.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",{...Ux(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{XP(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},XE.TF,n):this.client.callTool(e,void 0,n)}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{if(ZP(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{XP(t)}}async listResources(e){const t={stack:[],error:void 0,hasError:!1};try{if(ZP(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 PP({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{XP(t)}}async readResource(e,t){const r={stack:[],error:void 0,hasError:!1};try{return ZP(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{XP(r)}}async listPrompts(e){const t={stack:[],error:void 0,hasError:!1};try{return ZP(t,(0,$.VI)(e.withName("McpSdkClient.listPrompts")),!1),"requires_authentication"===this.stateValue.kind||"error"===this.stateValue.kind?[]:(this.client.getServerCapabilities()??{prompts:!1}).prompts?(await PP({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{XP(t)}}async getPrompt(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{return ZP(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{XP(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 fR=(0,u.Pu)("mcp_tool.schema",{description:"One MCP tool definition a tools/list repair touched",labelNames:["outcome"]}),mR=new Set;function gR(e,t,r){if(0!==r)try{fR.increment(e,r,{outcome:t})}catch{}}class wR 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 yR{constructor(e){this.tools=e}async execute(e,t,r,n){const o=this.tools[e];if(!o)throw new L_(e,Object.keys(this.tools));return o.execute(t,r,n)}async executeOn(e,t,r,n,o){const s=this.tools[t];if(!s)throw new L_(t,Object.keys(this.tools));if(s.client===e)return s.execute(r,n,o)}getTools(){return Object.entries(this.tools).map((([e,t])=>({...t.definition,name:e})))}}class vR{async getClients(e){return{}}async getClient(e,t){}async getInstructions(e){return[]}async getToolSet(e){return new yR({})}async getTools(e){return[]}async getToolsForServers(e,t){return[]}}class bR{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=ZP(t,(0,$.VI)(e.withName("ManagerMcpLease.getInstructions")),!1);return await this.manager.getInstructions(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{XP(t)}}async getToolSet(e){const t={stack:[],error:void 0,hasError:!1};try{const r=ZP(t,(0,$.VI)(e.withName("ManagerMcpLease.getToolSet")),!1);return await this.manager.getToolSet(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{XP(t)}}async getTools(e){const t={stack:[],error:void 0,hasError:!1};try{const r=ZP(t,(0,$.VI)(e.withName("ManagerMcpLease.getTools")),!1);return(await this.getToolSet(r.ctx)).getTools()}catch(e){t.error=e,t.hasError=!0}finally{XP(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 SR{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=ZP(t,(0,$.VI)(e.withName("McpManager.getToolSet")),!1),n=ZP(t,kR(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},client:i.client,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 yR(a)}catch(e){t.error=e,t.hasError=!0}finally{XP(t)}}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{const r=ZP(t,(0,$.VI)(e.withName("McpManager.getInstructions")),!1),n=ZP(t,kR(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{XP(t)}}}function kR(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(t,n,o)=>{const s=await Promise.race([t.getState(n).catch((()=>{})),r]);if("ready"!==s?.kind)return Promise.race([o(),r]);let i;try{return await Promise.race([o(),new Promise((t=>{i=setTimeout((()=>t(void 0)),Math.max(2e3,e-performance.now()))}))])}finally{clearTimeout(i)}},[Symbol.dispose]:()=>clearTimeout(t)}}function _R(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 CR{constructor(e){this.options=e,Wx({logger:e.logger,event:"mcp_oauth_provider_initialized",metadata:this.baseMetadata})}get baseMetadata(){return{identifier:this.options.identifier,...this.options.serverUrl?{serverUrl:Sx(this.options.serverUrl)}:{}}}async loadTokens(){const e=await this.options.inner.loadTokens();return Wx({logger:this.options.logger,event:"mcp_oauth_tokens_loaded",level:"debug",metadata:{...this.baseMetadata,...mP(e)}}),e}async saveTokens(e){await this.options.inner.saveTokens(e),Wx({logger:this.options.logger,event:"mcp_oauth_tokens_saved",metadata:{...this.baseMetadata,...mP(e,{expiresInIsFresh:!0})}})}async prepareForRefresh(){Wx({logger:this.options.logger,event:"mcp_oauth_refresh_prepare",metadata:this.baseMetadata}),await(this.options.inner.prepareForRefresh?.())}async releaseRefreshLeaseOnError(e){Wx({logger:this.options.logger,event:"mcp_oauth_refresh_error_release",level:"warn",error:e,metadata:{...this.baseMetadata,...Ux(e,this.options.redactLogText)}}),await(this.options.inner.releaseRefreshLeaseOnError?.(e))}async loadClientInformation(){const e=await this.options.inner.loadClientInformation();return Wx({logger:this.options.logger,event:"mcp_oauth_client_info_loaded",level:"debug",metadata:{...this.baseMetadata,...Cx(e)}}),e}async saveClientInformation(e){await this.options.inner.saveClientInformation(e),Wx({logger:this.options.logger,event:"mcp_oauth_client_info_saved",metadata:{...this.baseMetadata,...Cx(e)}})}async invalidateCredentials(e){void 0!==this.options.inner.invalidateCredentials&&(Wx({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 ER{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 xR{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 PR=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},RR=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 IR=(0,l.h)("DefinitionMcpLoader"),TR=(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 AR(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 $R(e){return"getManagedSlackWorkspaceLists"in e&&"function"==typeof e.getManagedSlackWorkspaceLists}function MR(e){return"getMcpNetworkControlsConfig"in e&&"function"==typeof e.getMcpNetworkControlsConfig}function DR(e){return e?.length??0}function OR(e){if(void 0!==e)return(0,mo.createHash)("sha256").update(KC(e)).digest("hex")}function FR(e){if(void 0===e)return;let t;return r=>(void 0===t&&(t=e(),queueMicrotask((()=>{t=void 0}))),t?gE(r):r)}async function NR(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=PR(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),IR.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=PR(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(MR);return await async function(e,t,n,o,s={}){const i=n.cwd?AR({filePath:n.cwd}):void 0;let a,c;if(n.args&&n.args.length>0)a=AR({filePath:n.command,baseDir:i}),c=n.args.map((e=>AR({filePath:e,baseDir:i})));else{const e=(0,wE.A)(n.command);a=AR({filePath:e[0],baseDir:i}),c=e.slice(1).map((e=>AR({filePath:e,baseDir:i})))}const l=n.env??{},{startupTimeoutSec:u}=n,d=await(o?.getMcpNetworkControlsConfig?.({command:[n.command,...n.args??[]].join(" ")})),h=(0,eb.$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);IR.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=${DR(e.networkControlsConfig?.mcpNetworkAllowlist)}, mcpNetworkDenylistCount=${DR(e.networkControlsConfig?.mcpNetworkDenylist)}, localAgentNetworkAllowlistCount=${DR(e.networkControlsConfig?.localAgentNetworkAllowlist)}, sandboxPolicyHash=${OR(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:DR(e.networkControlsConfig?.mcpNetworkAllowlist),mcpNetworkDenylistCount:DR(e.networkControlsConfig?.mcpNetworkDenylist),localAgentNetworkAllowlistCount:DR(e.networkControlsConfig?.localAgentNetworkAllowlist),sandboxPolicyHash:OR(e.sandboxNetworkControlsConfig)}}({serverName:t,networkControlsConfig:d,sandboxNetworkControlsConfig:h}));try{return await pR.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 JC(t,e);throw e}}return!0===d?.enabled&&"no_sandbox"===d.mcpNetworkMode&&(!0===d.win32UserExtensionUnsandbox?IR.info(e,`Starting local MCP server "${t}" without MCP sandboxing`,{event:"mcp_stdio_win32_user_extension_unsandbox",serverName:t}):IR.info(e,`Starting local MCP server "${t}" without MCP sandboxing`)),pR.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=_R(e,IR),u=function(e,t,r){return{logger:{debug:(t,r)=>IR.debug(e,t,r),info:(t,r)=>IR.info(e,t,r),warn:(t,r)=>IR.warn(e,t,r),error:(t,r,n)=>IR.error(e,t,r,n)},metadata:{identifier:t,source:"mcp-agent-exec"},redactLogText:FR(r)}}(e,t,a),d=void 0!==s&&YC(r.url)?eE(globalThis.fetch.bind(globalThis),{managedSlackWorkspaceLists:()=>s.getManagedSlackWorkspaceLists()}):void 0;return pR.fromStreamableHttp(t,r,n,r.headers,o,d,u,l,void 0,void 0,i,!1,c)}(h,t,n,o,e,d.find($R),a,c.isLinkSharedPaymentTokenLogRedactionEnabled,l)}throw new Error(`Invalid server: ${JSON.stringify(n)}`)}catch(e){s.error=e,s.hasError=!0}finally{RR(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=JP.get(e);void 0!==r&&JP.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=tE(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<lE;e++){const e=n.pop();if(!(e instanceof Error||hE(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=oE(e,r),s=rE(o,t);s!==o&&nE(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=JP.get(e);void 0!==r&&JP.set(t,r)}(e,r),r}(e,FR(c.isLinkSharedPaymentTokenLogRedactionEnabled))}}catch(e){u.error=e,u.hasError=!0}finally{RR(u)}}class LR{constructor(e,t=BC){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 jR{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{PR(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=FR(n)??(e=>e),s=function(e){if("object"==typeof e&&null!==e)return JP.get(e)}(r);IR.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 SR(o,this.options.elicitationFactory)}catch(e){r.error=e,r.hasError=!0}finally{RR(r)}}clearClient(e){this.clientCache.delete(e)}clearAllMcpCaches(){this.clientCache.clear()}async evictClientsOnSandboxPolicyChange(e,t){const r=this.middlewares.find(MR);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,KC(t)]}))))}catch{return}const o=this.sandboxPolicyFingerprint;this.sandboxPolicyFingerprint=n,void 0!==o&&o!==n&&(IR.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{PR(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{RR(n)}}async loadDefinitionClient(e,t,r){const n=t.authStorageKey??t.identifier,o=new ER(this.tokenStorage,n),s=_R(e,IR),i=new CR({inner:o,logger:s,redactLogText:FR(this.options.isLinkSharedPaymentTokenLogRedactionEnabled),identifier:n,serverUrl:"url"in t.serverConfig?t.serverConfig.url:void 0}),a=r?new xR(i):i;return NR(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){IR.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 G_||e instanceof V_||e instanceof K_||e instanceof UR}(r)}}class UR 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 BR=[1e3,3e3];class WR{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=function(e){return{command:"command"in e?[e.command,...e.args??[]].join(" "):void 0,url:"url"in e?e.url:void 0}}(r),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),TR.increment(e,1,{surface:"desktop",stage:"tool_call",reason:"server_not_allowed"})),new UR(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 XC)throw new UR(t,"teamPolicy",e.message);const r=e instanceof QC?BR[n]:void 0;if(void 0===r)throw e;await(0,Dr.cb)(r)}}}class HR extends jR{constructor(e,t,r=[],n={}){super(new LR(e),t,r,n),this.configPath=e}static init(e,t,r=[]){return new HR(t,e,r)}}function qR(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 zR=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth.js");function GR(e){const t=zR.VE.safeParse(e);return t.success?t.data:void 0}function VR(e){const t=zR.H5.safeParse(e);return t.success?t.data:void 0}class KR{constructor(e){this.mcpAuthPath=e;const t=KR.mcpAuthPromises.get(e);if(t)this.mcpAuthPromise=t;else{const t=this.loadMcpAuth();this.mcpAuthPromise=t,KR.mcpAuthPromises.set(e,t),t.catch((()=>{KR.mcpAuthPromises.get(e)===t&&KR.mcpAuthPromises.delete(e)}))}KR.saveLocks.has(e)||KR.saveLocks.set(e,Promise.resolve())}async loadMcpAuth(){try{const e=await(0,vo.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=GR(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?GR(n.tokens):void 0,clientInfo:"clientInfo"in n?VR(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=KR.saveLocks.get(this.mcpAuthPath)??Promise.resolve();let r;KR.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,vo.mkdir)(s.dirname(this.mcpAuthPath),{recursive:!0}),await(0,vo.writeFile)(this.mcpAuthPath,JSON.stringify(e,null,2))}}KR.mcpAuthPromises=new Map,KR.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 JR=(0,y.cF)(Symbol("execHookWorkspaceRoots"),void 0);var ZR=r("../proto/dist/generated/agent/v1/write_exec_pb.js"),XR=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},QR=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 YR=(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"]}),eI=(0,u.Pu)("mcp.filesystem.sync_check",{description:"MCP filesystem sync check executed",labelNames:["synced","mcp_source","configured_servers","mcp_version"]}),tI=(0,u.wt)("mcp.filesystem.sync_check.expected_servers",{description:"Number of expected MCP servers at last sync check",labelNames:["mcp_source","mcp_version"]}),rI=(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"]}),nI=(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"]}),oI=(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"]}),sI=(0,l.h)("McpFileSystemWriter"),iI="mcpFsStructuredLogOptIn";function aI(e,t){return t?.includeStructuredLogs?{...e??{},[iI]:!0}:e}const cI={debug(e,t,r,n){sI.debug(e,t,aI(r,n))},info(e,t,r,n){sI.info(e,t,aI(r,n))},warn(e,t,r,n){sI.warn(e,t,aI(r,n))},error(e,t,r,n,o){sI.error(e,t,r,aI(n,o))}},lI="mcps",uI="tools",dI="~staging",hI="~prev",pI=[25,50,100,200],fI=new Set(["EPERM","EBUSY","EACCES"]),mI=new Map;function gI(e){return e.slice(0,e.indexOf("~"))}function wI(e,t){return`${e}~${Date.now()}-${process.pid}-${(0,mo.randomBytes)(4).toString("hex")}${t}`}const yI=/~(\d+)-\d+-[0-9a-f]+~(?:staging|prev)$/;async function vI(e,t){const r=yI.exec(t),n=r?Number(r[1]):0;try{const{mtimeMs:r}=await(0,vo.stat)((0,s.join)(e,t));return Date.now()-Math.max(n,r)>6e4}catch{return!1}}const bI="mcp_auth",SI="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.",kI="# >>> CURSOR MANAGED BLOCK >>>",_I="# <<< CURSOR MANAGED BLOCK <<<",CI=["# 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 EI(e,t,r=15e3){let n;return Promise.race([e.catch((()=>t)),new Promise((e=>{n=setTimeout((()=>e(t)),r)}))]).finally((()=>clearTimeout(n)))}function xI(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_")}function PI(e){if(void 0===e)return;const t=e.trim();return t.length>0?t:void 0}function RI(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 II(e){if(Array.isArray(e))return e.map((e=>II(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,II(t)]));return Object.fromEntries(t)}return e}function TI(e){return JSON.stringify(II(e))}function AI(e){const t=e.map((e=>({value:e,key:TI(e)})));return t.sort(((e,t)=>e.key<t.key?-1:e.key>t.key?1:0)),t.map((e=>e.value))}function $I(e){const t=AI(e.tools.map((e=>({name:e.toolName,description:e.description,inputSchema:e.inputSchema,outputSchema:e.outputSchema})))),r=AI(e.resources.map((e=>({uri:e.uri,name:e.name,description:e.description,mimeType:e.mimeType})))),n=AI(e.prompts.map((e=>({name:e.name,description:e.description,arguments:e.arguments}))));return TI({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 MI{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=>{cI.info(this.ctx,"Lease change event received",{serverIdentifiers:e?.serverIdentifiers,reason:e?.reason}),this.onLeaseChanged(this.ctx,e)})),cI.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=`${kI}\n${CI}\n${_I}\n`;let n;await(0,vo.mkdir)(e,{recursive:!0});try{n=await(0,vo.readFile)(t,"utf-8")}catch(e){if("ENOENT"!==gc(e))throw e}if(void 0===n)return void await(0,vo.writeFile)(t,r);const o=n.indexOf(kI),i=n.indexOf(_I,o+30);if(-1===o||-1===i)await(0,vo.writeFile)(t,r);else{const e=`${n.slice(0,o)}${r}${n.slice(i+30).replace(/^\n/,"")}`;e!==n&&await(0,vo.writeFile)(t,e)}})((0,s.join)((0,o.homedir)(),".cursor")).catch((e=>{cI.warn(this.ctx,"Failed to ensure ~/.cursor/.gitignore",e)}))}async cleanupStaleStagingDirs(e){const t=this.getLogContext(e),r=(0,s.join)(this.projectDir,lI);try{const e=await(0,vo.readdir)(r);await Promise.allSettled(e.filter((e=>e.endsWith(dI))).map((async e=>{await vI(r,e)&&await(0,vo.rm)((0,s.join)(r,e),{recursive:!0,force:!0})})))}catch(e){"ENOENT"!==gc(e)&&cI.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:Jn(r)?{serverIdentifiers:void 0,reason:t?.reason??r?.reason}:void 0===t?r:Jn(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){cI.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 PI(this.mcpAuthCopyOverrides?.authToolDescription)??SI}shouldExposeVirtualMcpAuthToolForStatus(e,t){return this.exposeVirtualMcpAuthTool&&qn(e)&&(this.alwaysExposeVirtualMcpAuthTool||"needsAuth"===t)}getErrorStatusMessage(){return PI(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=PI(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:bI},t.replace(/\{serverIdentifier\}/g,r.serverIdentifier).replace(/\{authToolName\}/g,r.authToolName);var t,r}getNeedsAuthStatusMessageForWrite(e){return this.exposeVirtualMcpAuthTool&&qn(e)?this.getNeedsAuthStatusMessage(e):PI(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){cI.warn(r,`getToolsForServers() threw, falling back to filtered getTools(): ${wc(n)}`);const o=await this.mcpLease.getTools(e).catch((e=>(cI.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 EI(r.getState(e),{kind:"error"}).then((r=>("error"!==r.kind||"message"in r||cI.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?EI(r.listResources(e),{resources:[]}):Promise.resolve({resources:[]}),s?EI(r.listPrompts(e),[]):Promise.resolve([]),s&&n?.fetchInstructions?EI(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:RI(o)}}buildServerDataMap(e,t,r){const n=new Map;for(const e of t){const t=Yw(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,lI,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=Yw(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,lI,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===bI))||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:bI,name:bI,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)?cI.warn(e,`Skipping server "${o.serverIdentifier}" — sanitizedId "${o.sanitizedId}" collides with another server`):(n.add(o.sanitizedId),r.push(o)):cI.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===bI))){const t=e.tools.find((e=>e.toolName===bI));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??[])];cI.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=>(cI.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 cI.warn(r,`getClient("${t}") threw during scoped refresh, preserving cached data: ${wc(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=>{cI.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):cI.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)),cI.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=Yw(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{XR(r,(0,$.VI)(e.withName("McpFileSystemWriter.fetchAndWrite")),!1);const n=this.getLogContext(e);try{if(void 0!==this.cachedServerData&&void 0!==t&&!Jn(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=>(cI.warn(n,`getTools() threw, defaulting to []: ${e}`),[]))),this.mcpLease.getInstructions(e).catch((()=>[])),this.mcpLease.getClients(e).catch((e=>(cI.warn(n,`getClients() threw, defaulting to {}: ${e}`),{})))]),i=Object.keys(s);cI.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){cI.error(n,"Error fetching/writing MCP state",e)}}catch(e){r.error=e,r.hasError=!0}finally{QR(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,uI,`${xI(t.toolName)}.json`)})))})));this.onDidWrite(t)}catch{}}async writeServerData(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{XR(n,(0,$.VI)(e.withName("McpFileSystemWriter.writeServerData")),!1);const o=this.getLogContext(e),i=(0,s.join)(this.projectDir,lI);await(0,vo.mkdir)(i,{recursive:!0});const a=new Map;for(const e of t)try{a.set(e.serverIdentifier,$I(e))}catch(t){cI.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&&cI.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,vo.stat)((0,s.join)(i,e.sanitizedId))}catch{cI.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??Yw(e);r.has(n)?(cI.info(o,`Server "${e}" (sanitized="${n}") still in lease but excluded from write, preserving directory`),a.set(e,this.cachedFingerprints.get(e))):(cI.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,vo.readdir)(i),t=new Set(e.filter((e=>!e.endsWith(dI)&&!e.endsWith(hI))));for(const r of e){const e=r.endsWith(dI),n=r.endsWith(hI);if((e||n)&&await vI(i,r))if(e)await(0,vo.rm)((0,s.join)(i,r),{recursive:!0,force:!0});else{const e=gI(r);if(t.has(e))await(0,vo.rm)((0,s.join)(i,r),{recursive:!0,force:!0});else try{await(0,vo.rename)((0,s.join)(i,r),(0,s.join)(i,e)),t.add(e)}catch{await(0,vo.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){cI.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})));cI.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,mo.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),cI.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,vo.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];cI.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{QR(n)}}async writeServerAtomic(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{XR(n,(0,$.VI)(e.withName("McpFileSystemWriter.writeServerAtomic")),!1);const o=(0,s.join)(r,t.sanitizedId),i=mI.get(o),a=(async()=>{await(i?.catch((()=>{}))),await this.swapServerDirectory(e,t,r)})();mI.set(o,a);try{await a}finally{mI.get(o)===a&&mI.delete(o)}}catch(e){n.error=e,n.hasError=!0}finally{QR(n)}}async swapServerDirectory(e,t,r){const n=wI(t.sanitizedId,dI),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,vo.rm)(o,{recursive:!0,force:!0}).catch((()=>{})),e}const a=(0,s.join)(r,wI(t.sanitizedId,hI));let c=!1;try{try{await this.renameWithRetry(i,a),c=!0}catch(e){if("ENOENT"!==gc(e))throw e}await this.renameWithRetry(o,i)}catch(r){if(cI.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,vo.stat)(i).then((()=>!0),(()=>!1))&&await(0,vo.rm)(a,{recursive:!0,force:!0}).catch((()=>{}))}throw await(0,vo.rm)(o,{recursive:!0,force:!0}).catch((()=>{})),r}await(0,vo.rm)(a,{recursive:!0,force:!0}).catch((()=>{}))}async renameWithRetry(e,t){for(let r=0;;r++)try{return void await(0,vo.rename)(e,t)}catch(e){const t=gc(e);if(r>=pI.length||void 0===t||!fI.has(t))throw e;await(0,Dr.cb)(pI[r])}}async writeServerDirectory(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{XR(n,(0,$.VI)(e.withName("McpFileSystemWriter.writeServerDirectory")),!1);const o=(0,s.join)(r.basePath,r.dirName??t.sanitizedId);await(0,vo.mkdir)(o,{recursive:!0});const i=[];if(t.tools.length>0){const e=(0,s.join)(o,uI);await(0,vo.mkdir)(e,{recursive:!0});for(const r of t.tools){const t=xI(r.toolName);i.push({path:(0,s.join)(e,`${t}.json`),content:JSON.stringify(Vn(r),null,2)})}}if(t.resources.length>0){const e=(0,s.join)(o,"resources");await(0,vo.mkdir)(e,{recursive:!0});for(const r of t.resources){const t=xI(r.name||r.uri.replace(/[^a-zA-Z0-9_-]/g,"_")),n={uri:r.uri,name:r.name,description:r.description,mimeType:r.mimeType};i.push({path:(0,s.join)(e,`${t}.json`),content:JSON.stringify(n,null,2)})}}if(t.prompts.length>0){const e=(0,s.join)(o,"prompts");await(0,vo.mkdir)(e,{recursive:!0});for(const r of t.prompts){const t=xI(r.name),n={name:r.name,description:r.description,arguments:r.arguments};i.push({path:(0,s.join)(e,`${t}.json`),content:JSON.stringify(n,null,2)})}}t.instructions&&t.instructions.trim().length>0&&i.push({path:(0,s.join)(o,"INSTRUCTIONS.md"),content:t.instructions.trim()}),"error"!==t.status&&"needsAuth"!==t.status||i.push({path:(0,s.join)(o,"STATUS.md"),content:"error"===t.status?this.getErrorStatusMessage():this.getNeedsAuthStatusMessageForWrite(t.serverIdentifier)});const a={serverIdentifier:t.serverIdentifier,serverName:t.serverName};i.push({path:(0,s.join)(o,"SERVER_METADATA.json"),content:JSON.stringify(a,null,2)});if(new Set(i.map((e=>e.path.toLowerCase()))).size!==i.length){for(const e of i)await(0,vo.writeFile)(e.path,e.content);return}const c=(await(0,Dr.up)(i,(e=>(0,vo.writeFile)(e.path,e.content)),{max:8})).find((e=>"rejected"===e.status));if(c)throw c.reason}catch(e){n.error=e,n.hasError=!0}finally{QR(n)}}async getMcpFileSystemOptions(e,t){const r={stack:[],error:void 0,hasError:!1};try{if(this.disposed)return;XR(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&&cI.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=xI(t.toolName),n=(0,s.join)(e.folderPath,uI,`${r}.json`);return new fn.E$({toolName:t.toolName,definitionPath:n,...Yv(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{QR(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&&cI.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){cI.error(r,"Error waiting for pending write to complete",e)}finally{clearTimeout(e)}return n&&cI.warn(r,`getMcpFileSystemOptions timed out after ${t}ms waiting for write; returning stale cache`),n}try{await this.writePromise}catch(e){cI.error(r,"Error waiting for pending write to complete",e)}return!1}async buildOptionsFromSnapshots(e){const t={stack:[],error:void 0,hasError:!1};try{XR(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,lI),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=Yw(e.serverIdentifier),r=(0,s.join)(i,t),n=e.tools.map((e=>{const t=xI(e.name);return new fn.E$({toolName:e.name,definitionPath:(0,s.join)(r,uI,`${t}.json`),...Yv(e.annotations)})}));if(this.shouldExposeVirtualMcpAuthToolForStatus(e.serverIdentifier,e.status)&&!e.tools.some((e=>e.name===bI))){const e=xI(bI);n.push(new fn.E$({toolName:bI,definitionPath:(0,s.join)(r,uI,`${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 cI.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{QR(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<MI.DIVERGENCE_CHECK_COOLDOWN_MS||(this.lastDivergenceCheckMs=o,this._checkDescriptorsVsFilesystemAsync(e,t,r).catch((e=>{cI.warn(n,"Divergence check failed",e)})))}async _checkDescriptorsVsFilesystemAsync(e,t,r){const n=this.getLogContext(e),o=(0,s.join)(this.projectDir,lI),i=new Set,a=new Map;for(const e of t){const t=Yw(e.serverIdentifier);i.add(t),a.set(t,e.tools.length)}let c=[];try{c=await(0,vo.readdir)(o),c=c.filter((e=>!e.endsWith(dI)&&!e.endsWith(hI)))}catch(e){if("ENOENT"!==gc(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++,YR.increment(e,1,this.getMetricTags({divergence_type:"server_missing",mcp_source:r,configured_servers:f})),cI.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++,YR.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,uI);let h=0;try{h=(await(0,vo.readdir)(d)).filter((e=>e.endsWith(".json"))).length}catch{}h!==c&&(u=!1,p++,YR.increment(e,1,this.getMetricTags({divergence_type:"tool_count_mismatch",mcp_source:r,configured_servers:f})),cI.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}))}eI.increment(e,1,this.getMetricTags({synced:String(u),mcp_source:r,configured_servers:f})),tI.gauge(e,i.size,this.getMetricTags({mcp_source:r})),rI.gauge(e,l.size,this.getMetricTags({mcp_source:r})),nI.gauge(e,d,this.getMetricTags({mcp_source:r})),oI.gauge(e,p,this.getMetricTags({mcp_source:r})),cI.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||cI.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())}}MI.DIVERGENCE_CHECK_COOLDOWN_MS=1e4;var DI=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},OI=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 FI(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 NI=(0,l.h)("local-exec:mcp");function LI(e,t){const r=s.default.relative(e,t);return""===r||!s.default.isAbsolute(r)&&".."!==r&&!r.startsWith(`..${s.default.sep}`)}function jI(e){return e instanceof Error&&"code"in e&&"string"==typeof e.code?e.code:void 0}function UI(e){return new xc._Z({content:{case:"image",value:new xc.do({data:e.data,mimeType:e.mimeType})}})}function BI(e){return new xc._Z({content:{case:"text",value:new xc.zN({text:e})}})}async function WI(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 Uu(n,{onNeedsApproval:async(e,n)=>{if("mcp"!==n.type)return new xc.iz({result:{case:"error",value:new xc.Nh({error:"Invalid approval details type for MCP execution"})}});const o=await r.pendingDecisionProvider.requestApproval({type:ow.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 xc.iz({result:{case:"approved",value:new xc.Ke}}):null:new xc.iz({result:{case:"rejected",value:new xc.xo({reason:`User rejected MCP: ${t.name}${o.reason?` - ${o.reason}`:""}`})}})},onUserRejected:e=>new xc.iz({result:{case:"error",value:new xc.Nh({error:`User rejected MCP: ${t.name}${e?` - ${e}`:""}`})}}),onPermissionDenied:(e,r)=>HI({name:t.name,reason:e,isReadonly:r?.isReadonly??!1})});return o??void 0}function HI({name:e,reason:t,isReadonly:r}){return new xc.iz({result:{case:"permissionDenied",value:new xc.HQ({error:`MCP tool execution blocked: ${e} - ${t}`,isReadonly:r})}})}class qI{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=DI(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 xc.iz({result:{case:"error",value:new xc.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 WI(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=!0===await(this.permissionsService.enforcesMcpAdminToolLimits?.());let w;try{if(g&&void 0===h)throw new L_(t.name,a.map((e=>e.name)));const e=l?.name??t.name,r=Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t.toJson()])));if(g){const n=void 0===p?void 0:await(m.executeOn?.(p,e,r,t.toolCallId,this.elicitationFactory));if(void 0===n)return NI.warn(o,"Refusing an MCP tool whose client was not judged",{toolName:t.toolName,toolSetNamesClients:void 0!==m.executeOn}),HI({name:t.name,reason:kS,isReadonly:!1});w=n}else w=await m.execute(e,r,t.toolCallId,this.elicitationFactory)}catch(e){let r=e;if(j_(r)&&t.providerIdentifier.length>0&&!a.some((e=>e.clientKey===t.providerIdentifier||e.providerIdentifier===t.providerIdentifier))&&(r=new wR(t.providerIdentifier,c)),r instanceof wR){const e=await this.describeDisconnectedServer(o,[i,t.providerIdentifier]);return void 0!==e?new xc.iz({result:{case:"error",value:new xc.Nh({error:e})}}):new xc.iz({result:{case:"serverNotFound",value:new xc.JL({name:r.serverName,availableServers:r.availableServers})}})}if(j_(r))return new xc.iz({result:{case:"toolNotFound",value:new xc.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(BI(e.text));else if("resource"===r){const r=kC(e),n=void 0===r?void 0:Buffer.from(r,"base64"),s=void 0===n?void 0:await ov(n).then(UI,(e=>{NI.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??BI(_C(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 ov(s)}catch(e){NI.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(BI(`[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(UI(i))}else if("image"!==r){const t=_C(e);y.push(BI(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 xc._Z({content:{case:"text",value:new xc.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,Pc),n=s.default.join(r,`${(0,mo.randomUUID)()}.txt`);await(0,vo.mkdir)(s.default.dirname(n),{recursive:!0});const o=Wo(e,Rc),i=qs(o),a=Buffer.byteLength(o,"utf8");return await(0,vo.writeFile)(n,o,"utf8"),new Ic.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 xc.QW({content:v,isError:w.isError,structuredContent:b,resultMeta:void 0===w._meta?void 0:we.Struct.fromJson(w._meta)});return new xc.iz({result:{case:"success",value:S}})}catch(e){r.error=e,r.hasError=!0}finally{OI(r)}var n}}class zI{constructor(e,t){this.mcpLease=e,this.ensureMcpServersLoaded=t}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=DI(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 xc.kP({result:{case:"error",value:new xc.w2({error:`Server "${t.server}" not found`})}});const o=await this.listResourcesFromClient(n,r,t.server,!0);return new xc.kP({result:{case:"success",value:new xc.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 xc.kP({result:{case:"success",value:new xc.T2({resources:s})}})}catch(e){const t=e instanceof Error?e.message:String(e);return new xc.kP({result:{case:"error",value:new xc.w2({error:`Failed to list MCP resources: ${t}`})}})}}catch(e){r.error=e,r.hasError=!0}finally{OI(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 xc.X2({uri:e.uri,name:e.name,description:e.description,mimeType:e.mimeType,server:r,annotations:FI(e.annotations)}))):[]}}class GI{constructor(e,t=".",r,n=[],o,s,i){this.mcpLease=e,this.projectDir=t,this.pendingDecisionProvider=o,this.ensureMcpServersLoaded=s,this.writeExecutor=i,this.workspacePaths=n.filter((e=>e.length>0))}resolveProjectDir(e){const t=e.get(JR),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=DI(r,(0,$.VI)(e.withName("LocalReadMcpResourceExecutor.execute")),!1).ctx,o=t.smartModeApproval?.reason;if(void 0!==o){if(void 0===this.pendingDecisionProvider)return new xc.ZD({result:{case:"error",value:new xc.Jx({uri:t.uri,error:"Auto-review approval provider is not configured"})}});const e=await this.pendingDecisionProvider.requestApproval({type:ow.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 xc.ZD({result:{case:"rejected",value:new xc.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 xc.ZD({result:{case:"error",value:new xc.Jx({uri:t.uri,error:`Server "${t.server}" not found`})}});try{if("ready"!==(await a.getState(n)).kind)return new xc.ZD({result:{case:"error",value:new xc.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 xc.ZD({result:{case:"notFound",value:new xc.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,vo.realpath)(r),o=s.default.isAbsolute(t)?s.default.resolve(t):s.default.resolve(r,t),i=LI(r,o),a=s.default.isAbsolute(t)&&LI(n,o);if(!i&&!a)throw new Error("downloadPath must stay within the workspace");let c=s.default.dirname(o);for(;;)try{if(!LI(n,await(0,vo.realpath)(c)))throw new Error("downloadPath must stay within the workspace");break}catch(e){if("ENOENT"!==jI(e))throw e;const t=s.default.dirname(c);if(t===c)throw e;c=t}try{if((await(0,vo.lstat)(o)).isSymbolicLink())throw new Error("downloadPath must stay within the workspace")}catch(e){if("ENOENT"!==jI(e))throw e}return o}(this.resolveProjectDir(n),t.downloadPath);let o=e;if(r.text||r.blob){if(void 0===this.writeExecutor)throw new Error("File-write executor is not configured");const s=await this.writeExecutor.execute(n,new ZR.hY({path:e,fileText:r.text??"",fileBytes:r.text||void 0===r.blob?new Uint8Array:new Uint8Array(Buffer.from(r.blob,"base64")),toolCallId:t.toolCallId,confineToWorkspace:!0}));if("rejected"===s.result.case)return new xc.ZD({result:{case:"rejected",value:new xc.Dh({uri:t.uri,reason:s.result.value.reason})}});if("success"!==s.result.case)return new xc.ZD({result:{case:"error",value:new xc.Jx({uri:t.uri,error:VI(s)})}});o=s.result.value.path}return new xc.ZD({result:{case:"success",value:new xc.KZ({uri:t.uri,name:r.name,description:r.description,mimeType:r.mimeType,downloadPath:o})}})}if(r.text)return new xc.ZD({result:{case:"success",value:new xc.KZ({uri:t.uri,name:r.name,description:r.description,mimeType:r.mimeType,annotations:FI(r.annotations),metaJson:Gn(r._meta),content:{case:"text",value:r.text}})}});if(r.blob){const e=Buffer.from(r.blob,"base64");return new xc.ZD({result:{case:"success",value:new xc.KZ({uri:t.uri,name:r.name,description:r.description,mimeType:r.mimeType,annotations:FI(r.annotations),metaJson:Gn(r._meta),content:{case:"blob",value:e}})}})}return new xc.ZD({result:{case:"error",value:new xc.Jx({uri:t.uri,error:"Failed to read resource"})}})}catch(e){const r=e instanceof Error?e.message:String(e);return NI.warn(n,"LocalReadMcpResourceExecutor.execute failed",{server:t.server,hasDownloadPath:Boolean(t.downloadPath),errorName:e instanceof Error?e.name:typeof e,errorMessage:r}),new xc.ZD({result:{case:"error",value:new xc.Jx({uri:t.uri,error:`Failed to read MCP resource: ${r}`})}})}}catch(e){r.error=e,r.hasError=!0}finally{OI(r)}}}function VI(e){switch(e.result.case){case"error":return e.result.value.error;case"permissionDenied":return e.result.value.error||"Permission denied";case"noSpace":return"No space left on device";case"rejected":return e.result.value.reason||"Write rejected";case"success":return"";case void 0:return"Write executor returned result without case";default:{const t=e.result;return String(t)}}}var KI=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 JI=1e4,ZI=5e3,XI={PAGER:"cat",MANPAGER:"cat",LESS:"-R",PIP_PROGRESS_BAR:"off",TQDM_DISABLE:"1"};class QI{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<ZI&&(this.outputHead=Wo(this.outputHead+e,ZI)),this.outputTail=Ho(this.outputTail+e,ZI),t<JI){const r=Math.min(e.length,JI-t);this.fullOutput+=e.slice(0,r)}this.totalChars>JI&&(this.fullOutput="")}getOutput(){return this.totalChars<=JI?this.fullOutput:void 0}getTruncation(){if(!(this.totalChars<=JI))return{outputHead:this.outputHead,outputTail:this.outputTail,elidedChars:this.totalChars-this.outputHead.length-this.outputTail.length}}}class YI{constructor(){this.kept="",this.full=!1}append(e){if(this.full)return;const t=Xo-this.kept.length;this.full=e.length>=t,this.kept+=Wo(e,t)}get text(){return this.kept}}function eT(e,t){return null!==e?e:null===t?-1:-o.constants.signals[t]}class tT{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:ss(n)})}async runProcess({ctx:e,args:t,workingDirectory:r,sandboxPolicy:n,timeoutMs:o}){const s=performance.now(),i=this.defaultCwd,a=(await(0,To.resolveSandboxPolicyForWorkspace)(i,n?{perUser:n}:void 0)).policy,c="insecure_none"!==a.type?{...a,sandboxWorkspaceRoot:i}:a;return await new Promise((n=>{const i=new QI,a=new YI,l=new YI;let u,d,h=!1,p=!1,f="",m=()=>{};const g=(0,To.Qw)((0,To.ue)((0,To.Xw)({...process.env,...XI,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,Vl.D9)(Gl.spawn,y.executable,y.args,w):(0,To.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:Qw(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:eT(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,Ko.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?os(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:Bu(c.reason)})}});a=c.policy,Ps()&&(a=Ms(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{KI(r)}}}const rT=q("shell-executor",(e=>new B(e,Z("shellArgs"),X("shellResult"))),((e,t)=>{t.register(new I(e,Y("shellArgs"),Q("shellResult")))})),nT=q("mini-swe-agent-bash-executor",(e=>new B(e,Z("miniSweAgentBashArgs"),X("miniSweAgentBashResult"))),((e,t)=>{t.register(new I(e,Y("miniSweAgentBashArgs"),Q("miniSweAgentBashResult")))}));function oT(e){return`${e} changed on disk after this tool call read it. Nothing was written. Read the file again and retry.`}function sT(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 iT=q("write-executor",(e=>new B(e,Z("writeArgs"),X("writeResult"))),((e,t)=>{t.register(new I(e,Y("writeArgs"),Q("writeResult")))})),aT=q("delete-executor",(e=>new B(e,Z("deleteArgs"),X("deleteResult"))),((e,t)=>{t.register(new I(e,Y("deleteArgs"),Q("deleteResult")))})),cT=q("fetch-executor",(e=>new B(e,Z("fetchArgs"),X("fetchResult"))),((e,t)=>{t.register(new I(e,Y("fetchArgs"),Q("fetchResult")))})),lT=q("git-diff-executor",(e=>new B(e,Z("gitDiffRequest"),X("gitDiffResponse"))),((e,t)=>{t.register(new I(e,Y("gitDiffRequest"),Q("gitDiffResponse")))})),uT=q("grep-executor",(e=>new B(e,Z("grepArgs"),X("grepResult"))),((e,t)=>{t.register(new I(e,Y("grepArgs"),Q("grepResult")))})),dT="[REDACTED]",hT=new TextEncoder;async function pT(e){const t=hT.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 fT{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 pT(t.output.value),o=t.clone();return o.output={case:void 0},o.outputBlobId=void 0,o.sha256=r,o.sizeBytes=BigInt(n),new fy.sV({result:{case:"success",value:o}})}(await this.inner.execute(e,n,r))}}const mT=q("read-executor",(e=>new B(e,Z("readArgs"),X("readResult"))),((e,t)=>{t.register(new I(e,Y("readArgs"),Q("readResult")))})),gT=q("redacted-read-executor",(e=>new B(e,Z("redactedReadArgs"),X("redactedReadResult"))),((e,t)=>{t.register(new I(e,Y("redactedReadArgs"),Q("redactedReadResult")))})),wT=q("ls-executor",(e=>new B(e,Z("lsArgs"),X("lsResult"))),((e,t)=>{t.register(new I(e,Y("lsArgs"),Q("lsResult")))})),yT=q("diagnostics-executor",(e=>new B(e,Z("diagnosticsArgs"),X("diagnosticsResult"))),((e,t)=>{t.register(new I(e,Y("diagnosticsArgs"),Q("diagnosticsResult")))})),vT=q("canvas-diagnostics-executor",(e=>new B(e,Z("canvasDiagnosticsArgs"),X("canvasDiagnosticsResult"))),((e,t)=>{t.register(new I(e,Y("canvasDiagnosticsArgs"),Q("canvasDiagnosticsResult")))})),bT="$file:";const ST=(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"]}),kT=(0,u.v5)("mcp.symbolic_args.bytes",{description:"Total bytes substituted into one MCP tool call by $file:/abs/path arguments",labelNames:["route"]}),_T=(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"]}),CT=(0,u.v5)("mcp.symbolic_args.paths",{description:"Number of distinct $file:/abs/path arguments expanded in one MCP tool call",labelNames:["route"]});function ET(e,t,r){return{kind:e,message:`Could not resolve the symbolic argument "${bT}${t}": ${r} A string argument of the form "${bT}/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 xT={redacted:e=>`${e} contains a saved secret, and a saved secret is never sent through a "${bT}/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 "${dT}", 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 PT(e,t){return{kind:e,message:`Could not resolve the symbolic argument "${bT}${t}": ${xT[e](t)}`}}class RT extends Error{constructor(e){super(e.message),this.failure=e}}let IT;async function TT(e,t,r,n,o,{maxFileBytes:s=8388608,maxTotalBytes:i=16777216,refuseSavedSecrets:a=!1}){if(t.length>4)throw new RT(ET("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 RT(ET("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 fy.a2({path:r,toolCallId:n,...o.digestOnly?{digestOnly:!0}:{}}));if("success"!==s.result.case)throw new RT(function(e,t,r){switch(e.result.case){case"fileNotFound":return ET("not_found",t,"the file does not exist.");case"permissionDenied":return ET("permission_denied",t,"reading it was not permitted.");case"rejected":return ET("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 ET("not_text",t,"the file cannot be read as text.");case"error":return r?{kind:"read_error",message:`Could not resolve the symbolic argument "${bT}${t}": ${e.result.value.error}`}:ET("read_error",t,e.result.value.error);default:return ET("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 RT(ET("not_text",r,"the file is not a text file."));if(n){if(_T.increment(e,1,{source:void 0!==o?"vm_digest":"outdated_executor"}),void 0===o)throw new RT(ET("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 pT(a??""),u={content:a,bytes:l,sha256:c};if(t.truncated||l>n)throw new RT(ET("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 RT(PT("redacted",r));if(void 0===e.redacted&&await async function(e){return void 0!==e.content?e.content.includes(dT):(await(IT??=Promise.all([dT,`${dT}\n`,`${dT}\r\n`].map((async e=>(await pT(e)).sha256))).then((e=>new Set(e))),IT)).has(e.sha256)}(t))throw new RT(PT("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 RT(ET("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 AT(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=>(ST.increment(e,1,{route:r,outcome:t.kind}),{kind:"failed",failure:t,result:new xc.iz({result:{case:"error",value:new xc.Nh({error:t.message})}})});let c;try{c=await TT(e,i,n,t.toolCallId,!1,o)}catch(e){return a(function(e,t){return e instanceof RT?e.failure:ET("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(ET("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(bT))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,ST.increment(e,1,{route:r,outcome:"expanded"}),kT.record(e,l,{route:r}),CT.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 $T=/\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 MT(e,t,r,n){return $T.test(t)?(ST.increment(e,1,{route:n,outcome:"server_rejected_body"}),`${t}\n\nThe request carried ${r.bytes} bytes of file contents substituted from ${r.paths} "${bT}/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 DT(e){return e.files.map((e=>`"${bT}${e.path}" was replaced with the contents of ${e.path} (${e.bytes} bytes) before the call.`)).join("\n")}class OT{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 AT(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=MT(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 xc._Z({content:{case:"text",value:new xc.zN({text:DT(r)})}})):"error"===n.result.case&&(n.result.value.error=MT(e,n.result.value.error,r,"local")),n}(e,o,n.expansion)}}const FT=q("background-shell-executor",(e=>new B(e,Z("backgroundShellSpawnArgs"),X("backgroundShellSpawnResult"))),((e,t)=>{t.register(new I(e,Y("backgroundShellSpawnArgs"),Q("backgroundShellSpawnResult")))})),NT=q("write-background-shell-input-executor",(e=>new B(e,Z("writeShellStdinArgs"),X("writeShellStdinResult"))),((e,t)=>{t.register(new I(e,Y("writeShellStdinArgs"),Q("writeShellStdinResult")))})),LT=q("agent-store-conflict-executor",(e=>new B(e,Z("agentStoreConflictArgs"),X("agentStoreConflictResult"))),((e,t)=>{t.register(new I(e,Y("agentStoreConflictArgs"),Q("agentStoreConflictResult")))})),jT=q("shell-allowlist-precheck-executor",(e=>new B(e,Z("shellAllowlistPrecheckArgs"),X("shellAllowlistPrecheckResult"))),((e,t)=>{t.register(new I(e,Y("shellAllowlistPrecheckArgs"),Q("shellAllowlistPrecheckResult")))})),UT=q("mcp-allowlist-precheck-executor",(e=>new B(e,Z("mcpAllowlistPrecheckArgs"),X("mcpAllowlistPrecheckResult"))),((e,t)=>{t.register(new I(e,Y("mcpAllowlistPrecheckArgs"),Q("mcpAllowlistPrecheckResult")))})),BT=q("web-fetch-allowlist-precheck-executor",(e=>new B(e,Z("webFetchAllowlistPrecheckArgs"),X("webFetchAllowlistPrecheckResult"))),((e,t)=>{t.register(new I(e,Y("webFetchAllowlistPrecheckArgs"),Q("webFetchAllowlistPrecheckResult")))})),WT=q("force-background-shell-executor",(e=>new B(e,Z("forceBackgroundShellArgs"),X("forceBackgroundShellResult"))),((e,t)=>{t.register(new I(e,Y("forceBackgroundShellArgs"),Q("forceBackgroundShellResult")))})),HT=q("computer-use-executor",(e=>new B(e,Z("computerUseArgs"),X("computerUseResult"))),((e,t)=>{t.register(new I(e,Y("computerUseArgs"),Q("computerUseResult")))})),qT=q("record-screen-executor",(e=>new B(e,Z("recordScreenArgs"),X("recordScreenResult"))),((e,t)=>{t.register(new I(e,Y("recordScreenArgs"),Q("recordScreenResult")))}));var zT=r("../proto/dist/generated/agent/v1/agent_store_conflict_exec_pb.js");function GT(e){if(void 0!==e)return{journalEpoch:e.journalEpoch,seq:Number(e.seq),lastEventId:e.lastEventId}}class VT{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:GT(t.cursor),advance:!1!==t.advance});return new zT.Ev({result:{case:"success",value:new zT.iS({events:e.events.map((e=>new zT.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 zT.LK({journalEpoch:r.journalEpoch,seq:BigInt(r.seq),lastEventId:r.lastEventId})),gap:e.gap})}})}catch(e){return new zT.Ev({result:{case:"error",value:new zT.h6({error:e instanceof Error?e.message:String(e)})}})}var r}}class KT{constructor(e){this.shellStdinWriter=e}async execute(e,t){const r=t.shellId;try{await this.shellStdinWriter(r,t.chars)}catch(e){return new Io.nt({result:{case:"error",value:new Io.Gv({error:`Failed to write to shell ${r} stdin: ${e instanceof Error?e.message:"Unknown error"}`})}})}return new Io.nt({result:{case:"success",value:new Io.tR({shellId:r,terminalFileLengthBeforeInputWritten:0})}})}}var JT=r("../proto/dist/generated/agent/v1/canvas_diagnostics_exec_pb.js"),ZT=r("../proto/dist/generated/agent/v1/diagnostics_exec_pb.js");class XT{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"),QT(YT(t.path,"diagnostics unavailable"),await o)):(r(e.some((e=>1===e.severity))?"failed":"passed"),QT(new JT.GL({result:{case:"success",value:new JT.uX({path:t.path,diagnostics:e.map(eA)})}}),await o))}catch(e){return r("unavailable"),QT(YT(t.path,e instanceof Error?e.message:String(e)),await o)}}}function QT(e,t){return void 0===t||(e.saveState=t.saveState,e.canvasId=t.canvasId,e.title=t.title,e.saveDetail=t.saveDetail),e}function YT(e,t){return new JT.GL({result:{case:"error",value:new JT.HW({path:e,error:t})}})}function eA(e){return new ZT.oQ({severity:tA(e.severity),range:new Ic.Q6({start:new Ic.yX({line:e.range.start.line+1,column:e.range.start.character+1}),end:new Ic.yX({line:e.range.end.line+1,column:e.range.end.character+1})}),message:e.message,source:"ts",code:e.code??""})}function tA(e){switch(e){case 1:return ZT.h_.ERROR;case 2:return ZT.h_.WARNING;case 3:return ZT.h_.INFORMATION;case 4:return ZT.h_.HINT;default:return ZT.h_.UNSPECIFIED}}class rA{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 rA(e)}static fromUrl(e){if(!e.startsWith("file://"))throw new Error(`Expected file:// URL, got: ${e}`);return new rA(e)}static fromString(e){return new rA(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 nA=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 oA{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,Ko.o1)(t.path,this.workspacePath);try{const e=await(0,vo.stat)(r);if(!e.isFile()&&!e.isDirectory())return new ZT.Ek({result:{case:"fileNotFound",value:new ZT.Mu({path:t.path})}})}catch(e){if("ENOENT"===gc(e))return new ZT.Ek({result:{case:"fileNotFound",value:new ZT.Mu({path:t.path})}});if("EACCES"===gc(e))return new ZT.Ek({result:{case:"permissionDenied",value:new ZT.RP({path:t.path})}});throw e}const n=(0,Ko.o1)(r,this.workspacePath),o=new rA(n);await this.diagnosticsProvider.open(e,o);const s=(await this.diagnosticsProvider.getDiagnostics(e,o)).map((e=>this.convertDiagnostic(e)));return new ZT.Ek({result:{case:"success",value:new ZT.a1({path:t.path,diagnostics:s,totalDiagnostics:s.length})}})}catch(r){return e.canceled?new ZT.Ek({result:{case:"error",value:new ZT.Ho({path:t.path,error:"Request timed out after 10 seconds"})}}):new ZT.Ek({result:{case:"error",value:new ZT.Ho({path:t.path,error:r instanceof Error?r.message:String(r)})}})}finally{n()}}catch(e){r.error=e,r.hasError=!0}finally{nA(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 ZT.oQ({severity:this.convertSeverity(e.severity),range:e.range?new Ic.Q6({start:new Ic.yX({line:e.range.start.line,column:e.range.start.character}),end:new Ic.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 ZT.h_.ERROR;case 2:return ZT.h_.WARNING;case 3:return ZT.h_.INFORMATION;case 4:return ZT.h_.HINT;default:return ZT.h_.UNSPECIFIED}}}async function sA(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 jw().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 iA(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 iA(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 iA{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 aA=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]=uA(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=hA(e)}],[/^\+\+\+\s/,e=>{u(),n.to=hA(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},cA=/(a|i|w|c|o|1|2)\/.*(?=["']? ["']?(b|i|w|c|o|1|2)\/)|(b|i|w|c|o|1|2)\/.*$/g,lA=/^(a|b|i|w|c|o|1|2)\//,uA=e=>{const t=e?.match(cA);return t?.map((e=>e.replace(lA,"").replace(/("|')$/,"")))},dA=/^\\?['"]|\\?['"]$/g,hA=e=>{let t=pA(e,"-+").trim();return t=mA(t),t.replace(dA,"").replace(lA,"")},pA=(e,t)=>{if(e=wA(e),!t&&String.prototype.trimLeft)return e.trimLeft();const r=gA(t);return e.replace(new RegExp(`^${r}+`),"")},fA=/\t.*|\d{4}-\d\d-\d\d\s\d\d:\d\d:\d\d(.\d+)?\s(\+|-)\d\d\d\d/,mA=e=>{const t=fA.exec(e);return t&&(e=e.substring(0,t.index).trim()),e},gA=e=>null==e?"\\s":e instanceof RegExp?e.source:`[${wA(e).replace(/([.*+?^=!:${}()|[\]/\\])/g,"\\$1")}]`,wA=e=>`${e??""}`,yA=(0,l.h)("local-mercurial-diff"),vA=5242880,bA="0000000000000000000000000000000000000000";let SA,kA;async function _A(e,t,r={}){const n=await async function(){if(void 0===SA&&(SA=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 vo.stat(t)).isFile())continue;return"win32"!==process.platform&&await vo.access(t,So.constants.X_OK),t}catch{}}}(process.env.PATH??"")??null),null===SA){const e=new Error("hg executable not found");throw e.code="ENOENT",e}return SA}(),o=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 ta.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"}`))}}))}));return o}async function CA(e){const t=await async function(e){let t=s.default.resolve(e);for(;;){try{if((await vo.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!==kA)return kA;const e=await vo.mkdtemp(s.default.join((0,o.tmpdir)(),"hg-probe-"));try{const t=await _A(e,["help","environment"]);kA=/\bHGRCSKIPREPO\b/.test(t)?"skips-repo-config":"reads-repo-config"}catch(e){kA=function(e){return"object"==typeof e&&null!==e&&"code"in e&&"ENOENT"===e.code}(e)?"absent":"reads-repo-config"}finally{await vo.rm(e,{recursive:!0,force:!0})}return kA}());if("not-mercurial"===r)return;if("unsafe"===r)throw new Error("MercurialClientUnsafe: hg would read repository config");let n;try{n=(await _A(e,["root"])).trim()}catch{return}if(0!==n.length)try{return(await vo.stat(s.default.join(n,".hg"))).isDirectory()?n:void 0}catch{return}}function EA(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 xA(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 PA(e){const t=s.default.resolve(e);try{return await vo.realpath(t)}catch{return t}}function RA(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 IA(e){if(e.includes("\0")||/[\r\n]/.test(e))throw new Error("MercurialDiffFailed: base ref contains a newline")}async function TA({repositoryRoot:e,rev:t,filePath:r}){const n=await async function({repositoryRoot:e,rev:t,filePath:r}){let n;try{n=await _A(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>vA?"":_A(e,["cat","-r",t,"--",r])}async function AA(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 _A(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){IA(t),r.push("log");const n=(await _A(e,["log","-r",`ancestor(., (${t}))`,"-T","{node}"])).trim();if(0===n.length||n===bA)throw new Error("MercurialDiffFailed: base ref did not resolve");return n}r.push("log");const n=(await _A(e,["log","-r","max(::. and public())","-T","{node}"],{allowFailure:!0})).trim();if(n.length>0&&n!==bA)return n;const o=(await _A(e,["log","-r","ancestor(., default)","-T","{node}"],{allowFailure:!0})).trim();if(o.length>0&&o!==bA)return o;const s=(await _A(e,["log","-r",".","-T","{node}"],{allowFailure:!0})).trim();return s.length>0?s:bA}({cwd:t,baseRef:r.baseRef,commands:o});else if(IA(r.baseRef),o.push("log"),a=(await _A(t,["log","-r",r.baseRef,"-T","{node}"])).trim(),0===a.length)throw new Error("MercurialDiffFailed: base ref did not resolve");r.ref.length>0&&(IA(r.ref),o.push("log"),c=(await _A(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 _A(t,l),d=function(e){const t=e.replace(/\r\n/g,"\n");return new Le.o$({diffs:aA(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 _A(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 vo.stat(r);if(n.size>vA){const t=await async function(e){const t=(0,mo.createHash)("sha256"),r=await vo.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 vo.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=RA(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 TA({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 vo.stat(e);t.afterFileContents=r.size>vA?"":await vo.readFile(e,"utf8")}catch{t.afterFileContents=""}else try{t.afterFileContents=await TA({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=RA(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,mo.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 _A(t,["log","-r",".","-T","{node}"],{allowFailure:!0})).trim();m=e.length>0?e:bA,g=(await _A(t,["status","-0"])).length>0}yA.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 yA.info(e,"Local diff outcome",{sourceControl:"mercurial",outcome:"too_large"}),new Error(`GetDiffResponseTooLarge: ${t} bytes exceeds the ${y} byte limit`)}return yA.info(e,"Local diff outcome",{sourceControl:"mercurial",outcome:"ok",fileCount:d.diffs.length,patchIdPrefixed:!0===f?.startsWith("hg:")}),w}const $A=(0,l.h)("local-git-diff");function MA({exitCode:e,stderr:t}){return new Error(`Git command failed with code ${e}: ${t}`)}async function DA(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 MA(n);return!0===r.shouldNotTrimOutput?n.stdout:n.stdout.trim()}function OA(e){const t=aA(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 FA(e){const t=[];for(const n of e){const e={body:`+${(r=n.contents).replaceAll("\n","\n+")}`,numLines:qs(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 NA=["main","master","develop"];async function LA(e,t){const r=s.default.join(e,t),n=await vo.lstat(r);if(n.isSymbolicLink())return{contents:await vo.readlink(r),path:t,isSymlink:!0};if(!n.isFile())throw new Error("Not a regular file or symlink");return{contents:await vo.readFile(r,"utf8"),path:t,isSymlink:!1}}async function jA(e,t,r){const n=jw(),o=(e,r)=>n.run(t,e,r),i=await async function(e,t){let r;try{const e=(await DA(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 PA(t);let n=await PA(e);if(EA(n,r))return;let o=!1;for(;xA(n,r)&&!EA(n,r);){try{if((await vo.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?CA(e):void 0}({cwd:e,gitRoot:r});return void 0!==t?"mercurial":"git"}return void 0===await CA(e)?"none":"mercurial"}(t,o);if($A.info(e,"Local diff source control",{sourceControl:i}),"none"===i)throw $A.info(e,"Local diff outcome",{sourceControl:i,outcome:"no_version_control"}),new Error("NoVersionControl: no git or mercurial repository");if("mercurial"===i)return AA(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 DA(e,["symbolic-ref","--short","refs/remotes/origin/HEAD"]);if(t)return t.trim()}catch{}for(const t of NA){const r=`origin/${t}`;try{return await DA(e,["rev-parse","--verify",r]),r}catch{}}try{const t=(await DA(e,["branch","-r"])).split("\n").map((e=>e.trim())).find((e=>e.startsWith("origin/")));if(t)return t}catch{}try{const t=await DA(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 DA(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=OA(h);else{const t=MA(d);if(r.computePatchId||!await async function(e){return(await DA(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 DA(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})),$A.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 DA(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 LA(e,t)}catch{return}})))).filter((e=>void 0!==e))}(t,o,r.maxUntrackedFiles);for(const e of f){const t=e.isSymlink?`${FA([e])}\n\`:await DA(o,["diff","--no-color","--no-index","--","/dev/null",e.path],{ignoreErrors:!0,shouldNotTrimOutput:!0});p.diffs.push(...OA(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 DA(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 DA(o,["show","--end-of-options",`${n}:${s.to}`],{shouldNotTrimOutput:!0})}catch{s.afterFileContents=""}else try{s.afterFileContents=(await LA(t,s.to)).contents}catch{try{s.afterFileContents=await DA(o,["show","--end-of-options",`${n}:${s.to}`],{shouldNotTrimOutput:!0})}catch{s.afterFileContents=""}}else s.afterFileContents=""}catch(t){$A.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 sA({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 DA(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){$A.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,FA(f))):void 0,v=!0===r.returnHeadSha?(await DA(o,["rev-parse","HEAD"])).trim():void 0,b=!0===r.returnHeadSha?(await DA(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 UA{async execute(e,t){return jA(e,t.cwd,t)}}var BA=r("../proto/dist/generated/agent/v1/mcp_allowlist_precheck_exec_pb.js");class WA{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 BA.M({allowlisted:r})}}var HA=r("../proto/dist/generated/agent/v1/record_screen_exec_pb.js"),qA=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 zA(e){return null!==e.exitCode||null!==e.signalCode||e.killed}function GA(e,t){return"object"==typeof e&&null!==e&&"code"in e&&e.code===t}function VA(e){return e instanceof Error?e.message:String(e)}function KA(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: ${VA(r)}`),o.length>0?`${e} (${o.join("; ")})`:e}const JA=(0,Us.promisify)(Gl.execFile);class ZA{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(!zA(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),ZA.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 vo.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 vo.mkdir(this.stagingDir,{recursive:!0}),await vo.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:HA.y.UNSPECIFIED}:t.includes("/")||t.includes("\\")?{success:!1,reason:HA.y.SLASHES_NOT_ALLOWED}:(t=t.replace(/[^a-zA-Z0-9 ._-]/g,"_"),t=t.trim(),0===t.length?{success:!1,reason:HA.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 vo.rename(e,t)}catch(e){if(!GA(e,"EXDEV"))throw e}try{await vo.copyFile(e,t)}catch(e){throw await vo.rm(t,{force:!0}).catch((()=>{})),e}try{await vo.unlink(e)}catch(e){throw await vo.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 vo.open(e,"wx");return await t.close(),e}catch(e){if(!GA(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,Vl.D9)(JA,"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,Vl.D9)(JA,"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:ZA.PROXY_TARGET_FPS,includeBrandTag:!0}),await vo.access(n,vo.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,Vl.D9)(JA,"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 ${ZA.PROXY_TARGET_FPS}fps`)}catch(e){console.warn(`[record-screen] Failed to read video framerate: ${e instanceof Error?e.message:String(e)}, defaulting to ${ZA.PROXY_TARGET_FPS}fps`)}return ZA.PROXY_TARGET_FPS}async startFfmpegRecording(e,t){const r=s.join(t,"recording");await vo.mkdir(r,{recursive:!0});const n=s.join(r,"recording_render_proxy_1080p.mp4");let o;try{o=(await cg(this.display)).display.refreshRate}catch(e){console.warn(`[record-screen] Failed to detect refresh rate: ${e instanceof Error?e.message:String(e)}, using default ${ZA.DEFAULT_REFRESH_RATE}Hz`),o=ZA.DEFAULT_REFRESH_RATE}const i=["-video_size",e,"-framerate",String(o),"-draw_mouse","0","-f","x11grab","-i",this.display,"-vf",`scale=${ZA.PROXY_TARGET_WIDTH}:-2:flags=lanczos,fps=${ZA.PROXY_TARGET_FPS}`,"-c:v","libx264","-preset",ZA.PROXY_PRESET,"-crf",String(ZA.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,Vl.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,Vl.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 vo.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(zA(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),GA(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{!zA(r.childProcess)&&r.childProcess.pid&&await this.stopFfmpegRecording(r)}catch(e){a=e,console.warn(`[record-screen] Failed to stop ffmpeg: ${VA(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 vo.access(d,vo.constants.R_OK)}catch(e){await this.cleanupRecording(r),this.clearActiveRecordingIfCurrent(r);const t=GA(e,"ENOENT")?`Recording proxy not found at ${d}`:`Recording proxy at ${d} could not be validated: ${VA(e)}`;return new HA.Tj({result:{case:"failure",value:new HA.yH({error:KA(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=VA(e),o=t.includes(d)?t:`Recording proxy at ${d} could not be validated: ${t}`;return new HA.Tj({result:{case:"failure",value:new HA.yH({error:KA(o,r,a,n)})}})}const m={profileVersion:ZA.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:ZA.PROXY_TARGET_FPS,codec:"h264",profile:ZA.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 vo.copyFile(d,g);else{const t=await this.renderPolished(e,l);await this.movePolishedVideo(t,g)}}catch(e){throw await vo.rm(g,{force:!0}).catch((()=>{})),e}try{await vo.rm(l,{force:!0,recursive:!0})}catch(e){console.warn(`[record-screen] Failed to remove staging session ${l}: ${VA(e)}`)}return this.clearActiveRecordingIfCurrent(r),new HA.Tj({result:{case:"saveSuccess",value:new HA.ol({path:g,recordingDurationMs:we.protoInt64.parse(h.toString()),requestedFilePathRejectedReason:w})}})}catch(e){return await this.cleanupRecording(r),this.invokeStoppedCallbackIfCurrent(r),new HA.Tj({result:{case:"failure",value:new HA.yH({error:VA(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 HA.Tj({result:{case:"failure",value:new HA.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===HA.$u.UNSPECIFIED)return new HA.Tj({result:{case:"failure",value:new HA.yH({error:"Mode must be one of START_RECORDING, SAVE_RECORDING, DISCARD_RECORDING"})}});switch(t.mode){case HA.$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 vo.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 vo.mkdir(o,{recursive:!0});const{resolutionString:s,resolution:i}=await cg(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 wg({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 HA.Tj({result:{case:"startSuccess",value:new HA.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 vo.rm(o,{force:!0,recursive:!0}).catch((()=>{})),this.activeRecording=null,new HA.Tj({result:{case:"failure",value:new HA.yH({error:e instanceof Error?e.message:String(e)})}})}}case HA.$u.SAVE_RECORDING:{if(!this.activeRecording)return 1===this.inFlightSaves.length?await this.inFlightSaves[0].promise:new HA.Tj({result:{case:"failure",value:new HA.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 HA.$u.DISCARD_RECORDING:{if(!this.activeRecording)return new HA.Tj({result:{case:"failure",value:new HA.yH({error:"No active recording to discard"})}});const e=this.activeRecording;if(this.findInFlightSave(e))return new HA.Tj({result:{case:"failure",value:new HA.yH({error:"Save in progress for this recording; wait for it or start a new recording"})}});try{return await e.inputEventLogger.stop(),this.invokeStoppedCallbackOnce(),!zA(e.childProcess)&&e.childProcess.pid&&await this.stopFfmpegRecording(e),await vo.rm(e.sessionDir,{force:!0,recursive:!0}),this.activeRecording=null,new HA.Tj({result:{case:"discardSuccess",value:new HA.N8}})}catch(t){await this.cleanupRecording(e),this.invokeStoppedCallbackOnce();const r=e.sessionDir;let n=!1;try{await vo.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 HA.Tj({result:{case:"failure",value:new HA.yH({error:`Failed to discard recording: ${o}${s}`})}})}}default:{const e=t.mode;return new HA.Tj({result:{case:"failure",value:new HA.yH({error:`Unhandled recording mode: ${String(e)}`})}})}}}catch(e){r.error=e,r.hasError=!0}finally{qA(r)}}}async function XA(e){const t=await(0,vo.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 XA(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 QA(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(...QA(t,e,s))}))}return n}async function YA(e){if(!await(0,vo.access)(e,vo.constants.R_OK).then((()=>!0),(()=>!1)))return"(No notes directory yet - will be created when you write your first note)";const t=await XA(e);return 0===t.length?"(Notes directory is empty)":t.flatMap(((e,r)=>QA(e,"",r===t.length-1))).join("\n")}async function e$(e,t){return YA(s.join(e,"agent-notes",t))}async function t$(e){return YA(s.join(e,"agent-notes","shared"))}ZA.IN_FLIGHT_SAVE_DISPOSE_TIMEOUT_MS=3e4,ZA.PROXY_TARGET_WIDTH=1920,ZA.PROXY_TARGET_FPS=60,ZA.PROXY_CRF=17,ZA.PROXY_PRESET="veryfast",ZA.PROXY_PROFILE_VERSION="render-proxy-h264-all-i-v1",ZA.DEFAULT_REFRESH_RATE=60;var 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},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});const o$=3e3,s$=(0,l.h)("local-exec:request-context"),i$=Symbol("sectionLoadTimedOut");function a$(e,t){if(void 0===t)return e;let r;const n=new Promise((e=>{r=setTimeout((()=>e(i$)),t)}));return e.catch((()=>{})),Promise.race([e,n]).finally((()=>{clearTimeout(r)}))}class c${async read(e,t){const r=this.inFlight??this.begin(e),n=this.last;if(void 0===n)return r;const o=await a$(r,t).catch((()=>i$));return o===i$?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 l$(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{r$(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{n$(o)}}async function u$(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 d$(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(l$(e,t,r,n)),o(u$(e,t,r,n))]);return{status:s,branchName:i}}async function h$(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,To.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,R=n&&s&&!1!==i?`${n}/agent-notes/${s}`:void 0,I=n?`${n}/agent-transcripts`:void 0,T=!!d&&d(),A=h?.(),$=c?.();let M;if(p)try{const e=await a$(p(),3e3);e!==i$&&(M=e)}catch{M=void 0}return new Mr.GE({osVersion:S,workspacePaths:t,shell:k,sandboxEnabled:T,projectFolder:E,terminalsFolder:x,agentSharedNotesFolder:P,agentConversationNotesFolder:R,agentTranscriptsFolder:I,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 p$={type:"object",properties:{},additionalProperties:!1};function f$(e,t){return{tools:(!0===t?.internalBrowserProvidersOnly?e.servers.filter((e=>zn.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 m$(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,...Yv(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!qn(e.serverIdentifier)||!0!==t?.alwaysExposeVirtualMcpAuthTool&&"needsAuth"!==e.status||o.some((e=>e.toolName===bI))||o.push(new fn.E$({toolName:bI,...r?{}:{description:SI,...!0===t?.inputSchemaJson?{inputSchemaJson:JSON.stringify(p$)}:{inputSchema:we.Value.fromJson(p$)}}})),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 g$(e){const t=e?.trim();return t||void 0}function w$(e,t){const r=function(e){return g$(e.serverIdentifier)}(e);if(r)return r;const n=g$(e.serverName);return n?t.get(n)??n:void 0}class y${constructor(e){this.mcpLease=e}async getState(e){const[t,r]=await Promise.all([this.mcpLease.getTools(e).catch((t=>(s$.warn(e,"Error fetching MCP tools",{error:t}),[]))),this.mcpLease.getInstructions(e).catch((t=>(s$.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=>w$(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=>w$(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=>(s$.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 v$(e){return new xc._W({result:{case:"success",value:new xc.pv({servers:e.servers.map((e=>new xc.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:Gn(e._meta),...Yv(e.annotations)}))),instructions:e.instructions,status:e.status,errorMessage:e.errorMessage})))})}})}class b${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!==xc.ew.FORCE_IF_MISSING&&t.refreshPolicy!==xc.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 v$({...r,servers:n})}return v$(r)}}class S${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 c$,this.reusedAgentSkills=new c$,this.reusedAdminCommandDenylist=new c$,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:R,isAttributionDisabledByAdmin:I,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=R,this.isAttributionDisabledByAdmin=I,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,this.mcpFieldsFromCaller=c.mcpFieldsFromCaller??!1,!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=r$(r,(0,$.VI)(e.withName("LocalRequestContextExecutor.warmWorkspaceCache")),!1),o=await Ka(n.ctx,this.gitExecutor,t),s=o?await ec(n.ctx,this.gitExecutor,o):void 0,i={repoPath:o??void 0,remoteUrl:void 0!==s?tc(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((()=>d$((0,y.q6)(),this.gitExecutor,e,o$)))}}catch(e){r.error=e,r.hasError=!0}finally{n$(r)}}gitInfoSection(e){let t=this.reusedGitInfo.get(e);return void 0===t&&(t=new c$,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=r$(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{n$(e)}}async computeGlobalCache(e){const t={stack:[],error:void 0,hasError:!1};try{const r=r$(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&&s$.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{n$(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=r$(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:qa(r.remoteUrl)});if(void 0===r.repoPath)return;const c=r.repoPath,{status:l,branchName:u}=void 0===this.freshSectionWaitMs?await d$(n.ctx,t.gitExecutor,c,o$):await this.gitInfoSection(c).read((()=>d$((0,y.q6)(),t.gitExecutor,c,o$)),this.freshSectionWaitMs);return void 0===l&&(i=!1),new Mr.DS({path:r.repoPath,status:l,branchName:u,remoteUrl:r.remoteUrl,isOriginBacked:qa(r.remoteUrl)})})))).filter((e=>void 0!==e)),gitRepoInfoComplete:s,gitStatusInfoComplete:s&&i}}catch(e){r.error=e,r.hasError=!0}finally{n$(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=r$(n,(0,$.VI)(e.withName("LocalRequestContextExecutor.computeCachedRequestContext")),!1),s=this.projectDir,i=async()=>{const e={stack:[],error:void 0,hasError:!1};try{const t=r$(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{n$(e)}},a=performance.now(),c={},l=(e,t)=>{const r=performance.now();return t.finally((()=>{c[e]=Math.round(performance.now()-r)}))},u=e=>a$(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",this.mcpFieldsFromCaller?Promise.resolve({servers:[]}):u(p(this.reusedMcpState,(()=>d((()=>this.inFlightMcpState),(e=>{this.inFlightMcpState=e}),(()=>this.mcpStateAccessor.getState(f))))))),l("env",h$(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?e$(s,t.notesSessionId):Promise.resolve(void 0)),l("sharedNotes",this.agentNotesEnabled&&s?t$(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)))))))]),R=m===i$,I=g===i$,T=x===i$,A=P===i$,M=R?this.lastGoodGlobalCache??{rules:[...this.additionalRules],cloudRule:null,codebaseReference:void 0,customSubagents:[]}:m,D=I?{servers:[]}:g,O=T?[]:x,F=A?void 0:P;(R||I||T||A)&&s$.warn(o.ctx,"computeCachedRequestContext: section load timed out",{timeoutMs:this.sectionLoadTimeoutMs,rulesAndSubagents:R,mcpState:I,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&&s$.warn(o.ctx,"computeCachedRequestContext: slow parallel data collection",{durationMs:Math.round(N),...c});const L=this.mcpMetaToolEnabled?m$(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}]:[],...f$(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=!R,W.customSubagentsInfoComplete=!R,W.agentSkillsInfoComplete=!T,W.mcpInfoComplete=!I,W.mcpFileSystemInfoComplete=this.mcpMetaToolEnabled||void 0!==C,W.envInfoComplete=!0,W.gitStatusInfoComplete=S),W}catch(e){n.error=e,n.hasError=!0}finally{n$(n)}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{this.onRequestContext?.();const n=r$(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(wc(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{n$(r)}}}function k$(e){return 0!==e.timeout?e.timeout:e.isBackground||e.timeoutBehavior===he._d.BACKGROUND||void 0!==e.hardTimeout&&e.hardTimeout>0?0:3e4}var _$=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 C${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:ss(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:ss(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?{perUser: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=Qw(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:ss(o)}):e.signal.aborted?new he.W4({result:{case:"rejected",value:new he.pZ({command:t.command,workingDirectory:r,reason:"Command aborted"})},sandboxPolicy:ss(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:ss(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?os(t.requestedSandboxPolicy):void 0,i=t.workingDirectory||await this.coreExecutor.getCwd(t.conversationId),a=k$(t),c=(0,Ko.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(Ro(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:Wu(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:xo(t)},s);if("block"===e.kind)return new he.W4({result:Wu(o,c,e.reason)});l=e.policy}return l=await Ec(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{_$(r)}}}var E$=r("../proto/dist/generated/agent/v1/shell_allowlist_precheck_exec_pb.js");class x${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 E$.e({allowlisted:n})}}class P${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 R$=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 I$=(0,l.h)("local-exec:shell-stream");class T${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 A$(){let e=()=>{};return{promise:new Promise((t=>{e=t})),resolve:e}}class $${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:A$()},""!==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?os(t.requestedSandboxPolicy):void 0;const i=t.workingDirectory||await this.coreExecutor.getCwd(t.conversationId),a=k$(t),c=(0,Ko.o1)(i),l=Date.now(),u=performance.now(),d=new he.HO(No(o).structured),h=ws({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:Ro(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:Bu(p.reason)})}}));if(I$.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}),Ro(t)){const r=p.policy??s;I$.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:xo(t),onApprovalRequested:()=>{r.registered.resolve(void 0),r.registered=A$()}},s);if(r.awaitingApproval=!1,"block"===n.kind){if(I$.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=Bu(n.reason);return void(yield new he.FI({event:{case:"rejected",value:new he.pZ({command:o,workingDirectory:c,reason:r})}}))}s=n.policy,I$.info(e,"Shell stream: approval gate allowed command",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,effectivePolicyType:s.type})}s=await Ec(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:ss(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?{perUser: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 T$(b[Symbol.asyncIterator](),a):null;let _,C,E,x="",P=!1,R=!1;const I=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:Qw(performance.now()-u),backgroundReason:he.Jg.USER_REQUEST,interleavedOutput:x})}})}}:void 0;t.toolCallId&&I&&this.activeForegroundExecutions.set(t.toolCallId,I),this.settle(t.toolCallId,r,I);const T=()=>{t.toolCallId&&this.activeForegroundExecutions.get(t.toolCallId)===I&&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;R=!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:Qw(r.localExecutionTimeMs)})}})}}catch(r){if(!(r instanceof To.SandboxUnsupportedError))throw r;const n=s?.type??"unknown";return I$.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||R||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{R$(n)}}}const M$={kind:"absent"};class D${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 bo.q({max:1e3,ttl:6e4,ttlResolution:0,perf:e})}begin(e){this.entries.purgeStale();const t=++this.nextGeneration;return this.claims.set(B$(e),t),t}record(e,t,r){if(!this.claim(e,r))return;const n=B$(e);this.entries.set(n,{recorded:t,generation:r}),this.commitGeneration(n,r)}forget(e,t){if(!this.claim(e,t))return;const r=B$(e);this.entries.delete(r),this.commitGeneration(r,t)}end(e,t){this.claim(e,t)}take(e){const t=B$(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=B$(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=B$(e);return this.claims.get(r)===t&&(this.claims.delete(r),!0)}}class O${constructor(){this.views=new bo.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>Bs)return void this.views.delete(e);const r=(0,mo.createHash)("sha256").update(t).digest("hex");this.views.set(e,{kind:"fingerprint",byteLength:t.length,sha256:r})}recordDelete(e){this.views.set(e,M$)}}async function F$(e,t){if(void 0===e)return!1;try{if("absent"===e.kind)return await U$(t);const r=await j$(t);return void 0===r||r.byteLength!==e.byteLength||r.sha256!==e.sha256}catch{return!1}}async function N$(e,t){if("fingerprint"!==e?.kind)return!1;try{return!await U$(t)}catch{return!1}}class L${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,Ko.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,Ko.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 mk(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 j$(t)}catch{return}}(i,o.resolvedPath);return this.commit(o,s,i,a,n),i}try{a=await j$(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=M$: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 j$(e){try{const t=await(0,vo.stat)(e);if(!t.isFile()||t.size>Bs)return}catch(e){return W$(e)}let t;try{t=await(0,vo.open)(e,function(){const e=So.constants;return e.O_RDONLY|(e.O_NONBLOCK??0)}());const r=await t.stat();if(!r.isFile()||r.size>Bs)return;const n=(0,mo.createHash)("sha256");let o=0;const s=Buffer.alloc(65536);for(;o<=Bs;){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>Bs)return;return{byteLength:o,sha256:n.digest("hex")}}catch(e){return W$(e)}finally{await(t?.close())}}async function U$(e){try{return await(0,vo.stat)(e),!0}catch(e){if(H$(e))return!1;throw e}}function B$({toolCallId:e,resolvedPath:t}){return`${e}\0${t}`}function W$(e){if(!H$(e))throw e}function H$(e){const t=gc(e);return"ENOENT"===t||"ENOTDIR"===t}var q$=r("../proto/dist/generated/agent/v1/web_fetch_allowlist_precheck_exec_pb.js");class z${constructor(e){this.permissionsService=e}async execute(e,t){const r=await this.permissionsService.isWebFetchFullyAllowlisted(e,{url:t.url});return new q$.M({allowlisted:r})}}var G$=r("node:constants");const V$=[".md",".markdown",".mdown",".mkd",".mkdn",".mdx"];function K$(e){const t=e.trim().toLowerCase();return V$.some((e=>t.endsWith(e)))}function J$(e,t){const r=e.trim().toLowerCase().split("win32"===t?/[\\/]/:"/");if(r.some((e=>"."===e||".."===e)))return!1;const[n,o,s,i,a]=r.slice(-5);return r.length>=5&&".cursor"===n&&"projects"===o&&void 0!==s&&""!==s&&"canvases"===i&&void 0!==a&&a.length>11&&a.endsWith(".canvas.tsx")}const Z$="win32"===process.platform;process.platform;const X$="\\"===s.sep?"win32":"posix",Q$={allowed:!1};class Y$ extends Error{constructor(e,t){super(t),this.name="SymlinkRefusedError",this.path=e}}function eM(e,{nonBlocking:t}){const r=So.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}const tM=[20,40,80],rM=new Set(["UNKNOWN","EBUSY"]);async function nM(e,t){try{const[r,n]=await Promise.all([t.stat({bigint:!0}),(0,vo.lstat)(e,{bigint:!0})]);r.dev===n.dev&&r.ino===n.ino&&await(0,vo.unlink)(e)}catch{}}async function oM(e,t,r,{removeOnRefusal:n=!1}={}){let o;try{o=await async function(e,t){try{return await(0,vo.open)(e,eM(t,{nonBlocking:!0}),438)}catch(r){const n=gc(r);if(("EAGAIN"===n||"EWOULDBLOCK"===n)&&await async function(e){try{return(await(0,vo.lstat)(e)).isFile()}catch{return!1}}(e))return await(0,vo.open)(e,eM(t,{nonBlocking:!1}),438);throw r}}(e,t)}catch(t){if(function(e){const t=gc(e);return"ELOOP"===t||"EMLINK"===t||"EPERM"===t&&"number"==typeof So.constants.O_NOFOLLOW}(t))throw new Y$(e,`Refusing to ${r} through a symlink at ${e}`);throw t}try{let t;try{t=(0,So.realpathSync)(e)}catch{throw new Y$(e,`Cannot verify canonical path before ${r}: ${e}`)}if(t!==e)throw new Y$(e,`Refusing ${r}: ${e} now resolves through a symlinked parent to ${t}`);const n=await o.stat();if(!n.isFile())throw new Y$(e,`Refusing to ${r} non-regular file at ${e}`);return{fd:o,stats:n}}catch(t){throw n&&await nM(e,o),await o.close(),t}}var sM=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 iM=(0,l.h)("LocalWriteExecutor"),aM=(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"]}),cM=async(e,t,r,n)=>{const o=setTimeout((()=>{iM.warn(e,`[watchdog, LocalWriteExecutor] ${t} still not completed after ${r}ms`)}),r);try{return await n()}finally{clearTimeout(o)}};function lM(e){return new Error(`Could not create ${e}: directory creation exceeded the path depth and was stopped.`)}async function uM(e){try{return(await(0,vo.stat)(e)).isDirectory()?"directory":"present"}catch(e){if("ENOENT"===gc(e))return"missing";throw e}}async function dM(e,t){const r=[];let n=e;for(let o=0;o<=t;o+=1){const t=await uM(n);if("directory"===t)return r.reverse(),r;if("present"===t)return await(0,vo.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 lM(e)}class hM{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,pd.fileURLToPath)(e),!1}catch{return!0}}(t.path))return new ZR.v3({result:{case:"error",value:new ZR.QM({path:t.path,error:`${t.path} is not a valid file URL. Use an absolute path instead.`})}});const n=(0,Ko.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 mM(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=Nb(r,d)||void 0!==this.projectDir&&!this.workspacePaths.some((e=>{return t=e,n=r,Z$&&(t=t.toLowerCase(),n=n.toLowerCase()),t===n||(t.charAt(t.length-1)!==s.sep&&(t+=s.sep),n.startsWith(t));var t,n}))&&Lb(this.projectDir,r,d);if((0,Ko.fl)({targetPath:r,workspacePaths:this.workspacePaths,mainWorktreePath:this.worktreeMainPath}))return new ZR.v3({result:{case:"error",value:new ZR.QM({path:r,error:Ko.PS})}});let p,f,m,g,w=!1;try{const e=await(0,vo.stat)(r);if(g=511&e.mode,e.size<=Qo){const e=await cM(c,"readText before write",3e3,(()=>Oi(r,t.encodingHint)));p=e.text,f=e.encoding,m=iw(e)}else w=!0}catch(e){w="ENOENT"!==gc(e)}const y=await Yb(r),v=y.resolvedPath;if(t.confineToWorkspace){let e=(await Promise.all(this.workspacePaths.map((e=>(0,vo.realpath)(e).catch((()=>{})))))).filter((e=>void 0!==e));if(0===e.length&&void 0!==this.projectDir){const t=await(0,vo.realpath)(this.projectDir).catch((()=>{}));void 0!==t&&(e=[t])}if(!e.some((e=>(0,Ko.BJ)(v,e))))return new ZR.v3({result:{case:"error",value:new ZR.QM({path:r,error:"downloadPath must stay within the workspace"})}})}const b=async()=>{return await F$(n,v)?oT(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 F$(o,v)?void 0:sT(r));var e,t},S=t.planMode?await cM(c,"checkPlanModeWriteTarget",3e3,(()=>async function(e,t){switch(t.resolution.status){case"resolved":case"newFile":return K$(t.resolvedPath)?{allowed:!0}:await async function(e,t){if(!(J$(t.resolvedPath,X$)||J$(e,X$)&&t.resolvedPath===await async function(e){const t=(0,s.dirname)((0,s.dirname)((0,s.dirname)((0,s.dirname)(e)))),r=await Yb(t);if(eS(r.resolution))return(0,s.join)(r.resolvedPath,(0,s.relative)(t,e))}(e)))return Q$;if("newFile"===t.resolution.status)return{allowed:!0,singleLink:{kind:"create"}};const r=await async function(e){try{const t=await(0,vo.lstat)(e,{bigint:!0});return t.isFile()&&1n===t.nlink?{kind:"existing",dev:t.dev,ino:t.ino}:void 0}catch{return}}(t.resolvedPath);return void 0===r?Q$:{allowed:!0,singleLink:r}}(e,t);case"danglingSymlink":{const e=await async function(e){let t=e;for(let e=0;e<40;e++){let e;try{e=await(0,vo.readlink)(t)}catch(e){const r=gc(e);return"ENOENT"===r||"EINVAL"===r?t:void 0}t=(0,s.resolve)((0,s.dirname)(t),e)}}(t.resolvedPath);return void 0!==e&&K$(e)?{allowed:!0}:Q$}case"permissionDenied":case"symlinkLoop":case"unknownError":return Q$;default:return t.resolution,Q$}}(r,y))):void 0;if(void 0!==S&&!S.allowed)return new ZR.v3({result:{case:"rejected",value:new ZR.en({path:r,reason:"Cannot edit non markdown files in plan mode"})}});const k=(".cursorignore"===(r.split(s.sep).pop()?.toLowerCase()??"")?{type:"permissionsConfig"}:void 0)??await cM(c,"permissionsService.shouldBlockWrite",3e3,(()=>this.permissionsService.shouldBlockWrite(c,v,l)));if(k){const e=await cM(c,"handleBlockReason",3e3,(()=>Uu(k,{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 pM(r,a);const c=await this.pendingDecisionProvider.requestApproval({type:ow.Write,details:{path:r,reason:e,isNewFile:o,diffString:s,before:p,after:l,blockReason:i},toolCallId:t.toolCallId});return c.approved?null:new ZR.v3({result:{case:"rejected",value:new ZR.en({path:r,reason:c.reason||""})}})},onUserRejected:e=>new ZR.v3({result:{case:"rejected",value:new ZR.en({path:r,reason:e||""})}}),onPermissionDenied:(e,t)=>new ZR.v3({result:{case:"permissionDenied",value:new ZR.U7({path:r,error:e,isReadonly:t?.isReadonly??!1})}})})));if(null!==e)return e}const _=await cM(c,"anotherSpellingRefusal",3e3,(()=>async function(e){const t=(0,s.basename)(e);let r;try{if(!(await(0,vo.stat)(e)).isFile())return;const n=await(0,vo.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!==_)return new ZR.v3({result:{case:"error",value:new ZR.QM({path:r,error:_})}});const C=(0,s.dirname)(v);if(await N$(n,C))return pM(r,oT(r));if(await N$(o,C))return pM(r,sT(r));let E,x,P,R;try{E=await cM(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 dM(e,t),a=0;for(;a<i.length;){const c=i[a];if(n+=1,n>r)throw lM(e);try{await(0,vo.mkdir)(c,{recursive:!1})}catch(r){const n=gc(r);if("EEXIST"===n){if("directory"!==await uM(c))throw r;a+=1;continue}if("ENOENT"===n){const n=(0,s.dirname)(c);if(n===c||"missing"!==await uM(n))throw r;i=await dM(e,t),a=0,o=0;continue}throw r}o+=1,a+=1}return o}(C)))}catch(e){const t=gc(e);return"EACCES"===t||"EPERM"===t?new ZR.v3({result:{case:"permissionDenied",value:new ZR.U7({path:r,directory:C,operation:"create_directory",error:"Permission denied"})}}):new ZR.v3({result:{case:"error",value:new ZR.QM({path:r,error:wc(e)})}})}if(void 0!==u)x=u,P=0;else{const e=await cM(c,"getBufferForWrite",3e3,(()=>Ni(r,l,this.workspacePath,t.encodingHint)));x=e.buffer,P=e.lines,R=e.format.encoding}const I=()=>cM(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 async function(e,t,r){const n=r?.singleLink,{fd:o}=void 0===n?await oM(e,So.constants.O_WRONLY|So.constants.O_CREAT,"write"):await async function(e,t){const r="create"===t.kind,n=r?So.constants.O_WRONLY|So.constants.O_CREAT|So.constants.O_EXCL:So.constants.O_WRONLY;let o;try{o=await oM(e,n,"write",{removeOnRefusal:r})}catch(t){const r=gc(t);if("EEXIST"===r||"ENOENT"===r)throw new Y$(e,`Refusing to write: ${e} was ${"EEXIST"===r?"created":"removed"} after it was checked`);throw t}const{fd:s}=o;try{const r=await s.stat({bigint:!0});if(1n!==r.nlink)throw new Y$(e,`Refusing to write: ${e} has ${r.nlink} hard links`);if("existing"===t.kind&&(r.dev!==t.dev||r.ino!==t.ino))throw new Y$(e,`Refusing to write: ${e} was replaced after it was checked`);return o}catch(t){throw r&&await nM(e,s),await s.close(),t}}(e,n);try{await async function(e){for(let t=0;;t++)try{return void await e.truncate(0)}catch(e){const r=gc(e);if(t>=tM.length||void 0===r||!rM.has(r))throw e;await(0,ng.setTimeout)(tM[t])}}(o);const e=function(e){return Buffer.isBuffer(e)?e:Buffer.from(e)}(t);let n=0;for(;n<e.length;){const{bytesWritten:t}=await o.write(e,n,e.length-n,n);if(0===t)break;n+=t}r?.flush&&await o.sync()}finally{await o.close()}}(v,x,{flush:!0,singleLink:!0===S?.allowed?S.singleLink:void 0}),this.agentFileViews?.recordWrite(r,x),void 0!==R&&await Fi(r,{buffer:x,encoding:R});try{t=await(0,vo.open)((0,s.dirname)(v),G$.default.O_RDONLY),await t.sync()}catch{}finally{await(t?.close())}}));let T,A=!1;const M=async()=>{try{await I()}catch(e){throw T=e,A=!0,e}};try{void 0===this.writeFileMutationGuard?await I():await this.writeFileMutationGuard.runExclusive(v,M)}catch(e){if(void 0!==this.writeFileMutationGuard&&(!A||e!==T))return new ZR.v3({result:{case:"error",value:new ZR.QM({path:r,error:e instanceof Error?e.message:String(e)})}});if(e instanceof Y$)return new ZR.v3({result:{case:"permissionDenied",value:new ZR.U7({path:r,directory:"",operation:"create_file",error:e.message})}});const t=gc(e);return"EACCES"===t||"EPERM"===t?new ZR.v3({result:{case:"permissionDenied",value:new ZR.U7({path:r,directory:"",operation:"create_file",error:"Permission denied"})}}):"ENOSPC"===gc(e)?new ZR.v3({result:{case:"noSpace",value:new ZR.bM({path:r})}}):"EDQUOT"===t?new ZR.v3({result:{case:"error",value:new ZR.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 ZR.v3({result:{case:"error",value:new ZR.QM({path:r,error:wc(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},...E>0?{createdDirectories:E}:{}};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){iM.warn(c,"onWriteForAiTracking failed (write succeeded)",{path:r,error:e instanceof Error?e.message:String(e)})}}const D=x.byteLength;let O;if(void 0!==u||w||h||this.recordEncodingChecks(c,r,p,f,l),t.returnFileContentAfterWrite)try{O=await cM(c,"readText after write",3e3,(()=>Di(r,t.encodingHint)))}catch{}return new ZR.v3({result:{case:"success",value:new ZR.j6({path:r,linesCreated:P,fileSize:D,...void 0!==O&&{fileContentAfterWrite:O}})}})}catch(e){a.error=e,a.hasError=!0}finally{sM(a)}}recordEncodingChecks(e,t,r,n,o){try{const i={path:t,encoding:n,pages:(s=ou.pages(),"failed"===s?"none":s)};for(const t of function(e,t,r){return[el(e,t,r),tl(e,t,r)]}(r,n,o))aM.increment(e,1,al(t,i))}catch(t){for(const t of Vc)aM.increment(e,1,{detector:t,outcome:"error",file:"unclassified"});iM.warn(e,"encoding check failed (write succeeded)",{error:t instanceof Error?t.message:String(t)})}var s}}function pM(e,t){return new ZR.v3({result:{case:"error",value:new ZR.QM({path:e,error:t})}})}class fM extends Error{constructor(e){super("stale write refusal"),this.result=e,this.name="StaleWriteRefusal"}}function mM(e){if("error"!==e.result.case)return!1;const{error:t,path:r}=e.result.value;return t===oT(r)||t===sT(r)}const gM=(0,l.h)("local-exec:provider"),wM=new Set,yM=new id.AsyncLocalStorage;class vM extends K{getMcpExecutionPolicyDeps(){return{permissionsService:this.permissionsService,pendingDecisionProvider:this.pendingDecisionStore}}static dropOwnedRequestContextCaches(){for(const e of wM)e.ownedRequestContextExecutor?.invalidateGlobalCache()}static rebuildRequestContextCachesFor(e){for(const t of wM)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,So.readFileSync)(t,"utf-8"),n=JSON.parse(r),o=(0,To.$6)(n);return(0,To.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,To.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 Nu(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 ju(c,this.askpassConfig)),this.shellManager&&(c=new Lu(c,this.shellManager));const l=e.overrideShellExecutor??(!0===e.suppressDefaultShellExecutor?void 0:new C$(this.permissionsService,c,this.ignoreService,this.pendingDecisionStore));void 0!==l&&this.register(rT,tg(l)),this.register(nT,tg(new tT(this.permissionsService,this.ignoreService,a??t??this.projectDir)));const u=new D$,d=new O$,h=e.overrideWriteExecutor??new hM(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(iT,function(e){const t=(r={execute:(t,r,n)=>e.execute(t,r,n).then((e=>{if(mM(e))throw new fM(e);return e}))},tg(r));var r;return{async execute(e,r,n){try{return await t.execute(e,r,n)}catch(e){if(e instanceof fM)return e.result;throw e}}}}(h));const p=e.overrideDeleteExecutor??new lw(this.pendingDecisionStore,this.fileChangeTracker,this.permissionsService,a,e.onDeleteForAiTracking,d);this.register(aT,tg(p)),this.register(cT,tg(new mw({encodingSlices:e.encodingSlices}))),this.register(lT,new UA);const f=this.mcpStateAccessor??new y$(this.mcpLease),m=e.overrideGrepExecutor??new T_(this.ignoreService,this.grepProvider,this.workspacePaths,{mcpStateAccessor:f,permissionsService:this.permissionsService,useStreamingGrep:e.useStreamingGrep,encodingSlices:e.encodingSlices});this.register(uT,tg(m));const g=e.overrideReadExecutor??new L$(new n_(this.permissionsService,a,{mcpStateAccessor:f,useStreamingRead:e.useStreamingRead,pendingDecisionProvider:this.pendingDecisionStore,encodingSlices:e.encodingSlices}),u,this.permissionsService,a,d),w=new fT(g);this.register(mT,w),e.registerRedactedReadExecutor&&this.register(gT,w);const y=e.overrideLsExecutor??new N_(this.permissionsService,this.ignoreService,a);this.register(wT,tg(y)),this.register(yT,tg(new oA(a,this.diagnosticsProvider))),e.getCanvasDiagnostics&&this.register(vT,tg(new XT(e.getCanvasDiagnostics,e.beginCanvasSave))),this.register(Xn,tg(new OT(ql(new qI(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(mT))))),this.register(Qn,tg(new zI(this.mcpLease,e.ensureMcpServersLoaded))),this.register(Yn,tg(ql(new GI(this.mcpLease,a||this.projectDir,this.permissionsService,this.workspacePaths,this.pendingDecisionStore,e.ensureMcpServersLoaded,h),e.encodingSlices,"exec_mcp",(e=>"success"===e.result.case)))),this.register(eo,tg(new b$(f,e.ensureMcpServersLoaded,{filterToRequestedServers:this.mcpMetaToolEnabled&&this.mcpMetaToolSlimDescriptors})));const v=this.sharedRequestContextExecutor??this.createOwnedRequestContextExecutor(f,t,e),b=tg({execute:(e,t,r)=>{const n=yM.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 yM.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=f$(c,{internalBrowserProvidersOnly:this.mcpMetaToolEnabled&&this.mcpMetaToolSlimDescriptors,inputSchemaJson:this.mcpInputSchemaJson});if(a.tools=l.tools,a.mcpInstructions=l.mcpInstructions,a.mcpMetaToolOptions=this.mcpMetaToolEnabled?m$(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=[],gM.warn(t,"Failed to get mounted agent stores; continuing without prompt inventory")}return i}}),this.backgroundShellExecutor=new sd(this.permissionsService,c,this.ignoreService,this.projectDir,this.backgroundShellFactory,this.backgroundWorkRegistry,this.wakeupOwnerConversationId,e.backgroundShellManager),this.shellRedeliveryCaches=e.shellRedeliveryCaches??{backgroundShell:eg(),shellStream:eg(),writeStdin:eg()},this.register(FT,tg(this.backgroundShellExecutor,void 0,this.shellRedeliveryCaches.backgroundShell)),this.shellStreamExecutor=new $$(this.permissionsService,c,this.ignoreService,this.backgroundShellExecutor.getManager()),this.register(ee,function(e,t,r=eg(t)){return{async*execute(t,n,o){if(!o?.execId)return void(yield*e.execute(t,n,o));const s=Ym(o.execId,n),i=r.get(s);if(i)return void(yield*i.fork());const a=e.execute(t,n,o),c=new Qm(a);r.set(s,c),yield*c.fork()}}}(this.shellStreamExecutor,void 0,this.shellRedeliveryCaches.shellStream)),void 0!==e.agentStoreConflictDrainer&&this.register(LT,new VT(e.agentStoreConflictDrainer)),this.register(jT,new x$(this.permissionsService)),this.register(UT,new WA(this.permissionsService)),this.register(BT,new z$(this.permissionsService));const S=new P$(this.shellStreamExecutor);this.register(WT,tg(S));const k=!1===e.enableWriteBackgroundShellStdin?new KT((async()=>{throw new Error(e.writeBackgroundShellStdinDisabledReason??"write_shell_stdin is disabled for this session")})):new KT(((e,t)=>this.backgroundShellExecutor.writeStdin(e,t)));if(this.register(NT,tg(k,void 0,this.shellRedeliveryCaches.writeStdin)),e.computerUseExecutor&&(this.computerUseExecutor=e.computerUseExecutor,this.register(HT,tg(this.computerUseExecutor))),this.enableRecordScreen){if(!this.recordScreenArtifactsDir||!this.recordScreenDisplay)throw new Error("recordScreenArtifactsDir and recordScreenDisplay are required when enableRecordScreen is true");this.recordScreenExecutor=new ZA({artifactsDir:this.recordScreenArtifactsDir,display:this.recordScreenDisplay,disablePolishedRendering:this.disableRecordScreenRendering,polishedRenderer:e.polishedRecordingRenderer}),this.register(qT,tg(this.recordScreenExecutor))}}createOwnedRequestContextExecutor(e,t,r){const n=new S$(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,Ko.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,mcpFieldsFromCaller:!0===r.requestContextMcpFieldsFromOverlay,deferWarmup:!0===r.deferRequestContextWarmup});return!0===r.deferRequestContextWarmup&&(this.requestContextExecutorAwaitingWarmup=n),this.rebuildRequestContextOnRulesChange&&(this.ownedRequestContextExecutor=n,wM.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&&(wM.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 bM(e){return e.replace(/\\/g,"/")}function SM(e,t){for(const r of t){const t=bM(r);if(e===t||e.startsWith(`${t}/`))return!0}return!1}var kM;function _M(e,t,r){if(function(e){return Boolean(e.plugin?.trim()||e.pluginId?.trim()||e.marketplaceId?.trim())}(e))return kM.Plugin;const n=bM(e.fullPath);return SM(n,r.builtinDirs)?kM.Builtin:sm(e.fullPath,t).inAgentStore?kM.UserStore:SM(n,r.userDirs)?kM.UserHome:(SM(n,r.workspaceDirs),kM.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"}(kM||(kM={}));var CM=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 EM=(0,Us.debuglog)("merged-agent-skills"),xM=(0,l.h)("merged-agent-skills");class PM{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=>(EM("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 xM.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=am(c,l??nm);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(RM));var t})),void 0!==l?function(e,t){if(e.length<=1)return e;const r=function(e){const t=[jf(e.userHomeDirectory).dirPath],r=Gf(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 zf(t,!0))n.push(e.dirPath)}return{builtinDirs:t,userDirs:r,workspaceDirs:n}}(t),n=e.map(((e,n)=>({skill:e,index:n,tier:_M(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{CM(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()}),PM.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()}}PM.CHANGE_COALESCE_MS=1500;const RM=`/${Df.configDir}/${Df.subdir}/`;function IM(e,t){if((e.disabledEnvironments??[]).includes(t))return!1;const r=e.environments??[];return 0===r.length||r.includes(t)}const TM=(0,l.h)("skill-sync-manifest"),AM=".sync-manifest.json",$M=new Set(["EPERM","EBUSY"]),MM=[20,50,100],DM=new Map;async function OM(e,t){try{const r=await(0,vo.readFile)((0,s.join)(e,AM),"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:(TM.warn(t,"Manifest failed schema validation, resetting",{skillDir:e}),{version:1,skills:{}})}catch(r){return r instanceof Error&&"ENOENT"===gc(r)||TM.debug(t,"Failed to read sync manifest, resetting",{skillDir:e,error:String(r)}),{version:1,skills:{}}}}function FM(e,t,r){e.skills[t]={lastSyncedAt:r}}function NM(e,t){delete e.skills[t]}var LM=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 jM=(0,l.h)("builtin-skills-sync");function UM(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function BM(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 WM(e){const t=Wd(e.content),r=UM(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={...UM(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 HM(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 qM(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,vo.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,vo.mkdtemp)((0,s.join)(e,`.${t.id}-staging-`)),o=`${n}-backup`;let i=!1;try{await(0,vo.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,vo.mkdir)((0,s.dirname)(t),{recursive:!0}),await(0,vo.writeFile)(t,r,"utf-8")}try{await(0,vo.rename)(r,o),i=!0}catch(e){if(!(e instanceof Error)||"ENOENT"!==gc(e))throw e}try{await(0,vo.rename)(n,r)}catch(e){throw i&&(await(0,vo.rename)(o,r),i=!1),e}i&&(await(0,vo.rm)(o,{recursive:!0,force:!0}),i=!1)}finally{await(0,vo.rm)(n,{recursive:!0,force:!0})}}(t,r),!0}try{if(await(0,vo.readFile)(o,"utf-8")===i)return!1}catch(t){t instanceof Error&&"ENOENT"===gc(t)||jM.warn(e,"Unexpected error reading skill file",{skillId:r.id,error:String(t)})}return await(0,vo.mkdir)(n,{recursive:!0}),await(0,vo.writeFile)(o,i,"utf-8"),!0}async function qM(e,t=""){const r=t?(0,s.join)(e,...t.split("/")):e;let n;try{n=await(0,vo.readdir)(r,{withFileTypes:!0})}catch(e){if(e instanceof Error&&"ENOENT"===gc(e))return[];throw e}const o=[];for(const r of n){const n=t?`${t}/${r.name}`:r.name;r.isDirectory()?o.push(...await qM(e,n)):r.isFile()&&r.name.endsWith(".md")&&"SKILL.md"!==n&&o.push(n)}return o}async function zM(e,t){try{return(await(0,vo.readdir)(t,{withFileTypes:!0})).filter((e=>e.isDirectory()&&!e.name.startsWith("."))).map((e=>e.name))}catch(r){return r instanceof Error&&"ENOENT"===gc(r)||jM.warn(e,"Failed to list skills directory, skipping cleanup",{skillDir:t,error:String(r)}),[]}}async function GM(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??jf(c).dirPath;await(0,vo.mkdir)(l,{recursive:!0});const[u,d]=await Promise.all([OM(l,i),zM(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([VM((0,s.join)(r,"SKILL.md")),"canvas"===e?VM((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}})));jM.info(e,"managed_skills.startup_inventory",{skills_on_disk:o,manifest_present:Object.keys(n.skills).length>0})}catch(t){jM.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):jM.warn(i,"Skipping managed skill with unsafe id",{skillId:e.id});const f=void 0===t.canvasKit?void 0:Bf(c,t.canvasKit).dirPath,m=void 0!==f&&await VM((0,s.join)(f,Uf)),g=new Set([...p.keys(),...d,...m?[Uf]:[]]),w=e=>void 0!==f&&e===Uf?f:l,y=e=>void 0!==f&&e===Uf?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&&IM(t,"local"),d=void 0!==t&&!c,h=void 0!==r||y(e),f=w(e);if(t&&!1!==t.enabled&&c)BM(t),f!==l&&await(0,vo.mkdir)(f,{recursive:!0}),await HM(i,f,{id:e,fileContent:WM(t),resources:t.resources??{}})?v++:b++,FM(u,e,a);else if(!1===t?.enabled||d||o){const n=!1===t?.enabled?"enabled_false":d?"environment_ineligible":"grace_expired";await(0,vo.rm)((0,s.join)(f,e),{recursive:!0,force:!0}),NM(u,e),h&&(S.push(e),jM.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||FM(u,e,a)}catch(t){jM.warn(i,"Failed to apply skill, will retry next sync",{skillId:e,error:String(t)})}try{await function(e,t){const r=(DM.get(e)??Promise.resolve()).then((()=>async function(e,t){const r=(0,s.join)(e,`${AM}.${process.pid}.${(0,mo.randomBytes)(6).toString("hex")}.tmp`);await(0,vo.mkdir)(e,{recursive:!0});try{await(0,vo.writeFile)(r,JSON.stringify(t,null,2),"utf-8"),await async function(e,t){for(let r=0;;r++)try{return void await(0,vo.rename)(e,t)}catch(e){const t=gc(e),n=MM[r];if(void 0===n||void 0===t||!$M.has(t))throw e;await(0,Dr.cb)(n)}}(r,(0,s.join)(e,AM))}catch(e){throw await(0,vo.rm)(r,{force:!0}).catch((()=>{})),e}}(e,t))),n=r.catch((()=>{}));return DM.set(e,n),n.then((()=>{DM.get(e)===n&&DM.delete(e)})),r}(l,u)}catch(e){!function(e){if(e instanceof Error&&"ENOENT"===gc(e))return!0;const t=String(e);return t.includes("ENOENT")||t.includes("no such file or directory")}(e)?jM.warn(i,"Failed to persist sync manifest",{skillDir:l,error:String(e)}):jM.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{LM(r)}var n}async function VM(e){try{return await(0,vo.stat)(e),!0}catch(e){const t=gc(e);if("ENOENT"===t||"ENOTDIR"===t)return!1;throw e}}const KM=(0,l.h)("managed-skills-sync");function JM(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 ZM(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 XM{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(...JM(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=ZM(n.url);r.has(e)||(r.add(e),t.push(n))}return t}(t)}}var QM=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 YM(e,t){return void 0===e?[]:(Array.isArray(e)?e:[e]).map((e=>({...e,userHomeDir:t})))}class eD{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??qh,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: ${wc(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: ${wc(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(Ef));return this.plugins.filter((e=>"extension"!==e.identifier.source&&void 0===e.loadError&&e.installPath.length>0&&!t.has(Ef(e))))}async reloadPlugin(e){this.loadPromise&&await this.loadPromise;const t=YM(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 _f({...l,log:l.log??this.pluginLogger,pluginFilter:r})}catch(t){this.pluginLogger.log("error",`reloadPlugin: source load failed for ${e.name}: ${wc(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,vo.realpath)(r);if(!(await(0,vo.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,vo.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 vf(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}: ${wc(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=YM(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??qh,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(kf(e,0,{userHomeDir:t.userHomeDir,onError:t.onError,log:r})),c&&a.length>0&&(d=Promise.allSettled(a.map((e=>_f({...e,userHomeDir:e.userHomeDir??t.userHomeDir,log:e.log??r}))))),i&&l.push(async function(e={}){const t=e.log??qh,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,vo.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,vo.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,vo.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,vo.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 vf(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,vo.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=Cf(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=>Cf(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: ${wc(e)}`),{plugins:[],failures:[],sourceUnavailable:!0}}}catch(t){e.error=t,e.hasError=!0}finally{QM(e)}}}var tD=r("../proto/dist/generated/aiserver/v1/dashboard_pb.js");const rD=BigInt(0),nD=BigInt(8),oD=BigInt(16),sD=BigInt(65535);function iD(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 aD(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 cD(e){const t=e.split(".");if(4!==t.length)return;let r=rD;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<<nD|BigInt(t)}return{version:4,value:r}}function lD(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=cD(n);if(!o)return;t.push(Number(o.value>>oD&sD)),t.push(Number(o.value&sD))}else{if(!/^[0-9a-f]{1,4}$/i.test(n))return;t.push(Number.parseInt(n,16))}}return t}function uD(e){return cD(e)??function(e){const t=aD(e);if(0===t.length||t.includes(":::"))return;const r=t.indexOf("::");if(-1===r){const e=lD(t);if(!e||8!==e.length)return;return{version:6,value:e.reduce(((e,t)=>e<<oD|BigInt(t)),rD)}}if(-1!==t.indexOf("::",r+1))return;const n=lD(t.slice(0,r)),o=lD(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<<oD|BigInt(t)),rD)}}(e)}function dD(e,t){const r=aD(e),n=aD(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=uD(t.slice(0,r)),o=uD(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 hD(e,t){if(!e.includes("*"))return e===t;const r=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${r}$`).test(t)}function pD(e,t){if(hD(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=aD(r.hostname);return!!dD(aD(n.hostname),o)&&hD(`${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=aD(t.slice(0,r));if(e.length>0)return`${e}/${t.slice(r+1).trim()}`}const n=iD(t);if(n)return aD(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=aD(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=iD(e);if(t)return aD(t.hostname);const r=aD(e);return r.length>0?r:void 0}(t);return!(!r||!n)&&dD(n,r)}async function fD(e){try{return await e.current()}catch{return}}function mD(e){try{const t=new URL(e);return`${t.protocol}//${t.host}${t.pathname}`}catch{return}}function gD({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||mv(t.url,n)?{blocked:!1}:{blocked:!0,reason:"teamNetworkAllowlist",message:"Not on the team network allowlist"}}function wD(e){const t=e?.trim();return t&&t.length>0?t:void 0}function yD(e,t,r){if(!0===r?.useCorePolicy)return!function(e,t){if(void 0===t)return!0;if(!0===t.disableAll)return!1;if(U_(e))return!0;if(q_(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=B_(t.command),n=W_(t.serverUrl);if(void 0===r&&void 0===n)return!1;const o=void 0===r||void 0!==e.command&&(0,eb.mD)(r,e.command),s=void 0===n||void 0!==e.url&&(0,eb.vc)(n,e.url);return o&&s}))}(e,t)}(e,r)||!0===t.allowUserOverrideMcpServers&&!H_(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=wD(e.command),n=wD(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&&pD(n,t.url);return o&&s}(t,e)))}class vD{constructor(e,t={}){this.dashboardClient=e,this.options=t}getTeamAdminSettings(){return this.dashboardClient.getTeamAdminSettingsOrEmptyIfNotInTeam(new tD.Byz(!0===this.options.supportsHostMcpBridgeExemption?{supportsHostMcpBridgeExemption:!0}:{}))}getTeamRepos(){return this.dashboardClient.getTeamReposOrEmptyIfNotInTeam(new tD.aYW({}))}}function bD(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 SD{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 kD{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 SD((()=>this.fetchSettings())),this.droppedReplies=new WeakSet,this.hostMcpBridgeClients=new WeakSet,this.mcpServerByClient=new WeakMap,this.teamRepos=new SD((()=>this.teamAdminSettingsProvider.getTeamRepos())),this.defaultAllowlist=new SD((()=>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 refreshTeamAdminSettings(){try{await this.settings.refresh()}catch{}}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 fD(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 fD(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 fD(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 fD(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(q_(e,r?.offMcpServerRules))return{blocked:!0,reason:"teamPolicy",message:"Blocked by team policy"};if(n){if(yD(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,eb.ME)(e.url,n);if(!o.allowed)return{blocked:!0,reason:"teamNetworkAllowlist",message:o.message};const s=gD({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?gD({failOpenWhenEmpty:!0,server:t,settings:r}):{blocked:!1}}({isMcpAccessNetworkAllowlistEnabled:await this.isMcpAccessNetworkAllowlistEnabled(),server:e,settings:t});if(r.blocked)return r}return void 0!==t||this.lastFetchSucceeded?{blocked:!1}:{blocked:!1,settingsUnavailable:!0}}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,eb._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=mD(t.url);return void 0!==n&&r.some((e=>mD(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,eb.rM)(e,t)));if(void 0!==r)return nb({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?"":tb(e.name);if(0===t.length)return[];const r=nb({mode:e.toolAllowlistMode,tools:e.toolAllowlist});return[{name:t,policy:r,flattened:sb(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===tD.h0i.WORKSPACE?"workspace":"system");var n;return{sandboxingDisabled:t?.sandboxing===tD.faf.DISABLED,networkingDisabled:t?.sandboxNetworking===tD._mX.ALWAYS_DISABLED,gitDisabled:t?.sandboxGit===tD.i24.ALWAYS_DISABLED,readBoundary:r,readAllowlistPaths:bD(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 _D=new Hw,CD={async resolveWorkspaceState(e){const t=e.workingDirectory??e.projectRoot??e.workspaceRoots?.[0],r=e.projectRoot??(void 0!==t?await Ka((0,y.q6)(),_D,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?yo(r):void 0),workspaceRoots:n,createdAt:new Date}}},ED=(0,l.h)("ControlledConversationActionManager");class xD{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){ED.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 PD=r("../cursor-sdk-local-runtime/dist/utils/logger.js"),RD=r("../agent-kv/dist/agent-store.js");const ID="x-blob-encryption-key";function TD(e,t){const r={...t};return void 0!==r[ID]||(0,RD.TU)(e)&&(r[ID]=e),r}const AD=new Map;function $D(e){if("userMessageAction"===e.action.case)return e.action.value.userMessage?.text}function MD(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 DD(e){return new i.QFf({action:{case:"userMessageAction",value:new i.Vtf({userMessage:new i.RGk({text:e})})}})}function OD(e){return e instanceof DOMException&&"AbortError"===e.name||e instanceof Error&&("AbortError"===e.name||"The operation was aborted"===e.message)}function FD(e){e?.catch((e=>{PD.Jz.warn("[agent-session-runner] fire-and-forget hook failed:",e)}))}const ND=new Set(["mcp.slack.com","setup.shopify.com"]);async function LD(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?Ev(e):void 0}({serverUrl:i,restMcpHost:a}));var i,a;if(!ND.has(o)&&!s)return t;let c=await r.resolve(e);if(!c&&s){const t=(await xE(e,n))?.clientId;void 0!==t&&(c={CLIENT_ID:t})}return c?t?void 0===CE(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 jD{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 LD(e.serverConfig,this.resolver);return t===e.serverConfig?e:{...e,serverConfig:t}})))}clearCache(){this.inner.clearCache?.()}}class UD{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 BD{constructor(e,t){this.storage=e,this.prefix=t}async isServerApproved(e,t,r){return this.storage.isServerApproved(this.prefix+e,t,r)}}class WD{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 K_(t,n.configPath??"another config")}return await o(e,r)}}class HD{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 SR(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 qD{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 LR(e,"enterprise"===r||"env"===r?HC:void 0)}))),y=[];for(const{prefix:e,scope:o,fileSource:s}of w){const l=i?"":e,d=new UD(t,l),p=new BD(n,l),f=w.flatMap((e=>{return t=e.scope,r=o,qC.indexOf(t)<qC.indexOf(r)&&("enterprise"===t||"env"===r)?[e.fileSource]:[];var t,r})),m=[new lC,...zC(o)?[new Z_(p)]:[],new WR(r),...c?[new J_(c)]:[],...f.length>0?[new WD(f)]:[]],g=new jR(u?new jD(s,u):s,d,m,{authRedirectUrlGenerator:a,isLinkSharedPaymentTokenLogRedactionEnabled:h});y.push({prefix:l,loader:g})}this.loader=new HD(y)}static init(e,t,r,n=!1,o,i={}){const a=new KR(s.join(r,"mcp-auth.json"));(async function(e){await(0,vo.rm)(s.join(e,"mcp-cache.json"),{force:!0})})(r).catch((()=>{}));const c=n?{isServerApproved:()=>Promise.resolve(!0)}:new X_(s.join(r,"mcp-approvals.json"),t);return new qD(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 zD="cursor-plugins/local";function GD(e){var t;if(e)for(const r of e)if("object"==typeof(t=r)&&null!==t&&t.kind===zD)return r}class VD extends bR{constructor(e){super(e),this.runtimeManager=e,this.disposed=!1}async dispose(){this.disposed||(this.disposed=!0,await this.runtimeManager.closeAllClients())}}class KD{constructor(e){this.storagePath=e}async isServerDisabled(e){try{const t=await(0,vo.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,vo.mkdir)((0,s.dirname)(this.storagePath),{recursive:!0}),await(0,vo.writeFile)(this.storagePath,JSON.stringify(e,null,2))}}class JD{constructor(e,t){this.pluginMcpService=e,this.importThirdPartyPlugins=t}async getDefinitions(){let e;try{e=await this.pluginMcpService.getPluginMcpServers()}catch(e){return PD.Jz.warn("[cursor-config-mcp] Failed to enumerate plugin MCP servers:",e),[]}const t=[];for(const r of e){if(!this.importThirdPartyPlugins&&eO(r))continue;const e=qR(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}}):PD.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 ZD{constructor(e){this.servers=e}async getDefinitions(){return Object.entries(this.servers).map((([e,t])=>({identifier:e,authStorageKey:`inline:${e}`,serverConfig:YD(e,t),source:"inline",metadata:{source:"cursor-sdk"}})))}}function XD(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 vR;const d=new KD((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 qD.init(t,r,n,i,a,{isLinkSharedPaymentTokenLogRedactionEnabled:u});if(!c&&!l)return;const d=new KR((0,s.join)(n,"mcp-auth.json")),h=i?{isServerApproved:()=>Promise.resolve(!0)}:new X_((0,s.join)(n,"mcp-approvals.json"),r),p=[new lC,new Z_(h),new WR(t),new J_(a)],f=[];return c&&f.push({prefix:"",loader:new HR((0,s.join)(r,".cursor","mcp.json"),d,p,{isLinkSharedPaymentTokenLogRedactionEnabled:u})}),l&&f.push({prefix:"",loader:new HR((0,s.join)((0,o.homedir)(),".cursor","mcp.json"),d,p,{isLinkSharedPaymentTokenLogRedactionEnabled:u})}),QD(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 KR((0,s.join)(u,"mcp-auth.json")),r=[new lC,new WR(t)];p.push({prefix:"",loader:new jR(new ZD(f),e,r,i)})}const m=GD(a.services.pluginBootstrapOutputs);if(m&&(e.includePluginMcp??1)){const e=new X_((0,s.join)(u,"mcp-approvals.json"),l),o=new KR((0,s.join)(u,"mcp-auth.json")),a=[new lC];r||a.push(new Z_(e)),a.push(new WR(t),new J_(d));const c=new XM(m.pluginsService),h=new jR(new JD(c,n),o,a,i);p.push({prefix:"",loader:h})}if(h&&p.push({prefix:"",loader:h}),0===p.length)return new vR;const g=QD(p),w=await g.load(e.initializationCtx??(0,y.q6)(),e.cache);return new VD(w)}}}function QD(e){return 1===e.length?e[0].loader:new HD(e)}function YD(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 eO(e){return"claude-plugin"===e.pluginSource}const tO=["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass"];function rO(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 nO(e){return e.slice(Math.max(e.lastIndexOf("\\"),e.lastIndexOf("/"))+1)}const oO=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 sO(e){const t=rO(e),r=nO(t);return!oO.has(r.toLowerCase())&&(!!/\.(exe|bat|cmd|com)$/i.test(r)||t===r&&/^[A-Za-z0-9_]+$/.test(r))}function iO(e){if(sO(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=rO(e),r=nO(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=rO(e);if(0===t.length||sO(e))return!1;const r=nO(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 aO=[".ps1",".exe",".bat",".cmd"];function cO(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 lO(e){return e?.enableClaudeNestedHookSpecificOutputCompatibility??!1}function uO(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function dO(e){if(!uO(e))return;const t=e.hookSpecificOutput;return uO(t)?t:void 0}function hO(e,t){if(!e)return!1;const r=e.hookEventName;return void 0===r||""===r||r===t}function pO(e,t,r){if(!uO(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(!lO(t))return n;const o=dO(e),s=hO(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 fO=e=>{const t=[];return gd(e)?yd(!0):(t.push("Expected an object"),yd(!1,t))},mO=e=>{const t=[],r=fO(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"),yd(0===t.length,t)};function gO(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 wO=new Set([fd.sessionStart,fd.beforeSubmitPrompt,fd.preToolUse,fd.postToolUse,fd.postToolUseFailure]);function yO(e){return"prompt"===e.type}function vO(e){return"command"===e.type||void 0===e.type}const bO={[fd.beforeShellExecution]:mO,[fd.beforeMCPExecution]:mO,[fd.afterShellExecution]:e=>{const t=fO(e);return t.isValid,t},[fd.afterMCPExecution]:e=>{const t=fO(e);return t.isValid,t},[fd.beforeReadFile]:e=>{const t=[],r=fO(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"),yd(0===t.length,t)},[fd.afterFileEdit]:e=>{const t=fO(e);return t.isValid,t},[fd.beforeTabFileRead]:e=>{const t=[],r=fO(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"),yd(0===t.length,t)},[fd.afterTabFileEdit]:e=>fO(e),[fd.beforeSubmitPrompt]:e=>{const t=fO(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||md(e.additional_context)||r.push("additional_context must be a string if provided"),yd(0===r.length,r)},[fd.stop]:e=>{const t=fO(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"),yd(0===r.length,r)},[fd.afterAgentResponse]:e=>{const t=fO(e);return t.isValid,t},[fd.afterAgentThought]:e=>{const t=fO(e);return t.isValid,t},[fd.sessionStart]:e=>{const t=fO(e);if(!t.isValid)return t;const r=[];if(void 0!==e.env)if(gd(e.env))for(const[t,n]of Object.entries(e.env))md(t)||r.push(`env key "${t}" must be a string`),md(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||md(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||md(e.user_message)||r.push("user_message must be a string if provided"),yd(0===r.length,r)},[fd.sessionEnd]:e=>{const t=fO(e);return t.isValid?yd(!0,[]):t},[fd.preCompact]:e=>{const t=fO(e);if(!t.isValid)return t;if(null==e||0===Object.keys(e).length)return yd(!0,[]);const r=[];if(!wd(e))return r.push("PreCompact response must be an object"),yd(!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"),yd(0===r.length,r)},[fd.subagentStart]:e=>{const t=fO(e);if(!t.isValid)return t;if(!wd(e))return yd(!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||md(n.user_message)||r.push("user_message must be a string if provided"),yd(0===r.length,r)},[fd.subagentStop]:e=>{const t=fO(e);if(!t.isValid)return t;const r=[];return wd(e)&&void 0!==e.followup_message&&"string"!=typeof e.followup_message&&r.push("followup_message must be a string if provided"),yd(0===r.length,r)},[fd.preToolUse]:e=>{const t=[],r=fO(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"),vd(e.additional_context,"additional_context",t),yd(0===t.length,t)},[fd.postToolUse]:e=>{const t=[],r=fO(e);return r.isValid?(vd(e.additional_context,"additional_context",t),yd(0===t.length,t)):r},[fd.postToolUseFailure]:e=>{const t=fO(e);if(!t.isValid)return t;const r=[];return vd(e.additional_context,"additional_context",r),yd(0===r.length,r)},[fd.workspaceOpen]:e=>{const t=fO(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")),yd(0===r.length,r)}},SO=(e,t,r)=>{const n=function(e,t,r){let n;return n=e===fd.preToolUse?function(e,t){if(!uO(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(!lO(t))return r;const n=dO(e);if(!hO(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),uO(n.updatedInput)&&(o.updated_input=n.updatedInput,s=!0),s?o:r}(t,r):e===fd.stop?pO(t,r,"Stop"):e===fd.subagentStop?pO(t,r,"SubagentStop"):t,function(e,t,r,n){if(!wO.has(e)||!uO(r)||void 0!==r.additional_context)return r;const o=uO(t)?function(e){return"string"==typeof e.additionalContext?e.additionalContext:void 0}(t)??function(e,t,r){if(!lO(r))return;const n=Cd[e];if(void 0===n)return;const o=dO(t);return hO(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,bO[e])(n);return o.isValid?{success:!0,data:n}:{success:!1,errors:o.errors}},kO=[fd.beforeShellExecution,fd.beforeMCPExecution,fd.beforeReadFile,fd.beforeTabFileRead,fd.subagentStart,fd.preToolUse],_O=[fd.workspaceOpen];function CO(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 EO(e,t){return{..."object"==typeof e&&null!==e?e:{},...t}}function xO(e){return kO.includes(e)}function PO({step:e,command:t,failClosed:r,kind:n}){const o=xO(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:IO(e,s),cause:r?"script_fail_closed":"permission_hook_invalid_output",reason:s,shouldNotifyUser:o&&!r}}function RO(e,t){return t}function IO(e,t){return xO(e)?RO(0,{permission:"deny",user_message:t}):e===fd.beforeSubmitPrompt||e===fd.sessionStart?RO(0,{continue:!1,user_message:t}):e===fd.stop?RO(0,{}):void 0}function TO(e){try{return{value:JSON.parse(e)}}catch{return}}function AO(e){if("object"!=typeof e||null===e)return!1;const t=e.event;return"backgrounded"===t?.case}function $O(e){if("object"!=typeof e||null===e)return;const t=e.path;return"string"==typeof t&&t.length>0?t:void 0}class MO{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>MO.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===iT.symbol||e===aT.symbol?{kind:"path"}:e===rT.symbol||e===ee.symbol||e===FT.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=$O(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&&AO(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===iT.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=$O(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 DO(e){return new RegExp(`<${e}(?:\\s[^>]*)?>[\\s\\S]*?</${e}>`,"gi")}MO.CARRIERS_BY_EXEC_ID_MAX=32,Error,Gl.execFileSync,new Map,So.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 OO=["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(DO);function FO(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(NO,"\n\n"):r).trim()}(e,OO)}["system_reminder","system-reminder"].map(DO);const NO=/\n{3,}/g;function LO(e){const t=(0,go.sh)(e.conversationId);if("subagent"===e.kind&&e.parentConversationId){const r=(0,go.sh)(e.parentConversationId);return`${go.O2}/${r}/subagents/${t}.${e.ext}`}return`${go.O2}/${t}/${t}.${e.ext}`}function jO(e){const t=(0,go.sh)(e.conversationId);return`${go.O2}/${t}.${e.ext}`}function UO(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(LO({conversationId:e.conversationId,ext:n,kind:e.kind,parentConversationId:e.parentConversationId})),"subagent"===e.kind&&e.parentConversationId&&o(LO({conversationId:e.conversationId,ext:n,kind:"primary"})),r&&o(jO({conversationId:e.conversationId,ext:n}));return n}var BO;!function(e){e.INTERNAL="INTERNAL",e.EXTERNAL="EXTERNAL",e.NO_PREAMBLE="NO_PREAMBLE"}(BO||(BO={}));var WO=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},HO=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 qO(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 zO(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 GO(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 VO=new TextEncoder,KO=new TextDecoder,JO=new class{serialize(e){const t=JSON.stringify(e,zO);return VO.encode(t)}deserialize(e){const t=KO.decode(e);return t.includes('"__type":"Uint8Array"')?JSON.parse(t,GO):JSON.parse(t)}};function ZO(e){const t=e.providerOptions;return!0===t?.cursor?.isSummary}function XO(e){return"system"!==e.role&&!ZO(e)}function QO(e,t){return"user"===e.role&&"user"===t.role}async function YO(e,t,r){const n=await t.getBlob(e,r);return n?i.Anz.fromBinary(n).summarizedMessages:[]}async function eF(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=JO.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 tF(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 eF(e,t,o,n);r&&n.messages.push(r)}return n}async function rF(e,t,r,n,o){const s=[];let i=0;const a=()=>{const o=eF(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 nF(e,t){switch(e.type){case"text":return t?oF(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 oF(e){return FO(e)}const sF=/<think>[\s\S]*?<\/think>/gi,iF=/<thinking>[\s\S]*?<\/thinking>/gi,aF=/\n{3,}/g;function cF(e){let t=e;return t.includes("<")&&(t=t.replace(sF,"").replace(iF,"")),(t.includes("\n\n\n")?t.replace(aF,"\n\n"):t).trim()}function lF(e,t,r){if(void 0===e)return"";if("string"==typeof e){const n=t?oF(e):e;return r?cF(n):n}return e.map((e=>{if(r&&"text"===e.type){const r=cF(t?oF(e.text):e.text);return nF({...e,text:r},!1)}return nF(e,t)})).filter(Boolean).join("\n")}function uF(e,t){const r={role:e.role},n=e.content;if("string"==typeof n){const o=t?oF(n):n,s="assistant"===e.role?cF(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?oF(r.text):r.text,s="assistant"===e.role?cF(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 dF(e){return e.endsWith("\n")?e:`${e}\n`}function hF(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 pF(e){if("system"===e.role||ZO(e))return;const t=uF(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 fF{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=LO({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=WO(o,(0,$.VI)(e.withName("writeFromState")),!1);try{const{overviewFactory:e}=n,o=hF(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=WO(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 YO(i,t,e);return s+=r.length,await tF(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=WO(n,(0,$.VI)(e.withName("hydratePromptMessages")),!1),w=await tF(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(XO);return a.push(...y),a}catch(e){n.error=e,n.hasError=!0}finally{HO(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=lF(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=uF(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:qO(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&&QO(t[0],t[1])&&(t=t.slice(1));const r=[];for(const e of t){const t=pF(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"),dF(n))}return!0}catch(e){return console.error("[TranscriptStore] Failed to write transcript:",e),!1}}catch(e){o.error=e,o.hasError=!0}finally{HO(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 YO(e,t,s)}catch{continue}await rF(e,t,r,o,{skipFailedReads:!0,visit:n})}return await rF(e,t,r.rootPromptMessagesJson,o,{skipFailedReads:!1,visit:async e=>{XO(e)&&await n(e)}}),o}((0,$.OA)(e.ctx),this.blobStore,t.state,(async e=>{"system"!==e.role&&(d++,1!==d?(2===d&&u&&(QO(u,e)||await l(pF(u)),u=void 0),await l(pF(e))):u=e)}));u&&await l(pF(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=hF(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=WO(s,(0,$.VI)(e.withName("writeFromStateIncremental")),!1);if(i===n&&c)try{return await l(this.resolveFilePath(r,"jsonl"),dF(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 tF(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=pF(e);t&&s.push(t)}if(s.push(...a.jsonlLines),s.length>0){const e=dF(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{HO(s)}}}function mF(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 gF(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 wF(e){return`Tool blocked because this hook is configured to fail closed (block when it fails). ${e}`}function yF(e){return Object.values(fd).some((t=>t===e))}function vF(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 bF(e){return yO(e)?`prompt:${e.prompt}`:`command:${e.command}`}function SF(e){return(e.repoHooks??[]).flatMap((e=>[e.projectHooks,e.claudeProjectHooks,e.claudeProjectLocalHooks]))}class kF{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(bF(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=bF(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(!wd(e))return!1;if(!("hooks"in e))return!1;const r=e.hooks;if(!wd(r))return!1;const n=r;for(const[e,r]of Object.entries(n))if(e in _d&&Array.isArray(r)){const n=!0===t.allowMatcherlessStop&&"Stop"===e;for(const e of r)if(wd(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=jd(r,this.logger),o=kd(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=kd(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,...SF(e)];for(const e of r)if(e?.hooks)for(const r of Object.keys(e.hooks))yF(r)&&t.add(r);for(const r of e.pluginHooks??[])for(const e of Object.keys(r.config.hooks))yF(e)&&t.add(e);return t}}const _F="Read",CF="Write",EF="Delete",xF="List",PF="Grep",RF="Shell",IF="ReadLints";function TF(e,t){if("object"==typeof e&&null!==e)return Object.getOwnPropertyDescriptor(e,t)?.value}const AF=new Set([_F,CF,EF,xF,PF,IF]);function $F(e){const t=TF(e,"tool_name"),r=[TF(e,"file_path"),"string"==typeof t&&AF.has(t)?TF(TF(e,"tool_input"),"file_path"):void 0];for(const e of r)if("string"==typeof e&&e.length>0)return e}const MF=(0,l.h)("cli-hooks-executor");function DF(e){try{return(0,So.statSync)(e).isFile()}catch{return!1}}const OF="\nJSON Parse Error: Error: Failed to parse hook stdout as JSON";function FF(e,t){for(const[r,n]of Object.entries(e))if(r===t)return n}function NF(e,t){const r=FF(e,t);if("string"==typeof r||null===r)return r}class LF{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,status:e.status,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,Sp.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,go.Rv)((0,o.homedir)(),this.workspacePath),r=this.transcriptParentConversationIdById.get(e),n=UO(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,vo.access)(e),e}catch{}return null}catch{return null}}async getSubagentTranscriptPathIfExists(e){const{subagentId:t,parentConversationId:r}=e;try{const e=(0,go.Rv)((0,o.homedir)(),this.workspacePath),n=UO({conversationId:t,kind:"subagent",parentConversationId:r}).map((t=>(0,s.join)(e,t)));for(const e of n)try{return await(0,vo.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,...SF(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?gF(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?gF(n,t):n).some((e=>vO(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=FF(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 _O.includes(e)}(e),o=t,i=n?null:o.conversation_id?await this.getTranscriptPathIfExists(o.conversation_id):null;let a;if(e===fd.subagentStop){const e=NF(t,"subagent_id"),r=NF(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===fd.subagentStop&&{agent_transcript_path:a??null}},u=function(e,t){switch(e){case"beforeShellExecution":case"afterShellExecution":return mF(t,"command");case"beforeMCPExecution":case"afterMCPExecution":{const e=mF(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 mF(t,"subagent_type");case"preToolUse":case"postToolUse":case"postToolUseFailure":return mF(t,"tool_name");default:return}}(e,l),d=[],h=(e,t,n)=>{if(!e)return;const o=gF(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)yO(e)?this.promptHookClient&&d.push({type:"prompt",script:e,source:t}):vO(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,Ko.o1)(t,r),[o,i,a]=await Promise.all([(0,Ko.DN)(n),(0,Ko.DN)(s.default.dirname(n)),Promise.all(e.map((async e=>await(0,Ko.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:$F(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===fd.stop||e===fd.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 gF(n,u))vO(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=wF(`Hook execution failed: ${n}`),r=IO(e,t);if(r)return{success:!0,data:r,source:i,index:o}}return MF.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;const[r]=t;if(!(1!==t.length||wd(n=r)&&wd(n.updated_input)&&0===Object.keys(n.updated_input).length))return r;var n;const o=kO.includes(e),s=e===fd.sessionStart,i=e===fd.workspaceOpen,a=wO.has(e),c={};for(const e of t){const t=e;for(const[e,r]of Object.entries(t))if(void 0!==r)if(i&&"pluginPaths"===e&&Array.isArray(r)){const t=c[e],n=Array.isArray(t)?t:[],o=new Set(n),s=[...n];for(const e of r)"string"!=typeof e||o.has(e)||(o.add(e),s.push(e));c[e]=s}else"permission"===e&&o?c[e]=(u=r,"deny"===(l=c[e])||"deny"===u?"deny":"ask"===l||"ask"===u?"ask":"allow"===l||"allow"===u?"allow":void 0):"user_message"!==e&&"agent_message"!==e?"updated_input"!==e?a&&"additional_context"===e&&"string"==typeof r?c[e]=CO(c[e],r):"continue"!==e||"boolean"!=typeof r?c[e]=s&&"env"===e&&"object"==typeof r&&null!==r?EO(c[e],r):r:void 0===c[e]?c[e]=r:c[e]=c[e]&&r:void 0===c[e]&&wd(r)&&Object.keys(r).length>0&&(c[e]=r):c[e]=CO(c[e],r)}var l,u;return c}(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=IO(e,wF(`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=IO(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=IO(e,wF(`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=IO(e,wF(`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=TO(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=TO(t.slice(e));if(void 0!==r)return r.value}}(g);if(void 0===w){const r=PO({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+OF}),{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+OF}),{success:!1,source:s,index:i})}const y=SO(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=PO({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 xO(e)?RO(0,{permission:"allow"}):e===fd.beforeSubmitPrompt||e===fd.sessionStart?RO(0,{continue:!0}):e===fd.stop?RO(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=IO(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=IO(e,wF(`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=aO.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:DF}):t.command;let w;if(m)w=e?cO(g):g;else if("windows_temp_file"===f){d=await(0,vo.mkdtemp)((0,s.join)((0,o.tmpdir)(),"cursor-hooks-"));const e=(0,s.join)(d,"payload.json");await(0,vo.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 | ${cO(t)} }`+iO(t)}(e,g)}else w=e?`@'\n${c.replace(/'/g,"''")}\n'@ | & ${g}`+iO(g):`${t.command} <<'CURSOR_HOOK_EOF'\n${c}\nCURSOR_HOOK_EOF`;const v=NF(n,"conversation_id")??void 0,b=NF(n,"session_id")??void 0,S=NF(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 ta.StringDecoder("utf8"),R=new ta.StringDecoder("utf8");let I,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+=R.write(e.data);break;case"exit":$=e.code,I=e.aborted}if(T+=P.end(),A+=R.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(I??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,vo.rm)(d,{recursive:!0,force:!0})}catch{}}}}class jF{constructor(e){this.config=e,this.configuredSteps=kF.getConfiguredSteps(e)}getConfig(){return this.config}hasHookForStep(e){return this.configuredSteps.has(e)}getConfiguredSteps(){return new Set(this.configuredSteps)}}var UF=r("node:perf_hooks");const BF=(0,y.cF)(Symbol.for("@anysphere/agent-exec/toolCallHooks"),{kind:"none"});function WF(e){return"inExecute"!==e.get(BF).kind}function HF(e,t){const r=e.get(BF);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 qF=(0,y.cF)(Symbol.for("@anysphere/agent-exec/hookStepTime"),void 0),zF=new id.AsyncLocalStorage;function GF(e,t){return zF.run(e,t)}function VF(e,t){void 0!==e&&t.length>0&&e.push(...t)}class KF 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 JF=r("../proto/dist/generated/agent/v1/hook_additional_context_pb.js");function ZF({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 KF({hookEventName:e,actualLength:r.length,maxLength:1e4});return[new JF.C({hookEventName:e,content:r})]}Object.fromEntries(Array.from(wO).map((e=>{if(!function(e){return e===fd.sessionStart||e===fd.beforeSubmitPrompt||e===fd.preToolUse||e===fd.postToolUse||e===fd.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 XF="Agent note: Do not suggest workarounds to the blocked tool.";function QF(e){return e.includes(XF)?e:`${e}\n\n${XF}`}class YF extends Error{constructor(e){super(`Hook denied: ${e}`),this.failureType="permission_denied",this.name="HookDeniedError",this.reason=e}}class eN extends Error{constructor(e,t){super(`Hook failed (fail-closed): ${e}`),this.failureType="error",this.name="FailClosedError",this.reason=e,this.cause=t}}const tN="To view or modify configured hooks, go to Cursor Settings > Hooks.";function rN(e,t){return QF(`${t?`${e} was blocked by a hook: ${t}`:`${e} was blocked by a hook.`}\n\n${tN}`)}function nN(e){return function(e){return e instanceof YF}(e)||function(e){return e instanceof eN}(e)}const oN=(0,l.h)("generic-hooks");function sN(e,t,r,n){try{return ZF({hookEventName:r,additionalContext:n})}catch(n){if(n instanceof KF)return oN.warn(e,`${r} additional_context exceeded max size; dropping carrier`,{toolName:t,hookEventName:r,actualLength:n.actualLength,maxLength:n.maxLength}),[];throw n}}const iN=e=>Math.round(1e3*e)/1e3;function aN(e,t,r,n,o,s){const i=n(e),a=o.getToolCallId?.(t)??(0,mo.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 GF(e.signal,(()=>t.executeHookForStep(fd.postToolUseFailure,{...a,tool_name:r,tool_input:o,error_message:l,failure_type:u,duration:n,tool_use_id:c,is_interrupt:d,...s})));VF(i,sN(e,r,fd.postToolUseFailure,h?.additional_context))}catch(t){oN.warn(e,"postToolUseFailure hook error",{toolName:r,error:t instanceof Error?t.message:String(t)})}},fireSuccessAsync:async(n,l)=>{try{const u=await GF(e.signal,(()=>t.executeHookForStep(fd.postToolUse,{...a,tool_name:r,tool_input:o,tool_output:l,duration:n,tool_use_id:c,...s})));VF(i,sN(e,r,fd.postToolUse,u?.additional_context))}catch(t){oN.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 cN(e,t,r,n,o,s,i,a){const{baseHookRequest:c,toolUseId:l,extraHookFields:u}=n;try{const a=await GF(e.signal,(()=>r.executeHookForStep(fd.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=QF(r);try{VF(n.hookContextCollector,ZF({hookEventName:fd.preToolUse,additionalContext:a.additional_context}))}catch(t){if(!(t instanceof KF))throw t;oN.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))),VF(n.hookContextCollector,ZF({hookEventName:fd.preToolUse,additionalContext:a?.additional_context}))}catch(n){const a=r.hasFailClosedHooksForStep?.(fd.preToolUse,s.toolName)??!1,c=n instanceof KF;if(a){const e=wF(`${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}}oN.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(nN(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 lN(e){return e.toolCallId}function uN(e,t,r,n){return{async execute(o,s,i){const a=hN(o,t),{hookContext:c,helpers:l}=aN(o,s,a,r,n,i);let u;try{u=await cN(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=UF.performance.now();try{const t=await e.execute(o,s,i),r=iN(UF.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(nN(e))return await l.fireFailureAsync(r,e.reason,e.failureType),n.runCleanup?.(c.toolUseId),n.createRejectedResult(s,e.reason);oN.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=iN(UF.performance.now()-d);throw await l.fireFailureAsync(t,e instanceof Error?e.message:String(e),"error"),n.runCleanup?.(c.toolUseId),e}}}}function*dN(e,t){const r=t.hookContextCollector;e.createHookContextEvent&&void 0!==r&&0!==r.length&&(yield e.createHookContextEvent(r))}function hN(e,t){const r=WF(e),n=e.get(qF);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===fd.preToolUse||e===fd.postToolUse||e===fd.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 pN(e){if("object"!=typeof e||null===e||!("code"in e))return!1;const t=e.code;return"ENOENT"===t||"ENOTDIR"===t}class fN{async readFile(e){try{return await vo.readFile(e,"utf-8")}catch(e){if("ENOENT"===e?.code)return;throw e}}async exists(e){try{return await vo.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,vo.lstat)(e)).isSymbolicLink())return!0}catch(e){if(pN(e))return!0;throw e}return!1}(e,t)}}var mN=r("../proto/dist/generated/agent/v1/hooks_pb.js");const gN=q("hook-executor",(e=>new B(e,Z("executeHookArgs"),X("executeHookResult"))),((e,t)=>{t.register(new I(e,Y("executeHookArgs"),Q("executeHookResult")))})),wN=new Set(Object.values(fd));function yN(e){switch(e){case"completed":case"aborted":case"error":return e;default:return"error"}}function vN(e){switch(e){case"error":case"timeout":case"permission_denied":return e;default:return"error"}}function bN(e){const t=e?.toJson();return"object"!=typeof t||null===t||Array.isArray(t)?{}:t}class SN{constructor(e){this.hookExecutor=e}hasFailClosedHooksForStep(e,t){return!!function(e){return wN.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??"",...gO(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(fd.preCompact,t);return new d.S1({response:new d.w5({response:{case:"preCompact",value:new mN.$_({userMessage:n?.user_message})}})})}case"subagentStart":{const e=r.request.value,t={conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...gO(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(fd.subagentStart,t);return new d.S1({response:new d.w5({response:{case:"subagentStart",value:new mN.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??"",...gO(e),subagent_id:e.subagentId,subagent_type:e.subagentType,status:yN(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(fd.subagentStop,t);return new d.S1({response:new d.w5({response:{case:"subagentStop",value:new mN.AH({followupMessage:n?.followup_message,additionalContext:n?.additional_context})}})})}case"beforeSubmitPrompt":{const e=r.request.value,t=await this.hookExecutor.executeHookForStep(fd.beforeSubmitPrompt,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...gO(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 mN.u1({continue:t?.continue,userMessage:t?.user_message,additionalContext:t?.additional_context})}})})}case"afterAgentResponse":{const e=r.request.value;return await this.hookExecutor.executeHookForStep(fd.afterAgentResponse,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...gO(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 mN.FW}})})}case"afterAgentThought":{const e=r.request.value;return await this.hookExecutor.executeHookForStep(fd.afterAgentThought,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...gO(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 mN.H}})})}case"stop":{const e=r.request.value,t=await this.hookExecutor.executeHookForStep(fd.stop,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...gO(e),status:yN(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 mN.rT({followupMessage:t?.followup_message})}})})}case"preToolUse":{if(!WF(e))return this.skipToolUseStep();const t=r.request.value,n=bN(t.toolInput),o={conversation_id:t.conversationId??"",generation_id:t.generationId??"",model:t.model??"",...gO(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(fd.preToolUse,o);return new d.S1({response:new d.w5({response:{case:"preToolUse",value:new mN.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(!WF(e))return this.skipToolUseStep();const t=r.request.value,n=bN(t.toolInput),o={conversation_id:t.conversationId??"",generation_id:t.generationId??"",model:t.model??"",...gO(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(fd.postToolUse,o);return new d.S1({response:new d.w5({response:{case:"postToolUse",value:new mN.uB({additionalContext:s?.additional_context,updatedMcpToolOutput:void 0===s?.updated_mcp_tool_output?void 0:JSON.stringify(s.updated_mcp_tool_output)})}})})}case"postToolUseFailure":{if(!WF(e))return this.skipToolUseStep();const t=r.request.value,n=bN(t.toolInput),o={conversation_id:t.conversationId??"",generation_id:t.generationId??"",model:t.model??"",...gO(t),...t.parentToolCallId?{parent_tool_call_id:t.parentToolCallId}:{},tool_name:t.toolName,tool_input:n,error_message:t.errorMessage,failure_type:vN(t.failureType),duration:Number(t.durationMs),tool_use_id:t.toolUseId,is_interrupt:t.isInterrupt},s=await this.hookExecutor.executeHookForStep(fd.postToolUseFailure,o);return new d.S1({response:new d.w5({response:{case:"postToolUseFailure",value:new mN.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 kN{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 _N(e){return!!e&&e.type!==Yo.vc.INSECURE_NONE&&e.type!==Yo.vc.UNSPECIFIED}async function CN({hookExecutor:e,baseHookRequest:t,toolUseId:r,command:n,cwd:o,sandbox:s}){const i=await e.executeHookForStep(fd.beforeShellExecution,{...t,command:n,cwd:o,sandbox:s,tool_use_id:r});if("deny"===i?.permission){const e=rN("Command execution",i.user_message);throw new YF(e)}if("ask"===i?.permission)return a=i.user_message,new he.In({kind:he.b.FORCE_PROMPT,reason:a});var a}const EN={toolName:RF,getToolCallId:lN,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 Io.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=_N(r.sandboxPolicy);HF(t,fd.beforeShellExecution)&&Eo(r,await CN({hookExecutor:o,baseHookRequest:n,toolUseId:s,command:r.command,cwd:i,sandbox:a}))}};class xN{constructor(e,t,r){this.wrappedExecutor=uN(e,t,r,EN)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const PN={toolName:"WriteShellStdin",createToolInput:e=>({shell_id:e.shellId,chars_length:e.chars.length}),createRejectedResult:(e,t)=>new Io.nt({result:{case:"error",value:new Io.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 RN{constructor(e,t,r){this.wrappedExecutor=uN(e,t,r,PN)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const IN={toolName:"ComputerUse",getToolCallId:lN,createToolInput:e=>({actions_count:e.actions.length}),createRejectedResult:(e,t)=>new rg.ks({result:{case:"error",value:new rg.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 TN{constructor(e,t,r){this.wrappedExecutor=uN(e,t,r,IN)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const AN={toolName:EF,getToolCallId:lN,createToolInput:e=>({file_path:e.path}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new sw.Pi({result:{case:"rejected",value:new sw.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 $N{constructor(e,t,r){this.wrappedExecutor=uN(e,t,r,AN)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const MN={toolName:IF,getToolCallId:lN,createToolInput:e=>({file_path:e.path}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new ZT.Ek({result:{case:"rejected",value:new ZT.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 DN{constructor(e,t,r){this.wrappedExecutor=uN(e,t,r,MN)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const ON={toolName:"Fetch",getToolCallId:lN,createToolInput:e=>({url:e.url}),applyUpdatedInput:(e,t)=>{"string"==typeof t.url&&(e.url=t.url)},createRejectedResult:(e,t)=>new hw.uN({result:{case:"error",value:new hw.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 FN{constructor(e,t,r){this.wrappedExecutor=uN(e,t,r,ON)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const NN={toolName:PF,getToolCallId:lN,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 zw.Ud({result:{case:"error",value:new zw.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 LN{constructor(e,t,r){this.wrappedExecutor=uN(e,t,r,NN)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const jN={toolName:xF,getToolCallId:lN,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 D_.fv({result:{case:"rejected",value:new D_.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 UN{constructor(e,t,r){this.wrappedExecutor=uN(e,t,r,jN)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const BN=(0,l.h)("hooks-exec:mcp");function WN(e){return!!(null===e||"string"==typeof e||"boolean"==typeof e||"number"==typeof e&&Number.isFinite(e))||(Array.isArray(e)?e.every(WN):"object"==typeof e&&Object.values(e).every((e=>void 0!==e&&WN(e))))}function HN(e,t,r,n){try{return ZF({hookEventName:r,additionalContext:n})}catch(n){if(n instanceof KF)return BN.warn(e,`${r} additional_context exceeded max size; dropping carrier`,{toolName:t,hookEventName:r,actualLength:n.actualLength,maxLength:n.maxLength}),[];throw n}}class qN{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(fd.preToolUse)||!0===this.hooksConfigLease?.hasHookForStep(fd.beforeMCPExecution)))return new xc.iz({result:{case:"error",value:new xc.Nh({error:`"${bT}" 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=hN(e,this.hookExecutor),o=this.baseHookRequestExtractor(e),s=(0,mo.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(fd.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{VF(i,ZF({hookEventName:fd.preToolUse,additionalContext:r.additional_context}))}catch(t){if(!(t instanceof KF))throw t;BN.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 xc.iz({result:{case:"permissionDenied",value:new xc.HQ({error:rN("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(!WN(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){BN.warn(e,"Failed to merge updated_input for MCP",{error:t instanceof Error?t.message:String(t)})}VF(i,ZF({hookEventName:fd.preToolUse,additionalContext:r?.additional_context}))}catch(t){const r=n.hasFailClosedHooksForStep?.(fd.preToolUse,c)??!1,l=t instanceof KF;if(r){const r=wF(`${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 xc.iz({result:{case:"permissionDenied",value:new xc.HQ({error:rN("MCP tool execution",r),isReadonly:!1})}})}BN.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=HF(e,fd.beforeMCPExecution)?await n.executeHookForStep(fd.beforeMCPExecution,f):void 0;if("deny"===m?.permission){const t=rN("MCP tool execution",m.user_message);return await this.firePostToolUseFailureAsync(e,n,o,c,a,t,"permission_denied",0,s,!1,i),new xc.iz({result:{case:"permissionDenied",value:new xc.HQ({error:t,isReadonly:!1})}})}const g=UF.performance.now();try{const l=await this.innerExecutor.execute(e,t,r),u=iN(UF.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){BN.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(fd.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 xc._Z({content:{case:"text",value:new xc.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 xc._Z({content:{case:"text",value:new xc.zN({text:String(e.text)})}})):t.push(new xc._Z({content:{case:"text",value:new xc.zN({text:JSON.stringify(e)})}}))}else t.push(new xc._Z({content:{case:"text",value:new xc.zN({text:JSON.stringify(e)})}}));const r="object"==typeof e&&null!==e&&"isError"in e&&Boolean(e.isError);return new xc.iz({result:{case:"success",value:new xc.QW({content:t,isError:r})}})}catch(t){return BN.warn(e,"Failed to process updated_mcp_tool_output",{error:t instanceof Error?t.message:String(t)}),l}return l}catch(t){const r=iN(UF.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(fd.postToolUse,{...r,tool_name:n,tool_input:o,tool_output:s,duration:i,tool_use_id:a});return VF(c,HN(e,n,fd.postToolUse,l?.additional_context)),l}catch(t){return void BN.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(fd.postToolUseFailure,{...r,tool_name:n,tool_input:o,error_message:s,failure_type:i,duration:a,tool_use_id:c,is_interrupt:l});VF(u,HN(e,n,fd.postToolUseFailure,d?.additional_context))}catch(t){BN.warn(e,"postToolUseFailure hook error in MCP executor",{error:t instanceof Error?t.message:String(t)})}}}const zN={toolName:"ListMcpResources",createToolInput:e=>({server:e.server}),applyUpdatedInput:(e,t)=>{"string"==typeof t.server&&(e.server=t.server)},createRejectedResult:(e,t)=>new xc.kP({result:{case:"error",value:new xc.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 GN{constructor(e,t,r){this.wrappedExecutor=uN(e,t,r,zN)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const VN={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 xc.ZD({result:{case:"error",value:new xc.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 KN{constructor(e,t,r){this.wrappedExecutor=uN(e,t,r,VN)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const JN={toolName:_F,getToolCallId:lN,createToolInput:e=>({file_path:e.path}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new fy.sV({result:{case:"rejected",value:new fy.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?.(fd.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${tN}`}(t,e instanceof Error?e.message:String(e));throw new eN(r,e)}}((()=>o.executeHookForStep(fd.beforeReadFile,{...n,content:i,file_path:t.path,attachments:[],tool_use_id:s})),"File read");if("deny"===a?.permission){const e=rN("File read",a.user_message);throw new YF(e)}}};class ZN{constructor(e,t,r){this.wrappedExecutor=new fT(uN(e,t,r,JN))}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const XN={toolName:"RecordScreen",getToolCallId:lN,createToolInput:e=>({mode:e.mode,save_as_filename:e.saveAsFilename}),createRejectedResult:(e,t)=>new HA.Tj({result:{case:"failure",value:new HA.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 QN{constructor(e,t,r){this.wrappedExecutor=uN(e,t,r,XN)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}function YN(e){return"success"===e.result.case||"failure"===e.result.case?e.result.value.stdout+e.result.value.stderr:""}const eL={toolName:RF,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:YN(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||"";HF(t,fd.beforeShellExecution)&&Eo(r,await CN({hookExecutor:o,baseHookRequest:n,toolUseId:s,command:r.command,cwd:i,sandbox:_N(r.requestedSandboxPolicy)}))},runPostExecutionHooks:async e=>{const{args:t,result:r,baseHookRequest:n,hookExecutor:o,executionDurationMs:s,toolUseId:i}=e,a=YN(r);await o.executeHookForStep(fd.afterShellExecution,{...n,command:t.command,output:a,duration:s,sandbox:_N(t.requestedSandboxPolicy),tool_use_id:i})}};class tL{constructor(e,t,r){this.wrappedExecutor=uN(e,t,r,eL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}class rL{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 nL={toolName:RF,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 rL,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=_N(r.requestedSandboxPolicy);HF(t,fd.beforeShellExecution)&&Eo(r,await CN({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=_N(t.requestedSandboxPolicy);await n.executeHookForStep(fd.afterShellExecution,{...r,command:t.command,output:o.getOutput(),duration:s,sandbox:a,tool_use_id:i})}};class oL{constructor(e,t,r){this.wrappedExecutor=function(e,t,r,n){return{async*execute(o,s,i){const a=hN(o,t),{hookContext:c,helpers:l}=aN(o,s,a,r,n,i),u=n.runPreExecutionHooks?async e=>{await n.runPreExecutionHooks(e)}:void 0,d=await cN(o,s,a,c,l,n,((e,t)=>n.createRejectedEvent(e,t)),u);if("rejected"===d.type){yield d.result;for(const e of dN(n,c))yield e;return}const h=UF.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=iN(UF.performance.now()-h),r=e instanceof Error?e.message:String(e);await l.fireFailureAsync(t,r,"error");for(const e of dN(n,c))yield e;throw e}const f=iN(UF.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){oN.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 dN(n,c))yield e}}}(e,t,r,nL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}class sL{constructor(e,t,r){const n=new Map;this.wrappedExecutor=uN(e,t,r,function(e){return{toolName:CF,getToolCallId:lN,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 ZR.v3({result:{case:"error",value:new ZR.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?.(fd.afterFileEdit))return;let s,i=!1;try{(await(0,vo.stat)(r.path)).size>262144?i=!0:s=await Di(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?.(fd.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,Pb.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(fd.afterFileEdit,d);if(r.returnFileContentAfterWrite&&void 0!==h){const e=n.result.value.path;try{const t=await Di(e),r=qs(t),o=Buffer.byteLength(t,"utf8");return new ZR.v3({result:{case:"success",value:new ZR.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 iL(e,t,r){return t===e.symbol}function aL(e,t,r){return iL(rT,e)?new tL(t,r.hookExecutor,r.baseHookRequestExtractor):iL(ee,e)?new oL(t,r.hookExecutor,r.baseHookRequestExtractor):iL(iT,e)?new sL(t,r.hookExecutor,r.baseHookRequestExtractor):iL(Xn,e)?new qN(t,r.hookExecutor,r.baseHookRequestExtractor,r.mcpLease,r.hooksConfigLease):iL(mT,e)||iL(gT,e)?new ZN(t,r.hookExecutor,r.baseHookRequestExtractor):iL(wT,e)?new UN(t,r.hookExecutor,r.baseHookRequestExtractor):iL(uT,e)?new LN(t,r.hookExecutor,r.baseHookRequestExtractor):iL(cT,e)?new FN(t,r.hookExecutor,r.baseHookRequestExtractor):iL(aT,e)?new $N(t,r.hookExecutor,r.baseHookRequestExtractor):iL(yT,e)?new DN(t,r.hookExecutor,r.baseHookRequestExtractor):iL(Qn,e)?new GN(t,r.hookExecutor,r.baseHookRequestExtractor):iL(Yn,e)?new KN(t,r.hookExecutor,r.baseHookRequestExtractor):iL(FT,e)?new xN(t,r.hookExecutor,r.baseHookRequestExtractor):iL(NT,e)?new RN(t,r.hookExecutor,r.baseHookRequestExtractor):iL(HT,e)?new TN(t,r.hookExecutor,r.baseHookRequestExtractor):iL(qT,e)?new QN(t,r.hookExecutor,r.baseHookRequestExtractor):iL(Ar,e)&&(r.hooksAdditionalContextPromise||r.hooksConfigLease)?new kN(t,r.hooksAdditionalContextPromise??Promise.resolve(void 0),r.teamHooksReadyPromise,r.hooksConfigLease):void 0}class cL{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===gN.symbol)return new SN(t)}(e,this.hookExecutor);return void 0!==t?t:function(e,t,r){const n=aL(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=aL(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=gN;yield[e,new SN(this.hookExecutor)]}}const lL={cursor_version:process.env.AGENT_CLI_STATIC_VERSION??"1.0.0",user_email:null};function uL(e=process.cwd()){let t=e;const r={getCwd:async()=>t,clone:e=>uL(e??t),async*execute(e,r,n={}){const o=n.workingDirectory??t;t=o;const s=function(e){return"win32"===process.platform?{executable:(0,To.oG)(),args:[...tO,"-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}};return r}function dL(e,t,...r){for(const n of r){const r=t(e[n]);if(void 0!==r)return r}}function hL(e){return"string"==typeof e&&e.length>0?e:void 0}function pL(e){return"object"==typeof e&&null!==e&&"string"==typeof e.id&&"string"==typeof e.value}function fL(e){if(Array.isArray(e)&&e.every(pL))return e.map((e=>({id:e.id,value:e.value})))}class mL{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 gL(e,t={}){const r=await new kF(new fN,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?vF():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 jF(r),i=function(e){return e.projectRoot??e.workingDirectory??e.workspaceRoots[0]??process.cwd()}(e),a=function(e){return Object.freeze({...lL,...e.globalContext??{}})}(t);return{projectDir:e.projectRoot,workspacePath:i,hooksConfig:r,hooksConfigLease:n,globalContext:a,createSessionRuntime(){const e=new LF(r,i,a,(t.createTerminalExecutor??uL)(),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 wL(e={}){return{createHooksRuntime:t=>gL(t.workspaceState,e)}}var yL=r("../proto/dist/generated/aiserver/v1/dashboard_service_connect.js");async function vL(e){(function(e){return"object"==typeof e&&null!==e&&"dispose"in e&&"function"==typeof e.dispose})(e)&&await e.dispose()}function bL(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 Hw,l=(0,o.homedir)(),u=jf(l).dirPath;let d,h=!0;return{async prepareLocalExtensibility(){h=i&&await async function(e){if(!e)return!1;const t=(0,ye.createClient)(yL.I,e);return"synced"===(await async function(e,t){try{const r=await t.getManagedSkills()??[],n=await GM(e,{managedSkills:[...r]});return{status:"synced",managedSkillsCount:r.length,syncResult:n}}catch(t){return KM.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 tD.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:PL(),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=SL(t);return{getAllCursorRules:async t=>kL(await e.getAllCursorRules(t),r),reload(t){e.reload(t)},onDidChangeRules:t=>e.onDidChangeRules(t),dispose(){e.dispose()}}}(0===m.length?PL():1===m.length?m[0]:new Dm(m,(()=>nm)),{allowedRoots:n?i:[],excludedRoots:[]}),w=function(e,t){const r=SL(t);return{getAllCursorRules:async t=>kL(await e.getAllCursorRules(t),r),getAllAgentSkills:async t=>kL(await e.getAllAgentSkills(t),r),reload(t){e.reload(t)},onDidChangeRules:t=>e.onDidChangeRules(t),onDidChangeSkills:t=>e.onDidChangeSkills(t),dispose(){e.dispose()}}}(new Nm(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 Km(e,t))):[],b=0===v.length?new Wm:1===v.length?v[0]:new Zm(v),S=GD(o.services.pluginBootstrapOutputs),k=S&&a?new jm(p,(()=>({importThirdPartyPlugins:r})),void 0,S.pluginsService):void 0,_=S&&a?new Xm((()=>({importThirdPartyPlugins:r})),S.pluginsService):void 0,C=new Dm([g,w,...k?[k]:[]],(()=>nm)),E=new PM([w,...k?[k]:[]],(()=>[]),(()=>({workspacePaths:n?i:[],userHomeDirectory:l,agentStoreSkillsDirs:[]}))),x=new Zm([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 vL(e)}catch(e){t??=e}if(void 0!==t)throw t}(e)}}}function SL(e){const t=Promise.all(e.allowedRoots.map(EL)),r=Promise.all(e.excludedRoots.map(EL));return async e=>{const[n,o,s]=await Promise.all([xL(e.fullPath),t,r]);return void 0!==n&&!s.some((e=>_L(n,e)))&&o.some((e=>_L(n,e)))}}async function kL(e,t){const r=await Promise.all(e.map(t));return e.filter(((e,t)=>r[t]))}function _L(e,t){if(e===t)return!0;const r=`${t}/`;return e.startsWith(r)}function CL(e){return e.replace(/\\/g,"/").replace(/\/+$/,"")}async function EL(e){try{return CL(await(0,vo.realpath)(e))}catch{return CL(e)}}async function xL(e){try{return CL(await(0,vo.realpath)(e))}catch{return}}function PL(){return{getAllCursorRules:async()=>[],reload(){},onDidChangeRules:()=>()=>{},dispose(){}}}function RL(e,t){const r=e.releaseTag??t;if(e.releaseRepo&&e.releaseAsset&&r)return{kind:"release",releaseRepo:e.releaseRepo,releaseAsset:e.releaseAsset,releaseTag:r}}const IL=/^[a-z][a-z0-9+.-]*:\/\/([^/?#]*)/i,TL=/^(?:[^@/\s]+@)?([^:/\s\\]+):(?!\/\/)/,AL=/^([a-z][a-z0-9+.-]*)::(.*)$/i,$L=/^([a-z][a-z0-9+.-]*):\/\//i,ML=new Set(["file","git","http","https","ssh"]);function DL(e){if(/^(?:\\\\|\/\/)[^\\/]/.test(e))throw new Error("Cursor Orbit: plugin git remote could not be validated");const t=AL.exec(e);if(null!==t){const e=t[1].toLowerCase();if(!ML.has(e))throw new Error("Cursor Orbit: plugin git remote could not be validated");const r=t[2];if(!("http"!==e&&"https"!==e||null!==$L.exec(r)&&URL.canParse(r)))throw new Error("Cursor Orbit: plugin git remote could not be validated");const n=DL(r);if(0===n.length)throw new Error("Cursor Orbit: plugin git remote could not be validated");return n}const r=$L.exec(e)?.[1].toLowerCase();if(void 0!==r&&!ML.has(r))throw new Error("Cursor Orbit: plugin git remote could not be validated");const n=IL.exec(e)?.[1];if(void 0===n){const t=TL.exec(e)?.[1];if(void 0===t)return[];const r=function(e){const t=/^\[([^\]]+)\]$/.exec(e)?.[1],r=t??e;if(""!==r&&!/[\[\]\s@%\/\\]/.test(r))return OL(r)}(t);if(void 0===r)throw new Error("Cursor Orbit: plugin git remote could not be validated");return[r]}const o=[];URL.canParse(e)&&o.push(OL(new URL(e).hostname));const s=function(e){try{return decodeURIComponent(e)}catch{return e}}(n.slice(n.lastIndexOf("@")+1)),i=`https://${s}`;if(URL.canParse(i))o.push(OL(new URL(i).hostname));else{const e=/^\[([^\]]+)\](?::\d*)?$/.exec(s)?.[1];if(void 0===e)throw new Error("Cursor Orbit: plugin git remote could not be validated");o.push(OL(e))}const a=o.filter((e=>""!==e));if(0===a.length)throw new Error("Cursor Orbit: plugin git remote could not be validated");return[...new Set(a)]}function OL(e){return e.trim().toLowerCase().replace(/^\[|\]$/g,"").replace(/\.+$/,"")}function FL(){const e=["-c","credential.interactive=false","-c","core.fsmonitor=false"];return"1"===process.env[gv.K4]&&e.push("-c","http.followRedirects=false"),"win32"===process.platform&&e.push("-c","core.longpaths=true"),e}function NL(e){return"function"==typeof e?e():e}async function LL(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}),n=function(e){return function(e,t=process.env){if("1"!==t[gv.K4])return;const r=(0,gv.H)(t[gv.Zf]);for(const t of e)for(const e of DL(t))if((0,gv.ad)(e,r))throw new Error(`Cursor Orbit: plugin git egress to ${e} is refused`)}(e),[...FL(),...e]}(e);try{return await Pw("git",n,{...r,...void 0!==t?.timeoutMs&&{timeout:t.timeoutMs,killSignal:"SIGTERM"}})}catch(e){if("1"===process.env[gv.K4]&&function(e){if("object"!=typeof e||null===e||!("stderr"in e))return!1;const t=e.stderr;return"string"==typeof t&&/The requested URL returned error: 3\d{2}\b/i.test(t)}(e))throw new Error("Cursor Orbit: the plugin gitUrl redirected. Ask an administrator to update gitUrl to the final URL; redirects are disabled for plugin Git operations.",{cause:e});throw e}}const jL=/^[0-9a-f]{7,40}$/i,UL=/^[0-9a-f]{40}$/i;function BL(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 WL(e,t,r){const n=t.trim();if(UL.test(n))return{fullSha:n.toLowerCase()};if(jL.test(n)){try{const t=await async function(e,t,r){const{stdout:n}=await LL(["ls-remote",e,`refs/heads/${t}`,`refs/tags/${t}`,`refs/tags/${t}^{}`],{sshBatchMode:r?.sshBatchMode,extraGitConfig:r?.extraGitConfig,timeoutMs:r?.timeoutMs});return BL(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 LL(["ls-remote","--symref",e,"HEAD"],{sshBatchMode:r?.sshBatchMode,extraGitConfig:r?.extraGitConfig,timeoutMs:r?.timeoutMs}),n=BL(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 LL(["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=BL(o);if(!s)throw new Error(`git ls-remote did not return a resolvable commit for ref "${n}" (${e})`);return{fullSha:s.toLowerCase()}}const HL=sh.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 qL;function zL(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 GL(e){const t=[];for(const r of e){const e=zL(r);if(null===e)return"all";t.push(e)}return t}async function VL(e,t){const r="all"===e?"all":GL(e),n=t&&"all"!==r&&await(process.env.CURSOR_DISABLE_SPARSE_PLUGIN_CLONES?Promise.resolve(!1):(qL??=(async()=>{try{const{stdout:e}=await LL(["--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}})(),qL));return{materialize:r,sparse:n,sparseDirs:n?(o=r,[...new Set([...HL,...o])]):[]};var o}function KL(e){return e.toLowerCase().includes("filtering not recognized by server")}async function JL(e,t,r){await LL(["sparse-checkout","set","--cone","--",...t],{...r,cwd:e})}async function ZL(e){try{await(0,vo.access)((0,s.join)(e,".git","info","sparse-checkout"))}catch{return!1}try{const{stdout:t}=await LL(["config","--bool","--get","core.sparseCheckout"],{cwd:e});return"true"===t.trim()}catch{return!1}}async function XL(e,t,r){if("all"!==t&&0===t.length)return;if(!await ZL(e))return;const n={...r,cwd:e,sshBatchMode:!0};if("all"===t)return void await LL(["sparse-checkout","disable"],n);const o=GL(t);"all"!==o?await LL(["sparse-checkout","add","--",...o],n):await LL(["sparse-checkout","disable"],n)}(0,ys.J)((function(){qL=void 0}));const QL=/\.git$/i,YL=new Set(["account","dashboard"]);function ej(e){return e.replace(QL,"")}function tj(e){let t;try{t=decodeURIComponent(e)}catch{return}return t.length>0&&!t.includes("/")?t:void 0}function rj(e){const t=e.toLowerCase();return"github.com"===t||t.endsWith(".github.com")}function nj(e){return e.toLowerCase().split(".").includes("gitlab")}function oj(e){const t=e.toLowerCase();return"bitbucket.org"===t||"www.bitbucket.org"===t}function sj(e){const t=e.toLowerCase();return nj(e)?"GitLab":t.includes("bitbucket")?"Bitbucket":t.includes("gitea")||t.includes("codeberg")?"Gitea/Codeberg":t.includes("azure")&&t.includes("dev")?"Azure DevOps":null}function ij(e){return rj(e)?"github":nj(e)?"gitlab":oj(e)?"bitbucket":function(e){const t=e.toLowerCase();return"dev.azure.com"===t||"www.dev.azure.com"===t}(e)?"azure_devops":"generic"}function aj(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);Ba(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=ej(r);return n?{owner:t,repo:n,hasSubpath:e.length>2}:void 0}(n);return void 0===s?null:{provider:ij(r),owner:s.owner,repo:s.repo,host:r}}function cj(e){const t=lj(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 lj(e){try{const t=e.startsWith("git@")?`ssh://${e.replace(":","/")}`:e;return new URL(t.includes("://")?t:`https://${t}`)}catch{return null}}function uj(e){const t=e.trim();if(""===t)return{error:"URL cannot be empty"};const r=aj(t);if(null===r)return{error:"Invalid URL format. Expected: github.com/owner/repo or gitlab.com/namespace/repo"};if(nj(r.host)){const e=lj(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=ej(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=lj(e.trim());if(null!==t&&oj(t.hostname))return function(e){const t=e[0],r=e[1];if(void 0===t||void 0===r)return;const n=tj(t),o=tj(r);if(void 0===n||void 0===o||YL.has(n.toLowerCase()))return;const s=ej(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=lj(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=ej(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!Ba(e.host)&&null===sj(e.host);case"gitlab":case"bitbucket":case"azure_devops":return!1;default:return e.provider,!1}}(r)){const e=hj(r.host.replace(/^www\./i,""));return{url:`https://${e}/${cj(t)?"scm/":""}${r.owner}/${r.repo}`,owner:r.owner,repo:r.repo,host:e,provider:"github"}}const n=sj(r.host);return{error:"Only GitHub, GitLab, Bitbucket, and Azure DevOps URLs are currently supported."+(null!==n?` ${n} is not supported yet.`:"")}}function dj(e){const t=uj(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 hj(e){return rj(e)?"github.com":e}function pj(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 fj(e){return/[\n\r:#[\]{}&*!|>'"%@`]/.test(e)||e.startsWith(" ")||e.endsWith(" ")?`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:e}const mj=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 gj(e){const t=Cp(e).replace(/[. ]+$/g,"");return""===t||"."===t||".."===t?"_":mj.has(t.toLowerCase())?`_${t}`:t}const wj=18e5,yj=6e5,vj={recursive:!0,force:!0,maxRetries:3},bj=["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","you do not have access to"],Sj=["enotempty: directory not empty, rename","/_staging/"],kj=["upload-pack: not our ref","server does not allow request for unadvertised object"];function _j(e){const t=String(e).toLowerCase().replaceAll("\\","/");return bj.some((e=>t.includes(e)))?"user_git_access":Sj.every((e=>t.includes(e)))?"local_cache_race":kj.some((e=>t.includes(e)))?"stale_pinned_ref":"infrastructure"}function Cj(e){return"object"==typeof e&&null!==e&&(!0===e.killed||Cj(e.cause))}function Ej(e){return Cj(e)?"killed_by_budget":_j(e)}function xj(e){const t=uj(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=aj(e);if(null===r)throw new Error(`Invalid git URL: ${e}`);return{host:hj(r.host.replace(/^www\./i,"")).toLowerCase(),pathSegments:[r.owner.toLowerCase(),r.repo.toLowerCase()]}}const Pj=new Map;class Rj{constructor(e,t){this.cacheRoot=e,this.options=t,this.manifestCache=new Map}get sparsePluginClones(){return this.options?.sparsePluginClones??!1}remoteTimeoutMs(){return this.sparsePluginClones?wj:void 0}localTimeoutMs(){return this.sparsePluginClones?yj:void 0}lsRemoteTimeoutMs(){return this.sparsePluginClones?3e4:void 0}async cloneResolvedRef(e,t,r,n){const o={cwd:e,sshBatchMode:n?.sshBatchMode,extraGitConfig:{...NL(this.options?.extraGitConfig),"safe.directory":e}},{sparse:s,sparseDirs:i}=await VL(n?.materialize??"all",this.sparsePluginClones);await LL(["init"],{...o,timeoutMs:this.localTimeoutMs()}),s&&await JL(e,i,{sshBatchMode:n?.sshBatchMode,extraGitConfig:NL(this.options?.extraGitConfig),timeoutMs:this.localTimeoutMs()});const{stderr:a}=await LL(["fetch","--depth","1",...s?["--filter=blob:none"]:[],t,r],{...o,timeoutMs:this.remoteTimeoutMs()});return await LL(["checkout","FETCH_HEAD"],{...o,timeoutMs:this.remoteTimeoutMs()}),{strategy:s?"sparse":"full",filterIgnoredByServer:s&&KL(a??"")}}async createStagingDir(){const e=(0,s.join)(this.cacheRoot,"_staging",(0,mo.randomUUID)());return await(0,vo.mkdir)(e,{recursive:!0}),e}async moveToCanonicalDir(e,t){return await(0,vo.mkdir)((0,s.dirname)(t),{recursive:!0}),await(0,vo.rm)(t,vj),await(0,vo.rename)(e,t),t}async cleanStaleStagingDirs(){const e=(0,s.join)(this.cacheRoot,"_staging");try{const t=await(0,vo.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,vo.stat)(n);r-o.mtimeMs>Rj.STALE_STAGING_THRESHOLD_MS&&await(0,vo.rm)(n,vj)}catch{}})))}catch{}}getLegacyCloneDir(e,t){return(0,s.join)(this.cacheRoot,gj(e),gj(t))}getCanonicalCloneDir(e,t){const{host:r,pathSegments:n}=xj(e);return(0,s.join)(this.cacheRoot,gj(r),...n.map(gj),gj(t))}getCanonicalRepoRootDir(e){const{host:t,pathSegments:r}=xj(e);return(0,s.join)(this.cacheRoot,gj(t),...r.map(gj))}async pruneSiblingCloneDirs(e,t,r){const n=this.getCanonicalRepoRootDir(e),o=gj(t);try{const e=await(0,vo.readdir)(n,{withFileTypes:!0});await Promise.all(e.filter((e=>e.isDirectory()&&e.name!==o)).map((e=>(0,vo.rm)((0,s.join)(n,e.name),vj))))}catch{}if(void 0!==r)try{await(0,vo.rm)(r,vj)}catch{}}async ensureCloned(e,t,r,n=qh,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=qh){const n=this.serializedOnRepo((0,s.dirname)(e),(async()=>{const n=performance.now();try{await XL(e,t,{extraGitConfig:NL(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:Ej(o)}),r.increment("marketplace_cache_manager.ensure_materialized.error",1,{error_category:Ej(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=(Pj.get(r)??Promise.resolve()).catch((()=>{})).then(t);Pj.set(r,n);try{return await n}finally{Pj.get(r)===n&&Pj.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:dj(t);if(null!==a)try{i=(await WL(a,s,{sshBatchMode:!0,extraGitConfig:NL(this.options?.extraGitConfig),timeoutMs:this.lsRemoteTimeoutMs()})).fullSha}catch(e){if(this.sparsePluginClones&&Cj(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:_j(e)}),a=null,i=(await WL(t,s,{extraGitConfig:NL(this.options?.extraGitConfig),timeoutMs:this.lsRemoteTimeoutMs()})).fullSha}else i=(await WL(t,s,{extraGitConfig:NL(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 ZL(c);return e&&await XL(c,o,{extraGitConfig:NL(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,vo.utimes)(l,e,e).catch((()=>{}))}),Rj.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&&Cj(e))throw e;i.log("debug","Falling back to HTTPS clone due to SSH clone failure",{gitUrl:t,ref:s,error:String(e),errorCategory:Ej(e)}),await(0,vo.rm)(l,vj),await(0,vo.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=Ej(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,vo.rm)(l,vj)}catch{}}}async isCloneComplete(e){try{if(!(await(0,vo.stat)(e)).isDirectory())return!1;const t=await(0,vo.readdir)(e);if(!t.includes(".git"))return!1;if(t.length>1)return!0;try{return(await(0,vo.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,vo.mkdir)(t,{recursive:!0}),await(0,vo.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 sh){const n=(0,s.join)(e,r);let o;try{o=await(0,vo.readFile)(n,"utf-8")}catch{continue}const i=Dh(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=Fh(n.source,r.metadata?.pluginRoot);return o&&Nh(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=Fh(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":Nh(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):[]}}Rj.STALE_STAGING_THRESHOLD_MS=3e5,Rj.STAGING_HEARTBEAT_INTERVAL_MS=6e4;const Ij=(0,Us.debuglog)("cursor-plugins");function Tj(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Aj(e){return Tj(e)?e:void 0}function $j(e){const t=e.name?.trim();return void 0!==t&&t.length>0?t:e.pluginId}function Mj(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 Dj(e,t){const r=t?.distributionGitUrl?.trim();return r?t?.gitUrl&&!zj(e,t.gitUrl)?e:r:e}function Oj(e){return e?.distributionGitUrl?.trim()||e?.gitUrl}function Fj(e,t){if(e.pinnedGitRef)return e.pinnedGitRef;if(e.plugin?.gitRef)return e.plugin.gitRef;const r=Mj(e.plugin,t),n=e.plugin?.gitUrl,o=r?.gitUrl;return n&&o&&n!==o||!r?.gitRef?"main":r.gitRef}const Nj="backend-git://";function Lj(e,t,r){const n=r?`#${encodeURIComponent(r)}`:"";return`${Nj}${encodeURIComponent(e)}@${encodeURIComponent(t)}${n}`}function jj(e){if(!e.startsWith(Nj))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 Uj="backend-release://";function Bj(e){const t=e.tag?`@${encodeURIComponent(e.tag)}`:"";return`${Uj}${encodeURIComponent(e.repo)}#${encodeURIComponent(e.asset)}${t}`}function Wj(e){if(!e.startsWith(Uj))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 Hj=/^[0-9a-f]{7,40}$/i;function qj(e){let t;try{t=xj(e)}catch{return null}return`${t.host}\0${t.pathSegments.join("\0")}`}function zj(e,t){if(e.trim()===t.trim())return!0;const r=qj(e),n=qj(t);return null!==r&&r===n}const Gj=104857600;async function Vj(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(!(Tj(d=u)&&Array.isArray(d.assets)&&d.assets.every((e=>Tj(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>Gj)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||!Kj(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||!Kj(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>Gj)throw new Error(`Release asset "${r}" actual download size exceeds maximum of 104857600 bytes (actual: ${g.byteLength})`);if(e.expectedSha256){const t=(0,mo.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,vo.mkdir)(n,{recursive:!0});const u=await(0,vo.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,vo.writeFile)(d,c),await(0,vo.mkdir)(h,{recursive:!0});let e=0,t=0;await Ep.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,vo.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,vo.readdir)(e)).some((e=>oh.includes(e)))&&(a=e)}const p=await(0,vo.readdir)(a);await Promise.all(p.map((e=>(0,vo.cp)((0,s.join)(a,e),(0,s.join)(n,e),{recursive:!0,verbatimSymlinks:!0}))))}finally{await(0,vo.rm)(u,{recursive:!0,force:!0}).catch((()=>{}))}}function Kj(e,t){return!(e!==t&&!e.endsWith(".githubusercontent.com"))||("github.com"===t?"github.com"===e:e.endsWith(`.${t}`))}class Jj{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??qh,this.extraGitConfig=s.extraGitConfig,this.awaitAuthReady=s.awaitAuthReady,this.githubToken=s.githubToken,this.sparsePluginClones=s.sparsePluginClones??!1,this.marketplaceCache=s.marketplaceCacheRoot?new Rj(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=NL(this.extraGitConfig),s=this.sparsePluginClones?3e4:void 0,i=e.startsWith("git@")||e.startsWith("ssh://")?null:dj(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 WL(e,t,n):await WL(e,t)).fullSha};if(null!==i)try{n=await c(i,!0)}catch(t){if(this.sparsePluginClones&&Cj(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=Mj(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=$j({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,mo.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:Aj(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=Dj(c,r),d=Fj(e,o),h=RL(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?Bj({repo:h.releaseRepo,asset:h.releaseAsset,tag:h.releaseTag}):Lj(g,d,t.gitPath??void 0);const w=Oj(r);let y=w,v=r?.gitUrl,b=p;if(r?.gitUrl&&w){const e=zj(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:Lj(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:Aj(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=jj(e.downloadUrl);return!(!r||!zj(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,vo.mkdir)(t,{recursive:!0});const i={};if(o.rules&&o.rules.length>0){const e=(0,s.join)(t,"rules");await(0,vo.mkdir)(e,{recursive:!0});const r=[];for(const t of o.rules){if(!t.content)continue;if(!1===t.isActive)continue;const n=`${Cp(t.name)}.md`,o=[];o.push(`description: ${fj(t.name)}`),t.globs&&t.globs.length>0&&o.push(`globs: ${fj(t.globs.join(", "))}`),o.push(`alwaysApply: ${!0===t.isRequired}`);const i=`---\n${o.join("\n")}\n---\n\n`;await(0,vo.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,vo.mkdir)(e,{recursive:!0});const r=[];for(const t of o.commands){if(!t.content)continue;if(!1===t.isActive)continue;const n=`${Cp(t.name)}.md`,o=t.description?`---\ndescription: ${fj(t.description)}\n---\n\n`:"";await(0,vo.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,vo.mkdir)(e,{recursive:!0});const r={};for(const e of o.hooks){const t=e.hookStep;t&&!1!==e.isActive&&pj(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,vo.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,vo.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,vo.mkdir)(c,{recursive:!0}),await(0,vo.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,vo.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===Wj(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)&&Cj(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=qh,n,i){const a=i?.sparsePluginClones??!1,c=a?wj:void 0,l=Wj(e.downloadUrl);if(l){if(e.gitPath){const r=await(0,vo.mkdtemp)((0,s.join)((0,o.tmpdir)(),"release-plugin-"));try{await Vj(l.repo,l.asset,l.tag,r,i?.expectedReleaseAssetSha256,i?.githubToken);const n=Hp(r,e.gitPath);await(0,vo.mkdir)(t,{recursive:!0}),await(0,vo.cp)(n,t,{recursive:!0,verbatimSymlinks:!0})}finally{await(0,vo.rm)(r,{recursive:!0,force:!0}).catch((()=>{}))}}else await Vj(l.repo,l.asset,l.tag,t,i?.expectedReleaseAssetSha256,i?.githubToken);return}const u=jj(e.downloadUrl);if(!u)throw new Error(`Invalid download URL format for plugin ${e.pluginId}: ${e.downloadUrl}`);const d=await(0,vo.mkdtemp)((0,s.join)((0,o.tmpdir)(),"backend-plugin-"));try{let o;if(await async function(e,t,r,n=qh,o,s="all",i=!1){const a=performance.now(),c=Hj.test(t),l="HEAD"===t.toUpperCase(),u={...o,"safe.directory":r},d=i?wj:void 0,h=i?yj:void 0,{sparse:p,sparseDirs:f}=await VL(s,i),m=p?["--filter=blob:none","--sparse"]:[],g=!!p||void 0,w=async e=>{p&&await JL(r,f,{extraGitConfig:u,timeoutMs:e,sshBatchMode:!0})},y=async(e,n)=>{let o;return l?(({stderr:o}=await LL(["clone","--depth","1",...m,e,r],{extraGitConfig:u,timeoutMs:d,sshBatchMode:n})),await w(d)):c?(await LL(["init"],{cwd:r,extraGitConfig:u,timeoutMs:h}),await LL(["remote","add","origin",e],{cwd:r,extraGitConfig:u,timeoutMs:h}),await w(h),({stderr:o}=await LL(["fetch","--depth","1",...p?["--filter=blob:none"]:[],"origin",t],{cwd:r,extraGitConfig:u,timeoutMs:d,sshBatchMode:n})),await LL(["checkout","FETCH_HEAD"],{cwd:r,extraGitConfig:u,timeoutMs:d,sshBatchMode:n})):(({stderr:o}=await LL(["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:dj(e);let b;if(null!==v)try{b=await y(v,!0)}catch(t){if(i&&Cj(t))throw t;await(0,vo.rm)(r,{recursive:!0,force:!0}),await(0,vo.mkdir)(r,{recursive:!0}),b=await y(e,g)}else b=await y(e,g);p&&KL(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);Ij("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?GL([u.gitPath]):[],a),u.gitPath)o=Hp(d,u.gitPath);else{const t=await async function(e,t){for(const r of sh){const n=(0,s.join)(e,r);let o;try{o=await(0,vo.readFile)(n,"utf-8")}catch{continue}const i=Dh(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=Fh(c.source,a.metadata?.pluginRoot);return l&&Nh(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 XL(d,GL([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 XL(d,"all",{extraGitConfig:n,timeoutMs:c}),o=d}}await(0,vo.mkdir)(t,{recursive:!0}),await(0,vo.cp)(o,t,{recursive:!0,verbatimSymlinks:!0})}finally{await(0,vo.rm)(d,{recursive:!0,force:!0}).catch((()=>{}))}}(e,t,this.pluginLogger,NL(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=GL(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?GL([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,GL([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 Zj(e,t,r,n,o){return new Jj(e,t,r,n,o)}function Xj(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 Qj extends Error{constructor(e){super(e),this.name="SettingsParseError"}}function Yj(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function eU(e){return 65279===e.charCodeAt(0)?e.slice(1):e}async function tU(e){try{return eU(await(0,vo.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 rU(e){const t=await tU(e);return void 0===t?[]:function(e){const t=function(e){const t=eU(e);if(0===t.trim().length)return{};const r=[],n=(0,Lh.qg)(t,r,{allowTrailingComma:!0});if(r.length>0){const e=r.slice(0,3).map((e=>`${(0,Lh._n)(e.error)} at offset ${e.offset}`)).join("; ");throw new Qj(`.cursor/settings.json contains syntax errors: ${e}`)}if(!Yj(n))return{};const o=n.plugins;if(void 0===o)return{};if(!Yj(o))return{};const s={};for(const[e,t]of Object.entries(o))Yj(t)&&(s[e]=t);return{plugins:s}}(e);return t.plugins?Object.entries(t.plugins).filter((([,e])=>!0===e.enabled)).filter((([,e])=>!e.gitUrl||Xj(e.gitUrl))).map((([e,t])=>({key:e,entry:t}))):[]}(t)}function nU(e){const t=e.indexOf("/");return-1===t?{name:e}:{name:e.slice(t+1),marketplaceName:e.slice(0,t)}}function oU(e={}){const t=e.userHomeDirectory??(0,o.homedir)(),r=e.importThirdPartyPlugins??!1,n=e.pluginLogger??{log(e,t,r){switch(e){case"warn":PD.Jz.warn("[local-plugins-bootstrap]",t,r??{});break;case"error":PD.Jz.error("[local-plugins-bootstrap]",t,r??{})}},increment(){},distribution(){},captureException(e,t){PD.Jz.error("[local-plugins-bootstrap] Unexpected plugin exception:",e,t??{})}},i=sU(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 rU(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)(yL.I,e.dashboardTransport),n=Zj((async()=>{try{return await r.getEffectiveUserPlugins(new tD.EwF({}))}catch{return{plugins:[]}}}),t,void 0,void 0,{allowedMarketplaceNames:["cursor-public"]}),o=e.workspacePath,i=Zj((async()=>{if(void 0===o)return{plugins:[]};try{const e=await rU(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||Xj(t)})).map((({key:e,entry:t})=>{const r=nU(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=nU(e.key);return new tD.vwy({name:t.name,marketplaceName:t.marketplaceName})})),t=await r.resolvePluginsByRef(new tD.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 Tp(e.userHomeDirectory),pruneOldVersions:!0},{client:i,userId:"",cacheManager:new Tp(e.userHomeDirectory),pruneOldVersions:!0}]}({dashboardTransport:e.dashboardTransport,workspacePath:i,userHomeDirectory:t}):void 0),h=sU(d),p=new eD(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:zD,discoveredEntries:l,loadedPlugins:f,loadFailures:p.getLoadFailures(),bootstrapFailures:m,pluginsService:p,async dispose(){}};for(const e of m)PD.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)PD.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 sU(e){return void 0!==e&&(!Array.isArray(e)||e.length>0)}class iU{async getAllCursorRules(e){return[]}reload(e){}dispose(){}onDidChangeRules(e){return()=>{}}}const aU=["projectFolder","terminalsFolder","agentSharedNotesFolder","agentConversationNotesFolder","agentTranscriptsFolder","processWorkingDirectory","artifactsFolder"];function cU(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 lU(e){const t=cU(e).replaceAll("\\","/");return/^[A-Za-z]:\/$/.test(t)?t.slice(0,-1):t}function uU(e){const t=cU(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 dU(e){const t=lU(e.value),r=e.roots.filter((e=>e.host.length>0)).sort(((e,t)=>lU(t.host).length-lU(e.host).length));for(const e of r){const r=lU(e.host);if(t===r)return uU({reportedWorkspacePath:e.reported,suffix:""});const n="/"===r?"/":`${r}/`;if(t.startsWith(n)){const n="/"===r?t:t.slice(r.length);return uU({reportedWorkspacePath:e.reported,suffix:n})}}}const hU={powershellUtf8Console:!1,powershellUtf8ChildEnv:!1};class pU extends vM{constructor(e,t){super(e),this.sessionMcpLease=t}async dispose(){try{await super.dispose()}finally{await vL(this.sessionMcpLease)}}}function fU(e){const t=new Hw;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 iU,s=r.workspaceServices.subagentsService??new Wm,i=r.workspaceServices.mcpLease??new vR,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 vR:void 0:void 0,l=(u=c??i,0===(d=r.options.extraMcpTools??[]).length?u:"onDidChange"in(h=u)&&"function"==typeof h.onDidChange?new dw(u,d):new uw(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 hU;try{const t=await e();return{powershellUtf8Console:t.powershellUtf8Console,powershellUtf8ChildEnv:t.powershellUtf8ChildEnv}}catch{return hU}}(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,r.options),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 vM(u):new pU(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=>dU({value:e,roots:o})??e));for(const e of aU){const t=n[e];if(void 0===t||""===t)continue;const r=dU({value:t,roots:o});n[e]="processWorkingDirectory"===e&&void 0!==s?r??cU(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 vL(c),e}}}}const mU=["cursorRulesService","getAgentSkills","subagentsService"],gU=new WeakSet;function wU(e){("object"==typeof e&&null!==e||"function"==typeof e)&&gU.add(e)}function yU(e){return("object"==typeof e&&null!==e||"function"==typeof e)&&gU.has(e)}function vU(e,t){const r=Object.keys(t).filter((e=>!mU.includes(e)));if(r.length>0)throw new Error(`Workspace service contributors may only provide ${mU.join(", ")}. Received unsupported service keys: ${r.join(", ")}.`);for(const r of mU)Object.hasOwn(t,r)&&(e[r]=t[r])}async function bU(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&&(wU(s.cursorRulesService),wU(s.subagentsService),Object.assign(n,s));for(const t of e.workspaceServicesContributors??[]){const e=await t.contributeServices(o());void 0!==e&&vU(n,e)}return n}catch(t){try{await SU(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 SU(e,t){const r=t?.preserveSharedContributorsFrom;let n;const o=async e=>{try{await vL(e)}catch(e){n??=e}};if(e.subagentsService===r?.subagentsService||yU(e.subagentsService)||await o(e.subagentsService),e.cursorRulesService===r?.cursorRulesService||yU(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 vL(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 kU=["project","user","team","mdm","plugins"],_U=new Set([...kU,"all"]);function CU(e){if(void 0===e||0===e.length)return xU([]);for(const t of e)if(!_U.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{...xU(kU),all:!0}}return xU(e.filter((e=>"all"!==e)))}function EU(e,t){return e[t]}function xU(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 PU=Object.freeze({}),RU=Object.freeze({allowMcpServers:!0,allowPlugins:!0,allowBackgroundSessions:!0,requireMcpApproval:!1,maxParallelSessions:void 0,sandboxMode:void 0,metadata:PU});async function IU(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 vL(o)}catch(e){r??=e}}}if(void 0!==r)throw r}async function TU(e={}){const t=function(e={}){return{workspace:e.workspace??CD,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({...RU.metadata,...e.metadata}),r={...RU,...e,metadata:t};return{name:"permissive-sdk-local",resolvePolicy:()=>r}}(),{workspaceState:r});let o=await bU(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 IU(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 IU(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 bU(t,r,n);s?await SU(i,{disposeLocalExtensibility:l}):(o=i,await SU(e,{preserveSharedContributorsFrom:i,disposeLocalExtensibility:l}),await(t.lifecycle?.onWorkspaceReload?.(r)))}))},async dispose(){s||(s=!0,await a((async()=>{try{await SU(o,{disposeLocalExtensibility:l})}finally{await(t.lifecycle?.dispose())}})))}}}class AU{async requestApproval(e){return{approved:!0}}}class $U{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 MU{async open(e,t){}async getDiagnostics(e,t){return[]}}class DU{async getCodebaseReference(e,t){}}class OU{constructor(e,t){this.inner=e,this.allowlistReports=t}async getState(e){const t=await this.inner.getState(e);return await this.reportAllowlists(e),{...t,servers:t.servers.filter((e=>"needsAuth"!==e.status))}}async reportAllowlists(e){if(void 0===this.allowlistReports)return;const{mcpLease:t,onMcpAllowlistInUse:r,onMcpServerBlockedByAllowlist:n}=this.allowlistReports;let o;try{o=await t.getClients(e)}catch(e){return void PD.Jz.warn("[sdk-mcp-state] Could not read the MCP allowlist in use:",e)}for(const[e,t]of Object.entries(o))try{if(void 0!==r){const n=await(t.getAllowlistInUse?.());void 0!==n&&r({serverName:e,allowlist:n})}if(void 0!==n){const r=await(t.getAllowlistRefusal?.());void 0!==r&&n({serverName:e,refusal:r})}}catch(e){PD.Jz.warn("[sdk-mcp-state] Could not read the MCP allowlist in use:",e)}}}class FU{constructor(e){this.subagents=e.map((e=>new Um.zz({fullPath:`sdk-inline://${e.name}`,name:e.name,description:e.description,tools:[],model:e.model,prompt:e.prompt,permissionMode:Um.b$.DEFAULT,isBackground:!1,source:"sdk"})))}async getAllSubagents(){return this.subagents}async reload(){return this.subagents}}class NU{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 LU(e){return"string"==typeof e&&e.trim().length>0}function jU(e,t){return new he.jn({command:t.command??"",workingDirectory:t.workingDirectory??"",error:e,isReadonly:!0})}function UU(e){return{execute:async(t,r)=>new ZR.v3({result:{case:"permissionDenied",value:new ZR.U7({path:r.path,error:e,isReadonly:!0})}})}}function BU(e){return{execute:async(t,r)=>new sw.Pi({result:{case:"permissionDenied",value:new sw.QG({path:r.path,clientVisibleError:e,isReadonly:!0})}})}}function WU(e){return{execute:async(t,r)=>new xc.iz({result:{case:"permissionDenied",value:new xc.HQ({error:`${e} Tool: ${r.name}`,isReadonly:!0})}})}}var HU=r("../agent-kv/dist/subagent-states.js");let qU;function zU(e){const t=process.env.CURSOR_DATA_DIR;if(t?.trim())return yo(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,go.r_)(e.workspacePath)):void 0!==e.homeDir&&function(e){if(""===e.trim())return!1;try{return!!(0,So.statSync)(e).isDirectory()&&((0,So.accessSync)(e,So.constants.W_OK),!0)}catch{return!1}}(e.homeDir)?(0,s.join)(e.homeDir,".cursor","projects",(0,go.r_)(e.workspacePath)):(0,s.join)(e.ensureFallbackRoot(e.tempDir),(0,go.r_)(e.workspacePath))}({workspacePath:e,homeDir:r,tempDir:(0,o.tmpdir)(),ensureFallbackRoot:e=>(void 0===qU&&(qU=function(e){return(0,So.mkdtempSync)((0,s.join)(e,"cursor-transcripts-"))}(e)),qU)})}async function GU(e,t){const r=(0,s.dirname)(e);await(0,vo.mkdir)(r,{recursive:!0}),await(0,vo.writeFile)(e,t,"utf-8")}class VU{constructor(e){this.writeChain=Promise.resolve(),this.workspacePath=e.workspacePath,this.conversationId=e.conversationId,this.parentConversationId=e.parentConversationId,this.blobStore=e.blobStore,this.projectDir=zU(this.workspacePath);const t=this.parentConversationId?(e,t)=>{const r=LO({conversationId:e,ext:t,kind:"subagent",parentConversationId:this.parentConversationId});return(0,s.join)(this.projectDir,r)}:void 0;this.transcriptStore=new fF(this.projectDir,e.blobStore,GU,{writeText:!1,writeJsonl:!0,...t?{pathResolver:t}:{}}),this.nestedSubagentTranscriptStore=new fF(this.projectDir,e.blobStore,GU,{writeText:!1,writeJsonl:!0,pathResolver:(e,t)=>{const r=LO({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){PD.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,HU.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=LO({conversationId:this.conversationId,ext:"jsonl",kind:"subagent",parentConversationId:this.parentConversationId});return(0,s.join)(this.projectDir,e)}return function(e,t){const r=LO({conversationId:t,ext:"jsonl",kind:"primary"});return(0,s.join)(zU(e),r)}(this.workspacePath,this.conversationId)}getProjectDir(){return this.projectDir}}const KU=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,JU="User aborted/interrupted manually.";class ZU{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.childLineageRequestIds=new Map,this.untrackedParentRequestIds=new Map,this.agentClient=e.agentClient,this.getResources=e.getResources,this.mcpTools=e.mcpTools??[],this.workspacePath=e.workspacePath,this.parentConversationId=e.parentConversationId;const t=e.rootRequestId?.trim();this.rootLineageRequestId=void 0!==t&&t.length>0?t:(0,ge.C)(),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 NU}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(!KU.test(e))throw new Error(`Invalid resumeAgentId format: ${e}`)}(r),r&&!t.prompt)return r;if(r&&LU(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,RD.sh)(e),n=new RD.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 VU({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:Um.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:Um.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 to.a3({status:to.jh.ACCEPTED}):new to.a3({status:to.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){PD.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 to.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 to.Pw({...r,runInBackground:!1}):new to.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}lineageForChildRun(e){this.childLineageRequestIds.has(e.agentId)||this.childLineageRequestIds.set(e.agentId,(0,ge.C)());const t=e.parentConversationId?.trim()??"",r=e.toolCallId.trim();return{parentRequestId:""===t||t===this.parentConversationId?this.rootLineageRequestId:this.childLineageRequestIds.get(t)??this.untrackedParentRequestId(t),rootParentRequestId:this.rootLineageRequestId,...r.length>0?{parentAgentToolCallId:r}:{}}}untrackedParentRequestId(e){let t=this.untrackedParentRequestIds.get(e);return void 0===t&&(t=(0,ge.C)(),this.untrackedParentRequestIds.set(e,t)),t}async executeSubagentOnce(e,t,r,n){const o=this.lineageForChildRun({agentId:t,parentConversationId:r.parentConversationId,toolCallId:r.toolCallId});let s,a=0;const c=new i.QFf({action:{case:"userMessageAction",value:new i.Vtf({userMessage:new i.RGk({text:r.prompt})})}}),l=new i.Gmx({modelId:r.modelId,displayModelId:r.modelId,displayName:r.modelId});void 0!==r.credentials.case&&(l.credentials=r.credentials);const u=new xD,d={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&&a++,"textDelta"===r.message.case&&(s=(s??"")+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)},h={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(),p=r.parentConversationId?.trim(),f=void 0!==i&&""!==i?i:void 0!==p&&""!==p?p:t,m=await this.getResources({agentId:t,parentAgentId:r.parentConversationId}),g=r.readonly?new J(m,function(e){const t=[G(iT,UU(e.errorMessage)),G(aT,BU(e.errorMessage)),G(Xn,WU(e.errorMessage))];return e.wrapShell&&t.push(G(rT,function(e){return{execute:async(t,r)=>new he.W4({result:{case:"permissionDenied",value:jU(e,r)}})}}(e.errorMessage)),G(ee,function(e){return{async*execute(t,r){yield new he.FI({event:{case:"permissionDenied",value:jU(e,r)}})}}}(e.errorMessage)),G(FT,function(e){return{execute:async(t,r)=>new Io.Lt({result:{case:"permissionDenied",value:jU(e,r)}})}}(e.errorMessage))),e.includeWriteBackgroundShellStdin&&t.push(G(NT,function(e){return{execute:async(t,r)=>new Io.nt({result:{case:"error",value:new Io.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})):m;return await this.agentClient.run(e,n.agentStore.getConversationStateStructure(),c,l,d,g,n.agentStore.getBlobStore(),u,h,[...this.mcpTools],{conversationGroupId:f,conversationId:t,...n.transcriptWriter.parentConversationId?{transcriptParentConversationId:n.transcriptWriter.parentConversationId}:{},subagentTypeName:r.subagentType||void 0,...o,headers:TD(n.agentStore.getMetadata("blobEncryptionKey"),this.headers),endlessRetries:this.endlessRetries,subagentModelOverrides:[]}),await n.transcriptWriter.writeTurnEndedFromState(e,n.agentStore.getConversationStateStructure(),e.signal.aborted?{status:"aborted",error:JU}:{status:"success"}),{status:"completed",finalMessage:s,toolCallCount:a}}catch(r){const o=r instanceof Error?r.message:String(r);return PD.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:JU}:{status:"error",error:o}}}getTurnEndedFromError(e,t){return e.signal.aborted?{status:"aborted",error:JU}:{status:"error",error:t}}isAwaitBackgroundMode(e){if(!Boolean(e.resumeAgentId&&!LU(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 to.zJ({result:{case:"stillRunning",value:new to.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 to.zJ({result:{case:"complete",value:new to.bE({agentId:r,finalMessage:e.finalMessage,toolCallCount:e.toolCallCount??0})}}):new to.zJ({result:{case:"error",value:new to.Y({agentId:r,error:e.finalMessage||"Subagent was aborted"})}}):this.isBackgroundRunBusy(r)?new to.zJ({result:{case:"stillRunning",value:new to.L5({agentId:r})}}):new to.zJ({result:{case:"notFound",value:new to.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 to.zJ({result:{case:"stillRunning",value:new to.L5({agentId:r})}}):(this.takeQueuedChildCompletion(r,n.runId),"completed"===i.status?new to.zJ({result:{case:"complete",value:new to.bE({agentId:r,finalMessage:i.finalMessage,toolCallCount:i.toolCallCount??0})}}):new to.zJ({result:{case:"error",value:new to.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 XU=r("../proto/dist/generated/agent/v1/agent_service_connect.js"),QU=r("../proto/dist/generated/agent/v1/requested_model_pb.js"),YU=r("../proto/dist/generated/agent/v1/selected_context_pb.js"),eB=r("./src/agent/analytics.ts"),tB=r("../proto/dist/generated/agent/v1/todo_tool_pb.js");const rB={[rg.w3.UNSPECIFIED]:"unspecified",[rg.w3.LEFT]:"left",[rg.w3.RIGHT]:"right",[rg.w3.MIDDLE]:"middle",[rg.w3.BACK]:"back",[rg.w3.FORWARD]:"forward"},nB={[rg.Dh.UNSPECIFIED]:"unspecified",[rg.Dh.UP]:"up",[rg.Dh.DOWN]:"down",[rg.Dh.LEFT]:"left",[rg.Dh.RIGHT]:"right"},oB={[rg.EB.UNSPECIFIED]:"unspecified",[rg.EB.TAP]:"tap",[rg.EB.DOWN]:"down",[rg.EB.UP]:"up"};function sB(e){return rB[e]??"unspecified"}function iB(e){return void 0===e?void 0:{x:e.x,y:e.y}}function aB({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:iB(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 cB(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 lB("tool-call-started",e.message.value);case"partialToolCall":return lB("partial-tool-call",e.message.value);case"toolCallCompleted":return lB("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=cB(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 lB(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:mB(r)}:{}}:null}case"deleteToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"delete",args:{path:t.path},...r?{result:gB(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:wB(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:yB(r)}:{}}:null}case"readToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"read",args:{path:t.path},...r?{result:bB(r)}:{}}:null}case"editToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"edit",args:{path:t.path},...r?{result:SB(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:kB(r)}:{}}:null}case"readLintsToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"readLints",args:{paths:t.paths},...r?{result:CB(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:EB(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:PB(r)}:{}}:null}case"recordScreenToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"recordScreen",args:{mode:RB(t.mode)},...r?{result:IB(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:xB(r)}:{}}:null}case"createPlanToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"createPlan",args:{plan:t.plan},...r?{result:TB(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:$B(e.status)})))},...r?{result:AB(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:iB(e.value.coordinate)};case"click":return{type:"click",coordinate:iB(e.value.coordinate),button:sB(e.value.button),count:e.value.count,modifierKeys:e.value.modifierKeys};case"mouseDown":case"mouseUp":return{type:e.case,button:sB(e.value.button)};case"drag":return{type:"drag",path:e.value.path.map((e=>({x:e.x,y:e.y}))),button:sB(e.value.button),modifierKeys:e.value.modifierKeys};case"scroll":return{type:"scroll",coordinate:iB(e.value.coordinate),direction:nB[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:oB[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?aB(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:uB(t),...r?{result:pB(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 uB(e){return{description:e.description??"",prompt:e.prompt??"",...e.subagentType?{subagentType:dB(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:hB(e.mode)}:{},...e.respondingToMessageIds&&e.respondingToMessageIds.length>0?{respondingToMessageIds:e.respondingToMessageIds}:{}}}function dB(e){const t=e.type.case;return t?"custom"===t?{kind:t,name:e.type.value.name}:{kind:t}:{kind:"unspecified"}}function hB(e){switch(e){case Um.FL.AGENT:return"agent";case Um.FL.PLAN:return"plan";default:return"unspecified"}}function pB(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:fB(t.backgroundReason),...t.transcriptPath?{transcriptPath:t.transcriptPath}:{}}}}case"error":return{status:"error",error:{message:e.result.value.error??"Task failed"}};default:return}}function fB(e){switch(e){case Um.qL.AGENT_REQUEST:return"agentRequest";case Um.qL.USER_REQUEST:return"userRequest";case Um.qL.QUEUED_FOLLOW_UP:return"queuedFollowUp";default:return"unspecified"}}function mB(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 gB(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 wB(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 yB(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]=vB(n);return{status:"success",value:{...Object.keys(r).length>0?{workspaceResults:r}:{},...t.activeEditorResult?{activeEditorResult:vB(t.activeEditorResult)}:{}}}}return{status:"error",error:{message:e.result.value.error??e.result.case}}}}function vB(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 bB(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 SB(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 kB(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{directoryTreeRoot:_B(e.result.value.directoryTreeRoot)}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function _B(e){if(e)return{absPath:e.absPath??"",childrenDirs:e.childrenDirs?.map(_B)??[],childrenFiles:e.childrenFiles?.map((e=>({name:e.name})))??[],childrenWereProcessed:e.childrenWereProcessed??!1,fullSubtreeExtensionCounts:e.fullSubtreeExtensionCounts??{},numFiles:e.numFiles??0}}function CB(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:MB(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 EB(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 xB(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 PB(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 RB(e){switch(e){case HA.$u.START_RECORDING:return"START_RECORDING";case HA.$u.SAVE_RECORDING:return"SAVE_RECORDING";case HA.$u.DISCARD_RECORDING:return"DISCARD_RECORDING";default:throw new Error(`Unknown RecordingMode: ${e}`)}}function IB(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 TB(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 AB(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{todos:e.result.value.todos?.map((e=>({content:e.content,status:$B(e.status)})))??[],totalCount:e.result.value.totalCount??0}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function $B(e){switch(e){case tB.Vj.UNSPECIFIED:case tB.Vj.PENDING:return"pending";case tB.Vj.IN_PROGRESS:return"inProgress";case tB.Vj.COMPLETED:return"completed";case tB.Vj.CANCELLED:return"cancelled";default:return"pending"}}function MB(e){switch(e){case ZT.h_.UNSPECIFIED:case ZT.h_.ERROR:return"error";case ZT.h_.WARNING:return"warning";case ZT.h_.INFORMATION:return"information";case ZT.h_.HINT:return"hint";default:return"error"}}const DB={type:"object",properties:{},additionalProperties:!0};function OB(e){const t={};for(const[r,n]of Object.entries(e))t[r]=n;return t}function FB(e){return"text"===e.type?new xc._Z({content:{case:"text",value:new xc.zN({text:e.text})}}):new xc._Z({content:{case:"image",value:new xc.do({data:n.Buffer.from(e.data,"base64"),mimeType:e.mimeType??""})}})}function NB(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var LB=r("./src/agent/errors.ts");const jB="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 UB(e){return{async execute(){throw new Error(e)}}}function BB(e){var t;e.register(rT,UB(jB)),e.register(ee,(t=jB,{async*execute(){throw new Error(t)}})),e.register(FT,UB(jB)),e.register(WT,UB(jB)),e.register(NT,UB(jB)),e.register(nT,UB(jB)),e.register(yT,UB("ReadLints is not available when local.fs is set: lint diagnostics come from a host language service, not the FileSystem.")),e.register(lT,UB("Git is not available when local.fs is set: the agent's files live in a FileSystem, not a host git checkout."))}var WB=r("./src/agent/filesystem/executors.ts"),HB=r("./src/agent/filesystem/compose.ts"),qB=r("./src/agent/filesystem/trees.ts"),zB=r("./src/agent/filesystem/walk.ts");const GB="/tmp",VB=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.txt$/i;function KB(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,zB.eI)(e.hostProjectDir),r=(0,zB.eI)(e.writePath);return"/"!==t&&(0,zB.hJ)({path:r,prefix:t})?r.slice(t.length):void 0}(e),n=void 0===r?(0,zB.eI)(e.writePath):(0,zB.eI)(`${GB}/${r}`);if(!(0,zB.hJ)({path:n,prefix:GB}))return;const o=s.default.posix.basename(n),i=s.default.posix.join(GB,Pc);return s.default.posix.dirname(n)===i&&VB.test(o)?s.default.posix.join(GB,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 JB{constructor(e,t="/"){this.fs=e,this.listeners=new Set,this.workspace=(0,zB.eI)(t)}getAllCursorRules(e){return this.rules??=async function(e,t){const[r,n]=await Promise.all([ZB(e,s.posix.join(t,".cursor/rules")),XB(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 ZB(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 QB(e,t),n=void 0===r?null:Xr(r);if(null!==n)return Mm({path:t,body:n.body,frontmatter:n.frontmatter,rawFrontmatter:n.rawFrontmatter})}),{max:8})).filter((e=>void 0!==e))}async function XB(e,t){const r=await QB(e,t);if(void 0!==r)return Mm({path:t,body:Jr({content:r,filename:"AGENTS.md"}),frontmatter:{alwaysApply:!0}})}async function QB(e,t){try{const r=await e.read(t);return"string"==typeof r?r:(new TextDecoder).decode(r)}catch{return}}const YB={getAllCursorRules:async()=>[],reload(){},onDidChangeRules:()=>()=>{},dispose(){}},eW={async exec(){throw new Error("git is not available in a FileSystem session")}},tW={isIgnoredByAny:async()=>!1,isGitIgnored:async()=>!1,isCursorIgnored:async()=>!1,isRepoBlocked:async()=>!1,listCursorIgnoreFilesByRoot:async()=>[],getCursorIgnoreMapping:async()=>({}),getShellSandboxIgnoreMapping:async()=>({}),getGitIgnoreMapping:async()=>({}),getRepoBlockExcludeGlobs:async()=>[]};function rW(e){return{cursorRulesService:!0===e.includeProjectRules?new JB(e.fs,e.workspace):YB,getAgentSkills:async()=>[],subagentsService:e.subagentsService??new Wm,gitExecutor:eW,ignoreService:tW,requestContextIsWorkingDirHomeDir:!1,reportProcessWorkingDirectory:!1}}function nW(e,t){const r=t.workspace??"/",n=(0,WB.c9)(e,{workspace:r});return{localResourceProviderOptions:{overrideReadExecutor:n.read,overrideWriteExecutor:KB({write:n.write,hostProjectDir:t.hostProjectDir}),overrideGrepExecutor:n.grep,overrideLsExecutor:n.ls,overrideDeleteExecutor:n.delete,suppressDefaultShellExecutor:!0,...rW({...t.settings,fs:e,workspace:r})},reportedWorkspacePath:r,reportedProjectFolder:GB,excludeHooks:!0,excludeProjectMcp:!0}}var oW=r("./src/agent/executor-common.ts");class sW{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}}class iW{constructor(e=e=>{console.warn(e)}){this.write=e,this.printed=new Set,this.report=e=>{if(!this.printed.has(e.serverName)){this.printed.add(e.serverName);try{this.write(function(e){return`[cursor-sdk] ${e.refusal}`}(e))}catch{}}}}}const aW=new class{constructor(e=e=>{console.warn(e)}){this.write=e,this.printed=new Set,this.report=e=>{const t=JSON.stringify([e.serverName,(r=e.allowlist,JSON.stringify([r.list,r.name,r.reason,r.allowedServers??null,r.blockedServers??null]))]);var r;if(!this.printed.has(t)){this.printed.size>=1e3&&this.printed.clear(),this.printed.add(t);try{this.write(function(e){return`[cursor-sdk] MCP server "${e.serverName}" is under ${function(e){return`${e.name}, which applies because ${e.reason}.${r=e.allowedServers,void 0===r?"":0===r.length?" Allowed servers: none.":iC("Allowed servers",r)}${t=e.blockedServers,void 0===t||0===t.length?"":iC("Blocked",t)}`;var t,r}(e.allowlist)}`}(e))}catch{}}}}};var cW=r("./src/agent/native/vendored-tree-sitter.ts"),lW=r("./src/agent/platform-package-locator.ts"),uW=r("./src/agent/sdk-config.ts"),dW=r("../../node_modules/.pnpm/@statsig+js-client@3.31.0/node_modules/@statsig/js-client/src/index.js"),hW=r("./src/agent/utils/logger.ts");const pW={checkFeatureGate:()=>!1,getDynamicConfigValue:({defaultValue:e})=>e},fW=new Map;async function mW(e){try{const t=await async function(e){const t=await(0,oW.dC)(e,oW.EV);if(!t)return;const r=oW.EV.endsWith("/")?oW.EV.slice(0,-1):oW.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,oW.tF)(),"x-ghost-mode":(0,oW.U)(e)},body:JSON.stringify({})});if(!n.ok)return void hW.v.log(`Failed to bootstrap SDK Statsig: ${n.status} ${n.statusText}`);const o=await n.json();return gW(o)&&"string"==typeof o.config&&o.config.length>0?o.config:void 0}(e);if(!t)return pW;const r=new dW.StatsigClient("client-Bm4HJ0aDjXHQVsoACMREyLNxm5p6zzuzhO50MgtoT5D",function(e){try{const r=JSON.parse(e);if(gW(r)&&"object"==typeof(t=r.user)&&null!==t&&!Array.isArray(t))return{...r.user,custom:{...r.user.custom,clientType:"sdk",clientVersion:(0,oW.tF)()}}}catch(e){hW.v.log(`Failed to parse SDK Statsig bootstrap user: ${e instanceof Error?e.message:String(e)}`)}var t;return{custom:{clientType:"sdk",clientVersion:(0,oW.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 hW.v.log(`Failed to initialize SDK Statsig: ${e instanceof Error?e.message:String(e)}`),pW}}function gW(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function wW(e){let t;return e?.then((e=>{t=e}),(()=>{})),()=>t?.checkFeatureGate("grok_bot_mcp_app_payment_token_filter",{disableExposureLog:!0})??!1}var yW=r("./src/agent/tools-option.ts");class vW{async requestApproval(){return{approved:!0}}}function bW(e,t){if(!function(e){return void 0!==e&&Object.keys(e).length>0}(t))return;const r=e.resources.base;if(!(r instanceof vM))throw new LB.j1("SDK custom tools require the default local workspace resource provider.",{isRetryable:!1});const n=r.getMcpExecutionPolicyDeps(),o=r.get(Xn),s=function(e,t){return{async execute(r,n,o){const s=n.toolName||function(e){const t=`${Wn}-`;return e.startsWith(t)?e.slice(t.length):e}(n.name),i=e[s];if(void 0===i)return new xc.iz({result:{case:"error",value:new xc.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:NB(e)?e:void 0};var t}(e),r=void 0!==t.structuredContent?we.Struct.fromJson(t.structuredContent):void 0;return new xc.iz({result:{case:"success",value:new xc.QW({content:t.content.map(FB),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 xc.iz({result:{case:"error",value:new xc.Nh({error:e instanceof Error?e.message:String(e)})}})}}}}(t,e.state.sessionId),i=new vW;e.resources.base.register(Xn,{async execute(e,t,r){if(function(e){return e.providerIdentifier===Wn}(t)){const o=await WI(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 SW=new Set(["127.0.0.1","localhost","[::1]"]);function kW(e){if(void 0===e)return{};const t=e.resourceProviderOptions;return{...void 0!==t?{localResourceProviderOptions:t}:{},...void 0!==e.reportedWorkspacePath?{reportedWorkspacePath:e.reportedWorkspacePath}:{}}}function _W(){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 CW={warn(){},error(){}},EW={log(){}};class xW{async requestApproval(e){return{approved:!1,reason:`Local SDK runs cannot request interactive approval for ${PW(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 PW(e){switch(e.type){case ow.Shell:return"this shell command";case ow.Mcp:return"this MCP tool call";case ow.Write:return"this file edit";case ow.Delete:return"this file deletion";default:return"this operation"}}function RW(e){return void 0!==e&&"insecure_none"!==e.type}async function IW(e,t){const r="string"==typeof e||void 0===e?{workingDirectory:e,apiKey:t}:e,a=(0,y.q6)().with(l._O,EW),c=CU(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&&SW.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}`);pa=e}((0,uW.Mu)()),/:\/\/(localhost|127\.0\.0\.1)/.test(oW.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,oW.ly)(r.apiKey),(0,oW.mU)(r.apiKey)]),h=performance.now()-e}const p=r.workingDirectory||process.cwd();(0,cW.configureVendoredTreeSitterWorkspaceDir)(p);for(const e of r.dirs??[])(0,cW.configureVendoredTreeSitterWorkspaceDir)(e);const f=(0,go.Rv)((0,o.homedir)(),p),m={hostProjectDir:f,settings:{includeProjectRules:EU(c,"project"),subagentsService:new FU(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,lW.hQ)({binaryName:w,excludedWorkspaceDir:p}),g||(g=(0,To.xS)()),g&&(0,To.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,oW.KU)(r.apiKey,r.teamId);const e=(0,ye.createClient)(yL.I,b),t=function(e){let t=fW.get(e);return t||(t=mW(e),fW.set(e,t),t.then((r=>{r===pW&&fW.get(e)===t&&fW.delete(e)}),(()=>{fW.get(e)===t&&fW.delete(e)}))),t}(r.apiKey);S=t;const n={getDefaultNetworkAllowlist:async()=>(await t).getDynamicConfigValue({configName:"sandbox_default_network_allowlist",paramName:"allowlist",defaultValue:[]})};k=new kD(new vD(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){hW.v.log(`Failed to initialize authenticated dashboard services: ${e instanceof Error?e.message:String(e)}`)}const _=performance.now(),C=r.apiKey?await(0,To.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=RW(r)?r:!0===n?.enabled?function(e,t={}){return{type:e,...t}}("workspace_readwrite",{networkPolicy:(0,To.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,lW.hQ)({binaryName:t,excludedWorkspaceDir:e});r&&(0,To.St)({sandboxBinaryPath:r})}(t),!(0,To.K3)(void 0,{ctx:e.initializationCtx}))throw new LB.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,To.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,R=E?.defaultSandboxPolicySources,I=RW(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=CU(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,To.K3)(c,{ctx:e.initializationCtx})),u=e.getSandboxEnabled??(()=>"insecure_none"!==c.type&&l()),d=new Hw,h=new Sc(d,a,n),p=new MU,f=new DU,m=e.getSmartModeClassifierAutoModeEnabled?.(),g=new $U(m?"allowlist":e.approvalMode??"unrestricted",c,a,e.respectAdminControls??!1),w=e.pendingDecisionProvider,y={executeIndexedGrep:void 0},v=()=>!0,b=EU(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=_||EU(i,"project")||EU(i,"user")||b,x=EU(i,"project")||EU(i,"user")||EU(i,"mdm"),P=EU(i,"team"),R=P&&void 0!==e.dashboardTransport,I=EU(i,"project")||EU(i,"user")||P||R||b,T={teamSettingsService:a,initializationCtx:e.initializationCtx,importThirdPartyPlugins:S,ignoreApprovals:!0,includeProjectMcp:EU(i,"project"),includeUserMcp:EU(i,"user"),includePluginMcp:b,isLinkSharedPaymentTokenLogRedactionEnabled:e.isLinkSharedPaymentTokenLogRedactionEnabled},A=s=>TU({workingDirectory:t,...void 0!==o?{workspaceRoots:o}:{},adapters:{...s.includeMcp?{mcp:XD({...T,inlineMcpServers:e.mcpServers})}:{},...b?{pluginBootstrap:oU({importThirdPartyPlugins:S,dashboardTransport:e.dashboardTransport})}:{},...x?{hooks:wL({includeProjectHooks:EU(i,"project"),includeUserHooks:EU(i,"user"),includeEnterpriseHooks:EU(i,"mdm"),useCommandHookStdinTransport:e.useCommandHookStdinTransport})}:{},...I?{localExtensibility:bL({includeProjectExtensibility:EU(i,"project"),includeUserExtensibility:EU(i,"user"),includeManagedSkills:R,includeTeamExtensibility:P,includePluginExtensibility:b,teamSettingsService:a,getThirdPartyExtensibilityEnabled:v,dashboardTransport:e.dashboardTransport,importThirdPartyPlugins:S})}:{},resourceFactory:fU({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,t)=>new OU(new y$(e),void 0===t?.onMcpAllowlistInUse&&void 0===t?.onMcpServerBlockedByAllowlist?void 0:{mcpLease:e,onMcpAllowlistInUse:t.onMcpAllowlistInUse,onMcpServerBlockedByAllowlist:t.onMcpServerBlockedByAllowlist}),createSessionMcpLease:(t,r)=>XD({...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 AU;return{pendingDecisionStore:n,fileChangeTracker:new aw(t),permissionsService:new bk(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 mL(new cL(e.resources,n.hookExecutor,(()=>function(e,t){const r=dL(t,hL,"conversationId","conversation_id")??e.sessionId??"";return{conversation_id:r,generation_id:dL(t,hL,"generationId","generation_id")??r,model:dL(t,hL,"model")??"unknown",...gO({modelId:dL(t,hL,"modelId","model_id"),modelParams:dL(t,fL,"modelParams","model_params")})}}(e.sessionState,e.metadata)),e.workspaceServices.mcpLease,void 0,void 0,t.hooksConfigLease),n)}}]:[],...C?{workspaceServicesContributors:[{contributeServices:t=>{const r=new FU(e.customSubagents??[]),n=t.services.subagentsService;return{subagentsService:void 0===n?r:new Zm([r,n])}}}]}:{}}});if(!E)return A({includeMcp:!1});try{return await A({includeMcp:!0})}catch(e){return PD.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:R,approvalMode:I?"allowlist":void 0,pendingDecisionProvider:I||!0===r.autoReview?new xW:void 0,getNetworkAllowlistInfo:I?()=>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,To.tv)(i,t);if(a&&"insecure_none"!==a.type&&a.networkPolicy?.allow&&s.push(...a.networkPolicy.allow),"1"!==process.env[gv.K4]&&r){const e=await(0,To.tv)(`${r}/.cursor/sandbox.json`,r);e&&"insecure_none"!==e.type&&e.networkPolicy?.allow&&s.push(...e.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:_W,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:wW(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,eB.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,PD.ni)(CW,(async()=>{const s=(0,$.VI)((0,y.q6)().withName("sdk.run").with(l._O,EW)),[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:Wn,providerIdentifier:Wn,toolName:e,name:`${Wn}-${e}`,description:t.description??"",inputSchema:t.inputSchema??DB,...void 0===t.outputSchema?{}:{outputSchema:t.outputSchema},...void 0===t.annotations?{}:{annotations:OB(t.annotations)},source:"internal"})));var f;let g;const w={...m,workspace:t.fileSystemWorkspace},v=void 0===t.fileSystem?void 0:(_=await async function(e,t){return"function"==typeof e?await e(t):e}(t.fileSystem,{agentId:u,sessionId:u}),C=_,(0,HB.VL)({"/":C,[GB]:(0,qB.Om)()})),b=void 0===t.onMcpAdminToolLimitCounts?void 0:new sW,S=()=>{for(const e of b?.take()??[])try{t.onMcpAdminToolLimitCounts?.(e)}catch{}},k=new iW;var _,C;g=await D.createSessionRuntime({sessionId:u,mcpServersOverride:d,extraMcpTools:h,onMcpAdminToolLimitCheck:b?.record,onMcpAllowlistInUse:aW.report,onMcpServerBlockedByAllowlist:k.report,...void 0===v?kW(t.sessionResources):nW(v,w)});const E=new Map;try{const s=g.resources.wrapped;bW(g,t.customTools),void 0!==v&&BB(g.resources.base);const l=t.blobStore??new re.ve;let f=t.initialState??new i.Y9z({});const m=void 0!==t.model?new QU.G4({modelId:t.model.id,...!0===t.model.maxMode?{maxMode:!0}:{},parameters:(t.model.params??[]).map((e=>new QU.SR({id:e.id,value:e.value})))}):void 0,y=!0===e.summarize?void 0:e.images,_=Array.isArray(y)?y.map((e=>{const t=(0,ge.C)(),r=new Uint8Array(n.Buffer.from(e.data,"base64")),o=(0,oW.v8)(r);return new YU.d({uuid:t,...o?{mimeType:o}:{},dataOrBlobId:{case:"data",value:r}})})):[],C=_.length>0?new YU.xv({selectedImages:_}):void 0,R=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:C,...void 0!==R?{mode:R}:{}})})}}),T={sendUpdate:async(e,t)=>{const r=cB(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 LB.j1("Missing interaction query type",{isRetryable:!1});default:throw e.query,new LB.j1("Unhandled interaction query type",{isRetryable:!1})}}(t)};if(N!==t.apiKey||!L){await Promise.all([(0,oW.ly)(t.apiKey),(0,oW.mU)(t.apiKey)]);const e=(0,oW.KU)(t.apiKey,r.teamId),n=fo((0,ye.createClient)(XU.N,e),{injectTraceHeaders:!0});L=new jn(n),N=t.apiKey}const A=(0,oW.Vh)(L,(()=>{const e=(0,oW.KU)(t.apiKey,r.teamId),n=fo((0,ye.createClient)(XU.N,e),{injectTraceHeaders:!0}),o=new jn(n);return L=o,N=t.apiKey,o})),$=function(e){return{...void 0!==e.allowedTools?{[yW.$$]:e.allowedTools.join(",")}:{},...void 0!==e.disallowedTools&&e.disallowedTools.length>0?{[yW.VJ]:e.disallowedTools.join(",")}:{}}}(t),M=new ZU({agentClient:A,rootRequestId:t.requestId,getResources:async({agentId:e})=>{let r=E.get(e);return r||(r=await D.createSessionRuntime({sessionId:e,mcpServersOverride:d,extraMcpTools:h,onMcpAdminToolLimitCheck:b?.record,onMcpAllowlistInUse:aW.report,onMcpServerBlockedByAllowlist:k.report,...void 0===v?kW(t.subagentInherit):nW(v,w)}),bW(r,t.customTools),void 0!==v&&BB(r.resources.base),r.resources.base.register(no,O),r.resources.base.register(oo,F),r.resources.base.register(so,j),E.set(e,r)),r.resources.wrapped},mcpTools:h,workspacePath:p,parentConversationId:u,...(void 0!==t.subagentInherit||void 0!==v)&&Object.keys($).length>0?{headers:$}:{},onSessionReleased:e=>{const t=E.get(e);t&&(t.dispose(),E.delete(e))}}),O=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 to.vS({result:{case:"error",value:new to.od({agentId:o,error:s.error})}}):"aborted"===s.status?new to.vS({result:{case:"error",value:new to.od({agentId:o,error:s.error??"Subagent was aborted by the user"})}}):"background"===s.status?new to.vS({result:{case:"success",value:new to.HJ({agentId:o,finalMessage:s.finalMessage,toolCallCount:s.toolCallCount??0,backgroundReason:s.backgroundReason,transcriptPath:s.transcriptPath})}}):new to.vS({result:{case:"success",value:new to.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 ro&&e.agentId||e&&"object"==typeof e&&"agentId"in e&&"string"==typeof e.agentId?e.agentId:void 0}(t)??r.resumeAgentId;return new to.vS({result:{case:"error",value:new to.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}}}(M),F=(P=M,{execute:(e,t)=>P.awaitBackgroundRunBounded(e,t)}),j=function(e){return{execute:async(t,r)=>e.forceBackgroundByToolCallId(r.toolCallId)}}(M);g.resources.base.register(no,O),g.resources.base.register(oo,F),g.resources.base.register(so,j);const U=D.services.hooksRuntime,B="object"==typeof(x=U)&&null!==x&&"workspacePath"in x&&"string"==typeof x.workspacePath&&"createSessionRuntime"in x&&"function"==typeof x.createSessionRuntime?U:void 0,W=void 0!==B&&void 0===v&&!0!==e.summarize?function(e){const{workspaceRuntime:t}=e;if(!(t.hooksConfigLease.hasHookForStep(fd.sessionStart)||t.hooksConfigLease.hasHookForStep(fd.sessionEnd)||t.hooksConfigLease.hasHookForStep(fd.stop)||t.hooksConfigLease.hasHookForStep(fd.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(fd.sessionStart))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...gO(e),is_background_agent:!1},r=await n.executeHookForStep(fd.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){PD.Jz.warn("[hooks-adapter] sessionStart hook failed:",e)}},async onSessionEnd(e,t){if(n.hasHooksForStep(fd.sessionEnd))try{const r={conversation_id:o?.conversationId??"",generation_id:o?.generationId??"",model:o?.model??"unknown",...o?gO(o):{},reason:e,duration_ms:t,is_background_agent:!1,final_status:e};await n.executeHookForStep(fd.sessionEnd,r)}catch(e){PD.Jz.warn("[hooks-adapter] sessionEnd hook failed:",e)}finally{n.clearSessionEnvironment()}else n.clearSessionEnvironment()},async onBeforeSubmitPrompt(e){if(n.hasHooksForStep(fd.beforeSubmitPrompt))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...gO(e),prompt:e.promptText??"",attachments:[]};await n.executeHookForStep(fd.beforeSubmitPrompt,t)}catch(e){PD.Jz.warn("[hooks-adapter] beforeSubmitPrompt hook failed:",e)}},async onTurnCompleted(e){if(!n.hasHooksForStep(fd.stop))return;const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...gO(e),status:"completed",loop_count:e.loopCount},r=await n.executeHookForStep(fd.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(fd.stop))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...gO(e),status:"error",loop_count:e.loopCount};await n.executeHookForStep(fd.stop,t)}catch(e){PD.Jz.warn("[hooks-adapter] onTurnError stop hook failed:",e)}},async onTurnAborted(e){if(n.hasHooksForStep(fd.stop))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...gO(e),status:"aborted",loop_count:e.loopCount};await n.executeHookForStep(fd.stop,t)}catch(e){PD.Jz.warn("[hooks-adapter] onTurnAborted stop hook failed:",e)}},async dispose(){await r.dispose()}}}({workspaceRuntime:B,sessionState:g.state,metadata:g.metadata}):void 0,H=new VU({workspacePath:p,conversationId:u,blobStore:l}),q=function(e,t,r){const{hooks:n}=r,[o,s]=e.withCancel(),a=new xD;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"),DD(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=TD(function(e,t){if((0,RD.TU)(t))return t;const r=AD.get(e);if(void 0!==r)return r;const n=(0,RD.sh)(e).blobEncryptionKey;if(void 0===n)throw new Error("getDefaultAgentMetadata did not seed a blobEncryptionKey");return AD.set(e,n),n}(r.conversationId,r.blobEncryptionKey),r.runOptions?.headers);return{done:(async()=>{const e=MD(r,0,$D(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;PD.Jz.warn("[agent-session-runner] sessionStart hook failed:",e)}let s=t,i=0;for(;s;){const e=MD(r,i,$D(s));try{await(n?.onBeforeSubmitPrompt?.(e))}catch(e){PD.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=OD(t)?"aborted":"error",FD("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=DD(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||OD(r)?"aborted":"error",FD("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){PD.Jz.warn("[agent-session-runner] sessionEnd hook failed:",e)}try{await(n?.dispose?.())}catch(e){PD.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"),PD.Jz.warn("[agent-session-runner] context injection failed:",e),"revert_to_followup"}}}}(a,I,{agentClient:A,interactionListener:T,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($).length>0?{headers:$}:{},...void 0!==t.systemPrompt?{customSystemPrompt:t.systemPrompt}:{}},hooks:W,async nextAction(e,t){const r=await M.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,H.writeFromState(a,e),await(t.onCheckpoint?.(e))}}),z=q.done.finally((async()=>{try{await M.awaitBackgroundWorkers()}finally{await H.waitForPendingWrites().catch((()=>{}));for(const e of E.values())try{await e.dispose()}catch(e){hW.v.log(`Failed to dispose subagent session runtime: ${e instanceof Error?e.message:String(e)}`)}E.clear();try{await g.dispose()}finally{S()}}})).catch((e=>{throw e}));return{abort(){q.abort(),c()},done:z,steer:e=>q.steer(e)}}catch(e){for(const e of E.values())try{await e.dispose()}catch{}E.clear();try{await g.dispose()}finally{S()}throw e}var x,P})),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)},"../constants/dist/commercial-cursor-hosts.js"(e,t,r){r.d(t,{H:()=>c,K4:()=>i,Zf:()=>a,ad:()=>l});const n=["cursor.sh","cursor.com","cursorapi.com","cursor.so","cursor-marketplace.com","cursorusercontent.com","anysphere.co"],o=["cursor.blob.core.windows.net"];function s(e){return e.trim().toLowerCase().replace(/\.+$/,"")}const i="CURSOR_ORBIT_BUILD",a="CURSOR_ORBIT_DEPLOYMENT_HOSTS";function c(e){return new Set((e??"").split(",").map(s).filter((e=>""!==e)))}function l(e,t){return function(e){const t=s(e);return o.includes(t)||n.some((e=>t===e||t.endsWith(`.${e}`)))}(e)&&!t.has(s(e))}},"../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:()=>R});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 R(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>=R&&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>=R&&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(I.has(e))return I.get(e);I.size>=R&&I.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 I.set(e,t),t}const R=2048,I=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>=R&&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:()=>Eo,Ls:()=>f,SandboxUnsupportedError:()=>_r,J:()=>x,St:()=>Er,Fn:()=>Co,Qw:()=>a,ue:()=>s,r5:()=>Ie,getLastSandboxFailureReason:()=>kr,oG:()=>no,Ko:()=>T,CG:()=>ht,W1:()=>Z,G6:()=>_o,dA:()=>He,_B:()=>Qe,OK:()=>Ze,$b:()=>Xe,K3:()=>Rr,tv:()=>st,wG:()=>vt,fZ:()=>bt,s9:()=>mt,XX:()=>yt,T6:()=>et,Po:()=>Ye,$6:()=>nt,l7:()=>it,xS:()=>E,resolveSandboxPolicyForWorkspace:()=>Ct,fB:()=>Dt,spawnInSandbox:()=>xr,Xw:()=>I});var n=r("node:child_process");new Set;const o=["SSH_CLIENT","SSH2_CLIENT"];function s(e){const t=e||process.env,{ELECTRON_RUN_AS_NODE:r,...n}=t;for(const e of Object.keys(n))e.startsWith("AGENT_HOST_DAEMON_")&&delete n[e];for(const e of o)delete n[e];return n}const i="NODE_COMPILE_CACHE";function a(e){const{[i]:t,...r}=e;return r.NODE_DISABLE_COMPILE_CACHE="1",r}const c=["SSH_AUTH_SOCK","DBUS_SESSION_BUS_ADDRESS","XDG_RUNTIME_DIR","WAYLAND_DISPLAY"];function l(e){const t={...e};for(const e of c)delete t[e];return t}const u=[["core.quotePath","false"]];function d(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 u)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 h,p=r("node:perf_hooks");!function(e){e[e.SampleIntervalMs=250]="SampleIntervalMs",e[e.EventLoopResolutionMs=20]="EventLoopResolutionMs"}(h||(h={})),p.monitorEventLoopDelay;const f="\n[This shell is producing too much output to stream. The command will still run.]\n";var m=r("node:path"),g=r("node:fs"),w=r("../utils/dist/lru-cache.js");const y="undefined"!=typeof process&&"win32"===process.platform,v=new w.q({max:512});function b(e){try{return g.statSync(e)}catch{return null}}function S(e,t){if(e.match(/[\\/]/))return e;const r=t?`${e}\0${t.source}\0${t.flags}`:e,n=v.get(r);if(void 0!==n)return n;const o=m.join(".",e);if(b(o))return v.set(r,o),o;const s=process.env.PATH.split(y?";":":");for(const n of s){const o=m.join(n,e);if(b(o)&&(!t||t.test(o)))return v.set(r,o),o}return v.set(r,e),e}function k(e,t,r){if("win32"!==process.platform)return{cmd:S(e),args:t};if(!g.existsSync(e)){const n=[".exe",".bat",".cmd",".ps1"],o=e.toLowerCase();if(n.some((e=>o.endsWith(e)))){const n=S(e,r);if(g.existsSync(n))return k(n,t,r)}for(const o of n){const n=S(`${e}${o}`,r);if(g.existsSync(n))return k(n,t,r)}}return e.match(/\.ps1$/i)?{cmd:m.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:m.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 _;const C=["/usr/local/bin","/usr/bin","/bin"];function E(){const e=k("rg",[]).cmd;return"rg"!==e?e:void 0}function x(e){if(!e)throw new Error("configureRipgrepPath: path must not be empty");_=e}function P(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 R(e,t){const r=(0,m.dirname)(t);if(!r||"."===r)return e;let n=function(e){const t=P(e);return void 0!==t?e[t]??"":""}(e).split(m.delimiter).filter(Boolean);return 0===n.length&&"win32"!==process.platform&&(n=C),function(e,t){const r=P(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(m.delimiter))}function I(e){return _&&(0,m.isAbsolute)(_)?{...R(e,_),CURSOR_RIPGREP_PATH:_}:e}function T(){if(!_)throw new Error("Ripgrep path not configured. Call configureRipgrepPath() at startup.");return _}const A="win32"===process.platform;function $(e){return!A&&!!e?.SUDO_ASKPASS}function M(e){return $(e)?"alias sudo='sudo -A'; ":""}function D(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 O(e,t){const r=t.toUpperCase();return Object.entries(e).some((([e,t])=>void 0!==t&&e.toUpperCase()===r))}const F=["PYTHONIOENCODING","PYTHONUTF8","PYTHONLEGACYWINDOWSSTDIO"];function N(e){F.some((t=>O(e,t)))||(e.PYTHONIOENCODING="utf-8:surrogateescape")}function L(e){O(e,"WSL_UTF8")||(e.WSL_UTF8="1")}const j="-Dsun.stdout.encoding=UTF-8 -Dsun.stderr.encoding=UTF-8 -Dstdout.encoding=UTF-8 -Dstderr.encoding=UTF-8",U=["sun.stdout.encoding","sun.stderr.encoding","stdout.encoding","stderr.encoding"],B=`case " \${MAVEN_OPTS-} \${JAVA_TOOL_OPTIONS-} \${JDK_JAVA_OPTIONS-} \${_JAVA_OPTIONS-} " in ${U.map((e=>`*[[:space:]]-D${e}=*`)).join("|")}) ;; *) builtin export MAVEN_OPTS="\${MAVEN_OPTS:+$MAVEN_OPTS }${j}";; esac; `,W=`if ("$env:MAVEN_OPTS $env:JAVA_TOOL_OPTIONS $env:JDK_JAVA_OPTIONS \${env:_JAVA_OPTIONS}" -cnotmatch '(^|\\s)-D(${U.map((e=>e.replace(/\./g,"\\."))).join("|")})=') {\n if ($env:MAVEN_OPTS) { $env:MAVEN_OPTS = "$env:MAVEN_OPTS ${j}" } else { $env:MAVEN_OPTS = '${j}' }\n}`;var H=r("node:crypto?8af2"),q=r("node:os"),z=r("../utils/dist/workspace-paths.js"),G=r("../utils/dist/test-resets.js");let V;function K(e,t){const r=(0,g.lstatSync)(e);return r.isDirectory()&&r.uid===t&&!(18&r.mode)}function J(e){try{(0,g.mkdirSync)(e,{mode:448})}catch(e){if(!(e instanceof Error&&"code"in e&&"EEXIST"===e.code))throw e}}function Z(e){return X(e,{create:!1})}function X(e,{create:t}){const r=process.getuid?.();if(void 0===r)return;const n=(0,m.join)((0,q.tmpdir)(),`cursor-sandbox-${(0,z.r_)((0,m.resolve)(e))}`);try{for(const e of[n,(0,m.join)(n,"tmp")])if(t&&J(e),!K(e,r))return;return n}catch{return}}(0,G.J)((function(){V=void 0}));const Q='builtin eval "${__CURSOR_SANDBOX_TEMP_RESTORE:-}" 2>/dev/null; ',Y=["TMPDIR","TMP","TEMP","TMPPREFIX","NODE_COMPILE_CACHE","NODE_DISABLE_COMPILE_CACHE"],ee="builtin export NODE_DISABLE_COMPILE_CACHE=1; builtin unset NODE_COMPILE_CACHE; ";function te(e){const t=(0,m.join)(e,"tmp");return{TMPDIR:t,TMP:t,TEMP:t,TMPPREFIX:(0,m.join)(t,"sh-")}}function re(e=(0,m.join)((0,q.tmpdir)(),"cursor-sandbox-cache",function(){return V||(V=(0,H.randomBytes)(16).toString("hex")),V}())){return{NPM_CONFIG_CACHE:(0,m.join)(e,"npm"),PNPM_STORE_PATH:(0,m.join)(e,"pnpm-store"),GOCACHE:(0,m.join)(e,"go-build"),GOMODCACHE:(0,m.join)(e,"go-mod"),CARGO_TARGET_DIR:(0,m.join)(e,"cargo-target"),PIP_CACHE_DIR:(0,m.join)(e,"pip"),UV_CACHE_DIR:(0,m.join)(e,"uv"),BUN_INSTALL_CACHE_DIR:(0,m.join)(e,"bun"),YARN_CACHE_FOLDER:(0,m.join)(e,"yarn"),npm_config_devdir:(0,m.join)(e,"node-gyp"),PLAYWRIGHT_BROWSERS_PATH:(0,m.join)(e,"playwright"),PUPPETEER_CACHE_DIR:(0,m.join)(e,"puppeteer"),TURBO_CACHE_DIR:(0,m.join)(e,"turbo"),GRADLE_USER_HOME:(0,m.join)(e,"gradle"),CONDA_PKGS_DIRS:(0,m.join)(e,"conda"),POETRY_CACHE_DIR:(0,m.join)(e,"poetry"),GEM_SPEC_CACHE:(0,m.join)(e,"gem-specs"),COMPOSER_HOME:(0,m.join)(e,"composer"),HOMEBREW_CACHE:(0,m.join)(e,"homebrew"),CYPRESS_CACHE_FOLDER:(0,m.join)(e,"cypress"),NX_CACHE_DIRECTORY:(0,m.join)(e,"nx"),NUGET_PACKAGES:(0,m.join)(e,"nuget"),CCACHE_DIR:(0,m.join)(e,"ccache"),CP_HOME_DIR:(0,m.join)(e,"cocoapods")}}var ne=r("node:fs/promises"),oe=r("../utils/dist/safe-spawn-cwd.js"),se=r("../../node_modules/.pnpm/ignore@7.0.5/node_modules/ignore/index.js");function ie(){const e=process.env.CURSOR_SANDBOX_POLICY_DIR?.trim();return e?m.resolve(e):m.resolve(m.join(q.homedir(),".cursor","sandbox-policies"))}let ae=0;function ce(){const e=ie();g.mkdirSync(e,{recursive:!0,mode:448});try{g.chmodSync(e,448)}catch{}const t=Date.now();return t-ae>=9e5&&(ae=t,function(e){let t;try{t=g.readdirSync(e)}catch{return}const r=Date.now();for(const n of t){if(!n.startsWith("sandbox-policy-"))continue;const t=m.join(e,n);try{const e=g.statSync(t);if(!e.isFile())continue;r-e.mtimeMs>36e5&&g.unlinkSync(t)}catch{}}}(e)),e}function le(e){const t=ce(),r=H.randomBytes(8).toString("hex"),n=m.join(t,`sandbox-policy-${r}`);return g.writeFileSync(n,e,{encoding:"utf-8",mode:384}),n}const ue="/tmp/node-compile-cache",de="cursor-compile-cache",he=Symbol.for("cursor.startupNodeCompileCache"),pe=process.platform;function fe(e=q.tmpdir(),t=process.platform){if("win32"===t||0===e.length)return[];const r=m.posix.join(e,"node-compile-cache");return r===ue?[]:[r]}function me(e=q.tmpdir(),t=process.env,r=process.platform){if("win32"===r)return[];const n=new Set(fe(e,r));for(const e of["TMPDIR","TMP","TEMP"]){const o=t[e];if(void 0!==o&&m.posix.isAbsolute(o))for(const e of fe(m.posix.resolve(o),r))n.add(e)}return[...n]}function ge(e=process.env,t=q.homedir(),r=process.platform){if("darwin"===r)return t.length>0?m.posix.join(t,"Library/Caches",de):void 0;if("linux"!==r)return;const n=e.XDG_CACHE_HOME;return void 0!==n&&m.posix.isAbsolute(n)?m.posix.join(n,de):t.length>0?m.posix.join(t,".cache",de):void 0}function we(e=process.env,t=process.platform){if("win32"===t)return;const r=Object.getOwnPropertyDescriptor(globalThis,he)?.value,n="string"==typeof r?r:e.NODE_COMPILE_CACHE;if(void 0===n||!m.posix.isAbsolute(n))return;const o=m.posix.resolve(n);return"/"===o?void 0:o}function ye(e=q.homedir(),t=q.tmpdir(),r=process.env,n=process.platform){if("win32"===n)return[];const o=new Set([ue]);e.length>0&&(o.add(m.posix.join(e,".cache",de)),o.add(m.posix.join(e,"Library/Caches",de)));const s=[];for(const i of[...me(t,r,n),ge(r,e,n),we(r,n)])void 0===i||o.has(i)||(o.add(i),s.push(i));return s}function ve(e=q.homedir(),t=q.tmpdir(),r=process.platform,n=process.env){if("win32"===r)return[];const o=[ue,...me(t,n,r)],s=ge(n,e,r);return void 0===s||o.includes(s)||o.push(s),o}function be(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 Se(e){return"object"!=typeof e||null===e?{}:Object.fromEntries(Object.entries(e).filter((e=>"string"==typeof e[1])))}function ke(e){return"object"==typeof e&&null!==e&&"code"in e&&"string"==typeof e.code?e.code:"error"}const _e=[".local/bin",".local/share/mise",".local/share/pnpm",".nvm",".volta",".asdf",".pyenv",".rbenv",".rustup",".cargo/bin",".cargo/registry",".cargo/git"],Ce=["bin","sbin","lib","opt","Cellar","share","Frameworks","etc/gitconfig","etc/openssl@3/cert.pem","etc/openssl@3/openssl.cnf","etc/ca-certificates"],Ee=(e,t)=>t.flatMap((t=>Ce.map((r=>({platform:e,scope:"global",path:`${t}/${r}`}))))),xe={linux:[".cache/node",".cache/yarn"],darwin:[".cache/node","Library/Caches/Yarn"]},Pe=e=>[..._e,...xe[e]].map((t=>({platform:e,scope:"home-dir",path:t}))),Re=[{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"},...Pe("linux"),...Ee("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"},...Pe("darwin"),...Ee("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 Ie(e=process.platform,t=q.default.homedir(),r={}){const n=[];for(const o of Re){if(o.platform!==e)continue;if("global"===o.scope){n.push(o.path);continue}const s="bundled"===o.scope?r[o.path]:(0,m.join)(t,o.path);if(s)try{let e;switch(o.scope){case"home":e=(0,g.lstatSync)(s).isFile();break;case"home-dir":e=(0,g.lstatSync)(s).isDirectory();break;case"bundled":e=(0,g.statSync)(s).isFile()}e&&n.push(s)}catch{}}return n}const Te=[{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 Ae(e){const t=Te.filter((e=>"workspace"===e.type)).map((e=>e.pattern));return{[e]:t}}function $e(e){const t=Te.filter((e=>"git"===e.type)).map((e=>e.pattern));return{[e]:t}}function Me(e){const t=Te.filter((e=>"worktree"===e.type)).map((e=>e.pattern));return{[e]:t}}Te.filter((e=>"git"===e.type)).map((e=>e.pattern)),Te.filter((e=>"workspace"===e.type&&e.pattern.startsWith("!")&&!e.pattern.endsWith("/**"))).map((e=>e.pattern.replace(/^!(\*\*\/)?/,"")));const De=[];let Oe=null,Fe=null;function Ne(e){if(!(e instanceof Error&&"code"in e&&"string"==typeof e.code)||e.code.startsWith("ERR_"))throw e}async function Le(e,t=""){const r=await(0,ne.lstat)(e).catch(Ne);if(void 0===r||!r.isFile()||r.size>4096)return;const n=await(0,ne.readFile)(e,"utf8").catch(Ne),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 je(e){if(!(0,oe.$f)(e))return(0,ne.realpath)(e).catch(Ne)}async function Ue(e){const t=await Le((0,m.join)(e,".git"),"gitdir: ");if(void 0===t)return;const r=await je((0,m.resolve)(e,t));if(void 0===r)return;const n=await Le((0,m.join)(r,"commondir")),o=void 0===n?r:await je((0,m.resolve)(r,n));return void 0===o?void 0:{gitDir:r,commonDirLink:n,commonDir:o}}async function Be(e){const t=await Ue(e);if(void 0===t||void 0===t.commonDirLink||"worktrees"!==(0,m.basename)((0,m.dirname)(t.gitDir)))return;const r=(0,m.dirname)((0,m.dirname)(t.gitDir));if(".git"!==(0,m.basename)(r)||(ze?t.commonDir.toLowerCase()!==r.toLowerCase():t.commonDir!==r))return;const n=await Le((0,m.join)(t.gitDir,"gitdir"));if(void 0===n)return;const o=(0,m.join)(e,".git"),[s,i]=await Promise.all([je((0,m.resolve)(t.gitDir,n)),je(o)]);return void 0!==s&&void 0!==i&&(ze?s.toLowerCase()===i.toLowerCase():s===i)?r:void 0}let We=null;function He(e){return function(){const e=q.default.homedir();if(null===We){const t=[];for(const r of Te)switch(r.type){case"absolute":t.push(r.pattern);break;case"home":e.length>0&&t.push((0,m.join)(e,r.pattern))}We=t}return[...We,...ye(e)]}().some((t=>{if(Ke(e,t))return!0;const r=function(e){let t;try{t=g.realpathSync.native((0,m.dirname)(e))}catch(e){const t=e instanceof Error&&"code"in e?e.code:void 0;return"ENOENT"===t||"ENOTDIR"===t?void 0:qe}const r=(0,m.join)(t,(0,m.basename)(e));return r===(0,m.dirname)(r)?void 0:r}(t);return r===qe||void 0!==r&&Ke(e,r)}))}const qe=Symbol("unresolved parent");const ze="win32"===process.platform||"darwin"===process.platform;function Ge(e){if(!e.endsWith(m.sep))return e;const t=e.slice(0,-1);return""===t||"win32"===process.platform&&/^[a-zA-Z]:$/.test(t)?e:t}function Ve(e){return e.endsWith(m.sep)?e:e+m.sep}function Ke(e,t){const r=Ge(t);if(ze){const t=e.toLowerCase(),n=r.toLowerCase();return t===n||t.startsWith(Ve(n))}return e===r||e.startsWith(Ve(r))}function Je(e,t){const r=Ge(e);return ze?(0,m.relative)(r.toLowerCase(),t.toLowerCase()).replace(/\\/g,"/"):(0,m.relative)(r,t).replace(/\\/g,"/")}async function Ze(e,t){if(Ke(e,t)){const r=Je(t,e);if((null===Oe&&(Oe=se({ignoreCase:!0}),Oe.add(Te.filter((e=>"workspace"===e.type)).map((e=>e.pattern)))),Oe).ignores(r))return!0}const{isWorktree:r,gitDirParent:n}=await async function(e){const t=await(0,ne.lstat)((0,m.join)(e,".git")).catch(Ne);if(!t?.isFile())return{isWorktree:!1,gitDirParent:e};const r=await async function(e){return(await Ue(e))?.commonDir}(e);return{isWorktree:!0,gitDirParent:void 0===r?e:(0,m.dirname)(r)}}(t);for(const r of new Set([n,t]))if(Ke(e,r)){const t=Je(r,e);if((null===Fe&&(Fe=se({ignoreCase:!0}),Fe.add(Te.filter((e=>"git"===e.type)).map((e=>e.pattern)))),Fe).ignores(t))return!0}return!(!r||!Ke(e,t)||".git"!==Je(t,e))||He(e)}function Xe(e){return void 0!==e&&("allow"===e.default||void 0!==e.allow&&e.allow.length>0)}function Qe(e){return void 0!==e&&"allow"===e.default}function Ye(){return{version:1,default:"deny"}}function et(){return{version:1,default:"allow"}}var tt=r("../utils/dist/path-utils.js");function rt(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 nt(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:rt(e.networkPolicy),networkPolicyStrict:e.networkPolicyStrict,additionalReadonlyPaths:n,readBoundary:e.readBoundary,additionalReadPaths:Array.isArray(e.additionalReadPaths)?e.additionalReadPaths:void 0,disableTmpWrite:e.disableTmpWrite,privateTmp:e.privateTmp};return"workspace_readonly"===t?{type:"workspace_readonly",...o}:{type:"workspace_readwrite",...o,additionalReadwritePaths:e.additionalReadwritePaths}}function ot(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","privateTmp","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 st(e,t){const r=await async function(e,t){try{const r=await(0,ne.readFile)(e,"utf-8"),n=JSON.parse(r);if(void 0!==ot(n))return{success:!1,error:`Invalid sandbox policy: ${ot(n)??""}`};let o=nt(n);return t&&(o=it(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 it(e,t){if("insecure_none"===e.type)return e;const r=e.additionalReadonlyPaths?.map((e=>(0,tt.o1)(e,t))),n=e.additionalReadPaths?.map((e=>(0,tt.o1)(e,t)));if("workspace_readonly"===e.type)return{...e,additionalReadonlyPaths:r,additionalReadPaths:n};const o=e.additionalReadwritePaths?.map((e=>(0,tt.o1)(e,t)));return{...e,additionalReadonlyPaths:r,additionalReadPaths:n,additionalReadwritePaths:o}}var at=r("../constants/dist/commercial-cursor-hosts.js");function ct(e){const t=e.replace(/\\/g,"/").replace(/\/+$/,"");return""===t?"/":/^[a-zA-Z]:$/.test(t)?`${t}/`:t}function lt(e){const t=ct(e);return/^[a-zA-Z]:\//.test(t)||t.startsWith("//")?t.toLowerCase():t}const ut={insecure_none:0,workspace_readwrite:1,workspace_readonly:2};function dt(){return"1"===process.env[at.K4]}function ht(e){if(!dt())return e.teamAdmin?.type??e.perRepo?.type??e.perUser?.type??"insecure_none";const t=e.teamAdmin?.type??e.perUser?.type;return void 0===t&&void 0===e.perRepo?"insecure_none":Rt(t??"workspace_readwrite",e.perRepo?.type??"insecure_none")}function pt(...e){return e.some((e=>!0===e))}function ft(...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=lt(n);t.has(e)||(t.add(e),r.push(n))}return r}(t[0]).map(ct);let r=new Map(t[0].map((e=>{const t=ct(e);return[lt(t),t]})));for(let e=1;e<t.length;e++){const n=new Set(t[e].map(lt));r=new Map([...r].filter((([e])=>n.has(e))))}return[...r.values()]}function mt(...e){const t=new Map;for(const r of e)if(r)for(const e of r){const r=ct(e),n=lt(r);t.has(n)||t.set(n,r)}return[...t.values()]}const gt=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}}),wt=(...e)=>ft(...e);function yt(...e){return gt.merge(...e)}function vt(...e){return wt(...e)}function bt(...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 St(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 kt(...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]=St(r[t],n);return 0!==Object.keys(r).length?r:void 0}function _t(...e){for(let t=e.length-1;t>=0;t--)if(void 0!==e[t])return e[t]}async function Ct(e,t,r={}){if(!t)return{policy:{type:"insecure_none"}};if(dt()&&(t=Mt(t,e)),(0,oe.$f)(e))return Ot(t,{workspaceDir:e});if("workspace_readwrite"!==(Pt(t)??"workspace_readwrite"))return Ot(t,{workspaceDir:e});const n=r.stat??ne.stat,o=await async function(e,t){for(let r=e;;r=(0,m.dirname)(r)){if((0,oe.$f)(r))return;const e=await Et(r,t);if(void 0!==e)return e;if((0,m.dirname)(r)===r)return}}(e,n);let s=o?.root??e;if(o?.isFile){const e=await Be(o.root);void 0!==e&&(s=(0,m.dirname)(e)),t=xt(t,void 0===e?[]:[e],Me(o.root))}return t=await async function(e,t,r){const n=Nt(e,"workspace_readwrite"),o=mt(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(ct(e))||(0,oe.$f)(e))return[];const n=await Et(e,r);if(void 0===n)return[];const o=[Ae(e),$e(e)];if(n.isFile){o.push(Me(e));const t=await Be(e);void 0!==t&&o.push($e((0,m.dirname)(t)))}return o})))).flat();return 0===s.length?e:xt(e,[],...s)}(t,new Set([ct(e)]),n),Ot(t,{workspaceDir:e,gitDirParent:s})}async function Et(e,t){const r=await t((0,m.join)(e,".git")).catch(Ne);return r?.isFile()||r?.isDirectory()?{root:e,isFile:r.isFile()}:void 0}function xt(e,t,...r){const n=dt(),o=n?e.perUser:e.perRepo,s="workspace_readwrite"===o?.type||void 0===o?o:void 0,i={...s,type:"workspace_readwrite",additionalReadwritePaths:t.length>0?[...s?.additionalReadwritePaths??[],...t]:s?.additionalReadwritePaths,writeProtectionMapping:kt(s?.writeProtectionMapping,...r)};return n?{...e,perUser:i}:{...e,perRepo:i}}function Pt(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 Rt(e,t){return ut[e]>=ut[t]?e:t}function It(e,t){if(void 0===e||e.type===t)return e;if("insecure_none"===t)return{type:t,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,enableSharedBuildCache:e.enableSharedBuildCache};if("insecure_none"===e.type)return{...e,type:t};if("workspace_readonly"===t){if("workspace_readwrite"===e.type){const{additionalReadwritePaths:r,...n}=e;return{...n,type:t}}return e}return e}function Tt(e){if("deny"===e?.default||void 0!==e?.deny&&0!==e.deny.length)return{version:1,..."deny"===e.default?{default:"deny"}:{},...void 0!==e.deny&&e.deny.length>0?{deny:e.deny}:{}}}function At(e,t,r){if(void 0===e||"insecure_none"===t)return;const n="insecure_none"===e.type?void 0:e,o={captureDenies:!0===e.captureDenies||void 0,networkPolicy:Tt(n?.networkPolicy),networkPolicyStrict:!0===n?.networkPolicyStrict||void 0,readBoundary:"workspace"===n?.readBoundary?"workspace":void 0,additionalReadPaths:void 0===n?.additionalReadPaths?void 0:ft(n.additionalReadPaths,r),additionalReadonlyPaths:n?.additionalReadonlyPaths,disableTmpWrite:!0===n?.disableTmpWrite||void 0,ignoreMapping:n?.ignoreMapping,writeProtectionMapping:n?.writeProtectionMapping};return"workspace_readonly"===t?{type:t,...o}:{type:"workspace_readwrite",...o}}function $t(e,t){return void 0===e||"insecure_none"===e.type||void 0===t?e:{...e,additionalReadPaths:e.additionalReadPaths?.map((e=>ct((0,tt.o1)(e,t))))}}function Mt(e,t){const r=Pt({perUser:e.perUser,teamAdmin:e.teamAdmin})??"workspace_readwrite",n=void 0===e.perRepo?r:Rt(r,e.perRepo.type),o=$t(It(e.perUser,n),t),s=$t(It(e.teamAdmin,n),t),i=mt("insecure_none"===o?.type?void 0:o?.additionalReadPaths,"insecure_none"===s?.type?void 0:s?.additionalReadPaths);return{perUser:o,perRepo:At(e.perRepo,n,i),teamAdmin:s}}function Dt(e,t){return Mt(e,t)}function Ot(e,t){return function(e,t){dt()&&(e=Mt(e,t?.workspaceDir));const r=Pt(e);if(void 0===r)return Ut({},t);switch(r){case"workspace_readwrite":return Ut(Nt(e,r),t);case"workspace_readonly":return function(e,t){const r=t?.debug,n=Lt(e,t),o={policy:jt({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,privateTmp:n.privateTmp,ignoreMapping:n.ignoreMapping,writeProtectionMapping:n.writeProtectionMapping},"workspace_readonly")};return r&&(o.debug={fieldSources:n.fieldSources}),o}(Nt(e,r),t);case"insecure_none":return function(e,t){const{perUser:r,perRepo:n,teamAdmin:o}=e,s=t?.debug,i={policy:jt({type:"insecure_none",allowlistEscalated:pt(r?.allowlistEscalated,n?.allowlistEscalated,o?.allowlistEscalated)||void 0,debugOutputDir:_t(r?.debugOutputDir,n?.debugOutputDir,o?.debugOutputDir),captureDenies:pt(r?.captureDenies,n?.captureDenies,o?.captureDenies)||void 0,enableSharedBuildCache:_t(r?.enableSharedBuildCache,n?.enableSharedBuildCache,o?.enableSharedBuildCache)},"insecure_none")};return s&&(i.debug={fieldSources:{}}),i}(Nt(e,r),t);default:throw new Error(`Unknown policy type: ${String(r)}`)}}(e,t)}function Ft(e,t){return e?.type===t}function Nt(e,t){const{perUser:r,perRepo:n,teamAdmin:o}=e;return{perUser:Ft(r,t)?r:void 0,perRepo:Ft(n,t)?n:void 0,teamAdmin:Ft(o,t)?o:void 0}}function Lt(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!==De.length)return{version:1,deny:[...De]}}(),r=q.default.homedir(),n=[];for(const e of Te)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,m.join)(r,e.pattern));break;default:{const t=e.type;throw new Error(`Unknown entry type: ${String(t)}`)}}return n.push(...ye(r)),{type:"workspace_readwrite",additionalReadonlyPaths:n,writeProtectionMapping:Ae(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=pt(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=pt(n?.networkPolicyStrict,o?.networkPolicyStrict,s?.networkPolicyStrict,a.networkPolicyStrict);a.networkPolicyStrict&&d("networkPolicyStrict",3);const f=dt()?yt(_t(n?.readBoundary,s?.readBoundary)??"system",o?.readBoundary):_t(n?.readBoundary,o?.readBoundary,s?.readBoundary)??"system",g=_t(n?.additionalReadPaths,o?.additionalReadPaths),w=!1===s?.allowUserOverrideReadPaths?mt(s.additionalReadPaths):mt(g,s?.additionalReadPaths),y="workspace"===f?w:void 0,v=mt(n?.additionalReadonlyPaths,o?.additionalReadonlyPaths,s?.additionalReadonlyPaths,a.additionalReadonlyPaths),b=v.length>0?v:void 0;let S=bt(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=_t(n?.debugOutputDir,o?.debugOutputDir,s?.debugOutputDir),x=pt(n?.captureDenies,o?.captureDenies,s?.captureDenies),P=_t(n?.enableSharedBuildCache,o?.enableSharedBuildCache,s?.enableSharedBuildCache),R=_t(n?.privateTmp,o?.privateTmp,s?.privateTmp),I=kt(n?.ignoreMapping,o?.ignoreMapping,s?.ignoreMapping,a.ignoreMapping),T=$e(t?.gitDirParent??i);return{disableTmpWrite:h||void 0,networkPolicyStrict:p,readBoundary:f,additionalReadPaths:y,additionalReadonlyPaths:b,networkPolicy:_,debugOutputDir:E,captureDenies:x||void 0,enableSharedBuildCache:P,privateTmp:R,ignoreMapping:I,writeProtectionMapping:kt(n?.writeProtectionMapping,o?.writeProtectionMapping,s?.writeProtectionMapping,a.writeProtectionMapping,T),fieldSources:c}}function jt(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 Ut(e,t){const{perUser:r,perRepo:n,teamAdmin:o}=e,s=t?.debug,i=Lt(e,t),a=mt(r?.additionalReadwritePaths,n?.additionalReadwritePaths,o?.additionalReadwritePaths),c={policy:jt({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,privateTmp:i.privateTmp,ignoreMapping:i.ignoreMapping,writeProtectionMapping:i.writeProtectionMapping},"workspace_readwrite")};return s&&(c.debug={fieldSources:i.fieldSources}),c}var Bt=r("../utils/dist/workload-spawn.js"),Wt=r("../context/dist/logger.js"),Ht=r("../context/dist/core.js"),qt=r("../utils/dist/command-glob.js");const zt=n.execFile,Gt=new WeakMap;function Vt(e,t,r){return e===t?"related":r?.has(e)?"probably_unrelated":"maybe_related"}const Kt="darwin"===process.platform,Jt="linux"===process.platform,Zt=(0,Wt.h)("shell-exec:sandbox");function Xt(e){const t=ce();return e&&0!==e.length?e.includes(t)?e:[...e,t]:[t]}let Qt,Yt=!0,er=!1;function tr(){return Qt}function rr(e){"linux"===process.platform&&Object.assign(e,I(e))}let nr=null,or=null,sr=null,ir=null,ar=!1,cr=null;function lr(e){return{...e,additionalReadonlyPaths:Xt(e.additionalReadonlyPaths)}}class ur extends Error{}function dr(e){return e instanceof Error&&"code"in e&&"string"==typeof e.code?e.code:"unknown"}function hr(e,t,r){let n;e.ignoreMapping&&(n=function(e){return vr(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,g.existsSync)(r)&&(0,g.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=!Jt||yr(r),s={...n};for(const[e,r]of Object.entries(t??{})){const t=e.startsWith("file://")?br(e):e;(o||yr(t))&&(s[e]=St(s[e],r))}if(0!==Object.keys(s).length)return vr(s)}(e.additionalReadonlyPaths,e.writeProtectionMapping,t),s=(i=e.readBoundary,r?.workspaceReadEnabled??function(){const e=Yt;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=T()}catch{}for(const o of Ie(e,q.homedir(),n))r.has(o)||(r.add(o),t.push(o));return t}(),c=[t,..."workspace_readwrite"===e.type&&e.additionalReadwritePaths||[],Z(t)].filter((e=>void 0!==e)),l="workspace"===s?(e.additionalReadPaths??[]).flatMap((e=>function(e,t){let r=e.trim();(r.startsWith("~/")||r.startsWith("~\\"))&&(r=m.join(q.homedir(),r.slice(2)));const n=e=>e.includes("*")||e.includes("?"),o=/[/\\]\*\*?$/;if(o.test(r)&&n(m.basename(r.replace(/(?:[/\\]\*\*?)+$/,""))))return Zt.warn((0,Ht.q6)(),"[additionalReadPathGrants] a Read Allowlist file-name glob followed by /* or /** grants nothing"),[];const s=m.basename(r);if(o.test(r)||!n(s))return function(e){const t=[],r=new Set;for(const n of e){let e=n.trim();if(!e)continue;"~"===e?e=q.homedir():(e.startsWith("~/")||e.startsWith("~\\"))&&(e=m.join(q.homedir(),e.slice(2))),e=e.replace(/\/\*\*$/,"").replace(/\/\*$/,""),e=e.replace(/\\\*\*$/,"").replace(/\\\*$/,"");const o=m.basename(e);if((o.includes("*")||o.includes("?"))&&(e=m.dirname(e)),!e||"."===e)continue;const s=m.normalize(e);r.has(s)||(r.add(s),t.push(s))}return t}([e]);const i=m.dirname(r);return m.isAbsolute(i)?function(e,t,r){const n=(0,qt.b)(t),o=[];let s;try{const t=(0,g.realpathSync)(e);if(r.filter((e=>g.existsSync(e))).map((e=>(0,g.realpathSync)(e))).some((e=>(0,tt.BJ)(t,e))))return[];s=g.opendirSync(t);for(let e=1;;e++){const r=s.readSync();if(null===r)return o;if(e>1e4)throw new ur("its folder has more than 10000 entries");if(!n(r.name))continue;const i=m.join(t,r.name);try{if(!g.lstatSync(i).isFile()||m.dirname((0,g.realpathSync)(i))!==t)continue}catch(e){Zt.info((0,Ht.q6)(),`[fileNameGlobMatches] skips a matching file: error ${dr(e)}`);continue}if(256===o.length)throw new ur("more than 256 files match");o.push(i)}}catch(e){const t=e instanceof ur?e.message:`error ${dr(e)}`;return Zt.warn((0,Ht.q6)(),`[fileNameGlobMatches] a Read Allowlist file-name glob grants nothing: ${t}`),[]}finally{s?.closeSync()}}(i,s,t):[]}(e,c))):[],u=[...a],d=new Set(a);for(const e of l)d.has(e)||(d.add(e),u.push(e));const h={cwd:t,readBoundary:s,hardcodedReadPaths:u,additionalReadonlyPaths:o,networkAccess:Xe(e.networkPolicy),ignoreMapping:n};return"workspace_readonly"===e.type?{type:e.type,...h}:{type:e.type,...h,additionalReadwritePaths:e.additionalReadwritePaths||[],disableTmpWrite:e.disableTmpWrite||!1}}function pr(e){const t={sandbox:e};return Jt&&function(){const e=er;return"function"==typeof e?e():e}()&&(t.kernelMountBudget=!0),t}function fr(e){if(null!==nr)return nr;try{const t=tr();return Zt.info(e,`[checkBinaryAvailable] Resolved binary path: ${t}`),t?(nr=g.existsSync(t),nr?Zt.info(e,`[checkBinaryAvailable] Binary path exists: ${String(nr)}`):(or=new Error(`Sandbox binary not found at ${t}`),Zt.info(e,`[checkBinaryAvailable] Binary not found at: ${t}`)),nr):(or=new Error("Sandbox binary path was not configured"),nr=!1,Zt.info(e,"[checkBinaryAvailable] Binary path not set, returning false"),!1)}catch(t){return or=t instanceof Error?t:new Error(String(t)),nr=!1,Zt.info(e,`[checkBinaryAvailable] Exception checking binary: ${String(t)}`),!1}}function mr(e){if(null!==ir)return ir;const t=e??(0,Ht.q6)();if(Zt.info(t,"[isSandboxHelperSupported] Starting sandbox support check..."),!fr(t)){const e=or?.message||"Binary check failed";return sr=e,Zt.info(t,`[isSandboxHelperSupported] Binary not available, returning false. Reason: ${e}`),ir=!1,ir}if("win32"===process.platform)return sr="Windows sandbox helper only provides network proxy, not filesystem isolation",Zt.info(t,"[isSandboxHelperSupported] win32: returning false (proxy-only, no filesystem sandbox)"),ir=!1,ir;if("darwin"===process.platform)return sr=null,Zt.info(t,`[isSandboxHelperSupported] ${process.platform} platform, binary available, sandbox supported!`),ir=!0,ir;const{binaryPath:r,args:o,env:s}=function(e,t){const r=pr(hr(lr({type:"workspace_readwrite"}),t)),n=String(tr());Zt.info(e,`[sandboxPreflight] Running preflight with binary: ${n}`),Zt.info(e,`[sandboxPreflight] CWD: ${t}`);const o={...process.env};return rr(o),{binaryPath:n,args:["--policy",le(JSON.stringify(r)),"--preflight-only","--","/bin/true"],env:o}}(t,process.cwd());try{const e=Date.now();(0,Bt.D9)(n.execFileSync,r,o,{stdio:["ignore","ignore","pipe"],timeout:gr,env:s,shell:!1});const i=Date.now()-e;return sr=null,Zt.info(t,`[isSandboxHelperSupported] Preflight succeeded in ${i}ms, sandbox supported!`),ir=!0,ir}catch(e){return function(e,t){const{message:r,status:n,stderrText:o}=t;return Zt.error(e,`[sandboxPreflight] Preflight failed: ${r}`),Zt.error(e,`[sandboxPreflight] Exit status: ${n}`),o&&Zt.error(e,`[sandboxPreflight] Stderr: ${o}`),sr=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"}`,ir=!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,G.J)((function(){ir=null,ar=!1,cr=null,sr=null,nr=null,or=null}));const gr=15e3;function wr(e,t=[],r={},o){const i=(0,Ht.q6)();if(r.env=a(s(r.env)),!fr(i))throw new Error(`Sandbox binary not available: ${or?.message||"binary not configured"}. Please build the binary or use 'insecure_none' policy.`);if("insecure_none"===o.type)return(0,Bt.D9)(n.spawn,e,t,{...r,windowsHide:!0});if("workspace_readwrite"===o.type||"workspace_readonly"===o.type)return function(e,t,r,o){if("workspace_readwrite"!==o.type&&"workspace_readonly"!==o.type)throw new Error("Expected workspace_readwrite or workspace_readonly policy");const i=String(r.cwd??process.cwd()),c=o.sandboxWorkspaceRoot??i;let u=e,d=t;r.shell&&("win32"===process.platform?(u="string"==typeof r.shell?r.shell:"cmd.exe",d=["/c",`${e} ${t.join(" ")}`]):(u="string"==typeof r.shell?r.shell:"/bin/sh",d=["-c",`${e} ${t.join(" ")}`]));const h=function({workspaceRoot:e,executionCwd:t}){const r=m.resolve(e),n=m.resolve(t),o=Sr(r);if(n===r||n===o)return;const s=e=>(0,tt.ZU)({basePath:o,targetPath:e})?m.join(r,m.relative(o,e)):void 0,i=(0,tt.ZU)({basePath:r,targetPath:n})?n:s(n)??n;return{directory:i,fallbackDirectory:s(Sr(n))??i}}({workspaceRoot:c,executionCwd:i});"win32"!==process.platform&&void 0!==h&&({command:u,args:d}=(0,oe.kO)(u,d,h));const p=hr(lr(o),c),f=(0,Ht.q6)();!function({log:e,dirs:t=ve(q.homedir(),q.tmpdir(),pe),createOnly:r=[we(process.env,pe)].filter((e=>void 0!==e)),policyDir:n=ie(),uid:o=process.getuid?.()??-1}){const s=m.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=g.readFileSync(e,"utf8")}catch(e){const r=ke(e);return t("ENOENT"===r?void 0:r)}try{n=JSON.parse(r)}catch(e){return t(e instanceof SyntaxError?"not JSON":ke(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:Se("kept"in n?n.kept:void 0),failed:Se("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=g.lstatSync(n,{throwIfNoEntry:!1});if(void 0!==t){const r=be(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)&&(g.rmSync(n,{recursive:!0,force:!0}),e(`node compile cache: removed ${n}`))}g.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=ke(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{g.writeFileSync(r,`${JSON.stringify(t)}\n`,{mode:384}),g.renameSync(r,e)}catch{g.rmSync(r,{force:!0})}}(s,{...i,cleaned:[...c]})}({log:e=>Zt.info(f,e)});const w=function(e){if(!("workspace"!==e.readBoundary||"workspace_readwrite"===e.type&&e.disableTmpWrite||"win32"===process.platform))return X(e.cwd,{create:!0})}(p);let y;w&&(p.additionalReadwritePaths=[...p.additionalReadwritePaths??[],w],Jt&&!0===o.privateTmp&&(y=te(w).TMPDIR));const v=function(e){if("insecure_none"===e.type)return;const t=e.networkPolicy;if(void 0===t)return;if(!Xe(t))return;const r=void 0!==t.deny&&t.deny.length>0;return"allow"!==t.default||r?{version:1,...t}:void 0}(o),b=pr(p);void 0!==y&&(b.mapTmpTo=y),void 0!==v&&(b.networkPolicy=v),!1===o.networkPolicyStrict&&(b.networkPolicyStrict=!1);const S=["--policy",le(JSON.stringify(b)),"--",u,...d],k=s(process.env),_={..."linux"===process.platform?l(k):k,..."linux"===process.platform&&r.env?l(r.env):r.env,CURSOR_SANDBOX:"native"};rr(_);const C=new Set(Y);if(w){const e=function(e,t,r){const n=te(e);if(r){const r=re();for(const[o,s]of Object.entries(re(e)))t[o]===r[o]&&(n[o]=s)}return n}(w,_,o.enableSharedBuildCache);Object.assign(_,e);for(const t of Object.keys(e))C.add(t);_.__CURSOR_SANDBOX_TEMP_RESTORE=Object.entries(e).map((([e,t])=>`builtin export ${e}='${t.replace(/'/g,"'\\''")}'`)).join("; ")}_.__CURSOR_SANDBOX_OWNED_ENV=[...C].join(" ");const E={cwd:void 0!==y?p.cwd:r.cwd||i,env:a(_),stdio:r.stdio||["pipe","pipe","pipe"],detached:r.detached,windowsHide:!0};try{const e=new Date,t=(0,Bt.D9)(n.spawn,String(tr()),S,E);return Kt&&t.pid&&function(e,t){Gt.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,o);throw new Error(`Unsupported sandbox policy: ${String(o)}`)}function yr(e,t=e=>g.existsSync(e)){if((0,oe.$f)(e))return!0;let r=m.resolve(e);for(;;){try{if(t(m.join(r,".git")))return!0}catch{}const e=m.dirname(r);if(e===r)return!1;r=e}}function vr(e,t,r,n){const o={};for(const[t,r]of Object.entries(e)){const e=t.startsWith("file://")?br(t):t;o[e]=St(o[e],r);const n=Sr(e);n!==e&&(o[n]=St(o[n],r))}return o}function br(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,oe.$f)(e))return e;try{return(t??g.realpathSync)(e)}catch{return e}}function kr(){return sr}class _r extends Error{reason;constructor(e,t){super(e),this.reason=t,this.name="SandboxUnsupportedError"}}const Cr="darwin"===process.platform;function Er(e){!function(e){T();const{sandboxBinaryPath:t,workspaceReadEnabled:r,kernelMountBudget:n}=e;Qt||(Qt=t),void 0!==r&&(Yt=r),void 0!==n&&(er=n)}(e)}function xr(e,t=[],r={},o){if(r.env=s(r.env),o.enableSharedBuildCache&&(r={...r,env:{...s(process.env),...re(),...r.env}}),"insecure_none"!==o.type){if(mr())return wr(e,t,r,o);const n=kr();throw new _r(`Sandbox policy '${o.type}' is not supported on this system. Ensure the sandbox helper binary is available, or use 'insecure_none'. Reason: ${n||"unknown"}`,n??void 0)}return function(e,t,r,o={spawn:n.spawn,spawnWorkload:Bt.D9}){return o.spawnWorkload(o.spawn,e,t,{...r,env:a(r.env??process.env),windowsHide:!0})}(e,t,r)}function Pr(e){return Cr?async function(e){const t=Gt.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,Bt.D9)(zt,"/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:Vt(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:Vt(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 Rr(e,t){if(Cr)try{(0,g.accessSync)("/usr/bin/sandbox-exec",g.constants.X_OK)}catch{return!1}return mr(t?.ctx)}var Ir=r("node:stream"),Tr=r("../context/dist/otel.js"),Ar=r("../utils/dist/writable-iterable.js");const $r="--",Mr='builtin eval "$1" 3<&- 4>&-';var Dr=r("node:string_decoder");const Or=50,Fr=262144;class Nr{writable;pending=[];pendingBytes=0;flushTimeout;flushPromise;flushIntervalMs;maxBufferedBytes;constructor(e,t){this.writable=e,this.flushIntervalMs=t?.flushIntervalMs??Or,this.maxBufferedBytes=t?.maxBufferedBytes??Fr}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 Lr(e){const t=new oe.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 Nr(e.writable,e.outputLimiterOptions);let n;const o=Promise.all([jr(e.stdout,r,t),Ur(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 jr(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 Ur(e,t,r,n){if(e)for await(const o of e)n?.(o),await r.push(t,o)}var Br;!function(e){e.Zsh="zsh",e.ZshLight="zsh-light",e.Bash="bash",e.PowerShell="powershell",e.Naive="naive"}(Br||(Br={}));const Wr={TERM:"dumb",NO_COLOR:"1",FORCE_COLOR:"0",_ZO_DOCTOR:"0"};function Hr(e){return"win32"===e.platform?"windows_tree":e.detached?"process_group":"single_process"}function qr(e,t,r,o={spawn:n.spawn,killPid:process.kill.bind(process)}){const s=e.pid;if(void 0===s)return;const i=()=>{try{e.kill(r)}catch{}};switch(t){case"process_group":try{o.killPid(-s,r)}catch{i()}return;case"windows_tree":try{o.spawn("taskkill",["/pid",String(s),"/t","/f"],{stdio:"ignore",windowsHide:!0}).on("error",i)}catch{i()}return;case"single_process":return void i();default:throw new Error(`Unknown process tree kill mode: ${String(t)}`)}}function zr(e,t=[],r={},n,o){const s=xr(e,t,{...r,env:I(r.env??process.env)},n);return o?Vr(s,{detached:!0===r.detached},o):Gr(s,!0===r.detached),s}function Gr(e,t){"single_process"!==Hr({platform:process.platform,detached:t})&&e.pid}function Vr(e,t,r){const n=Hr({platform:process.platform,detached:t.detached});Gr(e,t.detached);const o=()=>{if(!e.pid)return;qr(e,n,"SIGTERM");const t=setTimeout((()=>{!e.killed&&e.pid&&qr(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 Kr(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 Jr=new Set(["SIGTERM","SIGINT","SIGHUP","SIGQUIT","SIGKILL"]);function Zr(e,t,r){null!==t&&Jr.has(t)&&!r&&"win32"!==process.platform&&Kr(e,t)}function Xr(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.`),qr(e,Hr({platform:process.platform,detached:!0}),"SIGKILL"),u("timed_out")}),s):void 0;e.stdout?.on("data",a),Qr(e.stdout),e.on("exit",c),e.on("close",l)}))}function Qr(e){e?.on("error",(()=>{}))}function Yr(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 en="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 tn(e,t){return 126===e&&""===t}function rn(){return"win32"!==process.platform}function nn(e,t){const r=e.stdio.at(5);r instanceof Ir.default.Writable&&(Qr(r),r.end(`${t}\0`))}function on(e,t){e&&(Qr(e),e.write(t),e.end())}function sn(e,t){if(!e)return;Qr(e);const r=new Dr.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 an(e){const t=e.indexOf("\n");return{cwd:Buffer.from(e.substring(0,t),"utf16le").toString("utf16le"),rest:e.substring(t)}}function cn(e,t){const r=t instanceof Error&&"code"in t&&"string"==typeof t.code?t.code:"unknown";console.warn(e,r)}function ln(e,t){const r=`${t}\n`,n=e.indexOf(r);return n>=0?e.slice(n+r.length):e}function un(e){return!1===e?.isLoginShellEnabled?"-ic":"-ilc"}function dn(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 hn="__CURSOR_BASH_STATE_START__",pn="__CURSOR_BASH_STATE_END__",fn="\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",mn=`\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${fn}}\n`,gn=`\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${fn}\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`,wn="# cursor-shell-timings ",yn="[long](([DateTime]::UtcNow.Ticks - 621355968000000000) / 10000)",vn="\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",bn=e=>e.map((e=>`'${e}'`)).join(", "),Sn=` # 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 @(${bn([".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 @(${bn([".ps1",".psm1",".psd1"])})) { return 'bom' }\n if ($__cursorExtension -in @(${bn([".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 @(${bn([".json",".py",".js",".ts",".sh",".yaml",".toml",".mdc"])}) -and\n [System.IO.Path]::GetFileName($__cursorFile).ToLowerInvariant() -notin @(${bn([".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 }`,kn=String.raw`
|
|
2
|
+
function global:__cursorUtf8FromLatin1 {
|
|
3
|
+
param([string]$Text)
|
|
4
|
+
Set-StrictMode -Off
|
|
5
|
+
if ($Text.Length -eq 0 -or $Text -cnotmatch '[\u0080-\u00FF]' -or $Text -cmatch '[\u0100-\uFFFF]') { return $null }
|
|
6
|
+
try {
|
|
7
|
+
$bytes = [System.Text.Encoding]::GetEncoding(28591).GetBytes($Text)
|
|
8
|
+
$decoded = (New-Object System.Text.UTF8Encoding($false, $true)).GetString($bytes)
|
|
9
|
+
} catch { return $null }
|
|
10
|
+
if ($decoded.Length -gt 0 -and $decoded[0] -eq [char]0xFEFF) { $decoded = $decoded.Substring(1) }
|
|
11
|
+
return $decoded
|
|
12
|
+
}
|
|
13
|
+
function global:__cursorDeclaresOtherCharset {
|
|
14
|
+
param([string]$Text)
|
|
15
|
+
Set-StrictMode -Off
|
|
16
|
+
if ($Text.Length -eq 0) { return $false }
|
|
17
|
+
$head = $Text.Substring(0, [Math]::Min($Text.Length, 1024))
|
|
18
|
+
$options = [System.Text.RegularExpressions.RegexOptions]'IgnoreCase, Singleline, CultureInvariant'
|
|
19
|
+
$declared = [regex]::Match($head, '<meta\s.*[^.><]*charset\s*=\s*["''\n]?(?<charset>[A-Za-z].[^\s"''\n<>]*)[\s"''\n>]', $options)
|
|
20
|
+
if (-not $declared.Success) { $declared = [regex]::Match($head, '<\?xml\s.*[^.><]*encoding\s*=\s*["''\n]?(?<charset>[A-Za-z].[^\s"''\n<>]*)[\s"''\n>]', $options) }
|
|
21
|
+
if (-not $declared.Success) { return $false }
|
|
22
|
+
try { return [System.Text.Encoding]::GetEncoding($declared.Groups['charset'].Value).CodePage -ne 65001 } catch { return $false }
|
|
23
|
+
}
|
|
24
|
+
function global:__cursorFixWebResponse {
|
|
25
|
+
param([Parameter(ValueFromPipeline = $true)]$Response)
|
|
26
|
+
process {
|
|
27
|
+
Set-StrictMode -Off
|
|
28
|
+
try {
|
|
29
|
+
if ($null -ne $Response -and $Response.Content -is [string]) {
|
|
30
|
+
$contentType = $null
|
|
31
|
+
try { $contentType = [string]$Response.BaseResponse.ContentType } catch { }
|
|
32
|
+
if (-not $contentType -and $Response.Headers) {
|
|
33
|
+
foreach ($name in @($Response.Headers.Keys)) {
|
|
34
|
+
if ($name -ieq 'Content-Type') { $contentType = [string]$Response.Headers[$name] }
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
if ($contentType -notmatch '(?i);\s*charset\s*=' -and -not (__cursorDeclaresOtherCharset $Response.Content)) {
|
|
38
|
+
$content = $Response.Content
|
|
39
|
+
$fixed = __cursorUtf8FromLatin1 $content
|
|
40
|
+
if ($null -ne $fixed) {
|
|
41
|
+
$raw = $Response.RawContent
|
|
42
|
+
$fixedRaw = $null
|
|
43
|
+
if ($raw -is [string] -and $raw.EndsWith($content)) { $fixedRaw = $raw.Substring(0, $raw.Length - $content.Length) + $fixed }
|
|
44
|
+
$Response | Add-Member -NotePropertyName Content -NotePropertyValue $fixed -Force -ErrorAction Stop
|
|
45
|
+
if ($null -ne $fixedRaw) {
|
|
46
|
+
# Content and RawContent change together or not at all.
|
|
47
|
+
try { $Response | Add-Member -NotePropertyName RawContent -NotePropertyValue $fixedRaw -Force -ErrorAction Stop }
|
|
48
|
+
catch { $Response | Add-Member -NotePropertyName Content -NotePropertyValue $content -Force -ErrorAction Stop }
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
} catch { }
|
|
54
|
+
,$Response
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
function global:__cursorIsRestContainer {
|
|
58
|
+
param($Value)
|
|
59
|
+
Set-StrictMode -Off
|
|
60
|
+
return $Value -is [System.Management.Automation.PSCustomObject] -or $Value -is [System.Collections.IList] -or $Value -is [System.Xml.XmlNode]
|
|
61
|
+
}
|
|
62
|
+
function global:__cursorRestOutputText {
|
|
63
|
+
param($Value)
|
|
64
|
+
Set-StrictMode -Off
|
|
65
|
+
if ($Value -is [string]) { return $Value }
|
|
66
|
+
if ($Value -is [System.Xml.XmlNode]) { return [string]$Value.OuterXml }
|
|
67
|
+
# Windows PowerShell's serializer writes every character above U+007F as a \uXXXX
|
|
68
|
+
# escape, so the text alone would never show one; the escapes are read back, in
|
|
69
|
+
# .NET, before the string test sees the text.
|
|
70
|
+
return [regex]::Unescape([string](ConvertTo-Json -InputObject $Value -Depth 100 -Compress -WarningAction SilentlyContinue))
|
|
71
|
+
}
|
|
72
|
+
function global:__cursorFixRestValue {
|
|
73
|
+
param($Value)
|
|
74
|
+
Set-StrictMode -Off
|
|
75
|
+
if ($Value -is [string]) {
|
|
76
|
+
$fixed = __cursorUtf8FromLatin1 $Value
|
|
77
|
+
if ($null -eq $fixed) { return ,$Value }
|
|
78
|
+
return ,$fixed
|
|
79
|
+
}
|
|
80
|
+
if (-not (__cursorIsRestContainer $Value)) { return ,$Value }
|
|
81
|
+
# A slot is a list and an index, a property or an XML node and no index, or neither
|
|
82
|
+
# for the value itself. Every rewrite is noted against its slot and made at the end,
|
|
83
|
+
# once every string with a character of U+0080-U+00FF has passed the strict round
|
|
84
|
+
# trip: one that does not, or one character above U+00FF, which no Latin-1 read
|
|
85
|
+
# produces, leaves the whole value as the cmdlet returned it.
|
|
86
|
+
$root = $Value
|
|
87
|
+
$edits = New-Object System.Collections.Generic.List[object]
|
|
88
|
+
$pending = New-Object System.Collections.Stack
|
|
89
|
+
$pending.Push(@{ Target = $null; Key = $null; Value = $Value; Depth = 0 })
|
|
90
|
+
while ($pending.Count -gt 0) {
|
|
91
|
+
$entry = $pending.Pop()
|
|
92
|
+
$current = $entry.Value
|
|
93
|
+
if ($entry.Depth -gt 100) { continue }
|
|
94
|
+
if ($current -is [System.Management.Automation.PSCustomObject]) {
|
|
95
|
+
$renamed = $false
|
|
96
|
+
foreach ($property in $current.PSObject.Properties) {
|
|
97
|
+
if ($property.Name -cmatch '[\u0080-\uFFFF]') {
|
|
98
|
+
if ($null -eq (__cursorUtf8FromLatin1 $property.Name)) { return ,$Value }
|
|
99
|
+
$renamed = $true
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
if ($renamed) {
|
|
103
|
+
$rebuilt = New-Object System.Management.Automation.PSObject
|
|
104
|
+
foreach ($property in $current.PSObject.Properties) {
|
|
105
|
+
$name = $property.Name
|
|
106
|
+
if ($name -cmatch '[\u0080-\uFFFF]') { $name = __cursorUtf8FromLatin1 $name }
|
|
107
|
+
$rebuilt | Add-Member -NotePropertyName $name -NotePropertyValue $property.Value -ErrorAction Stop
|
|
108
|
+
}
|
|
109
|
+
$edits.Add(@{ Target = $entry.Target; Key = $entry.Key; Value = $rebuilt })
|
|
110
|
+
$current = $rebuilt
|
|
111
|
+
}
|
|
112
|
+
foreach ($property in $current.PSObject.Properties) {
|
|
113
|
+
$item = $property.Value
|
|
114
|
+
if ($item -is [string]) {
|
|
115
|
+
if ($item -cmatch '[\u0080-\uFFFF]') {
|
|
116
|
+
$fixed = __cursorUtf8FromLatin1 $item
|
|
117
|
+
if ($null -eq $fixed) { return ,$Value }
|
|
118
|
+
$edits.Add(@{ Target = $property; Key = $null; Value = $fixed })
|
|
119
|
+
}
|
|
120
|
+
} elseif (__cursorIsRestContainer $item) {
|
|
121
|
+
$pending.Push(@{ Target = $property; Key = $null; Value = $item; Depth = $entry.Depth + 1 })
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
} elseif ($current -is [System.Collections.IList]) {
|
|
125
|
+
for ($i = 0; $i -lt $current.Count; $i++) {
|
|
126
|
+
$item = $current[$i]
|
|
127
|
+
if ($item -is [string]) {
|
|
128
|
+
if ($item -cmatch '[\u0080-\uFFFF]') {
|
|
129
|
+
$fixed = __cursorUtf8FromLatin1 $item
|
|
130
|
+
if ($null -eq $fixed) { return ,$Value }
|
|
131
|
+
$edits.Add(@{ Target = $current; Key = $i; Value = $fixed })
|
|
132
|
+
}
|
|
133
|
+
} elseif (__cursorIsRestContainer $item) {
|
|
134
|
+
$pending.Push(@{ Target = $current; Key = $i; Value = $item; Depth = $entry.Depth + 1 })
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
} elseif ($current -is [System.Xml.XmlNode]) {
|
|
138
|
+
foreach ($node in $current.SelectNodes('.//text() | .//@* | .//comment()')) {
|
|
139
|
+
if ($node.Value -cmatch '[\u0080-\uFFFF]') {
|
|
140
|
+
$fixed = __cursorUtf8FromLatin1 $node.Value
|
|
141
|
+
if ($null -eq $fixed) { return ,$Value }
|
|
142
|
+
$edits.Add(@{ Target = $node; Key = $null; Value = $fixed })
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
foreach ($edit in $edits) {
|
|
148
|
+
if ($null -eq $edit.Target) { $root = $edit.Value }
|
|
149
|
+
elseif ($null -eq $edit.Key) { $edit.Target.Value = $edit.Value }
|
|
150
|
+
else { $edit.Target[$edit.Key] = $edit.Value }
|
|
151
|
+
}
|
|
152
|
+
return ,$root
|
|
153
|
+
}
|
|
154
|
+
function global:__cursorFixRestResponse {
|
|
155
|
+
param([Parameter(ValueFromPipeline = $true)]$Response)
|
|
156
|
+
process {
|
|
157
|
+
Set-StrictMode -Off
|
|
158
|
+
$fixed = $Response
|
|
159
|
+
try {
|
|
160
|
+
if ($Response -is [string] -or (__cursorIsRestContainer $Response)) {
|
|
161
|
+
$text = __cursorRestOutputText $Response
|
|
162
|
+
$declared = ($Response -is [string] -or $Response -is [System.Xml.XmlNode]) -and (__cursorDeclaresOtherCharset $text)
|
|
163
|
+
if (-not $declared -and $null -ne (__cursorUtf8FromLatin1 $text)) { $fixed = __cursorFixRestValue $Response }
|
|
164
|
+
}
|
|
165
|
+
} catch { $fixed = $Response }
|
|
166
|
+
,$fixed
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
$__cursorWebProxyTemplate = @'
|
|
170
|
+
__BINDING__
|
|
171
|
+
param(
|
|
172
|
+
__PARAMS__
|
|
173
|
+
)
|
|
174
|
+
begin {
|
|
175
|
+
try {
|
|
176
|
+
$outBuffer = $null
|
|
177
|
+
if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { $PSBoundParameters['OutBuffer'] = 1 }
|
|
178
|
+
if ($PSBoundParameters.ContainsKey('SessionVariable') -and -not $PSBoundParameters.ContainsKey('WebSession')) {
|
|
179
|
+
$sessionName = [string]$PSBoundParameters['SessionVariable']
|
|
180
|
+
$webSession = New-Object Microsoft.PowerShell.Commands.WebRequestSession
|
|
181
|
+
if ($sessionName.Contains(':')) { $ExecutionContext.SessionState.PSVariable.Set($sessionName, $webSession) } else { Set-Variable -Name $sessionName -Value $webSession -Scope 1 }
|
|
182
|
+
[void]$PSBoundParameters.Remove('SessionVariable')
|
|
183
|
+
$PSBoundParameters['WebSession'] = $webSession
|
|
184
|
+
}
|
|
185
|
+
$wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Microsoft.PowerShell.Utility\__CMDLET__', [System.Management.Automation.CommandTypes]::Cmdlet)
|
|
186
|
+
$scriptCmd = { & $wrappedCmd @PSBoundParameters | __FILTER__ }
|
|
187
|
+
$steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)
|
|
188
|
+
$steppablePipeline.Begin($PSCmdlet)
|
|
189
|
+
} catch { $PSCmdlet.ThrowTerminatingError($_) }
|
|
190
|
+
}
|
|
191
|
+
process { try { $steppablePipeline.Process($_) } catch { $PSCmdlet.ThrowTerminatingError($_) } }
|
|
192
|
+
end { try { $steppablePipeline.End() } catch { $PSCmdlet.ThrowTerminatingError($_) } }
|
|
193
|
+
<#
|
|
194
|
+
.ForwardHelpTargetName Microsoft.PowerShell.Utility\__CMDLET__
|
|
195
|
+
.ForwardHelpCategory Cmdlet
|
|
196
|
+
#>
|
|
197
|
+
'@
|
|
198
|
+
foreach ($__cursorWebCmdletName in @('Invoke-WebRequest', 'Invoke-RestMethod')) {
|
|
199
|
+
$__cursorWebCmdlet = $ExecutionContext.InvokeCommand.GetCommand("Microsoft.PowerShell.Utility\$__cursorWebCmdletName", [System.Management.Automation.CommandTypes]::Cmdlet)
|
|
200
|
+
if (-not $__cursorWebCmdlet) { continue }
|
|
201
|
+
if (Test-Path -LiteralPath "Function:\$__cursorWebCmdletName") { continue }
|
|
202
|
+
$__cursorWebMetadata = New-Object System.Management.Automation.CommandMetadata $__cursorWebCmdlet
|
|
203
|
+
$__cursorWebFilter = if ($__cursorWebCmdletName -eq 'Invoke-WebRequest') { '__cursorFixWebResponse' } else { '__cursorFixRestResponse' }
|
|
204
|
+
$__cursorWebProxy = $__cursorWebProxyTemplate.Replace('__BINDING__', [System.Management.Automation.ProxyCommand]::GetCmdletBindingAttribute($__cursorWebMetadata)).Replace('__PARAMS__', [System.Management.Automation.ProxyCommand]::GetParamBlock($__cursorWebMetadata)).Replace('__CMDLET__', $__cursorWebCmdletName).Replace('__FILTER__', $__cursorWebFilter)
|
|
205
|
+
Set-Item -Path "Function:\global:$__cursorWebCmdletName" -Value ([scriptblock]::Create($__cursorWebProxy))
|
|
206
|
+
}`,_n=e=>{const t=e.includes("\r\n")&&!/\r(?!\n)|(?<!\r)\n/.test(e);return`(@(${["$__cursorCommand = {",...e.split(/\r\n|\r|\n/),"}"].map(Fn).join(",")}) -join "${t?"`r`n":"`n"}")`},Cn=e=>`${e}.command.ps1`,En=/^Set-Item -LiteralPath 'Env:[^']*' -Value \(\[System\.Text\.Encoding\]::UTF8\.GetString\(\[System\.Convert\]::FromBase64String\('[A-Za-z0-9+/=]*'\)\)\)\r?$/gm,xn=String.raw`\.(?:ps1|psm1)\b|\b(?:Invoke-Expression|iex|Invoke-Command|icm|Import-Module|ipmo|New-Module|nmo)\b|\[scriptblock\]::Create|\bInvoke(?:ReturnAsIs|WithContext)?\s*\(|ExpandString\s*\(|\b(?:Get-Command|gcm)\b[^;|&\r\n]*\*|(?<![>&\d])&(?!&)\s*\S|(?:^|[;|\r\n({]|&&|\|\|)\s*(?:\.(?:\s+\S|['"$({])|['"]?(?:\.\.?[\\/]|[A-Za-z]:[\\/]|[A-Za-z0-9_.$~-]+[\\/])\S)|(?:(?:(?<=\s)|(?<=\$[\w:]+)|(?<=[\])]))[+*/%-]?=|,|\b(?:return|throw)\b)\s*(?:\.\s+\S|(?:\.\.?[\\/]|[A-Za-z]:[\\/]|[A-Za-z0-9_.~-]+\\)\S)`,Pn=String.raw`\b(?:Get-Content|gc|cat|type)\b|PSDefaultParameterValues|__cursorGetContentBinding`,Rn=String.raw`\b(?:Set-Content|sc|Export-Csv|epcsv)\b|PSDefaultParameterValues|__cursorIsUtf8Bom|__cursorWriter`,In=String.raw`\b(?:Invoke-WebRequest|Invoke-RestMethod|iwr|irm|curl|wget)\b|__cursor(?:Utf8FromLatin1|DeclaresOtherCharset|FixWebResponse|IsRestContainer|RestOutputText|FixRestValue|FixRestResponse|Web)`,Tn=new RegExp(xn,"i"),An=new RegExp(Pn,"i"),$n=new RegExp(Rn,"i"),Mn=new RegExp(In,"i"),Dn=["begin","break","catch","cd..","cd\\","cd~","class","clear-host","continue","do","else","elseif","end","enum","exec","exit","filter","finally","for","foreach","function","get-verb","help","if","importsystemmodules","in","man","md","mkdir","more","oss","param","pause","process","prompt","return","switch","tabexpansion2","throw","trap","try","until","while"],On=new Set(Dn);function Fn(e){return`'${e.replace(/['\u2018\u2019\u201A\u201B]/g,"$&$&")}'`}const Nn=(e,t,r,n,o)=>{const s=!0!==o?.perLineStateDump,i=function(e,t,r){if(!0===r?.pwsh)return"";const n=`${e.replace(En,"")}\n${t}`,o=Tn.test(n),s=o||An.test(n),i=o||$n.test(n),a=o||Mn.test(n),c=o?[]:function(e){const t=new Set,r=[];for(const n of e.matchAll(/(?<![$:-])([\p{L}_][\p{L}\p{N}_.:?+-]*)/gu)){const e=n[1],o=e.toLowerCase();On.has(o)||/^[a-z]:$/i.test(e)||t.has(o)||(t.add(o),r.push(e))}return r}(t);return`${function(e,t,r,n){return`\ntry {\n $__cursorProfileDefs = ''\n $__cursorDynamic = $${r}\n if ($PSVersionTable.PSVersion.Major -lt 6 -and [Console]::OutputEncoding.CodePage -eq 65001) {\n $__cursorTokens = @(${bn(n)})\n # A walk that fails cannot rule a proxy out, so it installs them all.\n if (-not $__cursorDynamic -and $__cursorTokens.Count -gt 0) { try {\n $__cursorCmdTypes = [System.Management.Automation.CommandTypes]::Function -bor [System.Management.Automation.CommandTypes]::Filter -bor [System.Management.Automation.CommandTypes]::Alias\n $__cursorQueue = [System.Collections.Generic.Queue[string]]::new([string[]]$__cursorTokens)\n $__cursorSeen = [System.Collections.Generic.HashSet[string]]::new([string[]]@(${bn(Dn)}), [System.StringComparer]::OrdinalIgnoreCase)\n while ($__cursorQueue.Count -gt 0) {\n $__cursorToken = $__cursorQueue.Dequeue()\n if (-not $__cursorSeen.Add($__cursorToken)) { continue }\n foreach ($__cursorItem in $ExecutionContext.SessionState.InvokeCommand.GetCommands($__cursorToken, $__cursorCmdTypes, $false)) {\n if ($__cursorItem.Definition) {\n $__cursorProfileDefs += "\`n" + $__cursorItem.Definition\n foreach ($__cursorMatch in [regex]::Matches($__cursorItem.Definition, '(?<![$:-])[\\p{L}_][\\p{L}\\p{N}_.:?+-]*')) {\n $__cursorQueue.Enqueue($__cursorMatch.Value)\n }\n }\n }\n }\n if ($__cursorProfileDefs.Length -gt 0 -and ($__cursorProfileDefs -match '${xn.replace(/'/g,"''")}')) {\n $__cursorDynamic = $true\n }\n } catch { $__cursorDynamic = $true } }\n $__cursorNeedReader = $${e} -or $__cursorDynamic -or ($__cursorProfileDefs.Length -gt 0 -and ($__cursorProfileDefs -match '${Pn}'))\n $__cursorNeedWriters = $${t} -or $__cursorDynamic -or ($__cursorProfileDefs.Length -gt 0 -and ($__cursorProfileDefs -match '${Rn}'))\n if ($__cursorNeedReader) {\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 }\n if ($__cursorNeedWriters) {\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${Sn}\n }\n }\n} catch { }\n`}(s,i,o,c)}${r?.webRequestUtf8?function(e){return`\ntry {\n $__cursorNeedWeb = $${e} -or $__cursorDynamic -or ($__cursorProfileDefs.Length -gt 0 -and ($__cursorProfileDefs -match '${In}'))\n if ($PSVersionTable.PSVersion.Major -lt 6 -and [Console]::OutputEncoding.CodePage -eq 65001 -and $__cursorNeedWeb) {${kn}\n }\n} catch { }\n`}(a):""}`}(e,r,o);return`${s?`$__cursorTimingStart = ${yn}`:""}\n${o?.utf8Console?vn:""}\n${e}\n${i}\n${o?.envInjection??""}\nSet-Location ${Fn(t)}\n$env:NODE_DISABLE_COMPILE_CACHE = '1'\n$env:NODE_COMPILE_CACHE = $null${s?`\n$__cursorTimingRestored = ${yn}`:""}\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,t)=>{const r=Fn(t),n=[`Microsoft.PowerShell.Management\\Set-Content -LiteralPath ${r} -Value ${_n(e)} -Encoding UTF8 -NoNewline`,`. ${r}`,`Microsoft.PowerShell.Management\\Remove-Item -LiteralPath ${r} -ErrorAction SilentlyContinue`,"if ($__cursorCommand -isnot [scriptblock]) { exit 1 }"].join("; ");return`# The command is parsed here, after the statements above ran, so a syntax error in it is reported in the encoding they set.\n$__cursorCommand = $null; try { if ($ExecutionContext.SessionState.LanguageMode -eq 'FullLanguage') {\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() } } catch { $__cursorCommand = $null }; if ($__cursorCommand -isnot [scriptblock]) { ${n} }`})(r,Cn(n)):(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 = ${yn}\n\n${gn}\nDump-PowerShellState -OutputFile "${n}" -Trailer ('${wn}{0} {1} {2} {3}' -f $__cursorTimingStart, $__cursorTimingRestored, $__cursorTimingCommandDone, $PSVersionTable.PSVersion.Major)`:`\n${mn}\nDump-PowerShellState -OutputFile "${n}"`}\n\nexit $COMMAND_EXIT_CODE\n`},Ln="__CURSOR_ZSH_STATE_START__",jn="__CURSOR_ZSH_STATE_END__",Un=' 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',Bn=`#!/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${Un}\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`,Wn="__CURSOR_ZSH_STATE_LIGHT_VALID__",Hn="# end of zsh state dump (light)",qn=`#!/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${Un}\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 "${Hn}"\n _log_timing "finalize"\n}\n`;var zn=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 Gn(e){if("win32"===process.platform){const t=/git.*bash/i;if(e&&t.test(e))return e;const r=k("bash",[],t).cmd;return t.test(r)?r:null}const t=process.env.SHELL;return t?.includes("bash")?t:k("bash",[]).cmd}function Vn(e){if("win32"!==process.platform)return e;const t=m.default.normalize(e),r=t[0]?.toLowerCase();return r&&":"===t[1]&&t[2]===m.default.sep?`/${r}${t.slice(2).replace(/\\/g,"/")}`:t.replace(/\\/g,"/")}function Kn(e){const t=e.pipeStdin?Mr:`${Mr} < /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?en:"")+`${r} && builtin shopt -s extglob && builtin eval -- "$snap"; { builtin set +u 2>/dev/null || true; builtin eval "\${__CURSOR_SANDBOX_ENV_RESTORE:-}" 2>/dev/null; `+Q+ee+(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 Jn{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 Jn(e??this.cwd,this.state,this.userTerminalHint,this.useFileStateTransport,this.commandPipeUnreadable)}resetSessionCwdAfterHopCdFailure(e){const{cwd:t,sandboxWorkspaceRoot:r}=e;m.default.resolve(t)===m.default.resolve(this.cwd)&&(this.cwd=void 0===r||m.default.resolve(r)===m.default.resolve(t)||(0,oe.A)(r)?(0,oe.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,Tr.VI)(e.withName("BashState.execute")),!1),s=r?.pipeStdin??!1,i=(0,Ar.Jt)(),c=r?.workingDirectory??this.cwd,l=function(e,t=process.platform,r=process.env){const n={...r,...Wr,...e?.env};return d(n),"win32"===t&&(N(n),L(n)),a(n)}(r),u=M(l),h=this.useFileStateTransport,p=!h&&!this.commandPipeUnreadable;let f,g,w;if(h){f=await(0,ne.mkdtemp)(m.default.join(q.default.tmpdir(),"cursor-bash-state-")),g=m.default.join(f,"state-in"),w=m.default.join(f,"state-out"),await(0,ne.writeFile)(g,this.state,"utf8"),await(0,ne.writeFile)(w,"","utf8").catch((()=>{}));const e=Vn(g),t=Vn(w);l.CURSOR_STATE_INPUT_FILE=e,l.CURSOR_STATE_OUTPUT_FILE=t}const y=function(e){return["-O","extglob","-c",e.script,$r,...void 0===e.command?[]:[e.command]]}({script:Kn({pipeCommand:p,useFileTransport:h,sudoAliasInjection:u,pipeStdin:s,envInjection:"win32"===process.platform&&!0===r?.powershellUtf8ChildEnv?B:""}),command:p?void 0:t}),v=Gn(this.userTerminalHint);if(!v)throw new Error("Can't find Bash");const b=r?.sandboxWorkspaceRoot??c,S=(await Ct(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,ne.readFile)(w,"utf8")}catch(e){cn("[shell-exec] Failed to read bash state file",e),_=this.state}}},E=async()=>{if(f)try{await(0,ne.rm)(f,{recursive:!0,force:!0})}catch{}};let x;(0,oe.$Y)(c)&&(0,Tr.HF)(o.ctx,oe.yo);try{x=zr(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 i.write({type:"stdin_ready",stdin:x.stdin??void 0,pid:x.pid,shell:"bash"})}catch(e){}}));const P=Lr({stdout:x.stdout,stderr:x.stderr,writable:i,bufferOutputEvents:r?.bufferOutputEvents,outputLimiterOptions:r?.outputLimiterOptions});x.on("error",(async e=>{if((0,oe.fK)(e,c)){this.resetSessionCwdAfterHopCdFailure({cwd:c,sandboxWorkspaceRoot:r?.sandboxWorkspaceRoot}),(0,Tr.HF)(o.ctx,oe.Gq);const e=(0,oe.iA)(c);console.warn(`[shell-exec] working directory is not accessible (${e.cwdKind}:${e.cwdHash})`)}await E(),i.throw(e)}));let R=null,I=null,T=null,A=!1;const $=async e=>{if(A)return;if(A=!0,T&&(clearTimeout(T),T=null),(0,Tr.HF)(o.ctx,"exit"),e)try{await P.waitForOutput()}catch(e){return await E(),void i.throw(e instanceof Error?e:new Error(String(e)))}const t=(0,oe.wz)({exitCode:R,stdoutBytes:P.stdoutBytes,stdoutPrefix:P.stdoutPrefix,cwd:c})&&""===_;if(t&&P.dropHeldStdout(),await P.flush(),p&&tn(R,_)&&(this.commandPipeUnreadable=!0),t){this.resetSessionCwdAfterHopCdFailure({cwd:c,sandboxWorkspaceRoot:r?.sandboxWorkspaceRoot}),await E(),(0,Tr.HF)(o.ctx,oe.Gq);const e=(0,oe.iA)(c);return console.warn(`[shell-exec] working directory is not accessible (${e.cwdKind}:${e.cwdHash})`),void i.throw((0,oe.Vn)(c))}if(!r?.signal?.aborted){await C();const e=`${hn}\n`,t=`${pn}\n`;if(_.startsWith(e)&&_.endsWith(t)){let t=_.slice(e.length);t=t.slice(0,-26);const{cwd:r,rest:n}=an(t);this.state=n,"win32"!==process.platform&&r?.startsWith("/")&&(this.cwd=r)}}if(k.captureDenies)try{const e=await Pr(x);e&&e.length>0&&await i.write({type:"sandbox_denies",events:e})}catch{}try{await i.write({type:"exit",code:R,signal:I??void 0,data:"",aborted:r?.signal?.aborted??!1}),i.close()}catch{i.close()}await E()};x.on("exit",((e,t)=>{R=e,I=t,Zr(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.`),$(!1).finally((()=>{Yr(x)}))}),n))})),x.on("close",(async()=>{await $(!0)}));const D=x.stdio[3],O=x.stdio[4],F=D instanceof Ir.default.Writable?D:null,j=O instanceof Ir.default.Readable?O:null;p&&nn(x,t),h||(on(F,this.state),sn(j,(e=>{_+=e}))),yield*i}catch(e){n.error=e,n.hasError=!0}finally{zn(n)}}}async function Zn(e,t){const r={...process.env,...Wr,...e?.env},n="__CURSOR_STATE_MARKER__",o=["-O","extglob",un(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=Gn(e?.userTerminalHint);if(!s)throw new Error("Can't find Bash");const i=zr(s,o,{env:r,detached:!0,stdio:["ignore","pipe","ignore"]},{type:"insecure_none"},e?.signal);i.on("error",(e=>{cn("[shell-exec] bash state init spawn failed; falling back to empty state",e)}));const{stdout:a}=await Xr(i,{shellName:"bash",...t}),c=dn(ln(a,n),hn,pn)??`${process.cwd()}\n`,{cwd:l,rest:u}=an(c),d="win32"===process.platform,h="win32"===process.platform?process.cwd():l;return new Jn(h,u,e?.userTerminalHint,d)}var Xn=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 Qn{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 Qn((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,Tr.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{Xn(n)}}}var Yn=r("../metrics/dist/index.js"),eo=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 to=(0,Yn.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 ro;function no(){const e=[process.platform,process.env.SHELL,process.env.PATH,process.env.SYSTEMROOT,process.cwd()].join("\0");if(ro?.key===e)return ro.executable;const t=function(){if("win32"!==process.platform){const e=process.env.SHELL;if(e?.includes("pwsh")||e?.includes("powershell"))return e}let e=k("pwsh",[]).cmd;if("pwsh"!==e)return e;if(e=k("powershell",[]).cmd,"powershell"!==e)return e;if("win32"===process.platform&&(e=m.join(process.env.SYSTEMROOT,"System32","WindowsPowerShell","v1.0","powershell.exe"),(0,g.existsSync)(e)))return e;throw new Error("Neither 'pwsh' (PowerShell Core) nor 'powershell' (Windows PowerShell) found in PATH")}();return ro={key:e,executable:t},t}function oo(e,t=process.platform){return"win32"!==t||m.win32.basename(e).toLowerCase().startsWith("pwsh")?"pwsh":"powershell51"}class so{cwd;state;constructor(e,t){this.cwd=e,this.state=t}async getCwd(){return this.cwd}clone(e){return new so(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,Tr.VI)(e.withName("PowerShellState.execute")),!1),s=r?.pipeStdin??!1,i=r?.workingDirectory??this.cwd,c=(0,Ar.Jt)(),l=function(e,t=process.platform,r=process.env){const n={...r,...Wr,...e?.env};return d(n),"win32"===t&&!0===e?.powershellUtf8ChildEnv&&(N(n),L(n)),a(n)}(r),u=$(l)?D(t):t,h=q.tmpdir(),p=m.join(h,`ps-state-out-${(0,H.randomUUID)()}.txt`),f="win32"===process.platform,g=Nn(this.state,i,u,p,{utf8Console:f&&!0===r?.powershellUtf8Console,parseAfterUtf8Switch:f&&!0===r?.powershellParseAfterUtf8Switch,envInjection:f&&!0===r?.powershellUtf8ChildEnv?W:"",webRequestUtf8:f&&!0===r?.powershellWebRequestUtf8,perLineStateDump:!0===r?.powershellPerLineStateDump,pwsh:io(no())}),w=m.join(h,`ps-script-${(0,H.randomUUID)()}.ps1`);await async function(e,t){await ne.writeFile(e,"\ufeff"+t,{encoding:"utf8"})}(w,g);const y=["-ExecutionPolicy","Bypass"];s||y.push("-NonInteractive"),y.push("-File",w);const v=no(),b=r?.sandboxWorkspaceRoot??i,S=(await Ct(b,r?.sandboxPolicy)).policy,k="insecure_none"!==S.type?{...S,sandboxWorkspaceRoot:b}:S,_=Date.now();let C,E;const x=zr(v,y,{env:l,stdio:[s?"pipe":"ignore","pipe","pipe"],cwd:i,detached:!f},k,r?.signal);x.on("spawn",(async()=>{try{await c.write({type:"stdin_ready",stdin:x.stdin??void 0,pid:x.pid,shell:oo(v)})}catch(e){}}));const P=Lr({stdout:x.stdout,stderr:x.stderr,writable:c,bufferOutputEvents:r?.bufferOutputEvents,outputLimiterOptions:r?.outputLimiterOptions}),R=async()=>{try{const{state:e,timings:t}=function(e){const t=e.lastIndexOf(`\n${wn}`)+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 ne.readFile(p,"utf8"));E=t;const{cwd:r,rest:n}=an(e);this.state=n,this.cwd=r.trim(),await(0,ne.rm)(p).catch((()=>{}))}catch(e){await(0,ne.rm)(Cn(p),{recursive:!0,force:!0,maxRetries:5}).catch((e=>{const t=e instanceof Error&&"code"in e?e.code:void 0;console.warn("[shell-exec] Could not remove a PowerShell command file","string"==typeof t?t:"unknown")}))}await(0,ne.rm)(w,{recursive:!0,force:!0,maxRetries:5}).catch((e=>{cn("[shell-exec] Could not remove PowerShell script",e)}))};let I=null,T=null,A=null,M=!1;const O=async t=>{if(M)return;if(M=!0,A&&(clearTimeout(A),A=null),(0,Tr.HF)(o.ctx,"exit"),t)try{await P.waitForOutput()}catch(e){return await R(),void c.throw(e instanceof Error?e:new Error(String(e)))}await P.flush();try{await c.write({type:"exit",code:I,signal:T??void 0,data:"",aborted:r?.signal?.aborted??!1})}catch(e){}const n=Date.now();await R(),void 0!==C&&function(e,t){const r={shell_kind:(void 0!==t.script?t.script.majorVersion>=6:io(t.executable))?"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)to.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(),I=e,T=t;const n=r?.closeTimeout??5e3;n>0&&(A=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,ro?.executable===t&&(ro=void 0),R().catch((()=>{})),c.throw(e)})),yield*c}catch(e){n.error=e,n.hasError=!0}finally{eo(n)}}}function io(e){return m.win32.basename(e).toLowerCase().startsWith("pwsh")}async function ao(){return new so(process.cwd(),"")}var co=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 lo(e){const t=m.win32.parse(e).name.toLowerCase();return"powershell"===t||"pwsh"===t}function uo(e,t=process.platform){switch(m.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 ho{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 ho(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,Tr.VI)(e.withName("NaiveTerminalExecutor.execute")),!1),s=(0,Ar.Jt)(),i=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,...Wr,...t?.env};return"win32"!==r||!0!==t?.powershellUtf8ChildEnv&&lo(e)||(N(o),L(o)),a(o)}(c,{env:r?.env,powershellUtf8ChildEnv:u}),h=$(d)?D(t):t,p=function(e,t,r,n=process.platform){return"win32"===n&&lo(e)?`${!0===r?.powershellUtf8Console?vn:""}${!0===r?.powershellUtf8ChildEnv?`${W}\n`:""}${t}`:t}(c,h,{powershellUtf8Console:l,powershellUtf8ChildEnv:u}),f=r?.workingDirectory??this.cwd,m=r?.sandboxWorkspaceRoot??f,g=this.deps?.resolveSandboxPolicyForWorkspace??Ct,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&&!i&&"insecure_none"===y.type&&lo(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??zr,C=k??_(c,[...this.options?.shellArgs??[],"-c",p],{env:d,cwd:f,stdio:[i?"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:uo(c)})}catch(e){}};void 0!==k?(r?.signal&&Vr(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??Lr)({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()))})),R=r?.closeTimeout??250;C.on("exit",(async(e,t)=>{(0,Tr.HF)(o.ctx,"exit");const n=r?.signal?.aborted??!1;if(await(0===R?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,R)),await x.flush(),y.captureDenies)try{const e=await Pr(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{co(n)}}}var po=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 fo(){const e=process.env.SHELL;return e?.includes("zsh")?e:k("zsh",[]).cmd}class mo{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 mo(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,Tr.VI)(e.withName("ZshLightState.execute")),!1),s=r?.pipeStdin??!1,i=(0,Ar.Jt)(),a=r?.workingDirectory??this.cwd,c={...process.env,...Wr,...r?.env};d(c);let l='builtin eval "$1"';s||(l+=" < /dev/null");const u=M(c),h=rn()&&!this.commandPipeUnreadable,p=["-c",(h?en:"")+"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; "+`${qn} builtin eval "$snap"; { builtin unsetopt nounset 2>/dev/null || true; builtin eval "\${__CURSOR_SANDBOX_ENV_RESTORE:-}" 2>/dev/null; `+Q+ee+`builtin export PWD="$(builtin pwd)"; builtin setopt aliases 2>/dev/null; ${u}${l}; }; COMMAND_EXIT_CODE=$?; dump_zsh_state_light >&4; builtin exit $COMMAND_EXIT_CODE`,$r,...h?[]:[t]],f=r?.sandboxWorkspaceRoot??a,m=(await Ct(f,r?.sandboxPolicy)).policy,g="insecure_none"!==m.type?{...m,sandboxWorkspaceRoot:f}:m,w=zr(fo(),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=Lr({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,Tr.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&&tn(b,y)&&(this.commandPipeUnreadable=!0),!r?.signal?.aborted){const e=`${Wn}\n`;if(y.startsWith(e)){const t=y.slice(e.length),{cwd:r,rest:n}=an(t);r?.startsWith("/")&&(this.state=n,this.cwd=r)}}if(g.captureDenies)try{const e=await Pr(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,Zr(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((()=>{Yr(w)}))}),n))})),w.on("close",(async()=>{await C(!0)}));const E=w.stdio[3],x=w.stdio[4],P=E instanceof Ir.default.Writable?E:null,R=x instanceof Ir.default.Readable?x:null;h&&nn(w,t),on(P,this.state),sn(R,(e=>{y+=e})),yield*i}catch(e){n.error=e,n.hasError=!0}finally{po(n)}}}async function go(e,t){const r={...process.env,...Wr,...e?.env},n="__CURSOR_STATE_MARKER__",o=["-o","extendedglob",un(e),`${qn} builtin printf '${n}\\n'; dump_zsh_state_light`],s=zr(fo(),o,{env:r,stdio:["ignore","pipe","ignore"],detached:!0},{type:"insecure_none"},e?.signal);s.on("error",(e=>{cn("[shell-exec] zsh-light state init spawn failed; falling back to empty state",e)}));const{stdout:i}=await Xr(s,{shellName:"zsh-light",...t}),a=dn(ln(i,n),Wn,Hn)??`${process.cwd()}\n`,{cwd:c,rest:l}=an(a);return new mo(c,l)}var wo=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 yo(){const e=process.env.SHELL;return e?.includes("zsh")?e:k("zsh",[]).cmd}class vo{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 vo(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,Tr.VI)(e.withName("ZshState.execute")),!1),s=r?.pipeStdin??!1,i=r?.keepBackgroundJobs??!1,a=(0,Ar.Jt)(),c=r?.workingDirectory??this.cwd,l={...process.env,...Wr,...r?.env};d(l);let u='builtin eval "$1"';i&&(u+=" 3<&- 4>&-"),s||(u+=" < /dev/null");const h=M(l),p=rn()&&!this.commandPipeUnreadable,f=["-c",(p?en:"")+"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; "+`${Bn} builtin eval "$snap"; { builtin unsetopt nounset 2>/dev/null || true; builtin eval "\${__CURSOR_SANDBOX_ENV_RESTORE:-}" 2>/dev/null; `+Q+ee+`builtin export PWD="$(builtin pwd)"; builtin setopt aliases 2>/dev/null; ${h}${u}; }; COMMAND_EXIT_CODE=$?; dump_zsh_state >&4; builtin exit $COMMAND_EXIT_CODE`,$r,...p?[]:[t]],m=r?.sandboxWorkspaceRoot??c,g=(await Ct(m,r?.sandboxPolicy)).policy,w="insecure_none"!==g.type?{...g,sandboxWorkspaceRoot:m}:g,y=zr(yo(),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=Lr({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,Tr.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&&tn(S,v)&&(this.commandPipeUnreadable=!0),!r?.signal?.aborted){const e=`${Ln}\n`,t=`${jn}\n`;if(v.startsWith(e)&&v.endsWith(t)){let t=v.slice(e.length);t=t.slice(0,-25);const{cwd:r,rest:n}=an(t);r?.startsWith("/")&&(this.state=n,this.cwd=r)}}if(w.captureDenies)try{const e=await Pr(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,Zr(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.`),Kr(y.pid,"SIGKILL")),E(!1).finally((()=>{Yr(y)}))}),n))})),y.on("close",(async()=>{await E(!0)}));const x=y.stdio[3],P=y.stdio[4],R=x instanceof Ir.default.Writable?x:null,I=P instanceof Ir.default.Readable?P:null;p&&nn(y,t),on(R,this.state),sn(I,(e=>{v+=e})),yield*a}catch(e){n.error=e,n.hasError=!0}finally{wo(n)}}}async function bo(e,t){const r={...process.env,...Wr,...e?.env},n="__CURSOR_STATE_MARKER__",o=["-o","extendedglob",un(e),`${Bn} builtin printf '${n}\\n'; dump_zsh_state`],s=zr(yo(),o,{env:r,stdio:["ignore","pipe","ignore"],detached:!0},{type:"insecure_none"},e?.signal);s.on("error",(e=>{cn("[shell-exec] zsh state init spawn failed; falling back to empty state",e)}));const{stdout:i}=await Xr(s,{shellName:"zsh",...t}),a=dn(ln(i,n),Ln,jn)??`${process.cwd()}\n`,{cwd:c,rest:l}=an(a);return new vo(c,l)}function So(e){try{return k(e,[]).cmd!==e}catch(e){return!1}}function ko(){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=m.default.win32.basename(t).toLowerCase();return"bash.exe"===r?t:"bin"===r?m.default.win32.join(t,"bash.exe"):m.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(k(e,[]).cmd===e)return e}catch{}return"C:\\Program Files\\Git\\bin\\bash.exe"}function _o(e){if(e===Br.ZshLight)return Br.ZshLight;const t=e||process.env.SHELL||"",r="win32"===process.platform,n=r&&!e?ko():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")?Br.Zsh:t.includes("bash")&&s?Br.Bash:t.includes("pwsh")||t.includes("powershell")?Br.PowerShell:n?Br.Bash:r&&(So("pwsh")||So("powershell"))?Br.PowerShell:So("zsh")?Br.Zsh:So("bash")&&s?Br.Bash:So("pwsh")||So("powershell")?Br.PowerShell:Br.Naive}function Co(e,t){let r=e;if(!e?.userTerminalHint){const t=ko();t&&(r={...e,userTerminalHint:t})}const n=_o(r?.userTerminalHint??""),o=t?.initBashState??Zn,s=t?.initPowerShellState??ao,i=t?.initZshState??bo,a=t?.initZshLightState??go;switch(n){case Br.Zsh:return new Qn((()=>i(r)));case Br.Bash:return new Qn((()=>o(r)));case Br.PowerShell:return new Qn((()=>s()));case Br.ZshLight:return new Qn((()=>a(r)));default:{const e=t?.getPowerShellExecutable??no;return function(e){const t="win32"===process.platform,r=e?.shell??(t?no():void 0),n=process.cwd();return new ho(n,{...e,shell:r})}({env:r?.env,shell:"win32"===process.platform?e():void 0})}}}const Eo={perUser:{type:"insecure_none"}}},"../utils/dist/command-glob.js"(e,t,r){function n(e){const t=e.trim();return{trimmedPattern:t,regexSource:`^${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\\\*/g,".*")}$`}}function o(e,t){const{trimmedPattern:r,regexSource:o}=n(e);try{return new RegExp(o).test(t)}catch{return r===t}}function s(e){const{trimmedPattern:t,regexSource:r}=n(e);let o;try{o=new RegExp(r)}catch{return e=>t===e}return e=>{try{return o.test(e)}catch{return t===e}}}r.d(t,{T:()=>o,b:()=>s})},"../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,R,I,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),R.set(this,void 0),I.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,I,!!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,R,!!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,R=new WeakMap,I=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,I,"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,R,"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,R,"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,I,"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,I,"f")&&Y(this,s,"m",G).call(this,o)?o.__abortController.abort(new Error("evicted")):(Y(this,R,"f")||Y(this,T,"f"))&&(Y(this,R,"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,I,"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,R,"f")||Y(this,T,"f"))&&(Y(this,R,"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,R,"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:()=>R,A:()=>P,D1:()=>I,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 R(e){const t=a.default.resolve(e);return t===u||t.startsWith(`${u}/`)}function I(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=I({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:R(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:()=>f});var n=r("node:fs");function o(e){const t=(e.CURSOR_CHILD_OOM_SCORE_ADJ_OFFSET??"").trim();return/^\d+$/.test(t)?Number(t):0}let s=0===o(i=process.env)?0:function(e,t){const r=o(t);return 0===r||void 0===e||e<0?0:Math.min(e+r,1e3)}(function(){try{const e=Number.parseInt((0,n.readFileSync)("/proc/self/oom_score_adj","utf8"),10);return Number.isNaN(e)?void 0:e}catch{return}}(),i);var i;function a(){return s}function c(e){if(!("linux"!==process.platform||void 0===e||e<=0))try{(0,n.writeFileSync)(`/proc/${e}/oom_score_adj`,String(a()))}catch{}}var l=r("../utils/dist/safe-spawn-cwd.js");const u=/^\/sys\/fs\/cgroup\/[A-Za-z0-9_/.-]+$/,d=Object.freeze({kind:"direct"});function h({workloadCgroupDir:e,hopCwd:t}){const r=`echo $$ 2>/dev/null > '${e}/cgroup.procs'; echo ${a()} 2>/dev/null > /proc/$$/oom_score_adj; `;return void 0!==t?r+l.N6:`${r}exec "$0" "$@"`}function p(e){try{return!!(0,n.statSync)(e).isDirectory()&&((0,n.accessSync)(`${e}/cgroup.procs`,n.constants.W_OK),!0)}catch{return!1}}const f=function(e,t=c){return function(r,n,o,...s){const i=s[0],a=(0,l.qr)()&&null!==(c=i)&&"object"==typeof c&&!Array.isArray(c)?(0,l.mM)(n,o,i):void 0;var c;let u,d=n,p=[...o],f=s;!0===a?.hopped&&void 0!==a.hopCwd?(f=function(e,t){return[t,...e.slice(1)]}(s,a.options),"armed"===e.kind?(d="/bin/sh",p=["-c",h({workloadCgroupDir:e.workloadCgroupDir,hopCwd:a.hopCwd}),l.Gw,a.hopCwd,n,...o]):(d=a.command,p=a.args)):"armed"===e.kind&&(d=e.executable,p=[...e.argumentPrefix,n,...o]);try{u=r(d,p,...f)}catch(e){throw!0===a?.hopped&&void 0!==a.hopCwd&&(0,l.KX)(e,a.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)}(u,t),!0===a?.hopped&&void 0!==a.hopCwd?(0,l.wr)(u,a.hopCwd):u}}(function(e,t,r=p){return"linux"===e&&void 0!==t&&u.test(t)&&!t.includes("..")&&r(t)?Object.freeze({kind:"armed",workloadCgroupDir:t,executable:"/bin/sh",argumentPrefix:Object.freeze(["-c",h({workloadCgroupDir:t})])}):d}(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}))})}}}};
|