@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.
@@ -0,0 +1,206 @@
1
+ exports.id=144,exports.ids=[144],exports.modules={"./src/agent/local-executor.ts"(e,t,r){"use strict";r.d(t,{createLocalExecutor:()=>$W});var n=r("node:buffer"),o=r("node:os"),s=r("node:path"),i=r.t(s,2),a=r.n(s),c=r("../proto/dist/generated/agent/v1/agent_pb.js");const l={textDelta:(e,t)=>new c.Uq({messageStartedAtMs:t,message:{case:"textDelta",value:new c.PtE({text:e})}}),toolCallStarted:(e,t,r)=>new c.Uq({messageStartedAtMs:t.startedAtMs,message:{case:"toolCallStarted",value:new c.xuG({callId:e,toolCall:t,modelCallId:r})}}),toolCallCompleted:(e,t,r)=>new c.Uq({messageStartedAtMs:t.startedAtMs,message:{case:"toolCallCompleted",value:new c.LLS({callId:e,toolCall:t,modelCallId:r})}}),toolCallDelta:(e,t,r,n)=>new c.Uq({messageStartedAtMs:n,message:{case:"toolCallDelta",value:new c.I0n({callId:e,toolCallDelta:t,modelCallId:r})}}),thinkingDelta:(e,t,r)=>new c.Uq({messageStartedAtMs:r,message:{case:"thinkingDelta",value:new c.cHB({text:e,thinkingStyle:t})}}),thinkingCompleted:(e,t,r)=>new c.Uq({messageStartedAtMs:t,message:{case:"thinkingCompleted",value:new c.tr3({thinkingDurationMs:e,...!0===r?{narration:!0}:{}})}}),thinkingNote:e=>new c.Uq({message:{case:"thinkingNote",value:new c.Y$k({text:e})}}),taskChild:(e,t,r)=>"thinkingNote"===t.message.case?t:l.toolCallDelta(e,new c.V1v({delta:{case:"taskToolCallDelta",value:new c.aon({interactionUpdate:t})}}),r),userMessageAppended:e=>new c.Uq({messageStartedAtMs:e.startedAtMs,message:{case:"userMessageAppended",value:new c.v$T({userMessage:e})}}),partialToolCall:(e,t,r)=>new c.Uq({messageStartedAtMs:t.startedAtMs,message:{case:"partialToolCall",value:new c.fxF({callId:e,toolCall:t,modelCallId:r})}}),tokenDelta:e=>new c.Uq({message:{case:"tokenDelta",value:new c.Fyz({tokens:e})}}),summary:e=>new c.Uq({message:{case:"summary",value:new c.ECk({summary:e})}}),summaryStarted:()=>new c.Uq({message:{case:"summaryStarted",value:new c.lWT}}),heartbeat:()=>new c.Uq({message:{case:"heartbeat",value:new c.ih1}}),summaryCompleted:(e,t,r)=>new c.Uq({message:{case:"summaryCompleted",value:new c.ZM9({hookMessage:e,failed:t,fallback:r})}}),shellOutputDelta:e=>new c.Uq({message:{case:"shellOutputDelta",value:new c.Nn_({event:e})}}),modelCallCompleted:(e,t)=>new c.Uq({message:{case:"modelCallCompleted",value:new c.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 c.Uq({message:{case:"turnEnded",value:new c.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 c.QVp({rawCostCents:r,chargedCents:r,source:c.nnk.CATALOG})}:{}})}})},stepStarted:e=>new c.Uq({message:{case:"stepStarted",value:new c.dwJ({stepId:BigInt(e)})}}),toolRequestsListed:e=>new c.Uq({message:{case:"toolRequestsListed",value:new c.BU$({callCount:Math.max(0,e)})}}),voiceCallUtterance:e=>new c.Uq({message:{case:"voiceCallUtterance",value:e}}),stepCompleted:(e,t)=>new c.Uq({message:{case:"stepCompleted",value:new c.Lrv({stepId:BigInt(e),stepDurationMs:BigInt(t)})}}),activeBranchChange:(e,t)=>new c.Uq({message:{case:"activeBranchChange",value:new c.PSN({path:e,branchName:t})}}),feedbackRequest:(e,t,r,n=[],o={})=>new c.Uq({message:{case:"feedbackRequest",value:new c.apn({requestId:e,canonicalModelName:t,categories:[...r],categoryGroups:[...n],title:o.title,negativeTitle:o.negativeTitle,commentPlaceholder:o.commentPlaceholder})}})};class u{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 d=r("../context/dist/logger.js"),h=r("../metrics/dist/index.js"),p=r("../proto/dist/generated/agent/v1/exec_pb.js"),f=r("../utils/dist/writable-iterable.js");const m=/https?:\/\/\S+/gi,g=/[)"'<>,.;:\]}]$/;function w(e){const{url:t,wrappers:r}=function(e){let t=e.length;for(;t>0&&g.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 y=/ \[git: ([^\]]*)\]/;function v(e,t,r){if("object"!=typeof t||null===t)return e;if(y.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(m,w),i.length<=2048?i:`${i.slice(0,2048)}… [truncated to 2048 chars]`}`),s}var b=r("../context/dist/core.js");const S=(0,b.cF)(Symbol("machineProfile"),void 0),k=(0,d.h)("SimpleControlledExecManager"),_=(0,h.v5)("agent_exec.controlled.exec.duration_ms",{description:"Duration of controlled exec operations in milliseconds",labelNames:["exec_case"]}),C=(0,h.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"]}),E=new Set(["grepArgs","shellStreamArgs","executeHookArgs"]),x=(0,h.Pu)("agent_exec.controlled.exec.success",{description:"Count of successful controlled exec operations",labelNames:["exec_case"]}),P=(0,h.Pu)("agent_exec.controlled.exec.error",{description:"Count of failed controlled exec operations",labelNames:["exec_case"]}),R={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 I extends Error{constructor(e){super(e),this.name="ControlledExecDisposedError"}}function T(e){return e instanceof I?"EXEC_BACKEND_UNAVAILABLE":e instanceof Error&&"AgentExecStreamStartTimeoutError"===e.name?"AGENT_EXEC_STREAM_START_TIMEOUT":void 0}class A{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 ${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 p.yT({id:n,hookAdditionalContexts:e}))}}(this)}}class M{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,f.Jt)();let c;const l=()=>{c=setTimeout((()=>{a.write(new p.$Y({message:{case:"heartbeat",value:new p.VA({id:t.id})}})).then(l).catch((()=>{}))}),3e3)};l();const u=performance.now(),d=this.startResultObserver(r,o,t);return(async()=>{try{for await(const e of i){if(void 0!==d&&e instanceof p.yT)try{d.message(e)}catch{}await a.write(e)}await a.write(new p.$Y({message:{case:"streamClose",value:new p.D9({id:t.id})}})),x.increment(r,1,{exec_case:o})}catch(e){if(e instanceof f.W2)return;P.increment(r,1,{exec_case:o}),await a.write(new p.$Y({message:{case:"throw",value:new p.Fu({id:t.id,error:e instanceof Error?v(e.message,e,{includeStderr:this.includeGitStderrInThrows()}):"Unknown error",stackTrace:e instanceof Error?e.stack:void 0,errorCode:T(e)})}}))}finally{if(void 0!==d)try{d.done()}catch{}const e=performance.now()-u;if(_.histogram(r,e,{exec_case:o}),E.has(o)){const t=r.get(S)?.();void 0!==t&&C.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:R[s])??`No handler found for server message of type ${s}`;return k.error(e,i,{messageCase:s}),P.increment(e,1,{exec_case:o}),async function*(){yield new p.$Y({message:{case:"throw",value:new p.Fu({id:t.id,error:i})}}),yield new p.$Y({message:{case:"streamClose",value:new p.D9({id:t.id})}})}()}static fromResources(e,t){const r=new M(t);for(const[t,n]of e.entries())t.registerControlledImplementation(n,r);return r}}var D=r("../context/dist/otel.js");async function O(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 F=(0,b.cF)(Symbol("agentExec.remoteExecResultObserverFactory"),void 0),N={message(){},[Symbol.dispose](){}};function L(e){const t=e.get(F);if(void 0===t)return N;let r;try{r=t(e)}catch{return N}return void 0===r?N:{message(e){try{r?.message(e)}catch{r=void 0}},[Symbol.dispose](){const e=r;r=void 0;try{e?.end()}catch{}}}}var j=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},U=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const B=(0,d.h)("ExecutorResource"),W=(0,h.Pu)("agent_exec.hook_additional_context.delivered",{description:"Hook additional_context carriers drained into the caller collector",labelNames:["hook_event_name"]});class H{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=j(n,(0,D.VI)(e.withName("ExecutorResource.execute")),!1),s=o.ctx;void 0!==r?.execId&&o.span.setAttribute("exec.id",r.execId);const i=(0,D.mJ)(s),a=i?new p.Kg(i):void 0,c=this.execManager.createExecInstance(s,(e=>{const n=this.serializeArgs(e,t);return new p.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 O(c);if(void 0===l)throw new Error("No exec result");let{firstItem:u,rest:d}=l;const h=j(n,L(s),!1),f=e=>{if(h.message(e),void 0!==r?.hookContextCollector&&e.hookAdditionalContexts.length>0){r.hookContextCollector.push(...e.hookAdditionalContexts);for(const t of e.hookAdditionalContexts)W.increment(s,1,{hook_event_name:t.hookEventName})}};f(u);let m=this.deserializeResult(u);for(;void 0===m;){const e=await O(d);if(void 0===e)throw new Error("No result value");u=e.firstItem,d=e.rest,f(u),m=this.deserializeResult(u)}return(async()=>{try{for await(const e of d)f(e)}catch(e){B.info(s,"Ignoring exec stream shutdown during detached drain",{error:e})}})().catch((()=>{})),m}catch(e){n.error=e,n.hasError=!0}finally{U(n)}}}class q{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=j(n,(0,D.VI)(e.withName("StreamExecutorResource.execute")),!1).ctx,s=(0,D.mJ)(o),i=s?new p.Kg(s):void 0,a=this.execManager.createExecInstance(o,(e=>{const n=this.serializeArgs(e,t);return new p.Ye({id:n.id,message:n.message,execId:r?.execId,machineId:r?.machineId,spanContext:i,acceptHookAdditionalContexts:void 0!==r?.hookContextCollector||!0===r?.deliverAgentStoreConflictNotices})})),c=j(n,L(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{U(n)}}}function z(e){return Symbol.for(`@anysphere/agent-exec/resource/${e}`)}function G(e,t,r){return{name:e,symbol:z(e),remoteImplementation:t,registerControlledImplementation:r}}class V{constructor(e,t){this.resource=e,this.value=t}}function K(e,t){return[e,t]}function J(e,t){return t}class Z{constructor(){this.resources=new Map}register(e,t){this.resources.set(e.symbol,new V(e,t))}get(e){return J(0,this.resources.get(e.symbol)?.value)}entries(){return Array.from(this.resources.values()).map((e=>[e.resource,e.value]))}}class X{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?J(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 Q(e){return function(t,r){return new p.Ye({id:t,message:{case:e,value:r}})}}function Y(e){return t=>{if(t.message.case===e)return t.message.value}}function ee(e){return function(t,r){const n={case:e,value:r};return new p.yT({id:t,message:n})}}function te(e){return function(t){if(t.message.case===e)return{id:t.id,args:t.message.value}}}const re=G("shell-stream-executor",(e=>new q(e,Q("shellStreamArgs"),Y("shellStream"))),((e,t)=>{t.register(new $(e,te("shellStreamArgs"),ee("shellStream")))}));var ne=r("../proto/dist/generated/agent/v1/kv_pb.js"),oe=r("../agent-kv/dist/blob-store.js"),se=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 ie=(0,d.h)("ControlledKvManager");function ae(e,t,r){return e?(0,D.F)({traceId:e.traceId,spanId:e.spanId,traceFlags:e.traceFlags??1},t,r):r}function ce(e,t,r,n,o){o<=r||(0,D.xd)(e.withName(`${t}.slow`),{startTime:n,attributes:{durationMs:o,slowThresholdMs:r}},n+o)}const le=(0,h.v5)("agent_kv.controlled.get_blob.duration_ms",{description:"Duration of ControlledKvManager getBlob operations in milliseconds"}),ue=(0,h.v5)("agent_kv.controlled.set_blob.duration_ms",{description:"Duration of ControlledKvManager setBlob operations in milliseconds"});class de{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,D.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=ae(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 ne.gm({id:e.id,message:{case:"getBlobResult",value:{blobData:t?(0,oe.Fo)(t):void 0}}}))}catch(t){ie.error(o,"Error handling getBlob",t);const r=t instanceof Error?t.message:String(t);try{await this.clientStream.write(new ne.gm({id:e.id,message:{case:"getBlobResult",value:{blobData:void 0,error:{message:r}}}}))}catch(e){ie.error(o,"Error writing failed getBlobResult",e)}}finally{const e=performance.now()-t;le.histogram(o,e),ce(o,"ControlledKvManager.getBlob",50,n,e)}})());break}case"setBlobArgs":{const s=e.message.value.blobId,i=e.message.value.blobData;o((async()=>{const o=ae(e.spanContext,"ControlledKvManager.setBlob",r);try{await this.blobStore.setBlob(o,s,i),await this.clientStream.write(new ne.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 ne.gm({id:e.id,message:{case:"setBlobResult",value:{error:{message:r}}}}))}catch(e){ie.error(o,"Error writing setBlobResult",e)}}finally{const e=performance.now()-t;ue.histogram(o,e),ce(o,"ControlledKvManager.setBlob",100,n,e)}})());break}}}}finally{await Promise.allSettled(n)}}catch(e){t.error=e,t.hasError=!0}finally{se(t)}}}function he(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 pe=r("../proto/dist/generated/agent/v1/agent_service_pb.js"),fe=r("../proto/dist/generated/agent/v1/shell_exec_pb.js");Error;const me={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"},ge=Object.keys(me).filter((e=>e in me));function we(e){const t={};for(const r of ge){const n=e[r];void 0!==n&&(t[r]=n)}return t}new WeakMap;var ye=r("../utils/dist/fresh-uuid.js"),ve=r("@bufbuild/protobuf"),be=r("@connectrpc/connect"),Se=r("../../node_modules/.pnpm/@connectrpc+connect@1.6.1_patch_hash=c9c7616ccfc0246b19c6537f56676d8501713cb6c94b440d13_c9bdc997d82622067cc922804d7b4f50/node_modules/@connectrpc/connect/dist/esm/protocol/async-iterable.js"),ke=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 _e{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,D.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{ke(e)}}}const Ce=(0,d.h)("@anysphere/agent-client:checkpoint-store-waits");class Ee{constructor(e={}){this.options=e,this.inFlight=new Map}noteRouted(e){const t=Pe(e.pendingToolCalls);if(0===t.size)return xe;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){Ce.warn(e,"onExecHeldForCheckpointStore callback failed",{error:String(t)})}return Promise.all(r).then(xe)}}}function xe(){}function Pe(e){const t=new Set;for(const r of e){let e;try{e=JSON.parse(r)}catch{continue}const n=Ie(e)?e.content:void 0;if(!Array.isArray(n))continue;const o=n;for(const e of o)Ie(e)&&"tool-call"===e.type&&"string"==typeof e.toolCallId&&t.add(e.toolCallId)}return t}function Re(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 Ie(t)&&"string"==typeof t.toolCallId&&""!==t.toolCallId?t.toolCallId:void 0}function Ie(e){return"object"==typeof e&&null!==e}const Te=(0,d.h)("@anysphere/agent-client:exec-checkpoint-gate"),Ae=new Set(["shellArgs","shellStreamArgs","backgroundShellSpawnArgs","forceBackgroundShellArgs","miniSweAgentBashArgs","writeArgs","deleteArgs","mcpArgs","readMcpResourceExecArgs","computerUseArgs","recordScreenArgs","subagentArgs","forceBackgroundSubagentArgs","executeHookArgs"]),$e=new Set(["userMessageAction","resumeAction","backgroundTaskCompletionAction","goalContinuationAction","subscriptionNotificationAction","executePlanAction","asyncAskQuestionCompletionAction"]);function Me(e){const t=e.message.case;return void 0!==t&&Ae.has(t)?Re(e):void 0}const De=e=>e.replace(/[\r\n]/g,"");function Oe(e){return{...void 0!==e.parentRequestId?{"x-parent-request-id":De(e.parentRequestId)}:{},...void 0!==e.rootParentRequestId?{"x-root-parent-request-id":De(e.rootParentRequestId)}:{},...void 0!==e.parentAgentToolCallId?{"x-parent-agent-tool-call-id":De(e.parentAgentToolCallId)}:{},...!0===e.directMetaParentChildSubagent?{"x-direct-meta-parent-child-subagent":"true"}:{}}}const Fe="x-inference-authentication-jwt";function Ne(){const e=globalThis.process?.env,t=e?.INFERENCE_PROXY_JWT?.trim();return void 0===t||""===t||t.startsWith("$")?{}:{[Fe]:t}}class Le 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 je(e){return e instanceof Error&&(e instanceof Le||"isBlobNotFound"in e&&!0===e.isBlobNotFound||"BlobNotFoundError"===e.name)}var Ue=r("../proto/dist/generated/aiserver/v1/utils_pb.js"),Be=r("zod/v4");const We="relayedAttemptFailure",He=Be.object({transport:Be.boolean(),stallAborted:Be.boolean(),errorName:Be.string(),connectCode:Be.number().optional(),connectCodeName:Be.string().optional(),connectCause:Be.object({code:Be.union([Be.string(),Be.number()]).optional(),name:Be.string().optional()}).optional(),transportFailureKind:Be.string().optional(),loop:Be.string().optional(),transportMode:Be.string().optional()});function qe(e){const t=e?.details?.additionalInfo[We];if(void 0!==t)try{const e=He.safeParse(JSON.parse(t));return e.success?e.data:void 0}catch{return}}class ze 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 Ge extends ze{get kind(){return"RetriableError"}}class Ve extends ze{constructor(e,t,r={}){super(e,r),this.action=t}get kind(){return"ActionRequiredError"}}class Ke extends ze{get kind(){return"NonRetriableError"}}class Je extends Ke{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 Ze extends ze{get kind(){return"CancelledError"}}const Xe=new Set([Ue.yM.NOT_LOGGED_IN,Ue.yM.AGENT_REQUIRES_LOGIN,Ue.yM.AUTH_TOKEN_NOT_FOUND,Ue.yM.AUTH_TOKEN_EXPIRED,Ue.yM.INVALID_AUTH_ID,Ue.yM.UNAUTHORIZED,Ue.yM.GITHUB_NO_USER_CREDENTIALS,Ue.yM.GITHUB_USER_NO_ACCESS]),Qe=new Set([Ue.yM.FREE_USER_USAGE_LIMIT,Ue.yM.FREE_USER_RATE_LIMIT_EXCEEDED,Ue.yM.PRO_USER_ONLY,Ue.yM.PRO_USER_USAGE_LIMIT,Ue.yM.PRO_USER_RATE_LIMIT_EXCEEDED,Ue.yM.RATE_LIMITED,Ue.yM.RATE_LIMITED_CHANGEABLE,Ue.yM.GENERIC_RATE_LIMIT_EXCEEDED]),Ye=new Set([Ue.yM.USAGE_PRICING_REQUIRED,Ue.yM.USAGE_PRICING_REQUIRED_CHANGEABLE]),et=new Set([Ue.yM.BAD_API_KEY,Ue.yM.BAD_USER_API_KEY,Ue.yM.OUTDATED_CLIENT]),tt=new Set([Ue.yM.USER_ABORTED_REQUEST,Ue.yM.DEBOUNCED]),rt=new Set([Ue.yM.CUSTOM_MESSAGE]),nt=new Map([[be.Code.PermissionDenied,"Permission Denied"]]),ot=["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"],st=new Set(["ENOTFOUND","EAI_AGAIN","EAI_FAIL","ENODATA","ESERVFAIL","EHOSTUNREACH","ENETDOWN","ENETUNREACH","ECONNABORTED"]),it=new RegExp(`\\b(${[...st].join("|")})\\b`),at=["IMAGE_TOO_LARGE","MAX_TOKENS","CONVERSATION_TOO_LONG","CONTENT_POLICY","DEPRECATED","MAX_MODE_REQUIRED","MODEL_NO_LONGER_SUPPORTED","UNSUPPORTED_REGION","OUTDATED_CLIENT"],ct="x-cursor-inference-request-error-type",lt="AgentWebSocketDeliveryAmbiguousError";function ut(e,t={}){const{requestId:r}=t;if(e instanceof ze)return e;if(dt(e))return function(e,t){const r=pt(e),n=r.code,o=ft(e),s=void 0===o?void 0:function(e){if(void 0===e.details?.additionalInfo[We])return e;const t=e.clone();return void 0!==t.details&&(delete t.details.additionalInfo[We],t.details.equals(new Ue.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:mt(r,ct)??mt(e,ct),errorDetails:s},a={cause:e,requestId:t,displayInfo:i,...!0===qe(o)?.transport?{isTransport:!0}:{}};if(n===be.Code.Canceled||n===be.Code.Aborted)return kt(e)?new Ge(e.message,a):new Ze(e.message,a);if(void 0!==s?.error){const t=s.error;if(tt.has(t))return new Ze(vt(e,s),a);const r=s.details?.analyticsMetadata?.actionRequired;if(void 0!==r&&""!==r)return new Ve(vt(e,s),r,a);if(void 0!==Mt(s))return new Ge(vt(e,s),a);if(Xe.has(t))return new Ve(vt(e,s),"login",a);if(Qe.has(t))return new Ve(vt(e,s),"upgrade",a);if(Ye.has(t))return new Ve(vt(e,s),"payment",a);if(et.has(t))return new Ve(vt(e,s),"config",a);if(rt.has(t)&&!0!==s.details?.isRetryable)return new Ke(vt(e,s),a);if(!1===s.details?.isRetryable)return new Ke(vt(e,s),a)}if(n===be.Code.Unauthenticated)return new Ve(e.message,"login",{...a,displayInfo:ht(i,"Sign in required",r)});const c=yt(r);if(Tt.test(c))return new Ve(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(At.test(c))return new Ve(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=nt.get(n);return void 0===l||!0===s?.details?.isRetryable||kt(e)?new Ge(e.message,a):new Ke(vt(e,s),{...a,displayInfo:ht(i,l,r)})}(e,r);const n=function(e){let t=e;for(let e=0;e<10;e++){if(null==t)return;if(je(t))return t;if("object"!=typeof t||!("cause"in t))return;t=t.cause}}(e);if(void 0!==n)return new Ke(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===bt)return r;t.add(r),r=r.cause}}(e);if(void 0!==o)return new Ke(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 Ke(St,{cause:e instanceof Error?e:void 0,requestId:r,displayInfo:{title:"Out of disk space",detail:St,isRetryable:!1}});if(e instanceof Error){if("AbortError"===e.name)return new Ze(e.message,{cause:e,requestId:r});if(e.name===lt)return new Ge(e.message,{cause:e,requestId:r,isTransport:!0});if(kt(e))return new Ge(e.message,{cause:e,requestId:r})}const s=e instanceof Error?e.message:String(e);return new Ge(s,{cause:e instanceof Error?e:void 0,requestId:r})}function dt(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 ht(e,t,r){return{...e,title:e.title||t,detail:e.detail||yt(r),isRetryable:e.isRetryable??!1}}function pt(e){let t=e;for(let e=0;e<10&&t.code===be.Code.Unknown;e++){const e=t.cause;if(!dt(e))break;t=e}return t}function ft(e){let t=e;for(let e=0;e<10&&dt(t);e++){try{const e=t.findDetails?.(Ue.vj);if(void 0!==e&&e.length>0)return e[0]}catch{}t=t.cause}}function mt(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 gt(e){let t=e;for(let e=0;e<10&&"object"==typeof t&&null!==t;e++){if(dt(t))return t;t="cause"in t?t.cause:void 0}}function wt(e){const t=gt(e);return void 0===t?void 0:pt(t)}function yt(e){const t=e.rawMessage;return"string"==typeof t?t:e.message.replace(/^\[[a-z_]+\] /,"")}function vt(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 bt="SummaryPlaceholderRejectedError",St="Out of disk space. Free some space and try again.";function kt(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(ot.some((t=>e.includes(t)))||it.test(e))return!0;const n=r.code;if("string"==typeof n&&(ot.some((e=>n.includes(e)))||st.has(n)))return!0;r=r.cause}return!1}function _t(e){return ot.some((t=>e.includes(t)))||it.test(e)}function Ct(e){return e instanceof ze&&e.cause instanceof Error?kt(e.cause):e instanceof Error?kt(e):"string"==typeof e&&_t(e)}function Et(e){return void 0!==e&&e>0}function xt(e){return e+1}function Pt(e){return Object.defineProperty(e,"code",{value:"connection_stalled",enumerable:!0,configurable:!0}),e}function Rt(e){const{cause:t,requestId:r,transportErrorRetries:n,connectCode:o}=e;return Et(n)?Pt(new Ge("Connection stalled repeatedly",{cause:t,requestId:r,displayInfo:{title:"Connection stalled",detail:`The connection stalled ${xt(n)} times. Please check your network connection and try again.`,isRetryable:!0,connectCode:o}})):Pt(new Ge("Connection stalled",{cause:t,requestId:r,displayInfo:{title:"Connection stalled",detail:"The connection stalled. Please try again.",isRetryable:!0,connectCode:o}}))}const It=/^(?:Proxy \S+ refused to tunnel to |HTTP CONNECT through proxy \S+ failed: |Could not connect to proxy \S+: )/,Tt=/^Proxy \S+ refused to tunnel to \S+: 407\b/,At=/^Proxy \S+ refused to tunnel to \S+: 403\b/;function $t(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(dt(t)&&(t.code===be.Code.Canceled||t.code===be.Code.Aborted))return!0;t=null!==t&&"object"==typeof t&&"cause"in t?t.cause:void 0}return!1}function Mt(e){const t=e?.details?.additionalInfo;if(e?.error!==Ue.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 Dt=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},Ot=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Ft=(0,d.h)("@anysphere/agent-client:exec-controller");class Nt extends Error{constructor(e){super(e),this.name="LostConnection"}}class Lt{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{Dt(t,(0,D.VI)(e.withName("ClientExecController.run")),!1);const r=[],n=t=>{if((0,ve.isMessage)(t,p.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,ve.isMessage)(t,p.Nv)?void 0:Re(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,ve.isMessage)(t,p.Nv)||!i&&!e.canceled?n(t):Ft.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 be.ConnectError&&"protocol error: missing EndStreamResponse"===e.rawMessage)throw new Nt(e.message);if(e instanceof be.ConnectError&&e.code===be.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 Nt(e.message)}else{if(e instanceof f.W2)throw new Nt(e.message);if(e instanceof be.ConnectError&&e.code===be.Code.Internal){const t=e.cause;if(t instanceof Error&&t.message.includes("NGHTTP2_PROTOCOL_ERROR"))throw new Nt(e.message)}}throw e}}catch(e){t.error=e,t.hasError=!0}finally{Ot(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,D.V5)({traceId:r.traceId,spanId:r.spanId,traceFlags:r.traceFlags??1},"exec.handle",e),o=(0,D.fU)(n)}else n=e;Dt(r,o?new D.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{Ot(r)}}}const jt=(0,d.h)("@anysphere/agent-client:stall-detector"),Ut=e=>"number"==typeof e&&Number.isFinite(e)?e:void 0,Bt={nal:"[NAL client stall detector]",local_loop:"[local-loop client stall detector]",module:"[module client stall detector]"},Wt=new Set(["http2","http1_sse","http1_poll","websocket"]);function Ht(e){return void 0===e?"unknown":Wt.has(e)?e:"other"}const qt=(0,h.Pu)("agent_client.stream.stall.count",{description:"Number of bidirectional stream stalls detected",labelNames:["activity_type","message_type","loop","transport_mode"]}),zt=(0,h.v5)("agent_client.stream.stall.duration_ms",{description:"Duration of stream stalls in milliseconds",labelNames:["activity_type","loop","transport_mode"]}),Gt=(0,h.Pu)("agent_client.stream.did_stall",{description:"Number of streams that experienced at least one stall",labelNames:["loop","transport_mode"]}),Vt=(0,h.Pu)("agent_client.stream.total",{description:"Total number of streams monitored",labelNames:["loop","transport_mode"]});class Kt{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 Jt{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=Bt[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:Ht(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{jt.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($n),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"});jt.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($n);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(jt.warn(this.ctx,a,i),qt.increment(this.ctx,1,{activity_type:r?.type??"unknown",message_type:r?.messageType??"unknown",...this.metricLabels()}),this.hasEverStalled||(this.hasEverStalled=!0,Gt.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});jt.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"),zt.histogram(this.ctx,e,{activity_type:this.lastActivity?.type??"unknown",...this.metricLabels()})}[Symbol.dispose](){this.disposed||Vt.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 Zt={now:()=>performance.now(),setTimeout(e,t){const r=setTimeout(e,t);return r.unref?.(),r},clearTimeout(e){clearTimeout(e)}},Xt=(0,h.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"]}),Qt=(0,h.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"]}),Yt=(0,h.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 er=r("../proto/dist/generated/agent/v1/ask_question_tool_pb.js"),tr=r("../proto/dist/generated/agent/v1/create_plan_tool_pb.js"),rr=r("../proto/dist/generated/agent/v1/pr_management_tool_pb.js"),nr=r("../proto/dist/generated/agent/v1/replace_env_tool_pb.js"),or=r("../proto/dist/generated/agent/v1/setup_vm_environment_tool_pb.js"),sr=r("../proto/dist/generated/agent/v1/connect_scm_tool_pb.js"),ir=r("../proto/dist/generated/agent/v1/generate_image_tool_pb.js"),ar=r("../proto/dist/generated/agent/v1/mcp_auth_tool_pb.js"),cr=r("../proto/dist/generated/agent/v1/switch_mode_tool_pb.js"),lr=r("../proto/dist/generated/agent/v1/web_fetch_tool_pb.js"),ur=r("../proto/dist/generated/agent/v1/web_search_tool_pb.js");class dr 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 hr=e=>new c.Y5({id:e,result:{case:"webSearchRequestResponse",value:new ur.lI({result:{case:"approved",value:new ur.XJ}})}}),pr=(e,t)=>new c.Y5({id:e,result:{case:"webSearchRequestResponse",value:new ur.lI({result:{case:"rejected",value:new ur.yc({reason:t??""})}})}}),fr=e=>new c.Y5({id:e,result:{case:"webFetchRequestResponse",value:new lr.fS({result:{case:"approved",value:new lr.Hs}})}}),mr=(e,t)=>new c.Y5({id:e,result:{case:"webFetchRequestResponse",value:new lr.fS({result:{case:"rejected",value:new lr.m$({reason:t??""})}})}}),gr=(e,t)=>new c.Y5({id:e,result:{case:"askQuestionInteractionResponse",value:new c.zT({result:t})}}),wr=e=>new c.Y5({id:e,result:{case:"switchModeRequestResponse",value:new cr.w$({result:{case:"approved",value:new cr.q5}})}}),yr=(e,t)=>new c.Y5({id:e,result:{case:"switchModeRequestResponse",value:new cr.w$({result:{case:"rejected",value:new cr.rA({reason:t??""})}})}}),vr=(e,t)=>new c.Y5({id:e,result:{case:"createPlanRequestResponse",value:new tr.gz({result:t})}}),br=(e,t)=>new c.Y5({id:e,result:{case:"setupVmEnvironmentResult",value:t}}),Sr=(e,t)=>new c.Y5({id:e,result:{case:"replaceEnvResult",value:t}}),kr=(e,t)=>new c.Y5({id:e,result:{case:"prManagementResult",value:t}}),_r=(e,t)=>new c.Y5({id:e,result:{case:"mcpAuthRequestResponse",value:new ar.h({result:{case:"rejected",value:new ar.OI({reason:t??"Authentication was rejected"})}})}}),Cr=(e,t)=>new c.Y5({id:e,result:{case:"connectScmRequestResponse",value:new sr.qG({result:{case:"rejected",value:new sr.lB({reason:t??"Connecting GitHub was skipped"})}})}}),Er=(e,t)=>new c.Y5({id:e,result:{case:"generateImageRequestResponse",value:new ir.vW({result:{case:"approved",value:new ir.l3({description:t??""})}})}}),xr=(e,t)=>new c.Y5({id:e,result:{case:"generateImageRequestResponse",value:new ir.vW({result:{case:"rejected",value:new ir.Uq({reason:t??""})}})}});class Pr extends Error{constructor(e,t={}){super(e),this.name="InteractionListenerStreamClosedError",this.cause=t.cause,Object.setPrototypeOf(this,new.target.prototype)}}Pr.telemetryName="InteractionListenerStreamClosedError";var 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,d.h)("ClientInteractionController"),Tr=new Set(["askQuestionInteractionQuery","switchModeRequestQuery","mcpAuthRequestQuery","connectScmRequestQuery"]);class Ar{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,D.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=>{Ir.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{Rr(t)}}async handleInteractionUpdate(e,t){await this.interactionListener.sendUpdate(e,t)}handleInteractionQuery(e,t){const r=void 0!==t.query.case&&Tr.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 pr(e.id,t);case"webFetchRequestQuery":return mr(e.id,t);case"askQuestionInteractionQuery":return gr(e.id,new er.tz({result:{case:"rejected",value:new er.ox({reason:t})}}));case"switchModeRequestQuery":return yr(e.id,t);case"createPlanRequestQuery":return vr(e.id,new tr.bK({result:{case:"error",value:new tr.iY({error:t})}}));case"setupVmEnvironmentArgs":return br(e.id,new or.r$({result:{case:"success",value:new or.JH({})}}));case"replaceEnvArgs":return Sr(e.id,new nr.dV({result:{case:"failure",value:new nr.uq({errorMessage:t,setupLogs:""})}}));case"prManagementRequestQuery":return kr(e.id,new rr.HL({result:{case:"error",value:new rr.K$({error:t})}}));case"mcpAuthRequestQuery":return _r(e.id,t);case"connectScmRequestQuery":return Cr(e.id,t);case"generateImageRequestQuery":return xr(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 c.Y5))throw r;return Ir.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=>{Ir.error(e,"Error handling interaction query",t)})).finally(o)}}async function $r(e,t){let r;try{r=await e(t.signal)}catch(e){if(t.isCanceled())throw new Ze("User aborted request");throw new Ke("Failed to mint LLM Gateway credential",{cause:e instanceof Error?e:void 0,requestId:t.requestId})}if(void 0===r)throw new Ke("LLM Gateway credential minter returned no credential",{requestId:t.requestId});if(""===r.bearerToken.trim())throw new Ke("LLM Gateway credential minter returned an empty bearer token",{requestId:t.requestId});return new c.Ibo({bearerToken:r.bearerToken})}const Mr=G("request-context-executor",(e=>new H(e,Q("requestContextArgs"),Y("requestContextResult"))),((e,t)=>{t.register(new A(e,te("requestContextArgs"),ee("requestContextResult")))}));var Dr=r("../agent-kv/dist/serde.js"),Or=r("../proto/dist/generated/agent/v1/request_context_exec_pb.js"),Fr=r("../utils/dist/promise-extras.js");const Nr=15728640,Lr=(0,h.Pu)("agent_client.request_context_blob.prepared",{description:"Prepared RequestContext blob references"}),jr=(0,h.v5)("agent_client.request_context_blob.bytes",{description:"Serialized RequestContext bytes staged by the client"}),Ur=(0,h.v5)("agent_client.request_context_blob.preparation_ms",{description:"Time to hydrate, serialize, and hash RequestContext"});function Br(e){switch(e.action.case){case"userMessageAction":case"subscriptionNotificationAction":case"resumeAction":case"executePlanAction":return e.action.value;default:return}}class Wr{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,Dr.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,Dr.nj)(t),r);return this.transientBytes=r,!0}has(e){return this.transientBlobs.has((0,Dr.nj)(e))}hasAll(e){return e.every((e=>this.has(e)))}async getBlob(e,t){const r=(0,Dr.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,Dr.nj)(t),n=this.transientBlobs.get(r);void 0===n||this.persistedBlobIds.has(r)||(await(0,Fr.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 Hr({ctx:e,action:t,resources:r,blobStore:n,mode:o,maxBlobBytes:s,maxInlineDynamicBytes:i=1048576,notesSessionId:a}){const c=performance.now(),l=Br(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(Mr),o=await n.execute(e,new Or._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),Nr),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 Or.T3({rules:e.rules.map((e=>e.clone())),nonFileRules:e.nonFileRules.map((e=>e.clone())),cloudRule:e.cloudRule}),skills:new Or.CB({agentSkills:e.agentSkills.map((e=>e.clone())),skillOptions:e.skillOptions?.clone()}),subagents:new Or.yb({customSubagents:e.customSubagents.map((e=>e.clone()))}),mcps:new Or.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,oe.Bk)(i),(0,oe.Bk)(a),(0,oe.Bk)(c),(0,oe.Bk)(l)]),m=[{blobId:d,blobData:i},{blobId:h,blobData:a},{blobId:p,blobData:c},{blobId:f,blobData:l}],g=new Or.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,Lr.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,Lr.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 Lr.increment(e,1,{mode:o,outcome:d?"hydrated":"inline"}),jr.histogram(e,m,{mode:o}),Ur.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 qr(e){return Object.keys(e.fileContents).length>0}function zr(e,t){return Object.assign(new(e.getType()),e,t)}function Gr(e){return zr(e,{fileContents:{}})}function Vr(e){for(const[t]of e.entries())if(t.symbol===Mr.symbol)return e.get(Mr)}var Kr=r("../proto/dist/generated/agent/v1/cursor_rules_pb.js");const Jr=102400;function Zr(e){return"AGENTS.md"===e||"CLAUDE.md"===e||"CLAUDE.local.md"===e}function Xr({content:e,filename:t}){return Buffer.byteLength(e,"utf8")>Jr?function({content:e,filename:t}){const r=Buffer.from(e,"utf8");let n=Jr;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 Qr(e){const t=e.trim();return"true"===t||"false"!==t&&(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t)}function Yr(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=Qr(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=Qr(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 en(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 tn(e,t){return"/"===t?e.length>1:e.startsWith(`${t}/`)}const rn=[[".cursor","skills"],[".cursor","skills-cursor"],[".claude","skills"],[".claude","plugins"],[".codex","skills"],[".grok","skills"],[".agents","skills"],[".cursor","plugins"]];class nn{constructor(){this.allowed=!1}observeHeaders(e){this.allowed="1"===e.get("x-cursor-lazy-rule-bodies")}isAllowed(){return this.allowed}}function on(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!==Kr.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=en(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)=>rn.some((([n,o])=>t===n&&e[r+1]===o))))}(o))return!1;const i=t.map(en);if(!i.some((e=>tn(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&&!!(Zr(s)||s.endsWith(".mdc")&&c)&&!i.includes(a)&&i.some((e=>tn(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 Or._G({result:{case:"success",value:Object.assign(new(t.getType()),t,{requestContext:n})}})}function sn(e){return void 0!==e&&Number.isFinite(e)&&Number.isInteger(e)}function an(e,t){const{rulesByteLength:r,skillsByteLength:n}=e,{subagentsByteLength:o,mcpsByteLength:s}=e;if(!(sn(r)&&sn(n)&&sn(o)&&sn(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,...sn(i)?{dynamicBytes:i}:{}}}const cn=["alpn_failure","poll_seqno_gap","append_fatal","http_464","http_404_unimplemented","socket_reset","stream_closed_early","idle_deadline","stall","other"],ln=/\bHTTP (\d{3})\b/;function un(e){const t=e.message;return"string"==typeof t?t:""}function dn(e){return e instanceof Error&&("AbortError"===e.name||e.name===lt)}const hn={serverCap:3,transportCap:10},pn={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 fn(e){return{action:"retry",countAsServerError:!0,countAsTransportError:!1,transportFailureKind:e}}function mn(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 ze?e:ut(e,{requestId:n});const c=a instanceof Ze&&("owner"===r.abortOrigin||function(e){const t=e.displayInfo?.errorCode;return void 0!==t&&tt.has(t)}(a)),l="stall_detector"===r.abortOrigin&&!c&&(a instanceof Ze||a instanceof Ge),u="owner"===r.abortOrigin&&a instanceof Ge&&$t(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(un),o=e=>n.some((t=>t.includes(e))),s=function(e){return wt(e)?.code}(e),i=void 0===t.transportMode;if(i&&s===be.Code.Unavailable&&o("ALPN protocol failed to negotiate"))return"alpn_failure";if((i||"http1_poll"===t.transportMode)&&s===be.Code.Unavailable&&o("Unexpected seqno"))return"poll_seqno_gap";const a=n.map((e=>ln.exec(e)?.[1])).find((e=>void 0!==e));return i&&s===be.Code.Unknown&&"464"===a?"http_464":i&&s===be.Code.Unimplemented&&"404"===a?"http_404_unimplemented":s===be.Code.DeadlineExceeded&&function(e){const t=gt(e);return void 0===t?void 0:ft(t)?.error}(e)===Ue.yM.TIMEOUT?"idle_deadline":i&&s===be.Code.Unknown&&o("unsupported content type null")?"stream_closed_early":Ct(e)||function(e){return e instanceof Error&&"isTransport"in e&&!0===e.isTransport}(e)||r.some(dn)?"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(Rt(f()),{countAsTransportError:!0});const e=p((()=>Rt(f())),(()=>Rt({...f(),transportErrorRetries:void 0})),{immediateFirstRetry:!1});return"retry"===e.action?{...e,stall:!0}:e}if(a instanceof Ze&&!c&&$t(a)&&(a=new Ge(a.message,{cause:a.cause,requestId:n,displayInfo:a.displayInfo,isTransport:!0})),u)return h(new Ze(a.message,{cause:a.cause,requestId:n,displayInfo:a.displayInfo}));if(!0===t.retryAllInference&&(a instanceof Ve||a instanceof Ke)&&function(e){const t=e.displayInfo?.inferenceRequestErrorType;return void 0!==t&&!at.some((e=>e===t))}(a))return i(r.serverErrorRetries,t.serverCap)?h(a):fn(d);if(a instanceof Ze||a instanceof Ve||a instanceof Ke)return h(a);const m=function(e){return Mt(e.displayInfo?.errorDetails)}(a);if(a instanceof Ge&&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 Ge&&(!0===a.isTransport||function(e,t){const r=pn[e];return"by_signature"===r?Ct(t):"transport"===r}(d,a)||"owner"!==r.abortOrigin&&$t(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 Ge(Et(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=dt(r)?yt(r):r.message;if(It.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 Et(n)?new Ge("Connection failed repeatedly",{cause:t,requestId:r,displayInfo:{title:"Connection failed",detail:`${void 0===i?"":`${i}. `}The connection failed ${xt(n)} times. ${a}`,isRetryable:!0,connectCode:o}}):new Ge("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 Ge(t.message,{cause:t.cause,requestId:r,displayInfo:{...o,title:o?.title||"Server error",detail:o?.detail||`The server failed ${xt(n)} times. Please try again, or contact support if the issue persists.`,isRetryable:!0}})}({classified:a,requestId:n,serverErrorRetries:r.serverErrorRetries})):fn(d):h(a)}var gn=r("../proto/dist/generated/agent/v1/mcp_pb.js");const wn=(0,b.cF)(Symbol("agentTransportTimingRecorder"),void 0),yn=(0,d.h)("@anysphere/agent-client:turn-runner"),vn=1e3,bn=6e4,Sn=(0,h.Pu)("agent_client.turn.retry",{description:"Turn attempts retried by the turn runner",labelNames:["attempt","reason","loop"]});function kn(e){return e<=1?"1":2===e?"2":e<=5?"3_5":"gt5"}function _n(e){return!0===e.stall?"stall":!0===e.rateLimit?"rate_limit":e.countAsTransportError?"transport":e.countAsServerError?"server":!0===e.immediate?"speculative":"other"}const Cn=new Set(["textDelta","thinkingDelta","thinkingCompleted","partialToolCall","toolCallDelta","toolCallStarted","toolCallCompleted","tokenDelta"]);function En(e){const{message:t}=e;return("textDelta"!==t.case||void 0===t.value||!("isServerNotice"in t.value)||!0!==t.value.isServerNotice)&&Cn.has(t.case??"")}async function xn(e,t,r){await new Promise(((n,o)=>{if(t?.aborted)return void o(new Ze("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 Ze("Cancelled during backoff"))}t?.addEventListener("abort",c,{once:!0});try{r?.(s.signal)?.then(a,(()=>{}))}catch{}}))}function Pn(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 Rn(e){const{connectCode:t,connectCodeName:r,...n}=e;return void 0===r?n:{...n,connectCode:r}}async function In(e){const{ctx:t,checkpointHandler:r,runOptions:n,requestId:o,hooks:s,cancellation:i}=e,a=e.originalRequestId??o;let l=vn;const u=async(r,o,s,i,a)=>{if(s||(l=vn),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&&yn.info(t,`[${e.logging.tag}] Waiting out a rate limit`,{attempt:r,retryAfterMs:i.retryAfterMs,selectedDelayMs:n}),void await xn(n,o)}const c=s?function(e,t){const r=Math.min(3e5,3*e);return t??vn+(r-vn)*Math.random()}(l,n.fixedRetryDelayMs):function(e,t,r){const n=t?100:vn,o=r??Math.min(n*2**e,bn);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,bn),n=Math.min(r+.2*r*Math.random(),bn);return Math.max(e,n)}(c,i.retryAfterMs);u!==c&&e.logging&&yn.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&&yn.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 xn(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 i.toCancelledError(void 0,b);if(d=void 0,h=void 0,m=!1,g=!1,s.beginAttempt?.({attempt:v,originalRequestId:a}),v>0?(b=(0,ye.C)(),await(n.onRetryStarting?.(v,{actionCase:y.action.case,conversationState:w,isResume:"resumeAction"===y.action.case,attemptRequestId:b})),e.logging&&yn.info(t,`[${e.logging.tag}] Retrying attempt ${v}`,{attempt:v,actionCase:y.action.case,requestId:b,originalRequestId:a}),"resumeAction"===y.action.case&&(await(n.onRetryResuming?.({checkpointState:w,nextAttempt:v,reason:"resume_action"})),e.logging&&yn.info(t,`[${e.logging.tag}] Resuming from checkpoint`,{nextAttempt:v,reason:"resume_action"}))):(e.logging&&yn.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&&yn.info(t,`[${e.logging.tag}] Resuming from checkpoint`,{nextAttempt:v,reason:"resume_action"}))),t.canceled)throw i.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&&yn.info(t,`[${e.logging.tag}] Request successful`,{attempt:v,actionCase:y.action.case,requestId:b,originalRequestId:a}))}catch(r){if(!0===i.shortCircuit?.(r))throw i.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:a,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&&yn.warn(t,`[${e.logging.tag}] Resume attempts are streaming but not producing checkpoints; stopping automatic resume`,{noProgressResumeFailures:C,attempt:v,requestId:b,originalRequestId:a,errorName:r instanceof Error?r.name:typeof r}),T={action:"throw",error:new Ge("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}`;yn.warn(t,`[AGENT_ERROR_DIAGNOSTICS] requestId=${b} originalRequestId=${a} 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:a,...A,...$})}if("throw"===T.action){if(0===v){const r={attempt:0,actionCase:y.action.case,error:T.error,requestId:b,originalRequestId:a,enableAgentRetries:!0===n.enableAgentRetries,endlessRetries:o,stallAborted:!1,abortSources:[]};try{await(n.onErrorNotRetried?.(s.buildNonRetriedErrorInfo?.(r)??r))}catch(r){e.logging&&yn.warn(t,`[${e.logging.tag}] onErrorNotRetried callback failed`,{error:String(r),requestId:b,originalRequestId:a})}}throw e.logging&&yn.warn(t,`[${e.logging.tag}] Error not retryable`,{...A,...$,attempt:v,actionCase:y.action.case,requestId:b,originalRequestId:a,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&&yn.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:a,failedAttemptRequestId:b,nextAttempt:M})??{originatingRequestId:a,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{Sn.increment(t,1,{attempt:kn(M),reason:_n(T),loop:e.loop??"nal"})}catch{}void 0!==d&&(I=d,Pn((R=w).turns,I.turns)&&Pn(R.rootPromptMessagesJson,I.rootPromptMessagesJson)||(l=vn),w=d,y=new c.QFf({action:{case:"resumeAction",value:new c.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 Tn=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},An=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 $n=(0,b.cF)(Symbol("agentStreamMetadata"),void 0),Mn=(0,d.h)("@anysphere/agent-client:abort"),Dn=(0,d.h)("@anysphere/agent-client:retry"),On=(0,d.h)("@anysphere/agent-client:request-context-blob");async function Fn({ctx:e,action:t,resources:r,blobStore:n,options:o,source:s,transportMode:i,notifyBytes:a}){!0===o.omitRequestContextFileContents&&function(e){const t=Br(e);if(void 0===t)return;const r=t.requestContext;void 0!==r&&qr(r)&&(t.requestContext=Gr(r));const n=e.requestContextParts,o=n?.dynamicContext;void 0!==n&&void 0!==o&&qr(o)&&(e.requestContextParts=zr(n,{dynamicContext:Gr(o)}))}(t);try{const s=await Hr({ctx:e,action:t,resources:r,blobStore:n,mode:i??o.requestContextBlobTransportMode??"legacy",maxBlobBytes:o.requestContextBlobMaxBytes??Nr,maxInlineDynamicBytes:o.requestContextDynamicInlineMaxBytes??1048576,notesSessionId:o.conversationId});if(!0===a){const e=function({prepared:e,parts:t}){return"prepared"===e.kind?an(e,{dynamicByteLength:e.dynamicByteLength}):"already_prepared"===e.kind&&void 0!==t?an(t):void 0}({prepared:s,parts:t.requestContextParts});void 0!==e&&o.onRequestContextBytes?.(e)}}catch(r){t.requestContextParts=void 0,On.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 Nn=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 Ln(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 jn(e,t,r){for await(const n of t)switch(n.event.case){case"stdout":await r.sendUpdate(e,l.shellOutputDelta({case:"stdout",value:new fe.o0({data:n.event.value.data})}));break;case"stderr":await r.sendUpdate(e,l.shellOutputDelta({case:"stderr",value:new fe.Db({data:n.event.value.data})}));break;case"exit":await r.sendUpdate(e,l.shellOutputDelta({case:"exit",value:new fe.vb({code:n.event.value.code,aborted:n.event.value.aborted})}))}}function Un(e){return e instanceof Error?e.name:void 0}class Bn{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,c,l,d){const h={stack:[],error:void 0,hasError:!1};try{if(void 0!==d.maxSteps)throw new Je(d.maxSteps);const g=!0===d.omitRequestContextFileContents?function(e){const t=Vr(e);return void 0===t?e:new X(e,[K(Mr,{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&&qr(r)?new Or._G({result:{case:"success",value:zr(t,{requestContext:Gr(r)})}}):e}(await t.execute(e,r,n))})])}(s):s,w=!0===d.lazyFileScopedRuleBodies?new nn:void 0,y=void 0===w?g:function(e,t){const r=Vr(e);return void 0===r?e:new X(e,[K(Mr,{execute:async(e,n,o)=>{const s=await r.execute(e,n,o);return void 0!==o?.execId&&t.isAllowed()?on(s):s}})])}(g,w),v=void 0===w?d:{...d,onHeader:e=>{w.observeHeaders(e),d.onHeader?.(e)}},b=new Wr(i),S=d.generationUUID??(0,ye.C)(),k=new u,_=(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=gt(e);return void 0===t?void 0:qe(ft(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:Un(e)},r=wt(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=Un(n);return{...t,underlyingConnectError:{code:r.code,codeName:be.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){Dn.warn(e,"onNetworkPhaseStart callback failed",{error:String(t)})}const I=Tn(h,(0,D.VI)(e.withName("networkPhase")),!1);e=I.ctx,await(0,D.MG)(I.span,(()=>In({ctx:e,state:t,action:r,checkpointHandler:c,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,...Rn(n)}}},cancellation:{toCancelledError:()=>new Ze("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:u,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&&Dn.warn(n,"nal.await_stall.stale_completion_dropped",{attemptGen:t,currentGen:r()})},query:async(n,o)=>{if(t!==r())throw new Ze("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,l,v,i,S,k,C,c,u,d,s,R)},classify:(e,t)=>{const{abortOrigin:r,relayed:n}=E(e),o=mn(e,function(e,t,r=hn){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)&&cn.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 ze?e:ut(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{An(h)}var p,f,m}async runInternal(e,t,r,n,o,s,i,a,l,u,d,h,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:h,originalRequestId:m,runOptions:d})??e;const R=Tn(C,(0,D.VI)(e.withName(_)),!1);R.span.setAttribute("agent.attempt",S),R.span.setAttribute("agent.request_id",h),R.span.setAttribute("agent.original_request_id",m),e=R.ctx,e=(0,D.Mf)(e,"agent.request_id",h),e=(e=(0,D.Mf)(e,"agent.original_request_id",m)).with($n,{requestId:h,rootParentRequestId:d.rootParentRequestId,modelDetails:n});const I=new Set(w.sources);let T=void 0!==w.abortReasonName||void 0!==w.abortReasonMessage;const A=(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),Mn.error(e,"Agent client stream abort",new Error(t),{abortSource:t,requestId:h,conversationId:d.conversationId,...r??{}})};if(e.signal.aborted){const t=e.signal.reason;A("ctx_signal_abort",he(t))}else e.signal.addEventListener("abort",(()=>{const t=e.signal.reason;A("ctx_signal_abort",he(t))}),{once:!0});const[$,O]=e.withCancel();if(a.signal?.aborted){const e=a.signal?.reason;A("conversation_action_abort",he(e)),O()}else a.signal?.addEventListener("abort",(()=>{const e=a.signal?.reason;A("conversation_action_abort",he(e)),O()}),{once:!0});if(e.canceled||$.canceled){const t={ctxCanceled:e.canceled,softCancel:$.canceled};throw A("pre_run_cancel",t),new Ze("User aborted request")}const F=(0,D.VI)(e.withName("createControlledExecManager")),N=M.fromResources(s);F[Symbol.dispose]();const[L,j]=e.withCancel(),U=new Kt,{failThresholdMs:B,advisoryThresholdMs:W}=function(e,t){const r=Ut(e?.failTimeoutMs)??3e4,n=r>0&&!0!==t?.isRunningInTest?Math.max(r,2e4):r,o=Ut(e?.advisoryTimeoutMs);return{failThresholdMs:n,advisoryThresholdMs:void 0!==o&&o>0&&(n<=0||o<n)?o:void 0}}(d.stallDetectorConfig,{isRunningInTest:d.isRunningInTest});let H;const q=Tn(C,new Jt(L,{thresholdMs:B,advisoryThresholdMs:W,loop:this.options.loop,transportMode:()=>H,onStall:e=>{A("stall_detector",{thresholdMs:B,advisoryThresholdMs:W}),j(e)},onStallCallback:d.onStall,handlerTracker:U}),!1);let z,G,V;const K=(0,Se.Jt)(),J=new f.F8(K,(e=>(q.reset("outbound_write",Nn(e)),e))),Z=Tn(C,(0,D.VI)(e.withName("writeInitialRequest")),!1);let X;const Q=function(e){return new gn.Or({mcpTools:e.map((e=>({name:e.name,providerIdentifier:e.providerIdentifier,toolName:e.toolName,description:e.description,inputSchema:e.inputSchema?ve.Value.fromJson(e.inputSchema):void 0,outputSchemaJson:void 0!==e.outputSchema?JSON.stringify(e.outputSchema):void 0})))})}(u),Y=d.requestContextBlobTransportMode??"legacy",ee=0===S&&"userMessageAction"===r.action.case&&0===t.turns.length,te="ref_only"===Y&&ee?"dual":Y,[,ne]=await Promise.all([Fn({ctx:e,action:r,resources:s,blobStore:i,options:d,source:"run_request",transportMode:te,notifyBytes:0===S}),void 0===d.mintLlmGatewayCredential?Promise.resolve(void 0):$r(d.mintLlmGatewayCredential,{signal:$.signal,isCanceled:()=>$.canceled,requestId:h})]),oe={action:r,headers:d.headers??{}},se=this.options.decorateAttempt?.(oe,d)??oe,ie=new c.Mpn({conversationState:t,action:se.action,modelDetails:n,requestedModel:d.requestedModel,clientLlmGatewayCredential:ne,mcpTools:Q,conversationGroupId:d.conversationGroupId,conversationId:d.conversationId,agentSessionId:d.agentSessionId,mcpFileSystemOptions:d.mcpFileSystemOptions,customSystemPrompt:d.customSystemPrompt,systemPromptSpec:d.systemPromptSpec,harness:d.harness,computerUseCoordinateMode:d.computerUseCoordinateMode,subagentTypeName:d.subagentTypeName,excludeWorkspaceContext:d.excludeWorkspaceContext,devRawModelSlug:d.devRawModelSlug,selectedSubagentModels:d.selectedSubagentModels,subagentModelOverrides:d.subagentModelOverrides??[],selectedSubagentModelDetails:d.selectedSubagentModelsLegacy,clientSupportsInlineImages:d.clientSupportsInlineImages,clientSupportsPreviewCard:d.clientSupportsPreviewCard,startedAsNewProject:d.startedAsNewProject,firstProjectOnboarding:d.firstProjectOnboarding,clientSupportsSendToUser:d.clientSupportsSendToUser,clientSupportsRoutedModelUpdate:d.clientSupportsRoutedModelUpdate,emitModelCallUsage:d.emitModelCallUsage,canCreateCloudSubagents:d.canCreateCloudSubagents,suppressSubagentProgressUpdateTool:d.suppressSubagentProgressUpdateTool,transcriptParentConversationId:d.transcriptParentConversationId,runId:m,nextInteractionQueryId:g.peekNext(),voiceCallNotes:d.voiceCallNotes});if(X=J.write(new pe.KS({message:{case:"runRequest",value:ie}})),$.canceled){const t={ctxCanceled:e.canceled,softCancel:$.canceled};throw A("post_write_cancel",t),Z[Symbol.dispose](),new Ze("User aborted request")}const ae={...se.headers,"x-request-id":h,"x-original-request-id":m,...Oe(d),...Ne()};z=(0,D.VI)(e.withName("handshakeEstablishment")),z.span.setAttribute("handshake.firstStreamOnClient",!this.hasStartedStream),this.hasStartedStream=!0;const ce=function(e){return e?.get(wn)}(e)?.startTransportRun(),le=void 0===ce?z.ctx:function(e,t){return e.with(wn,t)}(z.ctx,ce),ue=0===S&&void 0!==d.onTtftBreakdown?k?.networkPhaseStartedAt:void 0;let me;const ge=void 0===ce&&void 0===ue?K:(E=K,x=()=>{me=performance.now(),ce?.markFirstRequestSent(me)},{[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}}),ye=this.client.run(le,ge,{signal:L.signal,headers:ae,onHeader:e=>{H=e.get("x-cursor-agent-transport-mode")??void 0,d.onHeader?.(e)},onNetworkStarted:()=>{void 0===G&&(G=performance.now(),0===S&&(V=function(e=Zt,t=25){let r,n=0,o=0,s=e.now()+t;const i=e=>{e<=0||(o+=e,e>n&&(n=e))},a=()=>{const r=e.now();i(r-s),s=r+t,c=e.setTimeout(a,t)};let c=e.setTimeout(a,t);return{stop:()=>(void 0===r&&(e.clearTimeout(c),i(e.now()-s),r={maxLagMs:n,totalLagMs:o}),r)}}()))}}),be=performance.now();let ke;const Ce=t=>{z&&(z.span.setAttribute("handshake.firstMessageHeartbeat",t),void 0!==G&&z.span.setAttribute("handshake.preNetworkMs",G-be),z[Symbol.dispose](),z=void 0),y();const r=performance.now();ke=r,d.onFirstMessage?.(r-be),void 0!==G&&(d.onFirstMessageNetwork?.(r-G),void 0!==V&&(function(e,t){const r={loop:t.loop??"nal",transport_mode:Ht(t.transportMode),first_message_slow:t.firstMessageNetworkMs>=1e3?"true":"false"};Xt.histogram(e,t.reading.maxLagMs,r),Qt.histogram(e,t.reading.totalLagMs,r),Yt.histogram(e,t.firstMessageNetworkMs,r)}(e,{loop:this.options.loop,transportMode:H,firstMessageNetworkMs:r-G,reading:V.stop()}),V=void 0))},xe=()=>{b(),d.onFirstNonHeartbeatResponse?.(performance.now()-be,S)},Re=d.onTtftBreakdown?e=>{const t=performance.now(),r=void 0===ue||void 0===me||"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:ue,transportRunCalledAt:be,firstRequestTakenAt:me,firstMessageAt:ke??t,firstOutputAt:t,firstOutputAtEpochMs:Date.now()});d.onTtftBreakdown(void 0===r?e:{...e,transit:r},S)}:void 0,Ie=!0===this.options.execCheckpointGate?function(e,t,r,n={}){return $e.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){Te.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 Pe(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&&Te.debug(e,"Handed held execs on after their checkpoint",{count:r.length,waitedMs:t}),yield*r}}else{const t="execServerMessage"===h.case?Me(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){Te.debug(e,"Held a tool call's exec for the checkpoint that names it",{toolCallId:t});try{n.onHeld?.(t)}catch(t){Te.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&&Te.info(e,"The stream ended before a checkpoint named held tool calls: dropped, never run",{toolCallIds:i().join(", ")}),u&&await(l.return?.())}}(e,t,Pe(r.state.pendingToolCalls),{holdMs:n.holdMs??5e3,now:n.now??(()=>performance.now()),onHeld:n.onHeld}):t}(e,ye,{action:se.action,state:t},void 0===this.options.onExecHeldForCheckpoint?{}:{onHeld:this.options.onExecHeldForCheckpoint}):ye,Ae=!0===this.options.execAfterCheckpointStored||!0===this.options.execCheckpointGate?new Ee(void 0===this.options.onExecHeldForCheckpointStore?{}:{onExecHeld:this.options.onExecHeldForCheckpointStore}):void 0,{interactionStream:De,execStream:Fe,checkpointStream:Le,kvStream:je,done:Ue}=function(e,t,r,n,o,s,i,a,c,l){const u=(0,Se.Jt)(),d=(0,Se.Jt)(),h=(0,Se.Jt)(),p=(0,Se.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:we(t.clientPrepLegs)},...void 0===t.preHandlerMs?{}:{preHandlerMs:t.preHandlerMs},clock:t.clientClock?"client":"server"})}catch(t){Dn.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){Dn.warn(e,"onFirstNonHeartbeatMessage callback failed",{error:String(t)})}}if(!g&&"interactionUpdate"===o.message.case&&En(o.message.value)){g=!0;try{l?.()}catch(t){Dn.warn(e,"onFirstModelOutput callback failed",{error:String(t)})}}r.reset("inbound_message",Nn(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 ze?e:ut(e);return t instanceof Ge&&function(e){return!0===e.isTransport||(e.cause instanceof Error?kt(e.cause):_t(e.message))}(t)}(w)&&(Dn.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}`;Dn.warn(e,t)}}else{const t="Stream ended without turnEnded — connection likely dropped mid-stream";void 0===w?(Dn.warn(e,t),y=new Ge(t,{isTransport:!0})):w instanceof Error&&"[aborted] aborted"===w.message?(Dn.warn(e,`${t}; retrying caught [aborted] aborted error`),y=new Ge(t,{cause:w,isTransport:!0})):Dn.warn(e,`${t}; caught non-retriable stream error, rethrowing as-is`,{caughtError:Ln(w)})}u.close(),d.close(),h.close(),p.close()}if(void 0!==y)throw y}()}}(e,Ie,q,Ce,$.signal,e.signal,xe,Re,Ae,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 He=5e3;let qe;const Ve=()=>{qe=setTimeout((()=>{J.write(new pe.KS({message:{case:"clientHeartbeat",value:new pe.kA}})).then((()=>q.onClientSentHeartbeat()),(()=>{})),Ve()}),He)},Je=()=>{void 0!==qe&&(clearTimeout(qe),qe=void 0)};Ve();try{let t;if("shellCommandAction"===r.action.case&&r.action.value.execId){const n=r.action.value,i=new fe.a({command:n.shellCommand?.command||"",parsingResult:new fe.HO,skipApproval:!0}),a=s.get(re).execute(e,i,{execId:n.execId}),c=new Ar(De,o,new f.F8(J,(e=>new pe.KS({message:{case:"interactionResponse",value:e}}))),q);t={run:async e=>{await Promise.all([U.track("handleShellStream",jn(e,a,o)),U.track("interactionController",c.run(e))])}}}else{const e=new Ar(De,o,new f.F8(J,(e=>new pe.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 c=new f.F8(J,(e=>{if((0,ve.isMessage)(e,p.yT))return new pe.KS({message:{case:"execClientMessage",value:e}});if((0,ve.isMessage)(e,p.$Y))return new pe.KS({message:{case:"execClientControlMessage",value:e}});throw new Error(`Unknown exec message (type: ${(0,ve.isMessage)(e)?e.getType().typeName:typeof e})`)})),l=new Lt(Fe,c,N,Ae),S=new de(je,new f.F8(J,(e=>new pe.KS({message:{case:"kvClientMessage",value:e}}))),i,{beforeGetBlob:async(e,t)=>i.persistForRemoteRead(e,t)}),k=new _e(Le,We,e);let _,C;const E={promise:new Promise(((e,t)=>{_=e,C=t})),resolve:_,reject:C};$.canceled?(E.resolve(),De.close()):$.signal.addEventListener("abort",(()=>{E.resolve(),De.close()}),{once:!0}),l.run($).then(E.resolve).catch(E.reject);const x=Promise.allSettled([U.track("streamSplitter",Ue.finally((()=>{Je(),a.close(),c.close()}))),U.track("execHandler",E.promise),t.run(e),U.track("checkpointController",k.run()),U.track("kvHandler",S.run(e)),U.track("conversationActionManager",a.run(e,{write:async t=>{await Fn({ctx:e,action:t,resources:s,blobStore:i,options:d,source:"queued_action"}),await J.write(new pe.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 Ze("User aborted request")):e.signal.addEventListener("abort",(()=>T.reject(new Ze("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:d.softCancelLingerMs}).then((t=>{Dn.info(e,"Soft-cancel transport linger finished",{outcome:t,requestId:h}),j()}))};$.canceled?(A(),T.reject(new Ze("User aborted request"))):$.signal.addEventListener("abort",(()=>{A(),T.reject(new Ze("User aborted request"))}),{once:!0});const M=await T.promise,D=M[0],O=M[1],F=M[3],L=e=>e.reason instanceof Error?`${e.reason.name}: ${e.reason.message}`:String(e.reason);if("rejected"===F.status)throw new Ke("Checkpoint persistence failed",{cause:F.reason instanceof Error?F.reason:void 0,requestId:h,displayInfo:{title:"Checkpoint persistence failed",detail:L(F),isRetryable:!1}});const B="ineligible_terminal_turn"===Be;if(B){const t={..."rejected"===D.status?{streamSplitter:L(D)}:{},..."rejected"===O.status?{execHandler:L(O)}:{}};Object.keys(t).length>0&&Dn.debug(e,"Ignoring handler errors after terminal checkpoint",t)}if("rejected"===D.status&&!B)throw D.reason;if("rejected"===O.status&&!B)throw O.reason;$.canceled||await this.processUnprocessedMessages(P,a,We,n,o,s,i,u,d,h,m,g,w,q,y,v,b)}finally{Je(),V?.stop(),V=void 0,z&&(z[Symbol.dispose](),z=void 0)}}catch(e){C.error=e,C.hasError=!0}finally{An(C)}var E,x}async processUnprocessedMessages(e,t,r,n,o,s,i,a,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 c.QFf({action:{case:"userMessageAction",value:new c.Vtf({userMessage:b})}}),n,o,s,i,t,r,a,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 Wn="cursor-ide-browser",Hn="cursor-dev-control",qn="custom-user-tools",zn=new Set(["cursor-app-control","cursor-backend-control","cursor-browser-extension",Wn,Hn,qn,"fsd","cursor-subscriptions","cursor-cloud","suggestions","Cursor Slack Tools","Cursor Automation Tools"]);function Gn(e){return!zn.has(e)}const Vn=new Set([Hn,Wn]);function Kn(e){if(void 0!==e&&0!==Object.keys(e).length)try{return JSON.stringify(e)}catch{return}}function Jn(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 Zn;function Xn(e){return void 0===e||void 0===e.serverIdentifiers}function Qn(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,b.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"}(Zn||(Zn={}));const Yn=G("mcp-executor",(e=>new H(e,Q("mcpArgs"),Y("mcpResult"))),((e,t)=>{t.register(new A(e,te("mcpArgs"),ee("mcpResult")))})),eo=G("list-mcp-resources-executor",(e=>new H(e,Q("listMcpResourcesExecArgs"),Y("listMcpResourcesExecResult"))),((e,t)=>{t.register(new A(e,te("listMcpResourcesExecArgs"),ee("listMcpResourcesExecResult")))})),to=G("read-mcp-resource-executor",(e=>new H(e,Q("readMcpResourceExecArgs"),Y("readMcpResourceExecResult"))),((e,t)=>{t.register(new A(e,te("readMcpResourceExecArgs"),ee("readMcpResourceExecResult")))})),ro=G("mcp-state-executor",(e=>new H(e,Q("mcpStateExecArgs"),Y("mcpStateExecResult"))),((e,t)=>{t.register(new A(e,te("mcpStateExecArgs"),ee("mcpStateExecResult")))}));var no=r("../proto/dist/generated/agent/v1/subagent_exec_pb.js");(0,b.cF)(Symbol("pendingSubagentReplay"),void 0);class oo extends Error{constructor(e,t){super(e),this.name="SubagentHostError",this.agentId=t?.agentId,this.cause=t?.cause}}const so=G("subagent-executor",(e=>new H(e,Q("subagentArgs"),Y("subagentResult"))),((e,t)=>{t.register(new A(e,te("subagentArgs"),ee("subagentResult")))})),io=G("subagent-await-executor",(e=>new H(e,Q("subagentAwaitArgs"),Y("subagentAwaitResult"))),((e,t)=>{t.register(new A(e,te("subagentAwaitArgs"),ee("subagentAwaitResult")))})),ao=G("force-background-subagent-executor",(e=>new H(e,Q("forceBackgroundSubagentArgs"),Y("forceBackgroundSubagentResult"))),((e,t)=>{t.register(new A(e,te("forceBackgroundSubagentArgs"),ee("forceBackgroundSubagentResult")))}));var co=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/status.js"),lo=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/span_kind.js");const uo=(0,be.createContextKey)(void 0,{description:"anysphere.callerContext"});function ho(e){return null!==e&&"object"==typeof e&&Symbol.asyncIterator in e}function po(e){return e instanceof Error?e:new Error(String(e))}function fo(e,t,r){return{[Symbol.asyncIterator](){const n=e[Symbol.asyncIterator]();let o=!1;const s=e=>{o||(o=!0,e?(t?.recordException(po(e)),t?.setStatus({code:co.s.ERROR,message:e instanceof Error?e.message:"Stream failed"})):t?.setStatus({code:co.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 mo(...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 go(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,D.fR)(i.withName(`rpc.${String(o)}`),{kind:lo.v.CLIENT,attributes:{"rpc.method":String(o),"rpc.system":"connect"}}),u=(0,D.fU)(l);let d;try{let o;if(r&&(o=function(e){const t=new Headers;try{const r=(0,D.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=mo(o,e))}const i=mo(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,be.createContextValues)()).set(uo,l),g={...c,headers:i,signal:p,contextValues:m},w=s.call(e,a,g);return ho(w)?fo(w,u,d):null!==(h=w)&&"object"==typeof h&&"then"in h&&"function"==typeof h.then?Promise.resolve(w).then((e=>ho(e)?fo(e,u,d):(u?.setStatus({code:co.s.OK}),u?.end(),d?.(),e))).catch((e=>{throw u?.recordException(po(e)),u?.setStatus({code:co.s.ERROR,message:e instanceof Error?e.message:"RPC call failed"}),u?.end(),d?.(),e})):(u?.setStatus({code:co.s.OK}),u?.end(),d?.(),w)}catch(e){throw u?.recordException(po(e)),u?.setStatus({code:co.s.ERROR,message:e instanceof Error?e.message:"RPC call failed"}),u?.end(),d?.(),e}var h}}})}var wo=r("node:crypto"),yo=r("../utils/dist/workspace-paths.js");function vo(){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 bo(e){return(0,s.join)(vo(),(0,yo.r_)(e))}var So=r("node:fs/promises"),ko=r("../../node_modules/.pnpm/lru-cache@11.2.5/node_modules/lru-cache/dist/esm/index.js"),_o=r("node:fs");const Co="local";function Eo(e,t){return`${e}:task_progress:${t}`}function xo(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 Po(e,t){e.hookApprovalRequirement=void 0!==t?new fe.In(t):void 0}function Ro(e){return e.hookApprovalRequirement}function Io(e){return e?.kind===fe.b.FORCE_PROMPT}function To(e){return!(!e.skipApproval||e.smartModeClassifierAllowed&&Io(e.hookApprovalRequirement))}var Ao=r("../proto/dist/generated/agent/v1/background_shell_exec_pb.js"),$o=r("../shell-exec/dist/api/index.js"),Mo=r("./src/agent/native/tree-sitter.webpack.cjs"),Do=r("./src/agent/native/tree-sitter-bash.webpack.cjs");const Oo=function(e,t=console.warn){let r;return()=>{if(void 0!==r)return r;try{const t=e();t.setLanguage(Do),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 Mo)),Fo=new Set(["file_redirect","heredoc_redirect","herestring_redirect","heredoc","here_string","redirect","redirection"]),No=new Set(["<",">",">>",">|","<>","<&",">&","&>","&>>"]);function Lo(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=>No.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)Fo.has(r.type)&&h(r,t)})(t),Fo.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 jo(e){return Lo(Oo(),e)}function Uo(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 Bo(e,t){return t>0?t>=e.length?e.length:Math.trunc(t):0}function Wo(e,t){const r=Bo(e,t);return Uo(e,r)?r-1:r}function Ho(e,t){const r=Bo(e,t);return Uo(e,r)?r+1:r}function qo(e,t){return t>0?e.length<=t?e:e.slice(0,Wo(e,t)):""}function zo(e,t){return t>0?e.length<=t?e:e.slice(Ho(e,e.length-Math.trunc(t))):""}let Go,Vo;function Ko(e,t){Go??=new TextEncoder,Vo??=new Uint8Array(65536);let r=0,n=0;for(;r<e.length&&n<t;){const o=Math.min(t-n,Vo.length),s=e.slice(r,r+o),i=Go.encodeInto(s,Vo.subarray(0,o));if(0===i.read)break;r+=i.read,n+=i.written}return{read:r,written:n}}var Jo=r("../../node_modules/.pnpm/re2js@1.2.2/node_modules/re2js/build/index.esm.js"),Zo=r("../utils/dist/path-utils.js");const Xo="path is empty or only whitespace",Qo=async e=>{const t=(0,Zo.o1)(e);try{return await(0,So.realpath)(t)}catch{return t}},Yo=1048576,es=52428800;var ts=r("../proto/dist/generated/agent/v1/sandbox_pb.js");function rs(e){if(!e)return;let t;return"allow"===e.default?t=ts.h1.ALLOW:"deny"===e.default&&(t=ts.h1.DENY),new ts.RB({version:e.version,defaultAction:t,deny:e.deny??[],allow:e.allow??[],logging:e.logging?(r=e.logging,new ts.Qq({decisionLogPath:r.decisionLogPath,logFormat:r.logFormat})):void 0});var r}function ns(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 ts.h1.ALLOW:t.default="allow";break;case ts.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,$o.T6)():(0,$o.Po)())}function os(e){switch(e){case"system":return ts.Sz.SYSTEM;case"workspace":return ts.Sz.WORKSPACE;default:return ts.Sz.UNSPECIFIED}}function ss(e){const t=function(e){switch(e){case ts.Sz.SYSTEM:return"system";case ts.Sz.WORKSPACE:return"workspace";case ts.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 is(e){if(!e)return{type:"insecure_none"};switch(e.type){case ts.vc.INSECURE_NONE:case ts.vc.UNSPECIFIED:return{type:"insecure_none",allowlistEscalated:e.allowlistEscalated,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies};case ts.vc.WORKSPACE_READWRITE:return{type:"workspace_readwrite",networkPolicy:ns(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,...ss(e)};case ts.vc.WORKSPACE_READONLY:return{type:"workspace_readonly",networkPolicy:ns(e),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadonlyPaths:e.additionalReadonlyPaths,disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicyStrict:e.networkPolicyStrict,...ss(e)};default:return{type:"insecure_none"}}}function as(e){if(e)return"insecure_none"===e.type?new ts.Mw({type:ts.vc.INSECURE_NONE,allowlistEscalated:e.allowlistEscalated,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies}):"workspace_readwrite"===e.type?new ts.Mw({type:ts.vc.WORKSPACE_READWRITE,networkAccess:(0,$o.$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:rs(e.networkPolicy),networkPolicyStrict:e.networkPolicyStrict,readBoundary:os(e.readBoundary),additionalReadPaths:"workspace"===e.readBoundary?e.additionalReadPaths??[]:[],privateTmp:e.privateTmp}):"workspace_readonly"===e.type?new ts.Mw({type:ts.vc.WORKSPACE_READONLY,networkAccess:(0,$o.$b)(e.networkPolicy),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadonlyPaths:e.additionalReadonlyPaths??[],disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicy:rs(e.networkPolicy),networkPolicyStrict:e.networkPolicyStrict,readBoundary:os(e.readBoundary),additionalReadPaths:"workspace"===e.readBoundary?e.additionalReadPaths??[]:[],privateTmp:e.privateTmp}):new ts.Mw({type:ts.vc.INSECURE_NONE})}function cs(e){return" "===e||"\t"===e||"\n"===e||"\r"===e||" "===e||"​"===e||"‌"===e||"‍"===e||"\ufeff"===e}function ls(e){let t="",r=!1;for(const n of e)cs(n)?r=!0:(r&&t.length>0&&(t+=" "),r=!1,t+=n);return t}function us(e){if(0===e.length)return!1;for(let t=0;t<e.length;t++)if("*"!==e[t])return!1;return!0}function ds(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 hs=r("../utils/dist/command-glob.js");function ps({command:e,parsingResult:t}){return[...new Set([e,...t.executableCommands.map((e=>e.fullText))])]}const fs={a:"",b:"\b",e:"",E:"",f:"\f",n:"\n",r:"\r",t:"\t",v:"\v","\\":"\\","'":"'",'"':'"',"?":"?"};function ms(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=fs[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 ls(t)}function gs({rule:e,command:t}){const r=ls(e).trim();return 0!==r.length&&(null!==function(e){const t=ls(e).trim();if(0===t.length)return"Rule cannot be empty";if(t.length>512)return"Rule cannot exceed 512 characters";if(us(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=ds(t);if(void 0!==r){const{executablePattern:e,argsPattern:t}=r;if(us(e)&&(0===t.length||us(t)))return"Rule cannot match every command; narrow the executable or argument pattern"}return null}(r)||[t.trim(),ls(t).trim(),ms(t).trim()].some((e=>function(e,t){const r=ds(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,hs.T)(e,s)&&(0,hs.T)(n,i))return!0}return e.includes("*")?(0,hs.T)(e,t):t===e||t.startsWith(`${e} `)}(r,e))))}function ws({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=>gs({rule:e,command:t}))))return e}function ys(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 vs({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=ws({matchForms:ps({command:e,parsingResult:t}),blockedCommands:r});return void 0===n?void 0:ys(n)}var bs=r("../utils/dist/test-resets.js");const Ss="CURSOR_FORCED_SHELL_EGRESS_NETWORK_DEFAULT",ks="CURSOR_FORCED_SHELL_EGRESS_DEPENDENCY_DENY_DOMAINS",_s=/\$\(|`|<\(|>\(/,Cs=/[;&|]/;let Es,xs,Ps,Rs;function Is(){if(void 0===Es){const e=(process.env.CURSOR_FORCED_SHELL_EGRESS??"").trim().toLowerCase();Es=""!==e&&"0"!==e&&"false"!==e&&"off"!==e}return Es}function Ts(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 As(e){return(process.env[e]??"").split(",").map((e=>e.trim())).filter((e=>e.length>0))}function $s(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 Ms(){if(void 0===Rs){const e=(process.env[Ss]??"").trim().toLowerCase();let t="deny";"allow"===e||"deny"===e?t=e:""!==e&&console.error(`[forced-egress] ignoring invalid value in ${Ss} (expected "allow" or "deny"); using "deny".`);const r=As("CURSOR_FORCED_SHELL_EGRESS_DENY_DOMAINS"),n=(process.env[ks]??"").trim();let o=r;"none"===n.toLowerCase()?o=[]:""!==n&&(o=As(ks)),Rs={networkDefault:t,denyDomains:r,dependencyDenyDomains:o,allowDomains:As("CURSOR_FORCED_SHELL_EGRESS_ALLOW_DOMAINS"),writablePaths:$s("CURSOR_FORCED_SHELL_EGRESS_WRITABLE_PATHS")}}return Rs}function Ds(e,t,r={}){const n=[Ts(e),Ts(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 Os(e,t){const r=function(){const e=Ms();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===xs&&(xs=Ds("CURSOR_FORCED_SHELL_EGRESS_DEPENDENCY_REGEX","CURSOR_FORCED_SHELL_EGRESS_EXTRA_DEPENDENCY_REGEX",{anchorToExecutable:!0})),xs);if(null===n)return r;const o=t?.executableCommands??[];if(t?.parsingFailed||0===o.length)return r;if(_s.test(e))return r;const s=(void 0===Ps&&(Ps=Ds("CURSOR_FORCED_SHELL_EGRESS_SOURCE_REGEX","CURSOR_FORCED_SHELL_EGRESS_EXTRA_SOURCE_REGEX")),Ps);for(const e of o){const t=e.fullText?.trim()||e.name?.trim()||"";if(!t||s?.test(t)||Cs.test(t))return r}return o.every((e=>n.test(e.fullText?.trim()||e.name?.trim()||"")))?function(){const e=Ms();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,bs.J)((function(){Es=void 0,xs=void 0,Ps=void 0,Rs=void 0}));var Fs=r("../utils/dist/lru-cache.js");const Ns=["Desktop","Documents","Downloads","Music","Movies","Pictures","Library",".Trash"],Ls="/Volumes";function js(e){const t=e.replace(/\/{2,}/g,"/");return t.length>1&&t.endsWith("/")?t.slice(0,-1):t}function Us(e,t){if("darwin"!==t.platform)return[];const r=js(e),n=r.toLowerCase(),o=js(t.homeDirectory),s="/"===r?1:r.split("/").length;return[...Ns.map((e=>`${o}/${e}`)),Ls].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 Bs=r("../utils/dist/safe-spawn-cwd.js"),Ws=r("node:util");const Hs=8388608;var qs=r("../../node_modules/.pnpm/iconv-lite@0.7.0/node_modules/iconv-lite/lib/index.js"),zs=r("../../node_modules/.pnpm/jschardet@3.1.4/node_modules/jschardet/index.js");function Gs(e){let t=1,r=0;for(;;){const n=e.indexOf("\n",r);if(-1===n)return t;t++,r=n+1}}const Vs="utf8",Ks="utf8bom",Js="latin1",Zs={"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 Xs(e){return Zs[e]||e}function Qs(e){return e.startsWith("\ufeff")?e.slice(1):e}function Ys(e){const t=e.toLowerCase();return"latin-1"===t?Js:"utf-8"===t?Vs:"utf-8-bom"===t||"utf-8 bom"===t?Ks:t}function ei(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 ti=new Ws.TextDecoder("utf-8",{fatal:!1}),ri=new Ws.TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),ni="�";function oi(e){return ti.decode(e)}function si(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 ii(e,t=1/0){let r=0,n=0;for(;r<t;){const t=e.indexOf(ni,n);if(-1===t)break;r++,n=t+1}return r}function ai(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 ci(e){return e<128?1:e<2048?2:e<65536?3:4}var li;!function(e){e.CRLF="CRLF",e.LF="LF"}(li||(li={}));const ui=[".mp4",".webm",".mov",".avi",".mkv",".wmv",".flv",".m4v"],di=new Set(ui),hi=new Ws.TextDecoder("utf-8",{fatal:!0}),pi=new Ws.TextDecoder("latin1"),fi=Buffer.from([239,187,191]),mi={utf16le:Buffer.from([255,254]),utf16be:Buffer.from([254,255]),utf32le:Buffer.from([255,254,0,0]),utf32be:Buffer.from([0,0,254,255])},gi=8192,wi="UTF-8",yi="windows-1252",vi=/[^\u0000-\u007f\ufffd]/u,bi=/(?:\p{Script=Cyrillic}\p{M}*){3,}/gu,Si=/(?:\p{Script=Greek}\p{M}*){3,}/gu,ki=/(?:\p{Script=Hebrew}\p{M}*){3,}/gu,_i=new Map([["windows-1251",bi],["ISO-8859-5",bi],["KOI8-R",bi],["x-mac-cyrillic",bi],["IBM866",bi],["IBM855",bi],["ISO-8859-7",Si],["windows-1253",Si],["windows-1255",ki],["ISO-8859-8",ki],["TIS-620",/(?:\p{Script=Thai}\p{M}*){3,}/gu]]),Ci=/\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,Ei=/[\p{L}\p{M}]+/gu,xi=String.raw`[\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u00FF\u0152\u0153\u0160\u0161\u017D\u017E\u0178]`,Pi=new RegExp(`[A-Za-z]${xi}{1,2}(?!${xi})|^${xi}{1,2}[A-Za-z]`,"u"),Ri=new Map,Ii=new Set([".png",".jpg",".jpeg",".gif",".webp",".ico",".bmp",".pdf",".zip",".tar",".gz",".exe",".dll",".so",".dylib",".bin",...ui]),Ti=/\.(png|jpg|jpeg|gif|webp|ico|bmp)$/i,Ai=new Set([".ps1",".psm1",".psd1"]),$i=/[^\u0000-\u007f]/u;function Mi(e){const t=e.toLowerCase(),r=t.lastIndexOf(".");return-1===r?"":t.substring(r)}function Di(e){const t=Mi(e);return di.has(t)}function Oi(e){const t=Mi(e);return{encoding:"binary",lineEnding:li.LF,isBinaryFile:!0,isImageFile:Ti.test(t),isVideoFile:di.has(t)}}async function Fi(e,t){return(await Ni(e,t)).text}async function Ni(e,t){const{stamp:r,buf:n}=await async function(e){const t=await(0,So.open)(e,"r");try{return{stamp:await t.stat(),buf:await t.readFile()}}finally{await t.close()}}(e),o=Bi(n);if(o.isBinaryFile)throw new Error("Binary file cannot be decoded as text");const s=Ji(e,r);let i;i=t||s||o.encoding;const{text:a,encoding:c}=Qi(n,i),l=Qs(a),u=c===Vs&&Yi(n)?Ks:c;Zi(e,r,u);const d=function(e,t){if(t===Ks)return Yi(e);const r=mi[Xs(Ys(t))];return void 0!==r&&e.subarray(0,r.length).equals(r)}(n,u);if(o.lineEnding===li.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 Li(e,t){if("binary"===t.encoding)return void Ki(e);let r;try{r=await(0,So.stat)(e)}catch{return void Ki(e)}r.size===t.buffer.byteLength?Zi(e,r,t.encoding):Ki(e)}async function ji(e,t,r,o){let s,i;try{s=r?await async function(e,t){try{return await Ui(e)}catch{}const r=Mi(e);if(Ii.has(r))return Oi(e);try{return await async function(e){const t=new Map;let r=0;for await(const n of Gi(e)){if(r>=100)break;try{const e=await Ui(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:Vi()}(t)}catch{return Vi()}}(e,r):await Ui(e)}catch{const t=Mi(e);s=Ii.has(t)?Oi(e):Vi()}const a=()=>i??=async function(e){try{const t=await(0,So.stat)(e);if(!t.isFile()||t.size>Hs)return;return await(0,So.readFile)(e)}catch{return}}(e),c=Ji(e,await async function(e){try{return await(0,So.stat)(e)}catch{return}}(e));let l;if(!s.isBinaryFile){let r;o?r=Ys(o):c?r=Ys(c):(r=Ys(s.encoding),r===Ks||qs.encodingExists(Xs(r))||(r=Vs),r!==Vs&&r!==Ks||(r=await async function(e,t){const r=await t();return void 0===r||(0,n.isUtf8)(r)?e:Xi(r).encoding===Js?Js:e}(r,a))),r===Vs&&!o&&function(e,t){return"win32"===process.platform&&Ai.has(Mi(e))&&$i.test(t)&&!t.startsWith("#!")}(e,t)&&(await async function(e){try{return await(0,So.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=Ks);const i=r===Ks||r===Vs&&!o&&await ea(e,fi),u=mi[Xs(r)];i?l=fi:u&&await ea(e,u)&&(l=u),s={...s,encoding:i?Ks:r}}const u=Gs(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=Qs(Qi(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=ei(t),o=ei(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===li.CRLF?"\r\n":"\n"}):s.lineEnding===li.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?Qs(t):t,p=s.encoding===Ks?Vs:s.encoding,f=p===Vs?await async function(e,t){if(!t.includes(ni))return;const r=await e();return void 0===r?void 0:function(e,t){if(!e.includes(ni)||(0,n.isUtf8)(t))return;const r=function(e){const t=[];let r=0;for(const n of ri.decode(e)){const o=n.codePointAt(0)??0;if(65533!==o){r+=ci(o);continue}const s=ai(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(ni);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(ni,"utf8"));return Buffer.concat(s)}(t,r)}(a,h):void 0,m=f??qs.encode(h,p,{defaultEncoding:Vs});return{lines:u,buffer:l?Buffer.concat([l,m]):m,format:s}}async function Ui(e){const t=Bi((r=await zi(e)).length===gi?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:Di(e)}:{...t,isVideoFile:!1}}function Bi(e){if(0===e.length)return Vi();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:Hi(qs.decode(e.subarray(0,gi),Xs(Ys(t)))),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1};if(!function(e){const t=Math.min(gi,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:li.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:wi,lineEnding:Wi(e),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1};if(!(0,n.isUtf8)(e)&&(o=oi(e),s=e.length,si(o)||1024*ii(o)<=s&&!vi.test(o)))return{encoding:wi,lineEnding:Wi(e),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1};const i=zs.detect(e);let a=i.confidence>.7?i.encoding:"utf-8";"ascii"===a&&(a="utf-8");const c=_i.get(a);return void 0!==c&&(a=function(e,t,r){const n=Xs(Ys(t));if(!qs.encodingExists(n))return t;const o=qs.decode(e,n);return Ci.test(o)&&function(e,t,r){const n=t.match(r)?.length??0;let o=0;for(const[t]of qs.decode(e,yi).matchAll(Ei))Pi.test(t)&&o++;return o>n}(e,o,r)?yi:t}(e,a,c)),a!==yi||function(e,t){const r=Xs(Ys(t));return!qs.getDecoder(r).write(e).includes(ni)}(e,a)||(a="utf-8"),{encoding:a??"utf-8",lineEnding:Wi(e),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1}}function Wi(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 qi(t,r)}function Hi(e){const t=e.match(/\n/g)?.length??0,r=e.match(/\r\n/g)?.length??0;return qi(r,t-r)}function qi(e,t){return 0===e&&0===t?li.LF:e/(e+t)*100>=5?li.CRLF:li.LF}async function zi(e){const t=await(0,So.open)(e,"r");try{const e=Buffer.allocUnsafe(gi),{bytesRead:r}=await t.read(e,0,gi,0);return e.subarray(0,r)}finally{await t.close()}}async function*Gi(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,So.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*Gi(r)):n.isFile()&&(yield r)}}catch(e){return}}function Vi(){return{encoding:Vs,lineEnding:"win32"===process.platform?li.CRLF:li.LF,isBinaryFile:!1,isImageFile:!1,isVideoFile:!1}}function Ki(e){Ri.delete(e)}function Ji(e,t){const r=Ri.get(e);if(void 0!==r)return void 0!==t&&r.size===t.size&&r.mtimeMs===t.mtimeMs?r.encoding:void Ri.delete(e)}function Zi(e,t,r){if(Ri.has(e)&&Ri.delete(e),Ri.set(e,{encoding:r,size:t.size,mtimeMs:t.mtimeMs}),Ri.size<=100)return;const n=Ri.keys().next().value;void 0!==n&&Ri.delete(n)}function Xi(e){try{return{text:hi.decode(e),encoding:Vs}}catch{const t=oi(e);return si(t)?{text:t,encoding:Vs}:{text:pi.decode(e),encoding:Js}}}function Qi(e,t){const r=Ys(t);if(r===Vs||r===Ks||"ascii"===r){const t=Xi(e);return r===Ks&&t.encoding===Vs?{text:t.text,encoding:Ks}:t}if(r===Js)return{text:pi.decode(e),encoding:Js};try{const t=Xs(r);if(qs.encodingExists(t))return{text:qs.decode(e,t),encoding:r}}catch{}return Xi(e)}function Yi(e){return e.length>=fi.length&&e[0]===fi[0]&&e[1]===fi[1]&&e[2]===fi[2]}async function ea(e,t){try{return(await zi(e)).subarray(0,t.length).equals(t)}catch{return!1}}var ta=r("../../node_modules/.pnpm/ignore@7.0.5/node_modules/ignore/index.js");class ra{constructor({ttlMs:e,now:t=Date.now}){this.entries=new Map,this.nextSweepAtMs=0,this.ttlMs="function"==typeof e?e:ra.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 na=r("node:string_decoder");const oa=new Map,sa=new Map;let ia;function aa(e){return(0,wo.createHash)("sha256").update(e).digest("hex").slice(0,16)}async function ca(e){try{return await(0,So.access)(e),!0}catch{return!1}}async function la(e){const t=await(0,So.stat)(e),r=oa.get(e);if(void 0!==r&&r.mtimeMs===t.mtimeMs&&r.size===t.size&&(r.ripgrepPath===e||await ca(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=Bi(t);return r.isBinaryFile?oi(t):Qs(Qi(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(ia??=(0,So.mkdtemp)((0,s.join)((0,o.tmpdir)(),"cursorignore-utf8-")).then((e=>(process.once("exit",(()=>{try{(0,_o.rmSync)(e,{recursive:!0,force:!0})}catch{}})),e))),ia),n=(0,s.join)(r,`cursorignore-${aa(e)}-${aa(t)}.txt`);if(await ca(n))return n;const i=`${n}.${process.pid}.${Date.now()}.tmp`;return await(0,So.writeFile)(i,t,"utf8"),await(0,So.rename)(i,n),n}(e,r)}(e,await(0,So.readFile)(e));return oa.set(e,{mtimeMs:t.mtimeMs,size:t.size,ripgrepPath:i}),i}function ua(e){return Promise.all(e.map((e=>async function(e){const t=sa.get(e);if(void 0!==t)return t;const r=la(e).catch((()=>e)).finally((()=>{sa.delete(e)}));return sa.set(e,r),r}(e))))}(0,bs.J)((function(){oa.clear(),sa.clear()}));var da=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 ha(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 pa(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 ua(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,$o.spawnInSandbox)((0,$o.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=ha(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 na.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{da(r)}}(),didTimeout:w}}var fa=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});let ma;function ga(e=process.env){if(void 0!==ma)return ma;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 wa({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 ya{constructor(e=()=>ga()){this.cache=new ra({ttlMs:e})}get size(){return this.cache.size}clear(){this.cache.clear()}delete(e){this.cache.delete(wa(e))}walk(e,t){const r=wa(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,ha(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{fa(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=pa(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 va=16777216,ba=new Set([32,9,10,13]),Sa="a path through /proc or /dev/fd",ka={kind:"none"},_a={kind:"stop"};function Ca(e,t){return{kind:"refused",refused:{name:e,reason:t}}}async function Ea(e){const t=await async function(e){if(void 0===await(0,So.lstat)(e).catch((()=>{})))return ka;if(await Ra(Buffer.from(e)))return Ca(".git",Sa);const t=await(0,So.stat)(e).catch((()=>{}));if(void 0===t)return ka;if(!t.isFile())return xa(e);const r=await $a(e,{whole:1048576});if("not-regular"===r.kind)return Ca(".git","not a regular file");if("bytes"!==r.kind)return _a;const n=Buffer.from("gitdir: "),o=Fa(r.bytes);if(!o.subarray(0,n.length).equals(n)||o.length<=n.length)return _a;const i=Oa({dir:(0,s.dirname)(e),target:Na(o.subarray(n.length))});if(await Ra(i))return Ca(".git",Sa);const a=await xa(i);return"none"===a.kind?_a:a}(Da(e,".git").toString());return"none"!==t.kind?t:xa(e)}async function xa(e){const t=await async function(e){const t=await(0,So.lstat)(e).catch((()=>{}));if(void 0===t||t.isDirectory())return ka;if(t.isSymbolicLink()){const t=await(0,So.readlink)(e,{encoding:"buffer"}).catch((()=>{}));return"refs/"===t?.subarray(0,5).toString("latin1")?"valid":ka}if(!t.isFile())return Ca("HEAD","not a regular file");const r=await $a(e,{prefix:255});if("not-regular"===r.kind)return Ca("HEAD","not a regular file");if("bytes"!==r.kind)return ka;const n=Na(r.bytes.subarray(0,255)).toString("latin1");if(n.startsWith("ref:")){let e=4;for(;e<n.length&&ba.has(n.charCodeAt(e));)e++;return n.startsWith("refs/",e)?"valid":ka}return/^[0-9a-fA-F]{40}/.test(n)?"valid":ka}(Da(e,"HEAD"));if("valid"!==t)return t;let r=e;const n=Da(e,"commondir");if(void 0!==await(0,So.lstat)(n).catch((()=>{}))){if(await Ra(n))return Ca("commondir",Sa);const t=await $a(n,{whole:va});switch(t.kind){case"bytes":{if(0===t.bytes.length)return _a;const n=Oa({dir:e,target:Na(Fa(t.bytes))});if(await Ra(n))return Ca("commondir",Sa);const o=await(0,So.realpath)(n,{encoding:"buffer"}).catch((()=>{}));if(void 0===o)return ka;r=o;break}case"too-large":return Ca("commondir","over the size cap");case"not-regular":return Ca("commondir","not a regular file");case"directory":case"unreadable":return _a;default:throw new Error(`unhandled read ${String(t)}`)}}for(const e of["objects","refs"]){const t=Da(r,e);if(await Ra(t))return Ca(e,Sa);if(!await Ma(t))return ka}return{kind:"repository",gitDir:e,commonDir:r}}async function Pa({gitDir:e,commonDir:t}){const r=[["HEAD",Da(e,"HEAD")],["config.worktree",Da(e,"config.worktree")],["config",Da(t,"config")],["info/exclude",Da(Da(t,"info"),"exclude")]];for(const[e,t]of r){if(await Ra(t))return{name:e,reason:Sa};const r=await(0,So.stat)(t).catch((()=>{}));if(void 0!==r&&!r.isDirectory()&&!await Aa(r)){if(!r.isFile())return{name:e,reason:"not a regular file"};if(r.size>va)return{name:e,reason:"over the size cap"}}}}async function Ra(e){if("win32"===process.platform)return!1;const t=Ia(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,So.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(...Ia(c).reverse())}return!1}function Ia(e){return e.split("/").filter((e=>""!==e&&"."!==e))}let Ta;async function Aa(e){if(!e.isCharacterDevice())return!1;Ta??=(0,So.stat)("/dev/null").catch((()=>{}));const t=await Ta;return void 0!==t&&e.dev===t.dev&&e.ino===t.ino}async function $a(e,t){const r=_o.constants.O_RDONLY|(_o.constants.O_NONBLOCK??0)|(_o.constants.O_NOCTTY??0),n=await(0,So.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 Ma(e){return(0,So.access)(e,_o.constants.X_OK).then((()=>!0),(()=>!1))}function Da(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 Oa({dir:e,target:t}){return(0,s.isAbsolute)(t.toString("latin1"))?t:Buffer.concat([Da(e,""),t])}function Fa(e){let t=e.length;for(;t>0&&(10===e[t-1]||13===e[t-1]);)t--;return e.subarray(0,t)}function Na(e){const t=e.indexOf(0);return-1===t?e:e.subarray(0,t)}const La=[{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 ja(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 Ua(e,t){const r=ja(t);return r?`${e}${r}`.toLowerCase():""}new Map(La.map((e=>[e.gitHost,e.apiHost]))),new Map(La.map((e=>[e.gitHost,e.gitCdnHost]))),new Map(La.map((e=>[e.gitHost,e.cloneKitS3Host]))),new Map(La.map((e=>[e.gitHost,e.rawUserContentHost]))),new Map(La.map((e=>[e.apiHost,e.gitHost]))),new Map(La.map((e=>[e.apiHost,e.internalHost])));const Ba=new Map;function Wa(e){const t=Ba.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 Ua(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 Ua(n.includes("@")?n.slice(n.lastIndexOf("@")+1):n,o)}}(e);return Ba.size>=16384&&Ba.clear(),Ba.set(e,r),r}function Ha(e){return/^origin(-[a-z0-9]+)?\.cursor\.com$/i.test(e)}(function(e){const t=La.find((t=>t.stage===e));if(void 0===t)throw new Error(`unknown Origin stage: ${e}`);return t})("prod").gitHost;const qa=new Map;function za(e){if(void 0===e)return;if(qa.has(e))return qa.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||!Ha(t.hostname))return;const r=ja(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 qa.size>=16384&&qa.clear(),qa.set(e,t),t}function Ga(e){return void 0!==function(e){const t=za(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 Va=(0,d.h)("local-exec:git-root"),Ka=new WeakMap,Ja=new Map;function Za(e,t,r){return Xa(e,t,r).then((e=>"repository"===e.kind?e.root:null))}function Xa(e,t,r){const n=performance.now();let o=Ka.get(t);void 0===o&&(o=new Map,Ka.set(t,o));const s=o.get(r);if(void 0!==s&&Qa(s,n))return s.result;for(const[e,t]of o)Qa(t,n)||o.delete(e);const i=t.guardedRootLookup,a=void 0===i?{result:tc(e,t,r,void 0),windowStart:n}:{result:Ya(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 Qa(e,t){return void 0===e.windowStart||t-e.windowStart<5e3}async function Ya(e,t,r,n){const o=new AbortController,i=performance.now()+n,a=await(0,Fr.wj)(async function({ctx:e,gitExecutor:t,startPath:r,deadline:n,settled:o}){const i=await function(e){let t=Ja.get(e);if(void 0===t){t=async function(e){const t=await(0,So.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,So.stat)(t).catch((()=>{})))?.dev;for(let e=t;;){const t=await Ea(e);switch(t.kind){case"refused":return t.refused;case"stop":return;case"repository":return Pa(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,So.stat)(n).catch((()=>{})))?.dev!==r)return;e=n}}(e),Ja.set(e,t);const r=()=>{Ja.delete(e)};t.then(r,r)}return t}(r);if(o.aborted)return{kind:"unknown",reason:"timed-out"};if(void 0!==i)return Va.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"}:tc(e,t,r,a)}({ctx:e,gitExecutor:t,startPath:r,deadline:i,settled:o.signal}),n).catch((t=>t instanceof Fr.MU?{kind:"unknown",reason:"timed-out"}:(Va.warn(e,"findGitRoot: the admin file check failed; not starting git",{code:ec(t)}),{kind:"unknown",reason:"refused"}))).finally((()=>{o.abort()}));return"unknown"===a.kind&&"timed-out"===a.reason&&Va.warn(e,"findGitRoot: the lookup ran past its bound; its answer is unknown",{timeoutMs:n}),a}function ec(e){return"object"==typeof e&&null!==e&&"code"in e&&"string"==typeof e.code?e.code:void 0}async function tc(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 rc(e,t,r){try{return(await t.exec(e,r,["config","--get","remote.origin.url"],{caller:"getGitRemoteUrl"})).stdout.trim()}catch{return}}function nc(e){const t=e.trim();if(""===t)return t;try{const e=new URL(t);return""===e.host?sc(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=oc.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)??sc(t)??t}}const oc=new Set(["ftp","file","http","https","ws","wss"]);function sc(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 ic=["**/node_modules/**","**/.git/**","**/.turbo/**","**/.next/**","**/.cache/**","**/.pnpm/**","**/.yarn/**","**/dist/**","**/build/**","**/out/**","**/target/**","**/.vscode/**","**/.idea/**","**/venv/**","**/__pycache__/**","**/logs/**","**/tmp/**","**/temp/**"];function ac(e,t){return Us(e,t).map((t=>`/${s.posix.relative(e,t)}`))}var cc=r("../../node_modules/.pnpm/picomatch@4.0.5/node_modules/picomatch/index.js");function lc(e,t){return e.some((e=>{return"*"===e.url.trim()?(e.patterns??[]).some((e=>hc(e.pattern,t))):!((r=e.url).includes("://")||r.includes("github.com")||r.includes("gitlab.com")||r.includes("bitbucket.org")||r.includes("@"))&&hc(e.url,t);var r}))}function uc(e,t,r){return dc(e.url,t)&&(e.patterns??[]).some((e=>hc(e.pattern,r)))}function dc(e,t){return e.includes("*")?"*"===e.trim()||function(e,t){const r=e.trim();return!!hc(r,t)||!!r.startsWith("*/")&&hc(`**/${r.slice(2)}`,t)}(wc(e),wc(t)):wc(e)===wc(t)}function hc(e,t){const r=e.trim();return!("."!==t&&""!==t||"**"!==r&&"**/*"!==r)||function(e){const t=mc.get(e);if(void 0!==t)return t;let r;try{const t=cc(e,{dot:!0});r=r=>{try{return t(r)}catch{return e===r}}}catch{r=t=>e===t}return gc(mc,pc,e,r)}(r)(t)}const pc=2048,fc=new Map,mc=new Map;function gc(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 wc(e){const t=fc.get(e);if(void 0!==t)return t;const r=(function(e){const t=za(e);if(void 0!==t)return`${t.hostname}/git/${t.owner}/${t.name}`.toLowerCase()}(n=e)??Wa(n))||function(e){let t=e.trim();t.startsWith("git@")&&(t=`https://${t.slice(4).replace(":","/")}`),/^[a-z][a-z0-9+.-]*:\/\//i.test(t)&&!/^https?:\/\//i.test(t)&&(t=t.replace(/^[a-z][a-z0-9+.-]*:\/\//i,"https://")),/^https?:\/\//i.test(t)||(t=`https://${t}`);try{const e=new URL(t),r=e.pathname.replace(/\/+$/,"").replace(/\.git$/i,"").replace(/\/+$/,"");return e.hostname+r}catch{return t=t.replace(/^https?:\/\//i,""),t=t.replace(/[?#].*$/,""),t=t.replace(/\/+$/,""),t=t.replace(/\.git$/i,""),t=t.replace(/\/+$/,""),t}}(e).toLowerCase();var n;return gc(fc,2048,e,r)}function yc(e){if("object"==typeof e&&null!==e&&"code"in e){const t=e.code;if("string"==typeof t)return t}}function vc(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,bs.J)((function(){fc.clear(),mc.clear()}));const bc=[".gitignore",".cursorignore"];async function Sc(e){if(!(0,s.isAbsolute)(e))return null;const t=await(0,Zo.DN)(e);return null===t?null:t}function kc(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 _c{constructor(e,t,r,n={}){this.disposeRequested=!1,this.initIgnoreService=()=>xc.init((0,b.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 Cc=Math.min(8,Math.max(1,Math.floor(o.availableParallelism()/2)));class Ec{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=ta().add(t),this.instances.set(e,r)),r}delete(e){this.instances.delete(e)}clear(){this.instances.clear(),this.lookups=0}}class xc{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 Fs.q({max:2e3}),this.cursorIgnoreCache=new Fs.q({max:2e3}),this.gitRootCache=new Fs.q({max:1e4}),this.gitRemoteUrlCache=new Fs.q({max:200}),this.hasGitDirCache=new Fs.q({max:1e3}),this.gitParsedIgnoreCache=new Ec(1e4),this.cursorParsedIgnoreCache=new Ec(1e4),this.ignoreMappingsHaveEntries=!1,this.directoryWalkPlacementCache=new Fs.q({max:1e4}),this.extraRootCursorIgnoreCache=new Fs.q({max:32}),this.extraGitRepoMappingCache=new Fs.q({max:32}),this.unwalkedFolders=o.flatMap((e=>Us(e,s)))}static getRipwalkCache(){return xc.ripwalkCache??=new ya,xc.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,Zo.DN)(e)??(0,Zo.o1)(e)}static async init(e,t,r,n,s={platform:process.platform,homeDirectory:o.homedir()}){const i={...s,homeDirectory:await(0,Zo.DN)(s.homeDirectory)??s.homeDirectory},a=await(0,Fr.PH)(r,(async e=>{const t=await(0,Zo.DN)(e);return null===t?(console.warn(`[IgnoreService] Cannot resolve workspace root, using as-is: ${e}`),e):t})),c={},l={},u=await(0,Fr.PH)(a,(async r=>({root:r,lookup:await Xa(e,t,r)}))),d=u.map((({root:e,lookup:t})=>"none"===t.kind?null:"unknown"===t.kind||Us(t.root,i).length>0?e:t.root)).filter((e=>null!==e)),h=u.filter((({lookup:e})=>"unknown"===e.kind)).map((({root:e})=>(0,Zo.o1)(e)));return d.length>0&&await Promise.all([xc.initializeIgnoreMapping({rootDirectories:d,ignoreFileName:".gitignore",mapping:c,scanEnvironment:i,unknownRoots:h}),xc.initializeIgnoreMapping({rootDirectories:a,ignoreFileName:".cursorignore",mapping:l,scanEnvironment:i,unknownRoots:h})]),new xc(t,c,l,n,a,i)}static async preloadHierarchy(e,t,r,n){let o=(0,Zo.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 xc.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,So.access)(n,So.constants.F_OK);const t=await Fi(n),o=xc.parseIgnoreRules(t);r[e]=o}catch(o){"ENOENT"===yc(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=xc.deduplicateRootDirectories(e),a=await xc.promiseQueue.enqueueList(i,(e=>xc.findFilesWithRipgrep({rootDirectory:e,fileName:t,scanEnvironment:n,noIgnoreVcs:o.some((t=>(0,Zo.ZU)({basePath:e,targetPath:t})))}))),c=Array.from(a.values()).flat();await Promise.all(c.map((async e=>{try{const t=await Fi(e),n=xc.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 xc.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,b.q6)(),i=[],a={root:e,includeGlobs:bc.map((e=>`**/${e}`)),excludeGlobs:[...ic,...ac(e,r)],noIgnoreVcs:n,source:"ignore_scan"},c=xc.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=xc.parseIgnoreRules(await Fi((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)=>ta().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,Zo.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,Zo.ZU)({basePath:t,targetPath:e})))?"walked":"outside",this.directoryWalkPlacementCache.set(e,r),r}async populateHierarchyIfNeeded(e,t,r){let n=(0,s.dirname)((0,Zo.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 xc.promiseQueue.enqueueList(o,(e=>xc.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,Zo.ZU)({basePath:n,targetPath:e}))continue;const t=(0,s.relative)(n,e);if(""===t)continue;const i=r(n,o),a=(0,Zo.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,Zo.ZU)({basePath:t,targetPath:e}))continue;const o=(0,s.join)(e,".cursorignore");try{await(0,So.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,Bs.$f)(t))continue;const e=await(0,Zo.DN)(t);if(null===e||".git"===(0,s.basename)(e)||this.rootDirectories.some((t=>(0,Zo.ZU)({basePath:t,targetPath:e})))||r.includes(e))continue;const n=await So.stat(e).catch((e=>{if(void 0===yc(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 Xa((0,b.q6)(),this.gitExecutor,e);await xc.initializeIgnoreMapping({rootDirectories:[e],ignoreFileName:".cursorignore",mapping:t,scanEnvironment:this.scanEnvironment,unknownRoots:"unknown"===o?.kind?[e]:[]}),r={mapping:t,expiresAt:n+ga()},this.extraRootCursorIgnoreCache.set(e,r)}for(const[e,n]of Object.entries(r.mapping))t[e]=kc(t[e],n)}for(const e of[...this.rootDirectories,...r]){const r=await this.getRepoBlockExcludeGlobs(e);0!==r.length&&(t[e]=kc(t[e],r))}return t}async getGitIgnoreMapping(){return{...this.gitIgnoreMapping}}static deduplicateRootDirectories(e){const t=[...e.map((e=>(0,Zo.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 Fs.q({max:1}),this.cursorIgnoreCache=new Fs.q({max:1}),this.gitRootCache=new Fs.q({max:1}),this.gitRemoteUrlCache=new Fs.q({max:1}),this.hasGitDirCache=new Fs.q({max:1}),this.directoryWalkPlacementCache=new Fs.q({max:1}),this.extraRootCursorIgnoreCache=new Fs.q({max:1}),this.extraGitRepoMappingCache=new Fs.q({max:1}),this.gitParsedIgnoreCache.clear(),this.cursorParsedIgnoreCache.clear(),this.gitRepoMappingPromise=void 0}async handleCursorIgnoreCreated(e){const t=(0,s.dirname)(e),r=await Fi(e),n=xc.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 Fi(e),n=xc.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,Zo.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,So.access)((0,s.join)(e,".git"),So.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,Zo.ZU)({basePath:await this.getCursorDataDir(),targetPath:e})&&function(e,t){return 0!==e.allowed.length&&!lc(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=>uc(e,o,s))))return!0;e.allowed.length>0&&!n&&(n=!0,r=e.allowed.some((e=>uc(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 rc((0,b.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,Zo.ZU)({basePath:r,targetPath:e})&&(void 0===t||r.length>t.length)&&(t=r);return void 0!==t?(0,Zo.oL)((0,s.relative)(t,e)):(0,Zo.oL)(e)}getCursorDataDir(){return this.cursorDataDirPromise??=(async()=>{const e=(0,s.join)(o.homedir(),".cursor");return await(0,Zo.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,Zo.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=>dc(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,b.q6)();for(const t of e){const e=(0,Zo.o1)(t);try{await(0,So.access)((0,s.join)(e,".git"),So.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,So.access)((0,s.join)(i,".git"),So.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,...ac(e,this.scanEnvironment)],noIgnoreVcs:!0,source:"ignore_scan"},i=xc.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 rc(o,this.gitExecutor,e);t.set(e,r)}catch{t.set(e,void 0)}}))),t}}async function Pc(e,t){let r=e;if(Is()&&(r=Os(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]=kc(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,$o.s9)(r.additionalReadwritePaths,[...n.roots,...n.commonDirs]);return{...r,additionalReadwritePaths:e.length>0?e:void 0,ignoreMapping:o}}return{...r,ignoreMapping:o}}xc.promiseQueue=new Fr.TJ({max:Cc});var Rc=r("../proto/dist/generated/agent/v1/mcp_exec_pb.js");const Ic="agent-tools",Tc=51380224;var Ac=r("../proto/dist/generated/agent/v1/utils_pb.js");const $c=new Ws.TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}),Mc=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]]),Dc=new Set([194,195,226,239]),Oc=/\p{Lu}/u,Fc=new Set([" ","­","«","»","‹","›","‘","’","“","”","•","–","—","…","™"]),Nc=new Set(["¿","¡"]),Lc=new Map([[215,new Set(["¹","²","³","¼","½","¾","°","±","€","¢","£","¤","¥"])],[216,new Set(["¹","²","³","¼","½","¾","°","±","€","¢","£","¤","¥"])],[197,new Set(["¹","²","³"])],[205,Nc],[209,Nc],[211,Nc],[218,Nc],[220,Nc]]),jc=new Set(["ƒ","Š","Œ","Ž","š","œ","ž","Ÿ"]),Uc=/[\p{Cc}\p{Cn}\p{Cs}\p{Co}]/u;function Bc(e){if(void 0===e)return;const t=e.charCodeAt(0);return t>=128&&t<=191?t:Mc.get(e)}function Wc(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=Bc(e[t+r]);if(void 0===n)return;o[r]=n}const s=e[t+1];if(Dc.has(r)){if(195===r&&Fc.has(s)&&t>0&&Oc.test(e[t-1]))return}else{if(Fc.has(s))return;if(!0===Lc.get(r)?.has(s))return;if(3===n&&jc.has(s)&&Fc.has(e[t+2]))return}let i;try{i=$c.decode(o)}catch{return}return Uc.test(i)?void 0:{index:t,text:e.slice(t,t+n),repaired:i}}function Hc(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=Wc(e,n);void 0!==o?(r.push(o),n+=o.text.length):n++}return r}const qc=`[\\u00c2-\\u00f0][\\u0080-\\u00bf${[...Mc.keys()].join("")}]`,zc=new RegExp(qc),Gc=/\p{L}/u;function Vc(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||!Mc.has(e[t+r])))return 0}return n}function Kc(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||!Oc.test(e[t.index-1]))return!0;const n=t.index+t.text.length;return n<e.length&&Gc.test(e[n])}const Jc=["mojibake","replacement_chars"];function Zc(e){return e<=1?"1":e<6?"2-5":"6+"}function Xc(e){return e<=0?"0":Zc(e)}function Qc(e,t,r){if(void 0===e)return"new";if(t>0)return"damaged";const n=ol(r);return"utf8"!==n&&"utf8_bom"!==n?"other_encoding":"intact"}function Yc(e,t){return e<=t?"existing_only":"new_damage"}function el(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(Hc(t,1).length>0)return!0;t=""}t+=n.repaired,r=n.index+n.text.length}return Hc(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 tl(e){return{detector:e,outcome:"clean",afterCount:0,beforeCount:0}}function rl(e,t,r){const n=Hc(r,1e3);if(0===n.length)return tl("mojibake");const o=void 0===e?[]:Hc(e,Math.max(n.length,6));return{detector:"mojibake",outcome:Yc(n.length,o.length),file:Qc(e,o.length,t),afterCount:n.length,beforeCount:o.length,pattern:el(n,o)}}function nl(e,t,r){const n=ii(r);if(0===n)return tl("replacement_chars");const o=void 0===e?0:ii(e);return{detector:"replacement_chars",outcome:Yc(n,o),file:Qc(e,o,t),afterCount:n,beforeCount:o}}function ol(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 sl=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 il(e){const t=(0,s.extname)(e).slice(1).toLowerCase();return""===t?"none":sl.get(t)??"other"}const al=new Map([[1252,"1252"],[1250,"1250"],[1251,"1251"],[874,"874"],[932,"932"],[936,"936"],[949,"949"],[950,"950"],[65001,"65001"]]);function cl(e){if("string"==typeof e)return e;const t=void 0===e.acp?void 0:al.get(e.acp);return void 0===t?"other":e.oemcp===e.acp?t:`${t}_split`}function ll(e,t){if("clean"===e.outcome)return{detector:e.detector,outcome:"clean",file:"unclassified"};const r={outcome:e.outcome,file:e.file,ext:il(t.path),encoding:ol(t.encoding),code_page:cl(t.pages),run_count:Zc(e.afterCount),delta:(n=e.afterCount-e.beforeCount,n<0?"neg":Xc(n)),before_count:Xc(e.beforeCount)};var n;return"mojibake"===e.detector?{detector:"mojibake",pattern:e.pattern,...r}:{detector:"replacement_chars",...r}}class ul{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+ii(t,6-r))}labels(e,t){const r=cl(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:Xc(o),branch:e[t],stream:t,code_page:r})}return n}}const dl=/[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/,hl=Object.getOwnPropertyDescriptor(String.prototype,"isWellFormed")?.value;const pl=["replacement","lone_surrogate","mojibake_high","mojibake_medium","utf16","c1","clean"],fl=/\0[^\0]\0/,ml=/[\u0080-\u009f]/,gl=new RegExp(`[\\u0080-\\u009f]|${qc}`),wl="\\u0000",yl=/\\u(?:[dD][89a-fA-F]|0000)/,vl=/\\u[dD](?:([89abAB])|[c-fC-F])[0-9a-fA-F]{2}/g,bl=/\\u[dD][c-fC-F][0-9a-fA-F]{2}/y;function Sl(e,t){let r=0;for(;r<t&&92===e.charCodeAt(t-1-r);)r++;return r%2==0}function kl(e,t){return 92!==e.charCodeAt(t)?1:117===e.charCodeAt(t+1)?6:2}function _l(e,t={}){const r=n.Buffer.byteLength(e,"utf8")===e.length;if(!r&&e.includes("�"))return"replacement";const o=!0===t.jsonEscaped&&yl.test(e);if(!r&&function(e){return"function"!=typeof hl?function(e){return dl.test(e)}(e):!0!==Reflect.apply(hl,e,[])}(e)||o&&function(e){vl.lastIndex=0;for(let t=vl.exec(e);null!==t;t=vl.exec(e))if(Sl(e,t.index)){if(void 0===t[1])return!0;if(bl.lastIndex=t.index+6,!bl.test(e))return!0;vl.lastIndex=t.index+12}return!1}(e))return"lone_surrogate";if(function(e,t){return!(!e.includes("\0")||!fl.test(e))||t&&function(e){for(let t=e.indexOf(wl);-1!==t;t=e.indexOf(wl,t+6)){if(!Sl(e,t))continue;const r=t+6;if(!(r>=e.length||e.startsWith(wl,r))&&e.startsWith(wl,r+kl(e,r)))return!0}return!1}(e)}(e,o))return"utf16";if(r)return"clean";if(!gl.test(e))return"clean";const s=function(e){if(!zc.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?Wc(e,o):void 0;if(void 0!==i){if(t++,r=Kc(e,i),o+=i.text.length,!n||!r&&t>=256)return"medium";continue}const a=n?Vc(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":ml.test(e)?"c1":"clean"}const Cl=/^v?(\d{1,9})\.(\d{1,9})(?:\.\d{1,9})?(?:[-+][0-9A-Za-z.+-]*)?$/,El=["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}]})),xl=El[0].major,Pl=El[0].minor;function Rl(e){if(null==e)return"unknown";const t=e.trim();if(0===t.length||t.length>128)return"unknown";const r=Cl.exec(t);if(null===r)return"unknown";const n=Number(r[1]),o=Number(r[2]);if(n!==xl)return"other";const s=El.find((e=>e.minor===o));return void 0!==s?s.bucket:o<Pl?"older":"newer"}const Il=(0,d.h)("local-exec:encoding-slices");function Tl(e,t){if(void 0===e)return!1;try{const{enabled:r}=e;return"function"==typeof r?r(t):r}catch{return!1}}function Al(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 $l(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 Ml{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=$l(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 Dl=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"})),Ol=(0,h.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"]}),Fl=pl[0],Nl=new Map(pl.map(((e,t)=>[e,t])));function Ll(e){return Nl.get(e)??pl.length}class jl{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===Fl}noteText(e){if(0===e.length)return;const t=e.length>this.remaining?qo(e,this.remaining):e;this.remaining-=Math.max(t.length,1);const r=_l(t);Ll(r)<Ll(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 Ul{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 Bl(e,t,r,n){const o={layer:r.layer,kind:n,origin:Al(n,r.evidence??"unseen",!0===r.partial),source:r.source??r.layer,version_bucket:Rl(e.clientVersion)};void 0!==r.codePageLookup&&(o.code_page_lookup=r.codePageLookup),void 0!==r.shellKind&&(o.shell_kind=r.shellKind),Ol.increment(t,1,o)}function Wl(e,t){Il.warn(e,"encoding slice was not counted (result unaffected)",{error:t instanceof Error?t.name:"unknown"})}function Hl(e,t,r,n){if(void 0!==e&&Tl(e,t))try{const o=new jl;o.note(n),Bl(e,t,r,o.kind())}catch(e){Wl(t,e)}}function ql(e,t,r,n){if(void 0!==e&&Tl(e,t))try{Bl(e,t,r,n)}catch(e){Wl(t,e)}}class zl{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 Gl(e,t,r,n){return void 0===t?e:{execute:async(o,s,i)=>{const a=await e.execute(o,s,i);if(Tl(t,o))try{n(a)&&Hl(t,o,{layer:r},a)}catch(e){Wl(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 Vl{constructor(){this.text={stdout:new jl,stderr:new jl},this.bytes={stdout:new Ml,stderr:new Ml},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":Dl.get(e)??"unknown"}(e)}record(e,t,r,n){for(const o of["stdout","stderr"])this.produced[o]&&ql(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 Kl=r("node:child_process"),Jl=r("../utils/dist/workload-spawn.js");const Zl=(0,d.h)("local-exec:shell-output-encoding"),Xl=(0,Ws.promisify)(Kl.execFile),Ql=/^\s*OEMCP\s+REG_\w+\s+(\d+)\s*$/m,Yl=/^\s*ACP\s+REG_\w+\s+(\d+)\s*$/m;function eu(e,t){const r=t.exec(e);return null===r?void 0:Number(r[1])}const tu="㐀-䶿一-鿿豈-﫿",ru=" -〿㈀-㏿︰-﹯＀-￯",nu="‐-※←-⇿─-◿★☆",ou="぀-ヿ",su=new Map([["cp932",{script:new RegExp(`[${tu}${ru}${nu}${ou}]`),doubleByte:!0}],["cp936",{script:new RegExp(`[${tu}${ru}${nu}${ou}㄀-ㄯ]`),doubleByte:!0}],["cp949",{script:new RegExp(`[${tu}${ru}${nu}${ou}㄰-㆏가-힯]`),doubleByte:!0}],["cp950",{script:new RegExp(`[${tu}${ru}${nu}㄀-ㄯ]`),doubleByte:!0}],["cp874",{script:new RegExp("[฀-๿]"),doubleByte:!1}]]);const iu=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,Jl.D9)(Xl,"\\\\.\\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=eu(t,Ql),o=eu(t,Yl);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 qs.encodingExists(t)?t:void 0}(t);return void 0!==n&&su.has(n)?n:void 0}(i),r=i,s=!0,n=void 0,o=void 0===i.oemcp&&void 0===i.acp?"unparsed":"answered",Zl.info((0,b.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),Zl.warn((0,b.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),au=Buffer.alloc(0),cu=/[\u0080-\uffff]/;function lu(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 uu(){const e=new na.StringDecoder("utf8");return{write:t=>e.write(t),end:()=>e.end()}}function du(e,t){return qs.decode(t,e,{stripBOM:!1})}const hu=/[\xe0-\xef][\x80-\xbf]\?/;const pu=10,fu=Buffer.alloc(0),mu=new Set([7,8,9,10,11,12,13,27]);function gu(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&&!mu.has(r))return!1}return!0}function wu(e,t,r=0,n){if("utf8"===t){const t=e.indexOf(pu);return-1===t?-1:t+1}const[o,s]="utf16le"===t?[pu,0]:[0,pu];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 yu(e){const t=new na.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 vu={encoding:"utf8",skip:0};function bu(e){const t=e();let r="utf8";const n={};let o=!1;const s=()=>"utf8"===r?t:n[r]??=yu(r),i=e=>("utf8"!==r&&e.length>0&&(o=!0),e);let a,c=!0,l=fu,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?vu:void 0;const r=0===e[0]?"utf16be":0===e[1]?"utf16le":void 0;if(void 0===r)return vu;const n=wu(e,r);if(-1!==n)return gu(e,r,n)?{encoding:r,skip:0}:vu;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)&&gu(e,r,o)?{encoding:r,skip:0}:vu}const o={encoding:r,skip:0},s=e.indexOf(0),i=e.indexOf(pu);if(-1!==s&&(-1===i||s<i)){const n=s-s%2+2;return n>e.length?t?o:void 0:gu(e,r,n)?o:vu}if(-1===i)return t?vu:void 0;if("utf16le"===r&&i%2==0){if(i+1>=e.length)return t?vu:void 0;if(0===e[i+1])return o}return vu},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]===pu,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=fu}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(pu),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]===pu&&(l=Buffer.of(pu),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=wu(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):yu(t.encoding).write(n)},end(){const e=m(fu,!0)+i(s().end());return c=!0,l=fu,u=!1,d=0,a=void 0,e},branch:()=>!0===t.usedCodePage?.()?"code_page":o?"utf16":"utf8"}}var Su=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},ku=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 _u=(0,d.h)("local-exec:shell-core"),Cu=(0,h.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"]}),Eu="win32"===process.platform,xu=["CURSOR_CONVERSATION_ID","CURSOR_REQUEST_ID","CURSOR_AGENT_STORE_FILES_DIR","CURSOR_AGENT_STORE_SHARED_PATHS"];function Pu(e){return`'${e.replace(/'/g,"'\\''")}'`}async function Ru(e){try{return(await(0,So.stat)(e)).isDirectory()}catch(e){const t=yc(e);if("ENOENT"===t||"ENOTDIR"===t)return!1;throw e}}const Iu=["eval-cursorbench","cursorbench","sand-eval","eval-harness"];function Tu(e){return Iu.some((t=>e.includes(t)))?(0,wo.createHash)("sha256").update(e).digest("hex"):e}function Au(e,t){return e[t]??process.env[t]}const $u=/^[A-Za-z_][A-Za-z0-9_]*$/,Mu=/CURSOR_SANDBOX/i;function Du(e){return $u.test(e)&&!Mu.test(e)}function Ou(e){return"function"==typeof e?e():e}function Fu(e,t){const r=void 0===e?[]:[...e];return r.includes(t)||r.push(t),r}function Nu(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 Lu extends Error{constructor(e){super(`working directory does not exist: ${e}; the command did not run`),this.name="WorkingDirectoryMissingError"}}class ju{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{Su(r,(0,D.VI)(e.withName("ShellCoreExecutor.execute")),!1);const o=performance.now(),i=this.executorFor(t.conversationId),a=t.workingDirectory||await i.getCwd(),c=(0,Zo.o1)(a,this.workspacePath);if(!((0,Bs.$f)(c)&&(0,Bs.A)(c)||await Ru(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,Zo.ZU)({basePath:"/tmp",targetPath:e}))return!1;const o=(0,$o.W1)(r);return void 0!==o&&await Ru(s.join(o,"tmp",s.relative("/tmp",e)))}(c,t.sandboxPolicy,this.workspacePath))){if(c!==(0,Zo.o1)(await i.getCwd(),this.workspacePath))throw new Lu(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,yo.sh)(t.conversationId)),t.requestId&&(w.CURSOR_REQUEST_ID=t.requestId),this.projectDir&&(w.AGENT_TRANSCRIPTS=s.join(this.projectDir,yo.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&&Du(e)&&(w[e]=t);const b=w.CURSOR_REQUEST_ID;void 0!==b&&(w.CURSOR_REQUEST_ID=Tu(b)),function(e,t){const r=xu,n=Object.keys(t).filter((e=>Du(e)&&!r.includes(e))),o=`builtin unset ${[...xu,...n].join(" ")} 2>/dev/null || true`,s=[];for(const t of xu){const r=Au(e,t);void 0!==r&&s.push(`builtin export ${t}=${Pu(r)}`)}for(const e of n){const r=t[e];void 0!==r&&s.push(`builtin export ${e}=${Pu(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=Tu(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=Au(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[]}}(Au(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=Fu(i.additionalReadonlyPaths,a):i.additionalReadwritePaths=Fu(i.additionalReadwritePaths,a));for(const e of n)e.readOnly||"workspace_readwrite"!==i.type?i.additionalReadonlyPaths=Fu(i.additionalReadonlyPaths,e.path):i.additionalReadwritePaths=Fu(i.additionalReadwritePaths,e.path);return{...e,perUser:i}}(t.sandboxPolicy,w),k=(0,$o.CG)(S??$o.BM);let _,C,E,x;S&&(yield{type:"start",sandboxed:"workspace_readonly"===k||"workspace_readwrite"===k}),t.askpassConfig&&!Eu&&(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??iu,R=(this.options.outputFallbackEncoding??(()=>P.current()))(),I=()=>function(e){if(void 0===e)return uu();const t=su.get(e);return void 0!==t&&qs.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=cu.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&&hu.test(a.toString("latin1")),o=t.test(i[i.length-1])}},isUtf8Text:()=>s,reset(){n=!1,o=!1,s=!1}}}(t);let s=au,i=0,a="utf8",c=!1;const l=()=>{a="utf8",o.reset(),i=0},u=(t,n)=>{const s=n?lu(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=du(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=du(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=cu.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=au,"utf8"===a){const e=t.subarray(0,t.length-lu(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?lu(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=au;const t=0===e.length?"":"utf8"===a?e.toString("utf8"):u(e,!1).text;return l(),t},usedCodePage:()=>c}}(e,t):uu()}(R),T={stdout:bu(I),stderr:bu(I)},A=new ul,$=Tl(this.options.encodingSlices,e)?new Vl:void 0;let M=!1;const O=()=>{if(!M){M=!0;try{const t={stdout:T.stdout.branch(),stderr:T.stderr.branch()};for(const r of A.labels(t,P.pages()))Cu.increment(e,1,r);$?.record(this.options.encodingSlices,e,t,P.lastOutcome())}catch(t){_u.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),$?.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:Ou(this.options.powershellUtf8Console),powershellUtf8ChildEnv:Ou(this.options.powershellUtf8ChildEnv),powershellParseAfterUtf8Switch:Ou(this.options.powershellParseAfterUtf8Switch),powershellWebRequestUtf8:Ou(this.options.powershellWebRequestUtf8),powershellPerLineStateDump:Ou(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+_<=Yo,f=void 0!==l&&!0!==l.truncated&&l.size+_<=Tc;"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),$?.noteBytes(r.type,r.data),$?.noteText(r.type,C)),void 0!==l&&l.size+_>Tc)l.truncated=!0;else if(f&&void 0!==l)if(l.size+=_,l.lineCount+=Nu(r.data),l.file)l.file.write(C);else if(l.buffer+=C,l.size>l.threshold){const e=s.join(this.projectDir,Ic);l.path=s.join(e,`${(0,wo.randomUUID)()}.txt`);try{await(0,So.mkdir)(e,{recursive:!0}),l.file=(0,_o.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),$?.noteDropped(r.type),$?.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:$o.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+=Gs(e)-1}const e=await new Promise((e=>l.file.end(e)));u??=e??void 0,u?await(0,So.rm)(l.path,{force:!0}):t=new Ac.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":$?.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"===yc(t)&&(0,Bs.$f)(c))try{_u.warn(e,"shell failed with ENOENT in an agent store working directory",{...await(0,Bs.KZ)(c)})}catch{}throw t}finally{O()}}catch(e){r.error=e,r.hasError=!0}finally{ku(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 Uu{constructor(e,t){this.innerExecutor=e,this.shellManager=t}async*execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{Su(r,(0,D.VI)(e.withName("ManagedShellCoreExecutor.execute")),!1),_u.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{ku(r)}}async getCwd(e){return this.innerExecutor.getCwd(e)}getWorkspacePath(){return this.innerExecutor.getWorkspacePath()}}class Bu{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 Wu(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(ys(e.pattern));case"unsafeResolution":return t.onPermissionDenied(e.message);default:{const t=e;throw new Error(`Unhandled block reason type: ${JSON.stringify(t)}`)}}}function Hu(e){switch(e.type){case"userRejected":return e.reason;case"unsafeResolution":return e.message;case"adminCommandDenylist":return ys(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 qu(e,t,r){return"permissionsConfig"===r.type?{case:"permissionDenied",value:new fe.jn({command:e,workingDirectory:t,error:"Command blocked by permissions configuration",isReadonly:r.isReadonly??!1})}:{case:"rejected",value:new fe.pZ({command:e,workingDirectory:t,reason:Hu(r)})}}var zu=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 Gu=(0,d.h)("local-exec:background-shell");function Vu(e,t,r){return new Ao.Lt({result:qu(e,t,r)})}class Ku{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 Ju(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 Zu(e){e().catch((()=>{}))}class Xu{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=Jo.L3.compile(e.config.pattern,Jo.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=Wo(e,n+t);o<=n&&(o=Ho(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=zo(r,1024)}finish(){this.finished||(this.finished=!0,this.flushPendingBatch("finish"),this.clearFlushTimer(),0===this.matchedOccurrences&&this.recordWatchOutcome("silent",{silent_ms:ed(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:ed(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=Eo(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:`${qo(i,500)}...`),detail:o,outputPath:this.args.outputPath,reason:"task_progress"}})}emitLimitReachedNotification(){this.emittedNotifications+=1;const e=this.args.config.pattern,t=Eo(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&&Gu.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 Qu{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 Xu({shellId:t,outputPath:i,config:o,conversationId:r??Co,toolCallId:n,registry:this.backgroundWorkRegistry,ctx:e})}catch(r){return void(void 0!==e&&Gu.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 Yu{async spawn(e,t){const r=new AbortController,n=new Ku(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 $o.SandboxUnsupportedError||e instanceof Lu)throw e}return Zu((()=>Ju(n,o))),n}async adopt(e){const t=new Ku(e.shellId,e.abortController);return t.stdin=e.stdin,t.pid=e.pid,Zu((()=>Ju(t,e.eventIterator))),t}}function ed(e){return Math.round(performance.now()-e)}function td(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`}function rd(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: ${td(e.cwd)}\n`,n+=`command: ${td(e.command)}\n`,void 0!==e.title&&e.title.trim().length>0&&(n+=`title: ${td(e.title)}\n`),n+=`status: ${r}\n`,n+=`started_at: ${e.startedAt}\n`,n+=`running_for_ms: ${t}\n`,n+="---\n",n}function nd(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 od{constructor(e,t){this.innerFactory=e,this.projectDir=t}async spawn(e,t){const r=s.join(this.projectDir,"terminals");await(0,So.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=ed(g),r=rd({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=ed(g),n=rd({pid:e,cwd:t.workingDirectory,command:t.command,title:t.description,status:y,startedAt:m,runningForMs:r});await(0,So.writeFile)(_,n,"utf8"),l=setInterval((()=>{E()}),5e3)},R=async()=>{a||(a=await _o.promises.open(_,"r+")),c||(c=await _o.promises.open(_,"a"))},I=async(e,t)=>{if(!v){if(v=!0,x(),p||await P(),await R(),void 0!==t){const e=ed(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(nd("stderr"));else d=!0,p||await P(),await R(),await S(nd("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=td(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,So.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=ed(i),l=rd({pid:e.pid,cwd:e.workingDirectory,command:e.command,title:e.description,status:a,startedAt:o,runningForMs:c})+(e.initialOutput??"");await(0,So.writeFile)(r,l,"utf8");const u=await _o.promises.open(r,"r+");let d;try{d=await _o.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=ed(i),r=rd({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=ed(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(nd("stderr"))):(f=!0,await k(nd("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 sd{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:xo(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??Co,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:ed(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 id{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 ad{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 id(s,i):s,l=o??function(e){const t=new Yu;return new od(t,e)}(n),u=new Qu(l,n,c);this.backgroundShellManager=new sd(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,D.VI)(e.withName("LocalBackgroundShellExecutor.execute")),!1);const n=t.command,o=t.sandboxPolicy?is(t.sandboxPolicy):void 0,s=t.workingDirectory||await this.coreExecutor.getCwd(t.conversationId),i=(0,Zo.o1)(s),a=new fe.HO(jo(n).structured),c=vs({command:n,parsingResult:a,blockedCommands:t.adminCommandDenylist});if(void 0!==c)return new Ao.Lt({result:{case:"rejected",value:new fe.pZ({command:n,workingDirectory:i,reason:c})}});let l;if(Gu.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}),To(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 Gu.info(e,"Background shell: invariant blocked command",{toolCallId:t.toolCallId,blockReasonType:r.reason.type,skipApproval:t.skipApproval}),Vu(n,i,r.reason);l=r.policy??o,Gu.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:Ro(t)},o);if("block"===r.kind)return Gu.info(e,"Background shell: approval gate blocked command",{toolCallId:t.toolCallId,blockReasonType:r.reason.type,hasSmartModeApproval:void 0!==t.smartModeApproval,skipApproval:t.skipApproval}),Vu(n,i,r.reason);l=r.policy,Gu.info(e,"Background shell: approval gate allowed command",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,effectivePolicyType:l.type})}l=await Pc(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 Ao.Lt({result:{case:"success",value:new Ao.Po({shellId:r,command:n,workingDirectory:i,pid:a.pid})}})}catch(r){if(r instanceof $o.SandboxUnsupportedError){const o=l?.type??"unknown";return Gu.debug(e,"Background shell: sandbox policy unsupported on this host",{toolCallId:t.toolCallId,policyType:o,reason:r.reason}),new Ao.Lt({result:{case:"sandboxUnsupported",value:new fe.rI({command:n,workingDirectory:i,sandboxPolicyType:o,reason:r.reason??r.message,isReadonly:"workspace_readonly"===o})}})}return new Ao.Lt({result:{case:"error",value:new Ao.Of({command:n,workingDirectory:i,error:r instanceof Error?r.message:"Unknown error"})}})}}catch(e){r.error=e,r.hasError=!0}finally{zu(r)}}writeStdin(e,t){return this.backgroundShellManager.writeStdin(e,t)}}var cd=r("node:async_hooks");r("../../node_modules/.pnpm/minimatch@10.2.5/node_modules/minimatch/dist/esm/index.js");function ld(e){return e instanceof Error?e.message:String(e)}function ud(e){return"Failed to read skill file: "+ld(e)}function dd(e){return"Invalid skill frontmatter: "+ld(e)}function hd(e,t){return e||t?void 0:"Description is required"}new Set(["EACCES","EPERM","ENOENT","ENOTDIR","EISDIR","ELOOP","ENAMETOOLONG"]);const pd=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function fd(e){return e.toLocaleString("en-US")}var md=r("node:url");const gd={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"},wd=e=>"string"==typeof e,yd=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),vd=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),bd=(e,t=[])=>({isValid:e,errors:t});function Sd(e,t,r){void 0===e||wd(e)||r.push(`${t} must be a string if provided`)}const kd=e=>{const t=[];if(!yd(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)"),bd(!1,t);const r=e.type;return"prompt"===r?((e,t)=>{wd(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&&(wd(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)=>{wd(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(wd(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),bd(0===t.length,t)},_d=(e,t)=>{const r=[];if(!Array.isArray(e))return r.push(`${t} must be an array of hook scripts`),bd(!1,r);for(let n=0;n<e.length;n++){const o=kd(e[n]);o.isValid||r.push(`${t}[${n}]: ${o.errors.join(", ")}`)}return bd(0===r.length,r)},Cd=e=>{const t=[];if(!yd(e))return t.push("Hooks config must be an object"),bd(!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"),!yd(e.hooks))return t.push("Config hooks must be an object"),bd(!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(gd),n=e.hooks;for(const[e,o]of Object.entries(n))if(r.includes(e)){if(void 0!==o){const r=_d(o,e);r.isValid||t.push(...r.errors)}}else t.push(`Unknown hook type: ${e}. Valid types are: ${r.join(", ")}`);return bd(0===t.length,t)},Ed={PreToolUse:gd.preToolUse,PermissionRequest:null,PostToolUse:gd.postToolUse,UserPromptSubmit:gd.beforeSubmitPrompt,Stop:gd.stop,SubagentStop:gd.subagentStop,SessionStart:gd.sessionStart,SessionEnd:gd.sessionEnd,PreCompact:gd.preCompact,Notification:null},xd=Object.fromEntries(Object.entries(Ed).filter((e=>Pd(e[0])&&null!==e[1])).map((([e,t])=>[t,e])));function Pd(e){return Object.prototype.hasOwnProperty.call(Ed,e)}const Rd={Bash:"Shell",Read:"Read",Write:"Write",Edit:"Write",Glob:null,Grep:"Grep",WebFetch:"WebFetch",WebSearch:"WebSearch",Task:"Task"},Id=["Glob"],Td=["Notification","PermissionRequest"],Ad=/^[A-Za-z0-9_./:=+-]+$/,$d=/^=|^-.*\./,Md=/\$\{(?:CLAUDE_PROJECT_DIR|CURSOR_PROJECT_DIR|CLAUDE_PLUGIN_ROOT|CURSOR_PLUGIN_ROOT)\}/g,Dd=/^[^\p{Cc}$`"]*$/u,Od=/\\(?:[$`"\\]|$)/;function Fd(e){return`'${e.replace(/'/g,"'\\''")}'`}function Nd(e){if(Ad.test(e)&&!$d.test(e))return e;const t=e.replace(Md,"");if((t!==e||e.includes("'"))&&Dd.test(t)&&!Od.test(e))return`"${e}"`;const r=[];let n=0;for(const t of e.matchAll(Md))t.index>n&&r.push(Fd(e.slice(n,t.index))),r.push(`"${t[0]}"`),n=t.index+t[0].length;return(n<e.length||0===r.length)&&r.push(Fd(e.slice(n))),r.join("")}const Ld={warn:()=>{},info:()=>{}};function jd(e,t,r=Ld){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(Nd).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 Ud(e,t,r=Ld){const n=[];let o;if("PreToolUse"===t||"PostToolUse"===t){const t=function(e,t=Ld){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=Rd[t];null!==r?void 0!==r?n.includes(r)||n.push(r):n.push(t):Id.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=jd(t,o,r);e&&n.push(e)}return n}function Bd(e,t=Ld){const r={};for(const[n,o]of Object.entries(e)){if(!Pd(n)){t.warn(`Unknown Claude Code event "${n}", skipping`);continue}if(Td.includes(n)){t.warn(`Claude Code event "${n}" is not supported in Cursor and will be ignored`);continue}const e=Ed[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=Ud(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 Wd=r("../../node_modules/.pnpm/gray-matter@4.0.3/node_modules/gray-matter/index.js");const Hd=()=>({});function qd(e,t){return Wd(e,{...t,engines:{...t?.engines,js:Hd,javascript:Hd}})}function zd(e,t,r){return Wd.stringify({content:e,data:{}},t,r)}function Gd(e){return e.replace(/\\/g,"/").replace(/\/+$/,"")||"/"}function Vd(e,t){if(Object.hasOwn(e,t))return e[t]}function Kd(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?Gd(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===Vd(i,e))continue;let r;void 0!==a&&(r=t.find((t=>!("project"!==t.scope&&"local"!==t.scope||!t.projectPath)&&(Gd(t.projectPath)===a&&!0===Vd(i,e))))),r||!0!==Vd(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 Jd=r("../../node_modules/.pnpm/js-yaml@4.3.1/node_modules/js-yaml/dist/js-yaml.mjs");const Zd=Be.enum(["canvas"]),Xd=Be.array(Zd).transform((e=>[...new Set(e)].sort())),Qd=new Set(["https://agent-plugins.org/schemas/1.0.0/plugin.schema.json","https://agent-plugins.org/schemas/1.0.0/mcp.schema.json"]),Yd=/^v?(\d+\.\d+(?:\.\d+)?)$/;function eh(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 th(e){let t;try{t=new URL(e).pathname.split("/")}catch{t=e.split("/")}for(const e of t){const t=Yd.exec(e);if(null!==t)return t[1]}}function rh(e){return void 0===e?{kind:"absent"}:Qd.has(e)?{kind:"supported",id:e,version:th(e)??e}:{kind:"unsupported",id:e}}const nh=10485760,oh=/^[a-z0-9]([a-z0-9.-]*[a-z0-9])?$/,sh=[".cursor-plugin/plugin.json",".claude-plugin/plugin.json","plugin.json"],ih=[".cursor-plugin",".claude-plugin"],ah=[".cursor-plugin/marketplace.json",".claude-plugin/marketplace.json"],ch=Be.object({source:Be.literal("github"),repo:Be.string().regex(/^[^/]+\/[^/]+$/,"Must be in owner/repo format"),ref:Be.string().optional(),sha:Be.string().length(40,"SHA must be 40 characters").regex(/^[a-f0-9]+$/,"SHA must be hexadecimal").optional()}),lh=Be.object({source:Be.literal("url"),url:Be.string().url().endsWith(".git","URL must end with .git"),ref:Be.string().optional(),sha:Be.string().length(40,"SHA must be 40 characters").regex(/^[a-f0-9]+$/,"SHA must be hexadecimal").optional()}),uh=Be.object({source:Be.literal("git-subdir"),url:Be.string().url().endsWith(".git","URL must end with .git"),path:Be.string().min(1),ref:Be.string().optional(),sha:Be.string().length(40,"SHA must be 40 characters").regex(/^[a-f0-9]+$/,"SHA must be hexadecimal").optional()}),dh=Be.union([Be.string(),ch,lh,uh]),hh=/^(\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?|never)$/,ph='Must be a semver version (X.Y.Z) or "never"',fh=Be.object({cursor:Be.string().regex(hh,ph).optional(),sand:Be.string().regex(hh,ph).optional(),sandMobile:Be.string().regex(hh,ph).optional()}),mh=Be.object({name:Be.string().min(1,"Author name is required"),email:Be.string().email().optional()}),gh=Be.enum(["string","number","integer","boolean","object","array","null"]),wh=Be.union([gh,Be.array(gh).nonempty().superRefine(((e,t)=>{new Set(e).size!==e.length&&t.addIssue({code:Be.ZodIssueCode.custom,message:"Schema type arrays must not contain duplicates"})}))]);function yh(e,t){if(void 0!==e.required)if(void 0===e.properties)for(const r of e.required)t.addIssue({code:Be.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:Be.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:Be.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:Be.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:Be.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:Be.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:Be.ZodIssueCode.custom,message:"minProperties must be less than or equal to maxProperties",path:["minProperties"]})}const vh=Be.lazy((()=>Be.object({type:wh.optional(),title:Be.string().optional(),description:Be.string().optional(),format:Be.string().optional(),writeOnly:Be.boolean().optional(),placeholder:Be.string().optional(),default:Be.unknown().optional(),enum:Be.array(Be.any()).nonempty().optional(),const:Be.unknown().optional(),properties:Be.record(Be.string(),vh).optional(),required:Be.array(Be.string()).optional(),additionalProperties:Be.union([Be.boolean(),vh]).optional(),items:Be.union([vh,Be.array(vh)]).optional(),minLength:Be.number().int().nonnegative().optional(),maxLength:Be.number().int().nonnegative().optional(),minimum:Be.number().optional(),maximum:Be.number().optional(),exclusiveMinimum:Be.number().optional(),exclusiveMaximum:Be.number().optional(),multipleOf:Be.number().positive().optional(),minItems:Be.number().int().nonnegative().optional(),maxItems:Be.number().int().nonnegative().optional(),uniqueItems:Be.boolean().optional(),minProperties:Be.number().int().nonnegative().optional(),maxProperties:Be.number().int().nonnegative().optional()}).strict().superRefine(yh)));function bh(e){const t=vh.superRefine(((e,t)=>{_h(e)&&"object"===e.type||t.addIssue({code:Be.ZodIssueCode.custom,message:'Plugin variable schemas must declare type "object"',path:["type"]})})).safeParse(e);return t.success?Ch(t.data)?{success:!0,data:t.data}:{success:!1,error:new Be.ZodError([{code:"custom",path:["type"],message:'Plugin variable schemas must declare type "object"'}])}:{success:!1,error:t.error}}const Sh=Be.unknown().superRefine(((e,t)=>{const r=bh(e);if(!r.success)for(const e of r.error.issues)t.addIssue({code:"custom",message:e.message,path:e.path})})).transform((e=>{if(!Ch(e))throw new Error('Plugin variable schema must declare type "object"');return e})),kh=(Be.object({name:Be.string().min(1).transform((e=>e.toLowerCase())).refine((e=>oh.test(e)),"Name must be kebab-case (lowercase alphanumeric with hyphens and periods)"),displayName:Be.string().optional(),source:dh,description:Be.string().optional(),version:Be.string().optional(),author:mh.optional(),publisher:Be.string().min(1).optional(),homepage:Be.string().url().optional(),repository:Be.string().url().optional(),license:Be.string().optional(),keywords:Be.array(Be.string()).optional(),capabilities:Xd.optional(),logo:Be.string().optional(),category:Be.string().optional(),tags:Be.array(Be.string()).optional(),minClientVersions:fh.optional(),strict:Be.boolean().default(!0),commands:Be.union([Be.string(),Be.array(Be.string())]).optional(),agents:Be.union([Be.string(),Be.array(Be.string())]).optional(),skills:Be.union([Be.string(),Be.array(Be.string())]).optional(),rules:Be.union([Be.string(),Be.array(Be.string())]).optional(),hooks:Be.union([Be.string(),Be.record(Be.string(),Be.unknown())]).optional(),variables:Sh.optional(),mcpServers:Be.union([Be.string(),Be.record(Be.string(),Be.unknown()),Be.array(Be.union([Be.string(),Be.record(Be.string(),Be.unknown())]))]).optional()}),Be.object({description:Be.string().optional(),version:Be.string().optional(),pluginRoot:Be.string().optional()}),Be.object({name:Be.string().min(1).regex(oh,"Name must be kebab-case (lowercase alphanumeric with hyphens and periods)"),displayName:Be.string().optional(),description:Be.string().optional(),version:Be.string().optional(),author:mh.optional(),publisher:Be.string().min(1).optional(),homepage:Be.string().url().optional(),repository:Be.string().url().optional(),license:Be.string().optional(),logo:Be.string().optional(),keywords:Be.array(Be.string()).optional(),capabilities:Xd.optional(),minClientVersions:fh.optional(),commands:Be.union([Be.string(),Be.array(Be.string())]).optional(),agents:Be.union([Be.string(),Be.array(Be.string())]).optional(),skills:Be.union([Be.string(),Be.array(Be.string())]).optional(),rules:Be.union([Be.string(),Be.array(Be.string())]).optional(),hooks:Be.union([Be.string(),Be.record(Be.string(),Be.unknown())]).optional(),variables:Sh.optional(),mcpServers:Be.union([Be.string(),Be.record(Be.string(),Be.unknown()),Be.array(Be.union([Be.string(),Be.record(Be.string(),Be.unknown())]))]).optional()}));function _h(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Ch(e){return _h(e)&&"object"===e.type}function Eh(e){return e.trim().toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")}function xh(e,t){if(_h(e)&&"string"==typeof e.name){const t=Eh(e.name);if(t.length>0)return t}return function(e){const t=void 0!==e.repoName?Eh(e.repoName):"";return t.length>0?t:`cursor-marketplace-${e.fallbackId??(0,wo.randomUUID)()}`}(t)}function Ph(e){if(_h(e)&&_h(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 Rh(e){return"string"==typeof e?e:void 0}function Ih(e){if(!Array.isArray(e))return;const t=e.filter((e=>"string"==typeof e));return t.length>0?t:void 0}function Th(e){return"string"==typeof e?e:Ih(e)}function Ah(e){if(!_h(e)||!_h(e.metadata))return;const t={description:Rh(e.metadata.description),version:Rh(e.metadata.version),pluginRoot:Rh(e.metadata.pluginRoot)};return void 0!==t.description||void 0!==t.version||void 0!==t.pluginRoot?t:void 0}function $h(e){if(!_h(e))return;const t=Rh(e.name);if(void 0===t||0===t.length)return;const r=Rh(e.email);return{name:t,...void 0!==r?{email:r}:{}}}function Mh(e){if("string"==typeof e||_h(e))return e;if(Array.isArray(e)){const t=e.filter((e=>"string"==typeof e||_h(e)));return t.length>0?t:void 0}}function Dh(e){if("string"==typeof e||_h(e))return e}function Oh(e){if(void 0===e)return;const t=bh(e);return t.success?t.data:void 0}function Fh(e,t={}){if(e.length>nh)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(!_h(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(!_h(e))return{skippedEntry:{index:t,error:`Plugin entry at index ${t} is not an object`}};const r="string"==typeof(n=e.source)?n:_h(n)?"github"===n.source&&"string"==typeof n.repo&&n.repo.length>0?{source:"github",repo:n.repo,ref:Rh(n.ref),sha:Rh(n.sha)}:("url"===n.source||void 0===n.source)&&"string"==typeof n.url&&n.url.length>0?{source:"url",url:n.url,ref:Rh(n.ref),sha:Rh(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:Rh(n.ref),sha:Rh(n.sha)}:"string"==typeof n.repo&&n.repo.length>0?{source:"github",repo:n.repo,ref:Rh(n.ref),sha:Rh(n.sha)}:void 0:void 0;var n;if(void 0===r){const r=Rh(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?Eh(e.name):"")||function(e){if("string"==typeof e){const t=Eh((0,s.basename)(e));return t.length>0?t:void 0}if("github"===e.source){const t=Eh(e.repo.split("/").at(-1)??"");return t.length>0?t:void 0}if("git-subdir"===e.source){const t=Eh((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=Eh((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=Xd.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=fh.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:Rh(e.displayName),source:r,description:Rh(e.description),version:Rh(e.version),author:$h(e.author),publisher:Rh(e.publisher),homepage:Rh(e.homepage),repository:Rh(e.repository),license:Rh(e.license),keywords:Ih(e.keywords),logo:Rh(e.logo),category:Rh(e.category),tags:Ih(e.tags),strict:"boolean"!=typeof e.strict||e.strict,commands:Th(e.commands),agents:Th(e.agents),skills:Th(e.skills),rules:Th(e.rules),hooks:Dh(e.hooks),variables:Oh(e.variables),mcpServers:Mh(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:xh(r,t),owner:Ph(r),description:Rh(r.description),plugins:n,metadata:Ah(r),skippedPluginEntries:o}}}function Nh(e){if(e.length>nh)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=rh(eh(t)),n=kh.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 Lh(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 jh(e){return!e.includes("..")&&!(0,s.isAbsolute)(e)&&!e.includes("://")}var Uh=r("../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/main.js");const Bh=/\$\{(?:env:([A-Za-z_][A-Za-z0-9_]*)|([^:}]+)(?::-([^}]*))?)\}/g,Wh=/\$%7B([^%/?#]+?)%7D/gi;function Hh(e,t){return qh(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 qh(e,t){if("string"==typeof e)return function(e,t){return e.replace(Wh,"${$1}").replace(Bh,((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=>qh(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]=qh(o,t);return r}return e}function zh(e,t){return e.replace(/\$\{CLAUDE_PLUGIN_ROOT\}/g,(()=>t)).replace(/\$\{CURSOR_PLUGIN_ROOT\}/g,(()=>t))}const Gh={log:()=>{},increment:()=>{},distribution:()=>{},captureException:()=>{}},Vh=Be.object({command:Be.string().optional(),args:Be.array(Be.string()).optional(),env:Be.record(Be.string(),Be.string()).optional(),url:Be.string().optional(),headers:Be.record(Be.string(),Be.string()).optional(),cwd:Be.string().optional(),envFile:Be.string().optional(),auth:Be.object({CLIENT_ID:Be.string(),CLIENT_SECRET:Be.string().optional(),scopes:Be.array(Be.string()).optional()}).optional(),enabledTools:Be.array(Be.string()).optional(),placement:Be.enum(["server","client"]).optional(),tls:Be.object({caBundle:Be.string().trim().min(1).max(131072)}).optional()}),Kh=Be.object({mcpServers:Be.record(Be.string(),Vh).optional()}),Jh=[".mcp.json","mcp.json"],Zh=new Set(["author","owner","source","metadata"].map((e=>e.toLowerCase())));function Xh(e,t){if(!function(e){return Zh.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 Qh(e){return"object"==typeof e&&null!==e&&("command"in e||"url"in e)}function Yh(e){const t=void 0!==e&&e.length>0?e.replace(/\/+$/,""):void 0;return Jh.map((e=>void 0!==t?`${t}/${e}`:e))}function ep(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=zh(o.command,t)),Array.isArray(o.args)&&(e.args=o.args.map((e=>"string"==typeof e?zh(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?zh(n,t):n;e.env=r}"string"==typeof o.cwd&&(e.cwd=zh(o.cwd,t)),n[r]=e}return function(e,t){const r=t?.cloudAgentEnvLookup,n=t?.configuredVariables;if(void 0!==r)return Hh(e,r);const o=new Map(Object.keys(n??{}).map((e=>[e.toLowerCase(),e])));return Hh(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 tp(e,t,r){try{const n=(0,Uh.qg)(e),o=eh(n);if(void 0!==o){const e=r?.log??Gh;"unsupported"===rh(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=th(e),n=th(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=Kh.safeParse(n),i=!0===r?.skipExpansion;if(s.success&&s.data.mcpServers&&Object.keys(s.data.mcpServers).length>0)return i?s.data:ep(s.data,t,r);const a={};for(const[e,t]of Object.entries(n))"mcpServers"!==e&&!Xh(e,t)&&Qh(t)&&(a[e]=t);if(Object.keys(a).length>0){const e=Kh.safeParse({mcpServers:a});if(e.success)return i?e.data:ep(e.data,t,r)}return null}catch{return null}}function rp(e,t,r){for(const[n,o]of Object.entries(t))e.mcpServers[n]=o,e.mcpServerSourcePaths[n]=r}async function np(e,t,r,n={}){const o=n.toSourcePath??(e=>e),s=n.installPathForExpansion??"",i=n.fallbackFileNames??Jh,a=n.manifestPrecedence??"override",c={},l={};for(const t of i){const r=await e(t);if(null===r)continue;const i=tp(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(!jh(i))return;const a=await t(i);if(null===a)return;const c=tp(a,o,r.parserOptions);c?.mcpServers&&Object.keys(c.mcpServers).length>0&&rp(s,c.mcpServers,n(i))},a=e=>{const t=tp(JSON.stringify(e),o,r.parserOptions);t?.mcpServers&&Object.keys(t.mcpServers).length>0&&rp(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 op=new Set(["CREDENTIAL","CREDENTIALS","KEY","PASSPHRASE","PASSWORD","SECRET","TOKEN"]);function sp(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=>op.has(e)))}const ip=/\$\{(?:env:([A-Z][A-Z0-9_]*)|([A-Z][A-Z0-9_]*)(?::-([^}]*))?)\}/g,ap=new Set(["CURSOR_PLUGIN_ROOT","CLAUDE_PLUGIN_ROOT"]),cp=new Set(["api","aws","db","dd","gcp","http","https","id","mcp","ssl","tls","uri","url"]);function lp(e){return e.split("_").filter((e=>e.length>0)).map((e=>{const t=e.toLowerCase();return cp.has(t)?e.toUpperCase():e.charAt(0).toUpperCase()+t.slice(1)})).join(" ")}function up(e,t){if("string"!=typeof e){if(Array.isArray(e))for(const r of e)up(r,t);else if(null!==e&&"object"==typeof e)for(const r of Object.values(e))up(r,t)}else for(const[,r,n,o]of e.matchAll(ip)){const e=r??n;if(void 0===e||ap.has(e)||t.has(e))continue;const s=void 0===r?`\${${e}}`:`\${env:${e}}`;t.set(e,{reference:s,defaultValue:o})}}function dp(e){if(void 0===e?.mcpServers)return;const t=new Map;if(up(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:lp(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.`,...sp(e)?{writeOnly:!0}:{}}}return{type:"object",properties:r}}const hp=[".md",".mdc",".markdown"],pp=[...hp,".txt"],fp=/^---\s*\n([\s\S]*?)\n---/;function mp(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function gp(e){return e.trim().toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9.-]/g,"")}function wp(e){const t=e.match(fp);if(!t)return{};try{const e=Jd.Ay.load(t[1],{schema:Jd.Ay.JSON_SCHEMA});if(!mp(e))return{};const r=mp(e.metadata)?e.metadata:void 0,n=yp(e.environments??r?.environments);return{disabledEnvironments:yp(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 yp(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 vp(e){return gp((0,s.basename)(e).replace(/\.(md|mdc|markdown|txt)$/i,""))}function bp(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 Sp{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=Jh.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,hp):s.has("skills")?this.discoverSkills(`${r}skills`):Promise.resolve([]),void 0!==n?.agents?this.discoverFromManifestPaths(r,n.agents,!1,hp):s.has("agents")?this.discoverMarkdownComponents(`${r}agents`,hp):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,pp):s.has("commands")?this.discoverMarkdownComponents(`${r}commands`,pp):Promise.resolve([]),void 0!==n?.rules?this.discoverFromManifestPaths(r,n.rules,!1,hp):s.has("rules")?this.discoverMarkdownComponents(`${r}rules`,hp):Promise.resolve([]),this.discoverMcpServers(r,n?.mcpServers,i)]);return{skills:bp(c?[c,...l]:l),agents:bp(u),hooks:d,commands:bp(h),rules:bp(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 mp(r)&&mp(r.hooks)?Object.keys(r.hooks).map((t=>({name:gp(t),path:e,description:`Hook: ${t}`}))):[]}catch{return[]}}async discoverHooksFromManifest(e,t){if("string"==typeof t){if(!jh(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:gp(e),path:"manifest",description:`Hook: ${e}`})))}async discoverFromManifestPaths(e,t,r=!1,n=hp){if("string"==typeof t){if(!jh(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(!jh(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=vp(t.endsWith("SKILL.md")?t.slice(0,-8).replace(/\/$/,""):t);const{content:n}=await this.fetcher.fetchFile(e),s=wp(n);if(r=s.name??r,r){const t={disabledEnvironments:s.disabledEnvironments,environments:s.environments,name:gp(r),path:e};void 0!==s.description&&(t.description=s.description),o.push(t)}}else{if(!await this.fetcher.fileExists(t))continue;let e=vp(t);const{content:r}=await this.fetcher.fetchFile(t),n=wp(r);e=n.name??e;const s=n.description;if(e){const r={name:gp(e),path:t};void 0!==s&&(r.description=s),o.push(r)}}}catch{}return o}async discoverMarkdownComponents(e,t=hp,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=vp(e.name);const{content:r}=await this.fetcher.fetchFile(e.path),n=wp(r);t=n.name?gp(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=gp((0,s.basename)(e.replace(/[\\/]+$/,"")));const{content:n}=await this.fetcher.fetchFile(t),o=wp(n);if(r=o.name?gp(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=wp(r),o=n.name?gp(n.name):gp(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=>np(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:gp(e),path:i.mcpServerSourcePaths?.[e]??"manifest"}))),variables:dp(a??i),configs:l}}}var kp=r("node:stream"),_p=r("node:stream/promises"),Cp=r("node:zlib");function Ep(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 xp(e){return e.replace(/[^a-zA-Z0-9._-]/g,"_")}var Pp=r("../../node_modules/.pnpm/tar@7.5.21/node_modules/tar/dist/esm/index.min.js");const Rp=".cache-complete";function Ip(e){return xp(e)}function Tp(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 Ap(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?Ip(t.version):void 0)}class $p{constructor(e,t){const r=e??process.env.HOME??"";this.cacheRoot=t?.cacheRoot??(0,s.join)(r,".cursor","plugins/cache")}getCacheDir(e){return Ap(this.cacheRoot,e)}async isCached(e){const t=this.getCacheDir(e);try{const e=Tp({parent:t,name:Rp});return(await(0,So.stat)(e)).isFile()}catch{return!1}}async extractToCache(e){const t=this.getCacheDir(e);await(0,So.mkdir)(t,{recursive:!0});const r=kp.Readable.from(e.tarball);return await(0,_p.pipeline)(r,(0,Cp.createGunzip)(),(0,Pp.o6)({cwd:t,strip:1})),await this.markCacheComplete(e),t}async listCachedVersions(e){const t=Ap(this.cacheRoot,e);try{return(await(0,So.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,So.rm)(t,{recursive:!0,force:!0})}catch{}}async removeAllVersions(e){const t=Ap(this.cacheRoot,e);await(0,So.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=>Ip(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,So.writeFile)(Tp({parent:t,name:Rp}),"")}}class Mp extends Error{constructor(e,t){super(`Invalid Claude Code plugin identifier "${t}": ${e}`),this.raw=t,this.name="CCPluginIdentifierError"}}function Dp(e){const t=e.trim();if(!t)throw new Mp("Empty identifier",e);const r=/^[a-zA-Z0-9_-]+$/,n=t.indexOf("@");if(n!==t.lastIndexOf("@"))throw new Mp("Plugin identifier cannot contain multiple @ symbols",e);if(-1===n){if(!r.test(t))throw new Mp("Plugin name must contain only alphanumeric characters, dashes, and underscores",e);if(t.length>100)throw new Mp("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 Mp("Missing plugin name before @",e);if(!s)throw new Mp("Missing source after @",e);if(!r.test(o))throw new Mp("Plugin name must contain only alphanumeric characters, dashes, and underscores",e);if(o.length>100)throw new Mp("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 Mp("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 Mp("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 Mp("Missing Git URL after 'url:'",e);try{new URL(t)}catch{throw new Mp("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 Mp("Missing marketplace name",e);if(!r.test(a))throw new Mp("Marketplace name must contain only alphanumeric characters, dashes, and underscores",e);return{name:o,sourceType:"marketplace",marketplace:a,version:c,raw:e}}function Op(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 Fp(e){return e.sourceInfo.name}function Np(e){switch(e.source){case"claude-plugin":case"cursor-first-party":case"cursor-third-party":return e.sourceInfo.marketplace;default:return}}function Lp(e){switch(e.source){case"cursor-first-party":case"cursor-third-party":return e.sourceInfo.pluginDbId;default:return}}function jp(e){switch(e.source){case"cursor-first-party":case"cursor-third-party":return e.sourceInfo.marketplaceDbId;default:return}}function Up(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Bp(e){return!!Up(e)&&(void 0===e.enabledPlugins||Up(e.enabledPlugins))}function Wp(e){return JSON.parse(e)}function Hp(e){const t=e??process.env.HOME??"";return(0,s.join)(t,".claude")}async function qp(e){const t={enabledPlugins:{}};let r=!1;const n=(0,s.join)(e,".claude","settings.json");try{const e=Wp(await(0,So.readFile)(n,"utf-8"));Bp(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=Wp(await(0,So.readFile)(o,"utf-8"));Bp(e)&&e.enabledPlugins&&(Object.assign(t.enabledPlugins,e.enabledPlugins),r=!0)}catch{}return r?t:null}function zp(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 Gp(e){try{return(await(0,So.lstat)(e)).isSymbolicLink()}catch{return!1}}async function Vp(e){if(await Gp(e))throw new Error(`Refusing to read symlink: ${e}`);return(0,So.readFile)(e,"utf-8")}async function Kp(e){if((await(0,So.stat)(e)).size>10485760)throw new Error(`File ${e} exceeds maximum size of 10485760 bytes`)}function Jp(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 Zp({installPath:e,logo:t}){const r=t?.trim();if(r&&!(0,s.isAbsolute)(r)&&!r.includes("://"))try{const t=await(0,So.realpath)(e),n=zp(t,r),o=await(0,So.realpath)(n);if(zp(t,o),!(await(0,So.stat)(o)).isFile())return;return await Kp(o),(0,md.pathToFileURL)(o).href}catch{return}}function Xp(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 Qp(e){return void 0!==e.version||void 0!==e.homepage||void 0!==e.repository}function Yp(e,t){return Xp({version:e.version??t?.version,homepage:e.homepage??t?.homepage,repository:e.repository??t?.repository})}async function ef(e,t,r){let n;for(const o of sh){const i=(0,s.join)(e,o);let a;try{if(await Gp(i))continue;if(!(await(0,So.stat)(i)).isFile())continue;await Kp(i),a=await Vp(i)}catch{continue}const c=Nh(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 Zp({installPath:e,logo:l.logo}),S=Xp(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&&!Qp(S))continue;if(!g&&!C){n=n?{...n,fields:Yp(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=Yp(S,n?.fields);return{manifestFilePath:i,...g&&{manifestOptions:{commands:u,agents:d,skills:h,rules:p,hooks:f,mcpServers:m}},...(C||Qp(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 tf(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,So.realpath)(o).catch((()=>o));function a(e){const t=(0,s.resolve)(e);try{return zp(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,So.realpath)(t);try{return zp(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,So.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,So.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 Kp(i);const l=await(0,So.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,So.stat)(n)).isFile()}catch{return!1}}}}(e),n=new Sp(r),o=await n.discoverComponents({manifest:t}),[i,a,c,l]=await Promise.all([rf(r,o.skills,e),of(r,o.agents,e),sf(r,o.commands,e),nf(r,o.rules,e)]);return{skills:i,agents:a,commands:c,rules:l}}async function rf(e,t,r){const n=[];for(const o of t)try{const{content:t}=await e.fetchFile(o.path),s=cf({content:zh(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:zh(t,r),relativePath:o.path});s&&n.push({...s,name:o.name})}catch{}return n}async function of(e,t,r){const n=[];for(const o of t)try{const{content:t}=await e.fetchFile(o.path),s=lf({content:zh(t,r),relativePath:o.path});s&&n.push(s)}catch{}return n}async function sf(e,t,r){const n=[];for(const o of t)try{const{content:t}=await e.fetchFile(o.path),s=uf({content:zh(t,r),relativePath:o.path});s&&n.push(s)}catch{}return n}function af(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 cf({content:e,relativePath:t}){try{const r=qd(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=yp(r.data.environments??r.data.metadata?.environments),u=yp(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:af(r.data.globs),alwaysApply:!0===r.data.alwaysApply,content:e,environments:l,disabledEnvironments:u}}catch{return null}}function lf({content:e,relativePath:t}){try{const n=qd(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 uf({content:e,relativePath:t}){try{const r=qd(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 df(e){if(void 0!==e)return{configuredVariables:e.configuredVariables}}async function hf(e,t,r){const n=r??df(t);return async function(e,t={}){const r=t.toSourcePath??(e=>e);let n,o,s;for(const t of sh){const i=await e(t);if(null===i)continue;let a;try{a=JSON.parse(i)}catch{continue}s=eh(a);const c=Nh(i);if(c.success){void 0!==c.data.mcpServers&&(n=c.data.mcpServers,o=r(t));break}}return np(e,n,o,void 0===s?t:{...t,parserOptions:{...t.parserOptions,pluginSchemaId:s}})}(function(e){return async t=>{if(!jh(t))return null;const r=(0,s.join)(e,t);try{return await Gp(r)?null:(await(0,So.stat)(r)).isFile()?(await Kp(r),await Vp(r)):null}catch{return null}}}(e),{fallbackFileNames:Yh(),manifestPrecedence:"override",toSourcePath:t=>(0,s.join)(e,t),installPathForExpansion:e,parserOptions:n})}async function pf(e,t,r){const n=await hf(e,void 0,{log:r});if(n)return n;for(const n of ah){const o=(0,s.join)(e,n);try{if(!(await(0,So.stat)(o)).isFile())continue;const n=await(0,So.readFile)(o,"utf-8"),i=JSON.parse(n);if(!gf(i)||!Array.isArray(i.plugins))continue;const a=i.plugins.filter(wf),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(!jh(n))continue;const o=(0,s.join)(e,n);try{await Kp(o);const t=tp(await Vp(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 ff=new Set(Object.values(gd));function mf(e){return ff.has(e)}function gf(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function wf(e){return!(!gf(e)||"string"!=typeof e.name)&&(void 0===e.mcpServers||Array.isArray(e.mcpServers)&&e.mcpServers.every((e=>"string"==typeof e)))}function yf(e,t){const r={};for(const[n,o]of Object.entries(e.hooks))Array.isArray(o)&&mf(n)&&(r[n]=o.map((e=>"command"in e&&"string"==typeof e.command?{...e,command:zh(e.command,t)}:"prompt"in e&&"string"==typeof e.prompt?{...e,prompt:zh(e.prompt,t)}:e)));return{...e,hooks:r}}async function vf(e,t,r,n,o){if("object"==typeof n){const s=bf(n,t,r);return s&&"config"in s?{config:yf(s.config,e),...void 0!==o&&{sourcePath:o}}:s}let i,a,c;if("string"==typeof n){const t=n.replace(/^\.\//,"");if(!jh(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 Gp(i))return;if(!(await(0,So.stat)(i)).isFile())return}catch{return}try{await Kp(i),a=await(0,So.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=bf(c,t,r);return l&&"config"in l?{config:yf(l.config,e),sourcePath:i}:l}function bf(e,t,r){const n=function(e){if(!vd(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(vd(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=Cd(e);return r.isValid&&Cd(e).isValid?{config:e}:{error:{source:"claude-plugin",message:`Plugin ${t} hooks: ${r.errors.join("; ")}`}}}if("claude-code"===n){if(!(gf(o=e)&&gf(o.hooks)&&Object.keys(o.hooks).length>0))return;const n=Bd(e.hooks,{warn:e=>r.log("warn",`Plugin ${t} hooks: ${e}`),info:e=>r.log("info",`Plugin ${t} hooks: ${e}`)}),s=Cd(n);return s.isValid?{config:n}:{error:{source:"claude-plugin",message:`Plugin ${t} hooks: ${s.errors.join("; ")}`}}}var o}async function Sf(e,t,r,n){const o=n?.log??Gh,s=await ef(e,t,o),i={...df(r)??(n?.configuredVariables?{configuredVariables:n.configuredVariables}:void 0),log:o},[a,c,l]=await Promise.all([tf(e,s?.manifestOptions),hf(e,r,i),vf(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 kf(e,t,r){const n=r?.log??Gh,o=await ef(e,t.raw,n),[s,i,a]=await Promise.all([tf(e,o?.manifestOptions),pf(e,t,n),vf(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 _f(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 Sf(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 Cf(e,t,r={}){const n=r.log??Gh,o=performance.now(),i=await async function(e){const t=Hp(e),r=(0,s.join)(t,"plugins","installed_plugins.json");try{const e=Wp(await(0,So.readFile)(r,"utf-8"));return Up(n=e)&&Up(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=Hp(e),r=(0,s.join)(t,"settings.json");try{const e=Wp(await(0,So.readFile)(r,"utf-8"));return Bp(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 Kd(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=Kd(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,Fr.PH)(c,(async e=>({workspacePath:e,settings:await qp(e)})),{max:8})),u=[],d=r.onError;for(const{pluginId:e,installPath:t}of l)try{const r=performance.now(),o=Dp(e),s=await kf(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(Dp(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 Ef(e){const t=e.log??Gh,r=performance.now(),{client:n,userId:o,teamId:s,onCursorError:i,pruneOldVersions:a,pluginFilter:c,onPluginsListed:l}=e,u=[],d=e.cacheManager??new $p(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,So.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,So.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 _f(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:Jp(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 xf(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 Pf(e){return xf(e)??`path:${e.installPath}`}function Rf(e,t={}){return{...e,model:t.stripModel?void 0:e.model,tools:t.stripTools?void 0:e.tools}}function If(e,t){const r=[];for(const o of e){const e=Op(o.identifier),i=`plugin:${e}`,a=Fp(o.identifier),c=Np(o.identifier),l=Lp(o.identifier),u=jp(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 Tf=r("../proto/dist/generated/agent/v1/agent_skills_pb.js");const Af=(0,Ws.debuglog)("agent-skills-catalog-cache");function $f(e){return(0,wo.createHash)("sha256").update(JSON.stringify({v:1,...e})).digest("hex")}async function Mf(e){try{return(await(0,So.stat)(e)).mtimeMs}catch{return}}function Df(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}const Of=[".kits","cursor-pages"],Ff={configDir:".cursor",subdir:"skills-cursor",thirdParty:!1,builtin:!0},Nf=[{configDir:".cursor",subdir:"skills",thirdParty:!1,builtin:!1},{configDir:".claude",subdir:"skills",thirdParty:!0,builtin:!1},{configDir:".codex",subdir:"skills",thirdParty:!0,builtin:!1},{configDir:".grok",subdir:"skills",thirdParty:!0,builtin:!1},{configDir:".agents",subdir:"skills",thirdParty:!1,builtin:!1},Ff],Lf=(new Set(Nf.map((e=>e.configDir))),new Set(["imagegen","openai-docs","opneai-docs","plugin-creator","skill-creator","skill-installer"]));function jf(e){return e.replace(/\\/g,"/").split("/").filter(Boolean)}function Uf(e){const t=jf(e);if(function(e){const t=e.findIndex(((t,r)=>function(e,t){return Nf.some((r=>r.configDir===e&&r.subdir===t))}(t,e[r+1])));return-1!==t&&e.slice(t+2).some((e=>e.startsWith(".")))}(t))return!0;const r=t.lastIndexOf(".codex");if(-1===r||"skills"!==t[r+1])return!1;const n=t.at(-1),o="SKILL.md"===n?t.at(-2):n;return void 0!==o&&Lf.has(o)}function Bf(e){return{dirPath:(0,s.join)(e,Ff.configDir,Ff.subdir),scope:"builtin",source:"builtin"}}const Wf="canvas";function Hf(e,t){return{dirPath:(0,s.join)(Bf(e).dirPath,...Of),scope:"builtin",source:"builtin"}}function qf(e,t){const r=e.replace(/\\/g,"/"),n=t.replace(/\\/g,"/").replace(/\/+$/,"");if(r.startsWith(`${n}/`))return jf(r.slice(n.length+1))}function zf(e,t){const r=qf(e,t);return void 0!==r&&!r.some((e=>e.startsWith(".")))}function Gf(e){return Nf.filter((t=>!t.builtin&&(e||!t.thirdParty)))}function Vf(e,t){return Gf(t).map((t=>({dirPath:(0,s.join)(e,t.configDir,t.subdir),scope:"project",source:"workspace"})))}function Kf(e,t){return Gf(t).map((t=>({dirPath:(0,s.join)(e,t.configDir,t.subdir),scope:"user",source:"user"})))}var Jf=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 Zf(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}const Xf=Nf.map((({configDir:e,subdir:t,thirdParty:r})=>({pattern:new RegExp(`[/\\\\]${Zf(e)}[/\\\\]${Zf(t)}[/\\\\]`,"i"),requiresThirdParty:r}))),Qf=/[/\\]\.cursor[/\\]rules[/\\]/i,Yf=[{pattern:/[/\\]\.cursor[/\\]agents[/\\]/i,requiresThirdParty:!1},{pattern:/[/\\]\.claude[/\\]agents[/\\]/i,requiresThirdParty:!0}],em=new Set(["AGENTS.md","CLAUDE.md","CLAUDE.local.md"]);function tm(e,t){const r=e.replace(/\\/g,"/"),n=(0,s.basename)(r);if(em.has(n))return"AGENTS.md"===n||t&&("CLAUDE.md"===n||"CLAUDE.local.md"===n)?"markdown":void 0;if(Qf.test(r)&&n.endsWith(".mdc"))return"rules";if("SKILL.md"===n)for(const{pattern:e,requiresThirdParty:n}of Xf)if(e.test(r)){if(n&&!t)continue;return"skills"}if(n.endsWith(".md"))for(const{pattern:e,requiresThirdParty:n}of Yf)if(e.test(r)){if(n&&!t)continue;return"agents"}}class rm{constructor(e,t,r,n){this.root=e,this.gitExecutor=t,this.userHomeDirectory=r,this.getThirdPartyExtensibilityEnabled=n}static getRipwalkCache(){return rm.ripwalkCache??=new ya,rm.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,D.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||Us(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 Za(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:ic,followSymlinks:!0,source:"nested_extensibility"},u={rules:[],skills:[],markdown:[],agents:[]},d=rm.getRipwalkCache();try{const e=d.walk(r.ctx,l);try{for await(const t of e.lines){const e=tm(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{Jf(t)}}buildIncludeGlobs(e){const t=["*/**/.cursor/**","*/**/.agents/**","*/**/AGENTS.md"];return e&&t.push("*/**/.claude/**","*/**/.codex/**","*/**/.grok/**","*/**/CLAUDE.md","*/**/CLAUDE.local.md"),t}}const nm=new Set(["node_modules","__pycache__","dist","build"]);async function om({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,So.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,So.realpath)(n);if(!l(e))continue;if(a.has(e))continue;a.add(e)}catch{continue}const d=await(0,So.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,So.stat)(r);a=e.isDirectory(),l=e.isFile()}catch{continue}if(a){if((u=e.name).startsWith(".")||nm.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 sm={agentStoreSkillsDirs:[],userHomeDirectory:""};function im(e){const t=e.replace(/\\/g,"/");return t.endsWith("/")?t.slice(0,-1):t}function am(e,t){const r=im(t.userHomeDirectory),n=e.replace(/\\/g,"/");if(r.length>0)for(const e of t.agentStoreSkillsDirs){const t=im(e);if(t.length>0&&n.startsWith(`${t}/`))return{key:`${r}::skills/${n.slice(t.length+1)}`,inAgentStore:!0}}return{key:cm(e),inAgentStore:!1}}function cm(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 lm(e,t){const r=new Map,n=[];for(const o of e){const{key:e,inAgentStore:s}=am(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 um=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},dm=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 hm=(0,d.h)("local-exec:cursor-rules");function pm(e){return"/"===e||"\\"===e}function fm(e){return e.split(/[\\/]+/).filter((e=>e.length>0)).length}async function mm(e){return await om({rootDir:e,includeFile:e=>"SKILL.md"===e})}async function gm(e){let t;try{t=await Fi(e)}catch(t){return{skillFilePath:e,error:ud(t)}}try{return{skillFilePath:e,content:t,parsed:qd(t)}}catch(t){return{skillFilePath:e,error:dd(t)}}}async function wm(e){const t=await Qo(e);return{...await gm(e),realSkillFilePath:t}}function ym(e){return Sm(e.data?.environments??e.data?.metadata?.environments)??[]}function vm(e){return Sm(e.data?.["disabled-environments"]??e.data?.metadata?.disabledEnvironments)??[]}function bm(e){return Sm(e.data?.metadata?.scopedTo??e.data?.["metadata.scopedTo"])??[]}function Sm(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 km(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 _m(e){return qo(e,1536)}function Cm(e){return!0===e.data?.alwaysApply}function Em(e){return!0===e.data?.["disable-model-invocation"]}function xm({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---`:zd("",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 ${fd(s.length)} characters; the limit is 64. Rename the skill's folder.`),pd.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 ${fd(i)} characters; the limit is ${fd(1024)}.`);const a=Math.round(n.length/4);return a>5e3&&o.push(`Body is about ${fd(a)} tokens; the recommended limit is ${fd(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(Cm(r))return new Kr.DX({fullPath:e,content:t,frontmatter:n,type:new Kr.f5({type:{case:"global",value:new Kr.i9}}),environments:ym(r),disabledEnvironments:vm(r),scopedTo:bm(r),warnings:o});const s="string"==typeof r.data?.description?_m(r.data.description):void 0,i=hd(s,Em(r));return i?new Kr.DX({fullPath:e,parseError:i,frontmatter:n,scopedTo:bm(r),type:new Kr.f5({type:{case:"agentFetched",value:new Kr.Xo}})}):new Kr.DX({fullPath:e,content:t,frontmatter:n,type:new Kr.f5({type:{case:"agentFetched",value:new Kr.Xo({description:s})}}),environments:ym(r),disabledEnvironments:vm(r),scopedTo:bm(r),warnings:o})}function Pm({skillFilePath:e,content:t,parsed:r}){const n="string"==typeof r.data?.description?_m(r.data.description):"",o=af(r.data?.paths??r.data?.globs),s=Em(r);return new Tf.N({fullPath:e,content:t,description:n,globs:o??[],parseError:hd(n,s),environments:ym(r),disabledEnvironments:vm(r),scopedTo:bm(r),disableModelInvocation:s})}function Rm({rules:e,agentSkills:t,skillFilePath:r,errorMessage:n}){e.push(function({skillFilePath:e,errorMessage:t}){return new Kr.DX({fullPath:e,parseError:t,type:new Kr.f5({type:{case:"agentFetched",value:new Kr.Xo}})})}({skillFilePath:r,errorMessage:n})),t.push(function({skillFilePath:e,errorMessage:t}){return new Tf.N({fullPath:e,parseError:t})}({skillFilePath:r,errorMessage:n}))}function Im(e,t,r,n){if("error"in t)return e.realSkillFilePathsByFullPath.set(t.skillFilePath,t.realSkillFilePath),void Rm({rules:e.rules,agentSkills:e.agentSkills,skillFilePath:t.skillFilePath,errorMessage:t.error});km(t.parsed,r,n)||(e.realSkillFilePathsByFullPath.set(t.skillFilePath,t.realSkillFilePath),e.rules.push(xm(t)),Cm(t.parsed)||e.agentSkills.push(Pm(t)))}const Tm=(0,Ws.debuglog)("cursor-rules-service");function Am(){return{rules:[],agentSkills:[],realSkillFilePathsByFullPath:new Map}}function $m(e){return t=>(Tm("%s: %O",e,t),Am())}function Mm(e,t){return $f({kind:"agent-store",surface:e,roots:[...t].sort()})}function Dm(e,t){const r=t.replace(/\\/g,"/").replace(/\/+$/,"");return""!==r&&e.replace(/\\/g,"/").startsWith(`${r}/`)}function Om(e){let t;if(!0===e.frontmatter.alwaysApply)t={case:"global",value:new Kr.i9};else{const r=af(e.frontmatter.globs);t=r&&r.length>0?{case:"fileGlobbed",value:new Kr.uT({globs:r})}:"string"==typeof e.frontmatter.description&&e.frontmatter.description.trim().length>0?{case:"agentFetched",value:new Kr.Xo({description:_m(e.frontmatter.description)})}:{case:"manuallyAttached",value:new Kr._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 Kr.DX({fullPath:e.path,content:e.body,type:new Kr.f5({type:t}),environments:n,disabledEnvironments:s,scopedTo:a,frontmatter:e.rawFrontmatter??""})}class Fm{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=um(t,(0,D.VI)(e.withName("MergedCursorRulesService.getAllCursorRules")),!1),n=this.cursorRulesServices.map((e=>e.getAllCursorRules(r.ctx).catch((e=>((0,Ws.debuglog)("Failed to load cursor rules from service:",e),[])))));return lm((await Promise.all(n)).flat(),this.getAgentStoreSkillsContext())}catch(e){t.error=e,t.hasError=!0}finally{dm(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()}),Fm.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()}}Fm.CHANGE_COALESCE_MS=1e3;class Nm{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 rm(r,t,(0,o.homedir)(),i),this.ignoreService=c??new _c(t,void 0,[this.rootDirectory]);const u=performance.now();if(this._rules=this.load(e,l).then((t=>{try{hm.info(e,"LocalCursorRulesService load completed",{durationMs:Math.round(performance.now()-u),ruleCount:t.length})}catch{}return t})).catch((e=>((0,Ws.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,b.q6)(),n=um(t,(0,D.VI)(r.withName("LocalCursorRulesService.fileWatcher.subscribe")),!1);if(".cursorignore"===(0,s.basename)(e))return Nm.getRipwalkCache().clear(),void this.reload(n.ctx);this.reloadAtPath(n.ctx,e)}catch(e){t.error=e,t.hasError=!0}finally{dm(t)}}))}}reload(e){this._rules=this.load(e).catch((e=>((0,Ws.debuglog)("Failed to load cursor rules:",e),[])));for(const e of this.onChangeCallbacks)e()}static getRipwalkCache(){return Nm.ripwalkCache??=new ya,Nm.ripwalkCache}reloadAtPath(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=um(r,(0,D.VI)(e.withName("LocalCursorRulesService.reloadAtPath")),!1);if(Zr((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,Ws.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{dm(r)}}isRuleMarkdownFile(e){return Zr(e)}async readRulesAtPath(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=um(r,(0,D.VI)(e.withName("LocalCursorRulesService.readRulesAtPath")),!1),o=(0,s.basename)(t);if(".cursorrules"===o){const e=(0,s.resolve)(this.rootDirectory),t=await Za(n.ctx,this.gitExecutor,e)||e,r=await this.loadCursorRulesRule(n.ctx,t);return r?[r]:[]}if(o.endsWith(".mdc"))return await Lm(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{dm(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=um(r,(0,D.VI)(e.withName("LocalCursorRulesService.load")),!1);this.loadTraceId=n.span.spanContext().traceId;const o=(0,s.resolve)(this.rootDirectory),i=await Za(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=>Zr((0,s.basename)(e.fullPath))));if(t.length<=1)return[...e];const r=await(0,Fr.PH)(t,(e=>async function(e){try{const t=await(0,So.stat)(e,{bigint:!0});if(0n!==t.ino)return`ino:${String(t.dev)}:${String(t.ino)}`}catch{}return await Qo(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=fm(e.dir)-fm(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)&&(pm(r.at(-1))||pm(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=>!Zr((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{dm(r)}}async loadCursorRulesRule(e,t){const r={stack:[],error:void 0,hasError:!1};try{um(r,(0,D.VI)(e.withName("LocalCursorRulesService.loadCursorrules")),!1);try{const e=(0,s.join)(t,".cursorrules");if((await(0,So.stat)(e)).isFile())return{filename:".cursorrules",path:e,frontmatter:{alwaysApply:!0},body:await Fi(e)}}catch{}return null}catch(e){r.error=e,r.hasError=!0}finally{dm(r)}}async getAllCursorRules(e){const t={stack:[],error:void 0,hasError:!1};try{return um(t,(0,D.VI)(e.withName("LocalCursorRulesService.getAllCursorRules")),!1).span.setAttribute("cacheTraceId",this.loadTraceId??"undefined"),await this._rules}catch(e){t.error=e,t.hasError=!0}finally{dm(t)}}toCursorRule(e){return Om({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=um(r,(0,D.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{dm(r)}}async loadRulesFromMarkdownFile(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{um(n,(0,D.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,So.stat)(e)).isFile()){const t=Xr({content:await Fi(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{dm(n)}}async isCursorIgnored(e){try{const t=await Sc((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=um(r,(0,D.VI)(e.withName("LocalCursorRulesService.parseNestedRuleFiles")),!1),o=(await Promise.all(t.map((async e=>{try{const t=Yr(await Fi(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{dm(r)}}async parseNestedMarkdownFiles(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=um(r,(0,D.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{dm(r)}}async loadRulesFromDirectory(e,t){return await async function(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=um(n,(0,D.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 Lm(r))}}catch{}return o.span.setAttribute("rules",i.length),i}catch(e){n.error=e,n.hasError=!0}finally{dm(n)}}(e,t,Nm.getRipwalkCache())}async dirIsDirectory(e,t){const r={stack:[],error:void 0,hasError:!1};try{um(r,(0,D.VI)(e.withName("LocalCursorRulesService.dirIsDirectory")),!1);try{return(await(0,So.stat)(t)).isDirectory()}catch{return!1}}catch(e){r.error=e,r.hasError=!0}finally{dm(r)}}}async function Lm(e){try{const t=Yr(await Fi(e));if(t)return[{filename:(0,s.basename)(e,".mdc"),path:e,frontmatter:t.frontmatter,rawFrontmatter:t.rawFrontmatter,body:t.body}]}catch{}return[]}class jm{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=Bf(r).dirPath,this.canvasKitSkillRootDir=void 0===h?void 0:Hf(r).dirPath,this.workspaceCatalogKey=$f({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 rm(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{hm.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,$m("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(!Df(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]))&&Df(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 Mf(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=>Kr.DX.fromJson(e,{ignoreUnknownFields:!0}))).filter((e=>r(e.fullPath))),agentSkills:e.agentSkills.map((e=>Tf.N.fromJson(e,{ignoreUnknownFields:!0}))).filter((e=>r(e.fullPath))),realSkillFilePathsByFullPath:t}}catch(e){return void Af("snapshot failed to decode: %O",e)}}(t)}catch(e){return void Tm("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 Mf(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=>{Tm("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 Vf(r,e))t.add(n.dirPath)}for(const r of Kf(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(zf(e,this.canvasKitSkillRootDir))return!1;if(function(e,t){const r=qf(e,t);return void 0!==r&&2===r.length&&r[0]===Wf&&"SKILL.md"===r[1]}(e,this.builtinSkillRootDir))return!0}return Uf(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,b.q6)(),n=um(t,(0,D.VI)(r.withName("AgentSkillsCursorRulesService.fileWatcher.subscribe")),!1);this.reloadAtPath(n.ctx,e)}catch(e){t.error=e,t.hasError=!0}finally{dm(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,Fr.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($m("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&&zf(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=um(r,(0,D.VI)(e.withName("AgentSkillsCursorRulesService.reloadAtPath")),!1),o=function(e,t,r=i){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),a=o.endsWith("SKILL.md")?o:(0,s.join)(o,"SKILL.md");if(void 0!==this.seededLoaded&&this._loaded===this.seededLoaded&&!this.getAgentStoreSkillRoots().some((e=>Dm(a,e))))return void(this.reloadRequestedDuringSeed=!0);if(this.getAgentStoreSkillRoots().some((e=>Dm(a,e))))return void this.refreshAgentStoreSkills();if(this.foldersToWatch.some((e=>""===(0,s.relative)(e,o))))return void this.reload(n.ctx);const c=this._loaded,l=(async()=>{const e=await c,{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([a]));if(this.isIgnoredSkillPath(a)||this.isPrunedByExtensibilityScan(a))return r;const o=t.get(a);if(void 0===o){try{await(0,So.stat)(a)}catch{return r}return await this.loadAll(n.ctx)}let s;try{s=await(0,So.realpath)(a)}catch{return await this.loadAll(n.ctx)}if(s!==o)return await this.loadAll(n.ctx);try{return Im(r,{...await async function(e){const t=await Fi(e);return{skillFilePath:e,content:t,parsed:qd(t)}}(a),realSkillFilePath:s},this.surface,this.getEnabledSkills()),r}catch{return await this.loadAll(n.ctx)}})().catch($m("Failed to load Agent Skills at path"));this._loaded=l,this.notifyChanged()}catch(e){r.error=e,r.hasError=!0}finally{dm(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,Fr.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(Mm(this.surface,e),r))}),(e=>{Tm("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(Mm(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=Am(),r=(await Promise.all(e.map((e=>mm(e))))).flat().filter((e=>!Uf(e))),n=await Promise.all(r.map((e=>wm(e)))),o=new Set;for(const e of n)o.has(e.realSkillFilePath)||(o.add(e.realSkillFilePath),Im(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=um(r,(0,D.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=>{Tm("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 mm(e)).filter((e=>!this.isIgnoredSkillPath(e)));return Promise.all(t.map((e=>wm(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),Rm({rules:o,agentSkills:s,skillFilePath:t.skillFilePath,errorMessage:t.error});else{if(km(t.parsed,this.surface,this.getEnabledSkills()))continue;i.set(t.skillFilePath,t.realSkillFilePath),o.push(xm(t)),Cm(t.parsed)||s.push(Pm(t))}const d=(await a).flatMap((e=>e?.skills??[])).filter((e=>!Uf(e))),h=await Promise.all(d.map((e=>Qo(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=>wm(e))));for(const e of f)if("error"in e)i.set(e.skillFilePath,e.realSkillFilePath),Rm({rules:o,agentSkills:s,skillFilePath:e.skillFilePath,errorMessage:e.error});else{if(km(e.parsed,this.surface,this.getEnabledSkills()))continue;i.set(e.skillFilePath,e.realSkillFilePath),o.push(xm(e)),Cm(e.parsed)||s.push(Pm(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{dm(r)}}}function Um(e){let t;switch(e.type){case"global":t=new Kr.f5({type:{case:"global",value:new Kr.i9}});break;case"fileGlobbed":t=new Kr.f5({type:{case:"fileGlobbed",value:new Kr.uT({globs:e.globs??[]})}});break;case"agentFetched":t=new Kr.f5({type:{case:"agentFetched",value:new Kr.Xo({description:_m(e.description??"")})}});break;case"manuallyAttached":t=new Kr.f5({type:{case:"manuallyAttached",value:new Kr._u}});break;default:e.type,t=new Kr.f5({type:{case:"manuallyAttached",value:new Kr._u}})}return new Kr.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 Bm{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{hm.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,Ws.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,Fr.wj)(o,5e3,"Cursor plugin load did not finish within the rules wait budget").catch((t=>(hm.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=um(r,(0,D.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 If(e,(e=>e.skills))}(e),a=function(e){return If(e,(e=>e.rules))}(e);for(const e of[...r,...a])o.push(Um(e));for(const t of e){const e=`plugin:${Op(t.identifier)}`,r=Fp(t.identifier),n=Np(t.identifier),o=Lp(t.identifier),a=jp(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===qd(c.content).data?.["disable-model-invocation"]}catch{}i.push(new Tf.N({fullPath:(0,s.join)(t.installPath,c.path),content:c.content,description:_m(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{dm(r)}}}var Wm=r("../proto/dist/generated/agent/v1/subagents_pb.js");const Hm=(0,Ws.debuglog)("local-subagents");class qm{async getAllSubagents(){return[]}async reload(){return[]}}function zm(e){return"true"===(e??"").trim().toLowerCase()}function Gm(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=zm(o["force-default-model"]),l="true"===(o.readonly??"").trim().toLowerCase()?Wm.b$.READONLY:Wm.b$.DEFAULT,u=zm(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 Vm(e){const t=(0,s.extname)(e).toLowerCase();return".md"===t||".mdc"===t||".markdown"===t}function Km(e){return(0,s.basename)(e,(0,s.extname)(e)).replace(/[\s_]+/g,"-")}async function Jm(e,t){return await om({rootDir:e,includeFile:Vm,containmentRootDir:t})}class Zm{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=>(Hm("Failed to load subagents: %o",e),[])))}async getAllSubagents(){return this.subagents}async reload(){return this.subagents=this.load().catch((e=>(Hm("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 Jm(r,this.allowExternalAgentSymlinks?void 0:this.workspacePath);for(const r of e){const e=(0,s.basename)(r);try{if(!(await(0,So.stat)(r)).isFile())continue}catch(e){Hm("Skipping subagent file %s due to stat error: %o",r,e);continue}try{const o=Gm(await Fi(r));if(!o)continue;t.push(new Wm.zz({fullPath:r,name:o.name||Km(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){Hm("Failed to parse subagent file %s: %o",r,e)}}}return t}}const Xm=new Set(["claude-code-tutor"]);class Qm{constructor(e){this.subagentsServices=e}async getAllSubagents(){const e=await Promise.all(this.subagentsServices.map((e=>e.getAllSubagents().catch((e=>(Hm("Failed to load subagents from merged service: %o",e),[])))))),t=new Map;for(const r of e)for(const e of r)Xm.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 Ym{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&&(Hm("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=Fp(n.identifier),o=Np(n.identifier),i=Lp(n.identifier),a=jp(n.identifier);for(const c of n.agents){const l=Rf(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?Wm.b$.READONLY:Wm.b$.DEFAULT;t.push(new Wm.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 eg{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,f.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 tg(e,t){return`${e}:${(0,wo.createHash)("sha256").update(t.toBinary()).digest("hex")}`}function rg(e){return new ko.q({max:e?.max??10,ttl:e?.ttl})}function ng(e,t,r=rg(t)){return{async execute(t,n,o){if(!o?.execId)return e.execute(t,n,o);const s=tg(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 og=r("../proto/dist/generated/agent/v1/computer_use_tool_pb.js");r("node:readline"),Error;var sg=r("node:timers/promises");const ig=Kl.execFile;function ag(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,Jl.D9)(ig,e,t.map(String),{...s,encoding:"utf8"},((e,t)=>{e?o(e):n(t)}))}))}og.w3.UNSPECIFIED,og.w3.LEFT,og.w3.MIDDLE,og.w3.RIGHT,og.w3.BACK,og.w3.FORWARD,og.Dh.UNSPECIFIED,og.Dh.UP,og.Dh.DOWN,og.Dh.LEFT,og.Dh.RIGHT;const cg=(0,Ws.promisify)(Kl.execFile);function lg(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 ug(e){const{stdout:t}=await(0,Jl.D9)(cg,"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:lg(r.width,r.height),resolutionString:`${r.width}x${r.height}`}}og.w3.UNSPECIFIED,og.w3.LEFT,og.w3.MIDDLE,og.w3.RIGHT,og.w3.BACK,og.w3.FORWARD,og.Dh.UNSPECIFIED,og.Dh.UP,og.Dh.DOWN,og.Dh.LEFT,og.Dh.RIGHT;const dg={pattern:"[\\w-]{1,64}",next:e=>e},hg={pattern:"[0-9a-f-]{36}",next:()=>wo.randomUUID()},pg={pattern:"webp",next:()=>"webp"},fg={native:[hg,pg],agent:[dg,hg,pg],legacyNative:[hg,{pattern:"png",next:()=>"png"}]};new RegExp(`^(?:${Object.values(fg).map((e=>e.map((e=>e.pattern)).join("\\."))).join("|")})$`),new RegExp(`^${dg.pattern}$`),og.Z8.NATIVE_X11,og.Z8.XDOTOOL,(0,h.v5)("computer_use.session.duration_ms",{description:"Duration of computer-use session in milliseconds"}),(0,h.v5)("computer_use.session.action_count",{description:"Number of actions executed in a computer-use session"}),(0,h.Pu)("computer_use.session.result",{description:"Result status of computer-use session",labelNames:["outcome"]}),(0,h.Pu)("computer_use.session.action_kind",{description:"Requested computer-use actions by bounded kind",labelNames:["kind"]}),(0,d.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,h.Pu)("computer_use.desktop_lease.check",{description:"Desktop lease action-gate outcomes",labelNames:["outcome","reason"]});var mg=r("../proto/dist/runtime/compact.js");mg.HL;var gg=(0,mg.QT)(ve.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);ve.proto3,ve.proto3,ve.proto3,ve.proto3;class wg{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 yg={left_ptr:gg.ARROW,arrow:gg.ARROW,default:gg.ARROW,top_left_arrow:gg.ARROW,hand:gg.POINTER,hand1:gg.POINTER,hand2:gg.POINTER,pointer:gg.POINTER,pointing_hand:gg.POINTER,xterm:gg.TEXT,ibeam:gg.TEXT,text:gg.TEXT,watch:gg.WAIT,wait:gg.WAIT,progress:gg.WAIT,left_ptr_watch:gg.WAIT,crosshair:gg.CROSSHAIR,cross:gg.CROSSHAIR,tcross:gg.CROSSHAIR,move:gg.MOVE,fleur:gg.MOVE,size_all:gg.MOVE,sb_v_double_arrow:gg.RESIZE_NS,v_double_arrow:gg.RESIZE_NS,ns_resize:gg.RESIZE_NS,row_resize:gg.RESIZE_NS,top_side:gg.RESIZE_NS,bottom_side:gg.RESIZE_NS,sb_h_double_arrow:gg.RESIZE_EW,h_double_arrow:gg.RESIZE_EW,ew_resize:gg.RESIZE_EW,col_resize:gg.RESIZE_EW,left_side:gg.RESIZE_EW,right_side:gg.RESIZE_EW,top_left_corner:gg.RESIZE_NWSE,bottom_right_corner:gg.RESIZE_NWSE,nwse_resize:gg.RESIZE_NWSE,size_fdiag:gg.RESIZE_NWSE,top_right_corner:gg.RESIZE_NESW,bottom_left_corner:gg.RESIZE_NESW,nesw_resize:gg.RESIZE_NESW,size_bdiag:gg.RESIZE_NESW,not_allowed:gg.NOT_ALLOWED,no_drop:gg.NOT_ALLOWED,forbidden:gg.NOT_ALLOWED,circle:gg.NOT_ALLOWED,grab:gg.GRAB,openhand:gg.GRAB,grabbing:gg.GRABBING,closedhand:gg.GRABBING};class vg{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 wg(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=gg.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 ag("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 ag("xdotool",["getmouselocation","--shell"],{env:this.env})).match(/CURSOR=(\S+)/i);if(e){const t=e[1].toLowerCase();return yg[t]??gg.ARROW}try{const e=await ag("xprop",["-root","_XSERVER_CURSOR"],{env:this.env,timeoutMs:500});for(const[t,r]of Object.entries(yg))if(e.toLowerCase().includes(t))return r}catch{}return gg.ARROW}catch{return gg.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,d.h)("computer-use-lazy");var bg=r("node:net");function Sg(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 kg extends Error{constructor(e){super(e),this.name="MacRPCProtocolError"}}const _g=Be.object({rpcSocketPath:Be.string().min(1).optional(),appControlSocketPath:Be.string().min(1).optional(),pid:Be.number().int().positive().optional().catch(void 0),protocolMajor:Be.number().int().positive().optional().catch(void 0)}).passthrough(),Cg=Be.object({data:Be.string(),mimeType:Be.string().min(1)}).strip(),Eg=Be.object({message:Be.string(),screenshot:Cg.optional(),screenshotBefore:Cg.optional(),structuredContent:Be.unknown().optional(),isError:Be.boolean()}).strip(),xg=Be.object({accessibilityTrusted:Be.boolean(),screenRecordingGranted:Be.boolean()}).strip(),Pg=Be.union([Be.object({id:Be.number().int(),result:Eg,ok:Be.never().optional(),error:Be.never().optional(),errorCode:Be.never().optional(),permissionStatus:Be.never().optional(),sessionId:Be.never().optional()}).strip(),Be.object({id:Be.number().int(),sessionId:Be.string().min(1),ok:Be.literal(!0).optional(),result:Be.never().optional(),error:Be.never().optional(),errorCode:Be.never().optional(),permissionStatus:Be.never().optional()}).strip(),Be.object({id:Be.number().int(),ok:Be.literal(!0),result:Be.never().optional(),error:Be.never().optional(),errorCode:Be.never().optional(),permissionStatus:Be.never().optional(),sessionId:Be.never().optional()}).strip(),Be.object({id:Be.number().int().nullable().optional(),error:Be.string().min(1),errorCode:Be.string().min(1).optional(),result:Be.never().optional(),ok:Be.never().optional(),permissionStatus:Be.never().optional(),sessionId:Be.never().optional()}).strip(),Be.object({id:Be.number().int(),permissionStatus:xg,result:Be.never().optional(),ok:Be.never().optional(),error:Be.never().optional(),errorCode:Be.never().optional(),sessionId:Be.never().optional()}).strip()]);function Rg(e,t){try{return JSON.parse(e)}catch{throw new kg(`local-cua ${t} is not valid JSON`)}}const Ig={responseMaxBytes:33554432,parseServiceState(e){const t=_g.safeParse(Rg(e,"service state")),r=t.success?t.data.rpcSocketPath??t.data.appControlSocketPath:void 0;if(!t.success||void 0===r)throw new kg("local-cua service state is malformed");return{...t.data,rpcSocketPath:r}},parseResponse({line:e,expectedID:t}){const r=Pg.safeParse(Rg(e.toString("utf8"),"RPC response"));if(!r.success)throw new kg("local-cua RPC response is malformed");if(void 0!==r.data.id&&null!==r.data.id&&r.data.id!==t)throw new kg("local-cua RPC response ID did not match");return r.data}};class Tg extends Error{constructor(e,t){super(e),this.name="MacComputerUseRPCError",this.code=t?.code,this.userFacing=!0===t?.userFacing,this.tool=t?.tool}}function Ag(e){return"object"==typeof e&&null!==e&&"code"in e&&"string"==typeof e.code?e.code:e instanceof Error?Sg(e.message)?e.name:e.message.length>0?`${e.name}: ${e.message}`:e.name:"unknown"}const $g=new Map([["co.anysphere.cursor-computer-use","cursor-computer-use"],["co.anysphere.cursor-computer-use.dev","cursor-computer-use-dev"]]),Mg=/^[A-Za-z0-9][A-Za-z0-9._-]*$/;class Dg{constructor(e){this.mode=e}static isInstalled(){if((0,_o.existsSync)(Dg.serviceExecutablePath()))return!0;let e;try{e=Ig.parseServiceState((0,_o.readFileSync)(Dg.serviceStatePath(),"utf8"))}catch{return!1}return void 0===e.pid||Dg.isProcessAlive(e.pid)}static async runningHelperPid(){const e=await Dg.readServiceState(),t=e?.pid;return void 0!==t&&Dg.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!==Dg.protocolMajor&&void 0!==e.pid&&!Dg.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;Dg.throwIfAborted(e.signal);const t=(0,wo.randomUUID)(),r=await this.sendWithRelaunchRetry(e,(()=>({id:Dg.requestID,method:"control/start",requestID:t,mode:this.mode})),"control/start");if(void 0!==r.error)throw Dg.rpcError(r);if(void 0===r.sessionId)throw new Tg("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 Dg.readServiceState();if(void 0===e)return;const r=await Dg.sendOnce(Dg.socketPathFrom(e),{id:Dg.requestID,method:"control/release",requestID:(0,wo.randomUUID)(),mode:this.mode,sessionId:t},Dg.defaultCallTimeoutMs);if(void 0!==r.error)throw Dg.rpcError(r)}catch(t){Dg.logger.warn(e,"local-cua control release failed",{error:Ag(t)})}}}async callTool(e,t,r){Dg.throwIfAborted(e.signal);const n=Dg.defaultCallTimeoutMs,o=await this.sendWithRelaunchRetry(e,(()=>{const e=Date.now()/1e3,o=this.activeSessionId;return{id:Dg.requestID,method:"tools/call",requestID:(0,wo.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 Dg.rpcError(o,t);const s=o.result;if(void 0===s)throw new Tg(`local-cua tool ${t} returned no result`,{tool:t});if(s.isError){const e=s.message.trim();throw new Tg(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=Dg.defaultCallTimeoutMs,o=await this.ensureSocketPath(e);Dg.throwIfAborted(e.signal);try{return await Dg.sendOnce(o,t(),n,e.signal)}catch(o){if(!Dg.isPreDeliveryConnectionError(o))throw o;Dg.logger.warn(e,"local-cua callTool failed; relaunching and retrying",{tool:r,error:Dg.spawnErrorCode(o)});const s=await this.ensureSocketPath(e,!0);return Dg.throwIfAborted(e.signal),void 0!==this.activeSessionId&&(this.activeSessionId=void 0,await this.startControl(e)),await Dg.sendOnce(s,t(),n,e.signal)}}static rpcError(e,t){return new Tg(e.error,{code:e.errorCode,userFacing:!0,tool:t})}async ensureSocketPath(e,t=!1){if(Dg.throwIfAborted(e.signal),!t){const e=await Dg.readServiceState();if(e&&!Dg.isExitedIncompatibleHelper(e))return Dg.socketPathFrom(e)}await this.launchAndWait(e);const r=await Dg.readServiceState();if(!r)throw new Tg("local-cua sidecar did not publish service.json after launch");return Dg.socketPathFrom(r)}static setLaunchGuard(e){Dg.launchGuard=e}async launchAndWait(e){const t=Dg.serviceAppPath(),r=Dg.launchGuard,n=()=>this.launchAppAndWait(e,t);await(void 0===r?n():r(t,n,e.signal))}async launchAppAndWait(e,t){Dg.logger.info(e,"launching local-cua sidecar",Dg.sidecarLaunchLogFields(t)),"1"===process.env[Dg.directLaunchEnv]?await Dg.spawnSidecarProcess(e,Dg.serviceExecutablePath(),[],{detached:!0}):await Dg.spawnSidecarProcess(e,"/usr/bin/open",["-g",t]);const r=Date.now()+Dg.launchReadyTimeoutMs;for(;Date.now()<r;){Dg.throwIfAborted(e.signal);const t=await Dg.readServiceState();if(t&&!Dg.isExitedIncompatibleHelper(t)){const r=Dg.socketPathFrom(t);try{if("ok"in await Dg.sendOnce(r,{id:Dg.requestID,method:"ping"},2e3,e.signal))return}catch{}}await(0,Fr.cb)(Dg.launchPollIntervalMs)}throw new Tg("local-cua sidecar did not become ready in time")}static isPreDeliveryConnectionError(e){const t=Ag(e);return"ENOENT"===t||"ECONNREFUSED"===t}static serviceStatePath(){return s.join(Dg.helperIdentity().appSupportDirectory,"service.json")}static serviceAppPath(){const e=process.env[Dg.serviceAppOverrideEnv];return e&&e.length>0?e:s.join(o.homedir(),...Dg.sharedInstallRelativePath,`${Dg.serviceAppBundleName}.app`)}static helperIdentity(){const e=Dg.serviceAppPath(),t=process.env[Dg.appSupportOverrideEnv],r=`${e}\0${t??""}`,n=Dg.identityCache;if(n?.key===r)return n.identity;const i=function(e){let t;try{t=(0,_o.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&&Mg.test(r.trim())?r.trim():void 0};return{executableName:r("CFBundleExecutable"),bundleIdentifier:r("CFBundleIdentifier")}}(e),a=s.join(e,"Contents","MacOS",i.executableName??Dg.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:$g.get(i.bundleIdentifier))??Dg.appSupportFolder)};return(0,_o.existsSync)(a)&&(Dg.identityCache={key:r,identity:c}),c}static sidecarLaunchLogFields(e){const t=`${Dg.serviceAppBundleName}.app`;return{appName:s.basename(e)===t?t:"custom",appPathHash:(0,wo.createHash)("sha256").update(e).digest("hex"),usingOverride:Boolean(process.env[Dg.serviceAppOverrideEnv])}}static spawnErrorCode(e){return Ag(e)}static socketError(e){const t=Ag(e);return new Tg(`local-cua RPC connection failed: ${t}`,{code:t})}static serviceExecutablePath(){return Dg.helperIdentity().executablePath}static spawnSidecarProcess(e,t,r,n){return new Promise(((o,s)=>{const i=(0,Kl.spawn)(t,[...r],{detached:!0===n?.detached,stdio:"ignore"}),a=e=>{s(new Tg(`local-cua sidecar launch failed: ${Dg.spawnErrorCode(e)}`))};i.once("error",a),i.once("spawn",(()=>{i.removeListener("error",a),i.on("error",(t=>{Dg.logger.warn(e,"local-cua sidecar process error after launch",{error:Dg.spawnErrorCode(t)})})),i.unref(),o()}))}))}static async readServiceState(){try{const e=await(0,So.readFile)(Dg.serviceStatePath(),"utf8");return Ig.parseServiceState(e)}catch(e){if(e instanceof Error&&"code"in e&&"ENOENT"===e.code)return;if(e instanceof kg)return;throw new Tg("local-cua service state could not be read")}}static socketPathFrom(e){if(void 0!==e.protocolMajor&&e.protocolMajor!==Dg.protocolMajor)throw new Tg(`The running Cursor Computer Use speaks protocol ${e.protocolMajor}, and this Cursor CLI speaks protocol ${Dg.protocolMajor}. Update the Cursor CLI.`,{userFacing:!0});return e.rpcSocketPath}static abortError(e){return e.reason instanceof Error?e.reason:new Tg("local-cua RPC aborted")}static throwIfAborted(e){if(e.aborted)throw Dg.abortError(e)}static sendOnce(e,t,r,n){return n?.aborted?Promise.reject(Dg.abortError(n)):new Promise(((o,s)=>{let i=!1,a=[],c=0,l=!1;const u=(0,bg.createConnection)({path:e}),d=e=>{i||(i=!0,clearTimeout(p),n?.removeEventListener("abort",h),u.destroy(),e())},h=()=>{d((()=>s(void 0===n?new Tg("local-cua RPC aborted"):Dg.abortError(n))))},p=setTimeout((()=>{d((()=>s(new Tg(`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(Dg.socketError(e))))}))})),u.on("data",(e=>{const t=e.indexOf(10),r=c+(t<0?e.length:t);if(r>Ig.responseMaxBytes)return void d((()=>s(new Tg("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=Ig.parseResponse({line:n,expectedID:Dg.requestID});d((()=>o(e)))}catch(e){d((()=>s(e)))}})),u.on("error",(e=>{d(l?()=>s(new Tg("local-cua RPC connection failed after request delivery")):()=>s(Dg.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 Tg(e))))})))}))}}let Og;function Fg(){if(void 0===Og){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 Og===e&&(Og=void 0),t}));Og=e}return Og}Dg.logger=(0,d.h)("local-cua:rpc"),Dg.serviceAppBundleName="Cursor Computer Use",Dg.appSupportFolder="cursor-computer-use",Dg.productionExecutableName="CUCursorService",Dg.sharedInstallRelativePath=[".cursor","computer-use-sidecar"],Dg.appSupportOverrideEnv="CUA_APP_SUPPORT_DIR",Dg.serviceAppOverrideEnv="CUA_SERVICE_APP",Dg.directLaunchEnv="CUA_DIRECT_LAUNCH",Dg.protocolMajor=1,Dg.defaultCallTimeoutMs=45e3,Dg.launchReadyTimeoutMs=8e3,Dg.launchPollIntervalMs=200,Dg.requestID=1;var Ng=r("node:module"),Lg=r.t(Ng,2);const jg="mac-webp-runtime.cjs";function Ug(e){return"function"==typeof e}function Bg(e){return"object"==typeof e&&null!==e&&"getFileName"in e&&"function"==typeof e.getFileName}function Wg(){const e=(new Error).stack;return Array.isArray(e)?e.filter(Bg):[]}let Hg,qg;function zg(){return Hg??=(()=>{const e=Error.prepareStackTrace;try{Error.prepareStackTrace=(e,t)=>t;const e=Wg()[0]?.getFileName();return function(){const e=Lg;if("createRequire"in e&&Ug(e.createRequire))return e.createRequire;if("default"in e&&"object"==typeof e.default&&null!==e.default&&"createRequire"in e.default&&Ug(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}})(),Hg}function Gg(){const e=globalThis.__MAC_WEBP_IMPORT__;return"function"==typeof e?t=>Promise.resolve(e(t)):(qg??=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 Wg()){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,md.fileURLToPath)(n):n);r((0,s.join)(t,jg)),r((0,s.join)(t,"..","..","src","computer-use",jg))}var n;"string"==typeof process.argv[1]&&process.argv[1].length>0&&r((0,s.join)((0,s.dirname)(process.argv[1]),jg)),r((0,s.join)(process.cwd(),"src","computer-use",jg)),r((0,s.join)(process.cwd(),"computer-use",jg));try{const e=(0,s.dirname)(zg().resolve("@anysphere/local-exec/package.json"));r((0,s.join)(e,"src","computer-use",jg)),r((0,s.join)(e,"dist","computer-use",jg))}catch{}for(const t of e)try{const e=zg()(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")}(),qg)}function Vg(...e){return t=["@jsquash","webp",...e].join("/"),zg().resolve(t);var t}async function Kg(...e){var t;return await(t=(0,md.pathToFileURL)(Vg(...e)).href,Gg()(t))}const Jg=e=>{let t;return()=>{if(void 0===t){const r=e();r.catch((()=>{t===r&&(t=void 0)})),t=r}return t}},Zg=(Jg((async()=>{const e=await Kg("decode.js");return await e.init({wasmBinary:await _o.promises.readFile(Vg("codec","dec","webp_dec.wasm"))}),e})),Jg((async()=>{const[e,t,r]=await Promise.all([Kg("utils.js"),Kg("meta.js"),Kg("codec","enc","webp_enc.js")]);return{module:await e.initEmscriptenModule(r.default,void 0,{wasmBinary:await _o.promises.readFile(Vg("codec","enc","webp_enc.wasm"))}),defaultOptions:t.defaultOptions}}))),Xg="image/png",Qg={async normalize(e){if(e.mimeType!==Xg)throw new Error(`Mac screenshot must be ${Xg}, received ${e.mimeType}`);const t=await Fg(),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 Zg(),n=new Uint8ClampedArray(e.data.buffer,e.data.byteOffset,e.data.byteLength);return Buffer.from(t.encode(n,e.width,e.height,{...r,lossless:1,exact:1}))})(n))).toString("base64");var n}},Yg={userFacing:function(e){if(e instanceof Tg&&e.userFacing&&e.message.trim().length>0&&!Sg(e.message))return e.message.trim()},isCaptureBlocked:function(e){return e instanceof Tg&&("computer_use_screenshot"===e.tool||"permission_required"===e.code)}},ew=new Set(["keys"]),tw=new Set(["matched","mismatch","unchecked"]),rw=new Set(["no_text","password","control_keys","too_long","unreadable","moved","chromium","gecko"]),nw=new Set(["matched"]),ow=new Set(["too_long"]),sw=new Set(["watched","fell_back","unavailable","over_budget"]);class iw{constructor({ctx:e,actions:t,sidecar:r,errors:n,reportTyping:o}){this.startTime=Date.now(),this.typingNotes=[],this.typing=[],this.geometryPrimed=!1,this.actionCount=0,this.hasCompletedActuation=!1,this.staleAfterWait=!1,this.ctx=e,this.actions=t,this.sidecar=r,this.errors=n??Yg,this.reportTyping=!0===o}async execute(){const e=this.actions.some((e=>iw.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:iw.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:iw.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:iw.mouseButtonName(t.value.button),action:"down"}));break;case"mouseUp":this.recordActuation(await this.sidecar.mouseButton(this.ctx,{button:iw.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:iw.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===og.EB.DOWN||t.value.stroke===og.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 og.ks({result:{case:"success",value:new og.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=iw.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=iw.cursorFromResult(e)??iw.coordinateFromPoint(t)??this.cursor}recordTyping(e){if(!this.reportTyping)return;const t=e.message.trim();""!==t&&this.typingNotes.push(t);const r=iw.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",tw),a=o("unchecked",rw),c=void 0!==n.get("unchecked")&&null!==n.get("unchecked"),l=void 0!==i&&nw.has(i)&&!c||"unchecked"===i&&void 0!==a&&ow.has(a);return new og.qA({method:o("method",ew)??"",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",sw)})}async errorResult(e){let t;if(iw.logger.error(this.ctx,"local-cua execute failed",void 0,{error:Ag(e)}),!this.errors.isCaptureBlocked(e))try{const e=await this.sidecar.screenshot(this.ctx);t=(await this.normalizeScreenshot(e.screenshot,"error")).data}catch(e){iw.logger.warn(this.ctx,"local-cua error screenshot capture failed",{error:Ag(e)})}const r=this.errors.userFacing(e);return new og.ks({result:{case:"error",value:new og.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 og.ks({result:{case:"error",value:new og.Jb({error:"Screenshot unavailable",actionCount:this.actionCount,durationMs:Date.now()-this.startTime,log:e})}})}abortedResult(){return new og.ks({result:{case:"error",value:new og.Jb({error:"Computer use aborted",actionCount:this.actionCount,durationMs:Date.now()-this.startTime,log:this.log(),typing:this.typing})}})}static mouseButtonName(e){return iw.mouseButtonNames[e]??"left"}static scrollDirectionName(e){return iw.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 Qg.normalize(e),failed:!1}}catch(r){const n=Ag(r);return iw.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 og.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 og.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()}))}}iw.logger=(0,d.h)("local-cua:actions"),iw.mouseButtonNames={[og.w3.UNSPECIFIED]:"left",[og.w3.LEFT]:"left",[og.w3.RIGHT]:"right",[og.w3.MIDDLE]:"middle",[og.w3.BACK]:"left",[og.w3.FORWARD]:"left"},iw.scrollDirectionNames={[og.Dh.UNSPECIFIED]:"down",[og.Dh.UP]:"up",[og.Dh.DOWN]:"down",[og.Dh.LEFT]:"left",[og.Dh.RIGHT]:"right"},s.join(o.tmpdir(),"computer-use"),(0,d.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 aw,cw=r("../proto/dist/generated/agent/v1/delete_exec_pb.js");function lw({encoding:e,bom:t,lineEnding:r}){return{encoding:e,bom:t,lineEnding:r}}class uw{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,So.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 ji(e,t,r,n);await(0,So.writeFile)(e,o),await Li(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"}(aw||(aw={}));var dw=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,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,D.VI)(e.withName("LocalDeleteExecutor.execute")),!1);const n=t.path;if(""===n.trim())return new cw.Pi({result:{case:"error",value:new cw.GU({path:n,error:Xo})}});const o=(0,Zo.o1)(n,this.workspacePath),i=await this.permissionsService.shouldBlockWrite(e,o,"");if(i){const e=await Wu(i,{onNeedsApproval:async(e,t)=>null,onUserRejected:e=>new cw.Pi({result:{case:"rejected",value:new cw.iq({path:o,reason:e||""})}}),onPermissionDenied:(e,t)=>new cw.Pi({result:{case:"permissionDenied",value:new cw.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,So.realpath)((0,s.dirname)(e)).catch((()=>{}));if(void 0===r)return e;if(void 0!==t){const n=await(0,So.realpath)(t).catch((()=>{}));if(void 0!==n&&(0,Zo.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:aw.Delete,details:{path:a},toolCallId:t.toolCallId});if(!c.approved)return new cw.Pi({result:{case:"rejected",value:new cw.iq({path:o,reason:c.reason||""})}});let l;try{l=await(0,So.stat)(o)}catch(e){return"ENOENT"===yc(e)?new cw.Pi({result:{case:"fileNotFound",value:new cw.n0({path:o})}}):new cw.Pi({result:{case:"error",value:new cw.GU({path:o,error:vc(e)})}})}if(!l.isFile()){const e=l.isDirectory()?"directory":"other";return new cw.Pi({result:{case:"notFile",value:new cw.LX({path:o,actualType:e})}})}const u=l.size;let d,h;if(u<=es)try{const e=await Ni(o);d=e.text,h=lw(e)}catch{}const p=d??"",f=await(0,So.realpath)(o).catch((()=>o)),m=await(0,So.stat)(o).catch((()=>{}));if(m?.dev!==l.dev||m.ino!==l.ino)return new cw.Pi({result:{case:"error",value:new cw.GU({path:o,error:"File changed while deleting; nothing was removed"})}});e.signal.throwIfAborted();try{await(0,So.unlink)(o),this.agentFileViews?.recordDelete(o)}catch(e){return"EACCES"===yc(e)?new cw.Pi({result:{case:"permissionDenied",value:new cw.QG({path:o,clientVisibleError:"Permission denied"})}}):"EBUSY"===yc(e)?new cw.Pi({result:{case:"fileBusy",value:new cw.vX({path:o})}}):new cw.Pi({result:{case:"error",value:new cw.GU({path:o,error:vc(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 cw.Pi({result:{case:"success",value:new cw.fl({path:o,deletedFile:o,fileSize:BigInt(u),prevContent:p})}})}catch(e){r.error=e,r.hasError=!0}finally{dw(r)}}}class pw{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===qn));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 gn.I0({serverIdentifier:qn,serverName:qn,instructions:`User-defined tools for this session (server "${qn}"). 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 fw extends pw{constructor(e,t){super(e,t),this.observableInner=e}onDidChange(e){return this.observableInner.onDidChange(e)}}var mw=r("../proto/dist/generated/agent/v1/fetch_exec_pb.js"),gw=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 ww=/;\s*charset\s*=\s*"?([^";\s]+)/i;class yw{constructor(e){this.encodingSlices=e?.encodingSlices}async readText(e,t){if(!Tl(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=ww.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{Hl(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,D.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 mw.uN({result:{case:"success",value:new mw.Uk({url:n,content:r,statusCode:t.status,contentType:o})}})}catch(e){return new mw.uN({result:{case:"error",value:new mw.fk({url:n,error:vc(e)})}})}}catch(e){r.error=e,r.hasError=!0}finally{gw(r)}}}const vw=[["safe.bareRepository","explicit"]],bw=[["core.fsmonitor","false"],["core.hooksPath",o.devNull],["core.attributesFile",o.devNull]],Sw=[["core.quotePath","false"]];function kw(e){const t="allow-hooks"===e?bw.filter((([e])=>"core.hooksPath"!==e)):bw;return[...vw,...t]}const _w=(0,Ws.promisify)(Kl.execFile),Cw=new Set(["-c","-C","--git-dir","--work-tree","--namespace","--super-prefix","--config-env","--attr-source"]),Ew=new Set(["diff","show","blame","log","whatchanged"]);function xw(e){for(let t=0;t<e.length;t++){const r=e[t];if(Cw.has(r))t++;else if(!r.startsWith("-"))return t}return-1}function Pw(e){const t=xw(e);return-1===t?void 0:e[t]}function Rw(e){const t=xw(e);if(-1===t||!Ew.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 Iw(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,[...kw(e.repoConfigExecution??"block"),...Sw])}({command:Pw(e),optionsEnv:t})}async function Tw(e,t,r){const{env:n,encoding:o="utf8",...s}=r??{},i=Rw(t),a=await _w(e,i,{...s,encoding:o,env:Iw(i,n)});return{stdout:a.stdout,stderr:a.stderr}}class Aw extends Error{constructor(e,t){super(`git did not run: repository config refused (${e})`),this.name="GitRepoConfigRefusedError",this.reason=e,this.exitCode=t}}const $w=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]]]),Mw=["recurse-submodules","submodule","remerge-diff","diff-merges","alternate-refs"],Dw=/^[A-Za-z0-9][A-Za-z0-9_-]*$/,Ow=/^filter\.(.*)\.(?:clean|smudge|process)$/s,Fw=new Set(["system","global","command"]),Nw={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 Lw(e){return e.flatMap((([e,t])=>["-c",`${e}=${t}`]))}const jw=Lw([...kw("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 Uw(e){const t=e?.timeout??0,r=Number.isFinite(t)&&t>0?Math.min(t,2147483647):6e4;return performance.now()+r}function Bw(e,t=2147483647){return Math.max(1,Math.ceil(Math.min(t,e-performance.now())))}function Ww(){const e=new Map;return{async exec(t,r,n){const o=Uw(n);return Tw("git",await Hw(e,t,r,o),{cwd:t,env:Nw,windowsHide:!0,killSignal:"SIGTERM",timeout:Bw(o)})},async run(t,r,n){const o=Uw(n);return function(e,t,r,n){return new Promise(((o,s)=>{const i=function(e,t,r){const{env:n,...o}=r??{},s=Rw(t);return(0,Kl.spawn)("git",s,{...o,env:Iw(s,n)})}(0,t,{cwd:e,env:Nw,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"})))}),Bw(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 Hw(e,t,r,o),o,n?.input)}}}async function Hw(e,t,r,n){const{prefix:o,tail:s,readsConfig:i}=function(e){const t=Rw(e),r=xw(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=$w.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=[...Mw,..."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),...jw],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 Tw("git",[...t,"config","--list","--show-scope","--includes","-z"],{cwd:e,env:Nw,windowsHide:!0,killSignal:"SIGTERM",timeout:Bw(r,1e4),maxBuffer:16777216})).stdout}catch(e){throw function(e){if(!(e instanceof Error))return new Aw("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 Aw("timed-out");const t="code"in e&&"number"==typeof e.code?e.code:void 0;return new Aw("read-failed",t)}(e)}if(performance.now()>=r)throw new Aw("timed-out");return function(e){if(""===e)return[];const t=e.split("\0");if(""!==t.pop()||t.length%2!=0)throw new Aw("read-failed");const r=new Set;for(let e=0;e<t.length;e+=2){if(Fw.has(t[e]))continue;const n=t[e+1].split("\n",1)[0],o=Ow.exec(n)?.[1];if(void 0!==o){if(!Dw.test(o))throw new Aw("unpinnable");r.add(o)}else(n.startsWith("lfs.extension.")||"lfs.storage"===n)&&r.add("lfs")}return[...r].sort().flatMap((e=>Lw([[`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 qw(e,t,r){return Ww().exec(e,t,r)}var zw=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 Gw{constructor(e={}){void 0!==e.guardedRootLookup&&(this.guardedRootLookup=e.guardedRootLookup)}async exec(e,t,r,n){return Vw(e,t,r,n,qw)}forRequest(){const e=Ww();return{exec:(t,r,n,o)=>Vw(t,r,n,o,((t,r,n)=>e.exec(t,r,n))),...void 0===this.guardedRootLookup?{}:{guardedRootLookup:this.guardedRootLookup}}}}async function Vw(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,D.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{zw(s)}}var Kw=r("../proto/dist/generated/agent/v1/grep_exec_pb.js");class Jw{constructor(){this.lineEnd=0,this.nextStart=0}}function Zw(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 Xw(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 Qw=-(2**31),Yw=2**31-1;function ey(e){return Number.isNaN(e)?0:e<Qw?Qw:e>Yw?Yw:e}function ty(e){if("number"==typeof e&&Number.isFinite(e)&&!(e<0))return ey(Math.trunc(e))}function ry(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 ny(e,t){const r=ry(t),n=(0,s.join)(e,"mcps",r,"tools");let o;try{o=await(0,So.readdir)(n)}catch(e){if("ENOENT"===yc(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,So.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 oy=(0,d.h)("local-exec:mcp-disk-freshness-on-access"),sy="/mcps/",iy=(0,h.Pu)("mcp.discovery_freshness.check",{description:"MCP discovery surface freshness comparison outcome against canonical live tools",labelNames:["surface","outcome"]}),ay=(0,h.v5)("mcp.discovery_freshness.missing_tools",{description:"Number of tools present in canonical live state but missing from the observed discovery surface",labelNames:["surface"]}),cy=(0,h.v5)("mcp.discovery_freshness.extra_tools",{description:"Number of tools present on the observed discovery surface but absent from canonical live state",labelNames:["surface"]}),ly=(0,h.v5)("mcp.discovery_freshness.symmetric_difference",{description:"Total symmetric difference between canonical live tools and the observed discovery surface",labelNames:["surface"]}),uy=new Map;function dy(e){const t=e.replace(/\\/g,"/");return t.endsWith("/mcps")?`${t}/`:t}async function hy({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 oy.warn(e,"mcp_disk_state_read_failed",{error_type:t instanceof Error?t.name:typeof t})}const a=i.servers.find((e=>ry(e.serverIdentifier)===n));if(void 0===a)return;let c;try{c=await o(r,a.serverIdentifier)}catch(t){return void oy.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"};iy.increment(e,1,{...l,outcome:c}),ay.histogram(e,i.length,l),cy.histogram(e,a.length,l),ly.histogram(e,i.length+a.length,l),"mismatch"===c&&oy.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 py(e,t,r,n=ny){if(void 0===r||(void 0===(o=r)||!dy(o).includes(sy)))return;var o;const s=function(e){const t=dy(e),r=t.indexOf(sy);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=uy.get(i);void 0!==l&&clearTimeout(l);const u=e,d=setTimeout((()=>{uy.delete(i),(async()=>{if(c){const e=await t.getState(u);for(const r of e.servers){const o=ry(r.serverIdentifier);await hy({ctx:u,mcpStateAccessor:t,projectDir:s.projectDir,sanitizedServerFolder:o,readDiskCatalog:n,state:e})}}else void 0!==a&&await hy({ctx:u,mcpStateAccessor:t,projectDir:s.projectDir,sanitizedServerFolder:a,readDiskCatalog:n})})().catch((e=>{oy.warn(u,"mcp_disk_discovery_freshness_schedule_failed",{error_type:e instanceof Error?e.name:typeof e})}))}),2e3);uy.set(i,d)}async function fy(e){try{return(await(0,So.stat)(e,{bigint:!0})).mtimeNs}catch{return}}function my(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 gy(e,t,r=fy){const n=e.map((e=>({item:e,path:t(e)})));let o;try{o=await(0,Fr.wj)(Promise.all(n.map((({path:e})=>r(e)))),2e3,"stat timed out")}catch(t){if(t instanceof Fr.MU)return{items:[...e],statTimedOut:!0};throw t}return{items:my(n,o,s.sep).map((({item:e})=>e)),statTimedOut:!1}}var wy=r("../proto/dist/generated/agent/v1/read_exec_pb.js");const yy=Buffer.from([137,80,78,71,13,10,26,10]),vy=Buffer.from([0,0,0,0,73,69,78,68,174,66,96,130]),by=e=>{if(e.length<yy.length+25+vy.length||!e.subarray(0,yy.length).equals(yy)||13!==e.readUInt32BE(8)||"IHDR"!==e.toString("ascii",12,16)||!(e=>e.subarray(e.length-vy.length).equals(vy)||(e=>{let t=yy.length+25;for(;t+vy.length<=e.length;){const r=e.readUInt32BE(t);if(r>e.length-t-vy.length)return!1;if("IEND"===e.toString("ascii",t+4,t+8))return e.subarray(t,t+vy.length).equals(vy);t+=vy.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)}},Sy=e=>1===e||e>=208&&e<=216,ky=e=>192===e||193===e||194===e,_y=e=>e>=195&&e<=207&&196!==e&&200!==e&&204!==e,Cy=e=>0===e||e>=208&&e<=215,Ey=(e,t)=>{let r=e.indexOf(255,t);for(;-1!==r&&r+1<e.length;){const t=e[r+1];if(255!==t){if(!Cy(t))return r;r=e.indexOf(255,r+2)}else r+=1}},xy=e=>(e=>{const t=by(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(Sy(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=Ey(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(Sy(r)){t+=2;continue}if(218===r||217===r||_y(r))return;const n=e.readUInt16BE(t+2);if(n<2)return;if(ky(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),Py=(e,t)=>({width:Math.max(e?.width??0,t.width),height:Math.max(e?.height??0,t.height)}),Ry=(e,t)=>{for(;t<e.length&&0!==e[t];)t+=1+e[t];return t+1},Iy=e=>{const t=e.toString("latin1",0,6);return e.subarray(0,yy.length).equals(yy)?"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},Ty={0:1,2:3,4:2,6:4},Ay=async({data:e,width:t,height:r})=>{const n=$y(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=kp.Readable.from(n.idat).pipe((0,Cp.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;My({filter:d,row:u,previous:l,bytesPerPixel:n.channels}),Dy({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||Oy({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},$y=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=Ty[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}},My=({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}`)}}},Dy=({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]]++}},Oy=({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)},Fy={0:1,2:3,3:1,4:2,6:4},Ny=[1,2,4,8,16],Ly=[[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]],jy=async e=>{const t=Uy(e);if(void 0===t)return;const r=By(t);let n=0;const o=kp.Readable.from(t.idat).pipe((0,Cp.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`)},Uy=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=Fy[i[9]];if(void 0===e||!Ny.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}},By=({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?Ly.reduce(((r,[n,s,i,a])=>r+o(Math.ceil((e-n)/i),Math.ceil((t-s)/a))),0):o(e,t)};const Wy=()=>{throw new Error("webp codec not registered: registerWebpCodec() must be called by a Node server before decoding/encoding webp")},Hy=e=>e.length>=12&&"RIFF"===e.toString("ascii",0,4)&&"WEBP"===e.toString("ascii",8,12),qy=e=>{if(!Hy(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)}}},zy=e=>Wy().decode(e);async function Gy(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);xy(e.data);return e.resizeWithoutBudget(e.data)}const Vy=[{width:1280,height:800},{width:1456,height:840}],Ky=e=>void 0!==e&&Vy.some((t=>t.width===e.width&&t.height===e.height)),Jy=1048576,Zy=e=>{const t=e.buffer;return t instanceof ArrayBuffer?new Uint8Array(t,e.byteOffset,e.byteLength):Uint8Array.from(e)};function Xy(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 Qy=(e,t,r=1024)=>Xy(e,t,r),Yy=(e,t)=>Ky({width:e,height:t})?{width:e,height:t,needsResize:!1}:Xy(e,t),ev=(e,t,r)=>{e.resize({w:t,h:r})};function tv(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 rv=(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:tv(((e,t)=>{switch(t){case"png":return(e=>{let t,r=yy.length;for(;r+16<=e.length;)"IHDR"===e.toString("ascii",r+4,r+8)&&(t=Py(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 Py(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=Ry(e,n+2);else{if(33!==e[n]||255!==e[n+1])break;r=11===e[n+2]?Ry(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))}},nv=e=>{const{width:t,height:r}=Qy(e.width,e.height,1280);return{width:t,height:r}},ov=async(e,t)=>{let{width:r,height:n}=e,o=await t({width:r,height:n});for(;o.length>Jy&&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:Zy(o),mimeType:"image/webp",reencoded:!0}},sv=async(e,t)=>{const r=(await Fg()).fromBitmap({data:Buffer.from(e.data),width:e.width,height:e.height});return ov(t,(async e=>(r.bitmap.width===e.width&&r.bitmap.height===e.height||ev(r,e.width,e.height),(e=>Wy().encode(e))({data:r.bitmap.data,width:r.bitmap.width,height:r.bitmap.height}))))};let iv;const av=async(e,t)=>{if(void 0!==t?.pngByteBudgetBytes){const{pngByteBudgetBytes:r,...n}=t,o=xy(e);return"image/png"===o?.mimeType&&Ky(o)&&await jy(e),Gy({data:e,budgetBytes:r,maxImageBytes:Jy,fitImage:Yy,resizeWithoutBudget:e=>av(e,n)})}const r=await(async(e,t)=>{const r=Hy(e);if(r&&!0===t?.preserveWebpDimensions)return;const n=r?void 0:xy(e),o=r?qy(e):n;if(void 0===o||!Ky(o))return;const s=iv;if(void 0!==n&&void 0!==s&&!Ky(await s.readOrientedDimensions(e)))return;const i="image/png"===n?.mimeType;if(i&&await jy(e),e.length<=Jy)return{data:Zy(e),mimeType:n?.mimeType??"image/webp"};const a=s?.resizeWebp;if(void 0!==a)return ov(o,(t=>a({data:e,...t})))})(e,t);if(void 0!==r)return r;if(Hy(e))return(async(e,t)=>{const r=qy(e);if(!0===t?.preserveWebpDimensions&&void 0!==r)return{data:Zy(e),mimeType:"image/webp"};if(void 0!==r&&!Qy(r.width,r.height,1280).needsResize&&e.length<=Jy)return{data:Zy(e),mimeType:"image/webp"};if("passthrough"===t?.webpWithoutCodec)return{data:Zy(e),mimeType:"image/webp"};tv(r);const n=undefined;if(void 0!==n)return ov(nv(r),(t=>n({data:e,...t})));const o=await zy(e);return sv(o,nv(o))})(e,t);const n=xy(e);if(void 0!==n&&e.length<=Jy&&!Qy(n.width,n.height).needsResize)return{data:Zy(e),mimeType:n.mimeType};const o=Iy(e);void 0!==o&&rv(e,o);const s=void 0===n?void 0:Qy(n.width,n.height),i="image/png"===n?.mimeType&&!0===s?.needsResize?await Ay({data:e,width:s.width,height:s.height}).catch((()=>{})):void 0;void 0===i&&"png"===o&&await jy(e);const a=await Fg(),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}=Qy(c.width,c.height);if(void 0===i&&!p&&e.length<=Jy&&u===l)return{data:Zy(e),mimeType:l};let f=d,m=h;p&&ev(c,f,m);let g=await c.getBuffer(u);for(;g.length>Jy&&f>8&&m>8;)f=Math.max(8,Math.round(.8*f)),m=Math.max(8,Math.round(.8*m)),ev(c,f,m),g=await c.getBuffer(u);return{data:Zy(g),mimeType:u,reencoded:!0}},cv=async e=>{const t=Buffer.from(e.buffer,e.byteOffset,e.byteLength),r=Iy(t);let n;if(Hy(t))return{kind:"unchecked"};if(void 0===r)return{kind:"unchecked"};{rv(t,r);const e=await Fg();n=async()=>("png"===r&&await jy(t),e.read(t))}try{return await n(),{kind:"decodes"}}catch(e){return{kind:"undecodable",reason:e instanceof Error?e.message:String(e)}}},lv=BigInt(0),uv=BigInt(8),dv=BigInt(16),hv=BigInt(65535);function pv(e){const t=e.trim().toLowerCase();return t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t}function fv(e){const t=e.split(".");if(4!==t.length)return;let r=lv;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<<uv|BigInt(t)}return{version:4,value:r}}function mv(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=fv(n);if(!o)return;t.push(Number(o.value>>dv&hv)),t.push(Number(o.value&hv))}else{if(!/^[0-9a-f]{1,4}$/i.test(n))return;t.push(Number.parseInt(n,16))}}return t}function gv(e){return fv(e)??function(e){const t=pv(e);if(0===t.length||t.includes(":::"))return;const r=t.indexOf("::");if(-1===r){const e=mv(t);if(!e||8!==e.length)return;return{version:6,value:e.reduce(((e,t)=>e<<dv|BigInt(t)),lv)}}if(-1!==t.indexOf("::",r+1))return;const n=t.slice(0,r),o=t.slice(r+2),s=mv(n),i=mv(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<<dv|BigInt(t)),lv)}}(e)}function wv(e,t){const r=pv(e),n=pv(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=gv(t.slice(0,r)),o=gv(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 yv(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=>wv(e,t)))}(r.hostname,t)}var vv=r("../constants/dist/commercial-cursor-hosts.js");new Set([1,2]);const bv="cursor/requiresConfirmation",Sv="https://grok.com/connectors-oauth-exchange-code/",kv="https://x.com/i/connectors/oauth_callback",_v="https://chat.x.com/connectors/oauth_callback",Cv="https://lite.x.com/i/connectors/oauth_callback",Ev={provider:"google-workspace",clientRegistration:"static",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!0,authorizationParams:{access_type:"offline",prompt:"select_account consent"}},xv={provider:"x-money",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0,registeredAppRedirectUris:[Sv,kv]},Pv="x-cursor-auth";function Rv(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 Iv="https://mcp.shop.com",Tv={provider:"grok-connectors",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,scopes:["grok-plugins:access","offline_access"]},Av=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/}]]),$v=new Map([["gmailmcp.googleapis.com",{...Ev,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",{...Ev,scopes:["https://www.googleapis.com/auth/drive.readonly","https://www.googleapis.com/auth/drive.file"]}],["calendarmcp.googleapis.com",{...Ev,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",{...Ev,scopes:["https://www.googleapis.com/auth/documents"]}],["sheetsmcp.googleapis.com",{...Ev,scopes:["https://www.googleapis.com/auth/spreadsheets"]}],["slidesmcp.googleapis.com",{...Ev,scopes:["https://www.googleapis.com/auth/presentations"]}],["bigquery.googleapis.com",{...Ev,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",xv],["mcp.money-staging.x.com",xv],["mcp.money.x.com",xv],["connectors-gateway.grok.gcp.mouseion.dev",Tv],["connectors-gateway.grok.com",Tv],["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:Iv}}],["api.elections.kalshi.com",{provider:"kalshi",clientRegistration:"dynamic",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!0}],["mcp.squarespace.com",{provider:"squarespace",clientRegistration:"dynamic",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!0}]]),Mv=[".databricks.com",".azuredatabricks.net"];const Dv=/^\/sncapps\/mcp-server\/mcp\/[^/]+$/,Ov={provider:"databricks",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,requiresHostedCallback:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0,scopes:["ai-gateway","offline_access"],pinsScopesOverConfiguredScopes:!0},Fv={provider:"servicenow",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,unauthenticatedEndpointBlocked:!0,backendOnlyTokenExchange:!0,ownMcpJsonClientMayExchange:!0};function Nv(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("."))&&Mv.some((e=>t.endsWith(e)&&t.length>e.length))}(e.hostname)&&"/ai-gateway/mcp-services/system.ai.genie_one_mcp"===e.pathname.replace(/\/+$/,"")}(t)?Ov:function(e){return"https:"===e.protocol&&""===e.port&&""===e.username&&""===e.password&&Dv.test(e.pathname.replace(/\/+$/,""))}(t)?Fv:(r=t.hostname,$v.get(r.toLowerCase()));var r}function Lv(e){return e.endsWith("/")?e:`${e}/`}async function jv(e,t){if(void 0===t)return;const r=new URL(e),n=new URL(t);if(r.origin!==n.origin||!Lv(r.pathname).startsWith(Lv(n.pathname)))throw new Error(`Protected resource ${t} does not match expected ${r.href} (or origin)`);return n}const Uv=/^\/shops\/[A-Za-z0-9-]+\/mcp$/;function Bv(e){if(void 0!==e)try{return new URL(e)}catch{return}}async function Wv(e,t){if(void 0===t)return;const r=new URL(e),n=Bv(t);if(void 0===n||n.origin!==r.origin||n.pathname!==r.pathname&&!Uv.test(n.pathname))throw new Error(`Protected resource ${t} does not match expected ${r.href} (or origin)`);return n}function Hv(e){const t=Bv(e);return void 0===t?void 0:Av.get(t.hostname.toLowerCase())}const qv=new Set([...$v].filter((([,e])=>"google-workspace"===e.provider)).map((([e])=>e))),zv="https://www.cursor.com/bot/mcp/oauth/callback",Gv={portal:"https://www.cursor.com/agents/mcp/oauth/callback",grokBotBounce:zv},Vv="tailnet_";new Set([`${Vv}waiting_for_approval`,`${Vv}tailnet_locked`,`${Vv}joining`]);const Kv="grokbot://mcp/oauth/callback",Jv="http://localhost:8787/callback",Zv="gb";function Xv(e){const t=new URL(Jv);return t.port=String(e),t.toString()}function Qv(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 Yv(e){const t=e.redirectUrl??Jv;if(!0!==e.loopbackIpv4||!Qv(t))return t;const r=new URL(t);return r.hostname="127.0.0.1",r.toString()}function eb(e,t=Gv){const r=new Set,n=void 0!==e&&Qv(e);return e&&!n&&r.add(e),r.add(t.portal),e===Kv&&r.add(t.grokBotBounce),r.add(Jv),e&&n&&r.add(e),Array.from(r)}function tb(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 rb(e){if(void 0===e)return{};const t={};"string"==typeof e.title&&e.title.length>0&&(t.title=qo(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?.[bv]}(e)&&(t[bv]=!0),0===Object.keys(t).length?{}:{annotationsJson:JSON.stringify(t)}}new Map([[Zv,Kv],["gw",Sv],["gd",Jv],["xa",kv],["xc",_v],["xl",Cv],...[18787,28787,31787].map((e=>[`gd${e}`,Xv(e)]))]),new Map([[Kv,Zv],[zv,Zv],[Sv,"gw"],[kv,"xa"],[_v,"xc"],[Cv,"xl"]]),Yv({loopbackIpv4:!0});var nb=r("../mcp-core/dist/transport/mcp-url-utils.js");function ob(e){return e.trim().toLowerCase()}const sb="<no-mcp-tool-allowed>";function ib({mode:e,tools:t}){const r=(t??[]).map(ob).filter((e=>e.length>0)),n=void 0===e?void 0:ob(e);return"all"===n?{mode:"all"}:"reads"===n?{mode:"reads"}:r.length>0?{mode:"custom",tools:r}:{mode:"all"}}function ab(e,t){switch(e.mode){case"all":return!0;case"custom":return function(e,t){const r=ob(e);return 0!==r.length&&r!==sb&&t.some((e=>ob(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 cb(e,t){switch(t.mode){case"all":return[`${e}:*`];case"custom":return t.tools.filter((e=>ob(e)!==sb)).map((t=>`${e}:${t}`));case"reads":return[];default:return t}}const lb=new Set(["ash","bash","csh","dash","fish","ksh","powershell","pwsh","sh","tcsh","zsh","cmd"]);function ub(e){return e.trim().split(/\s+/).filter(Boolean)}function db(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 ub(t)[0]}(e);if(!t)return!1;const r=t.replace(/^["']|["']$/g,"").replaceAll("\\","/").split("/"),n=(r[r.length-1]??"").replace(/\.exe$/i,"").toLowerCase();return lb.has(n)}function hb(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 pb(e,t){return e.commandName.localeCompare(t.commandName)}function fb(e){return e.split(" ")[0]??e}function mb(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=ub(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(pb);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=hb(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&&hb(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(fb(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(fb(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(fb(e.id))}}if(0===o.length)return{defaultSelectedOptionIds:n,hasClassifierSuggestions:!1};const i=n.filter((e=>!s.has(fb(e))));return{defaultSelectedOptionIds:[...new Set([...i,...o])],hasClassifierSuggestions:!0}}(e,t).defaultSelectedOptionIds}const gb=["com.todesktop.230313mzl4w4u92","co.anysphere.cursor","com.anysphere.molten-glass"],wb=["cursor","molten glass"];function yb(e){return gb.some((t=>e===t||e.startsWith(`${t}.`)))}const vb=[{bundleId:"com.apple.scripteditor2",name:"Script Editor"},{bundleId:"com.apple.automator",name:"Automator"},{bundleId:"com.apple.shortcuts",name:"Shortcuts"}],bb=[{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"},...vb,{bundleId:gb[0],name:"Cursor"}];function Sb(e){const t=e.toLowerCase(),r=(0,s.basename)(e,".app").toLowerCase(),n=bb.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}:yb(t)?{bundleId:t,name:"Cursor"}:[t,r].some((e=>wb.some((t=>e===t||e.startsWith(`${t} `)))))?{bundleId:gb[0],name:"Cursor"}:void 0}const kb=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 _b(e){return kb.has(e.toLowerCase())}function Cb(e){return`app/${e}`}function Eb(e){return"object"==typeof e&&null!==e}function xb(e){return Rb.includes(e)}function Pb(e){if(!Eb(e))return;const{appArg:t,appSelectorArgs:r,capturesScreen:n}=e;if("boolean"==typeof n){if(void 0!==r){if(void 0!==t||!Eb(r))return;const e={};for(const[t,n]of Object.entries(r)){if(!xb(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 Rb=["pid","bundleId","path","appName"],Ib=/^[+-]?\d+$/;var Tb=r("../../node_modules/.pnpm/diff@8.0.3/node_modules/diff/libesm/patch/create.js");const Ab=".cursor/worktrees",$b=".grok/build-desktop/worktrees",Mb="win32"===process.platform||"darwin"===process.platform,Db=new Map;function Ob(e,t){if(!(0,Zo.BJ)(t,e))return;const r=(Mb?(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 Fb(e,t){const r=Ob(e,t);if(void 0!==r)return r;const n=function(e){if(Db.has(e))return Db.get(e);const t=[];let r,n=e;for(;;)try{const e=_o.realpathSync.native(n);r=0===t.length?e:(0,s.join)(e,...t);break}catch(e){const r=yc(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 Db.size>=64&&Db.clear(),Db.set(e,r),r}(e);var o,i;return void 0!==n&&(o=n,i=e,Mb?o.toLowerCase()!==i.toLowerCase():o!==i)?Ob(n,t):void 0}function Nb(e){const t=e?.trim();return t&&".cursor"!==t?[".cursor",t]:[".cursor"]}function Lb(e,t){const r=(0,o.homedir)();return Nb(t?.dataFolderName).some((t=>void 0!==Fb((0,s.join)(r,t,"projects"),e)))}function jb(e){const t=(0,o.homedir)();return[Ab,$b].some((r=>void 0!==Fb((0,s.join)(t,...r.split("/")),e)))}function Ub(e,t,r){const n=function(e,t){const r=(0,o.homedir)();for(const n of Nb(t?.dataFolderName)){const t=Fb((0,s.join)(r,n,"projects"),e);if(void 0!==t&&t.length>=2)return t[1]}}(e,r);return void 0!==n&&(Mb?t.some((e=>e.toLowerCase()===n.toLowerCase())):t.includes(n))}function Bb(e,t,r){const n=Fb(e,t);if(void 0===n)return!1;const o=n[0];return Mb?r.some((e=>e.toLowerCase()===o.toLowerCase())):r.includes(o)}const Wb=/[\s"'`=/\\:;()[\]{},&|<>]/,Hb="win32"===process.platform||"darwin"===process.platform;async function qb(e,t,r,n){const o=Zb(await Jb((0,s.join)(e,"gitdir")),"");if(void 0===o)return;const i=(0,s.resolve)(e,o);if(".git"!==(0,s.basename)(i)||(0,Bs.$f)(i))return;const a=(0,s.dirname)(i);if(r&&jb(a))return;const c=await Xb(i);if(void 0===c)return;const l=(0,s.dirname)(c);if(r&&jb(l))return;if(void 0!==n&&(u=Yb(a,l)?[l]:[a,l],d=n.command,!(void 0!==(h=n.realWorkingDirectory)&&u.some((e=>(0,Zo.BJ)(h,e)))||void 0!==d&&u.some((e=>{const t=(0,s.basename)(e);return t.length>0&&function(e,t){const r=Hb?e.toLowerCase():e,n=Hb?t.toLowerCase():t;let o=0;for(;;){const e=r.indexOf(n,o);if(-1===e)return!1;const t=0===e||Wb.test(r[e-1]),s=e+n.length,i=s===r.length||Wb.test(r[s]);if(t&&i)return!0;o=e+1}}(d,t)})))))return;var u,d,h;const p=await Kb(i,c);return void 0!==p&&Yb(p.commonDir,t)?l:void 0}async function zb(e,t){const r=await(0,So.readdir)(e).catch(Qb);return void 0===r?[]:r.sort().slice(0,t)}function Gb(e,t){return t.some((t=>(0,Zo.BJ)(t,e)))}async function Vb(e){for(let t=e;;t=(0,s.dirname)(t)){if((0,Bs.$f)(t))return;const e=(0,s.join)(t,".git"),r=await(0,So.lstat)(e).catch(Qb);if(r?.isFile())return(await Kb(e))?.commonDir;if(r?.isDirectory())return e;if(void 0!==r||(0,s.dirname)(t)===t)return}}async function Kb(e,t){const r=Zb(await Jb(e),"gitdir: ");if(void 0===r)return;const n=await Xb((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=Zb(await Jb((0,s.join)(n,"commondir")),"");if(void 0===i)return;const a=await Xb((0,s.resolve)(n,i));if(void 0===a||!Yb(a,o))return;const c=Zb(await Jb((0,s.join)(n,"gitdir")),"");if(void 0===c)return;const[l,u]=await Promise.all([Xb((0,s.resolve)(n,c)),t??Xb(e)]);return void 0!==l&&void 0!==u&&Yb(l,u)?{commonDir:o,realDotGit:u}:void 0}async function Jb(e){const t=await(0,So.lstat)(e).catch(Qb);if(void 0!==t&&t.isFile()&&!(t.size>4096))return(0,So.readFile)(e,"utf8").catch(Qb)}function Zb(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 Xb(e){if(!(0,Bs.$f)(e))return(0,So.realpath)(e).catch(Qb)}function Qb(e){const t=yc(e);if(void 0===t||t.startsWith("ERR_"))throw e}function Yb(e,t){return Hb?e.toLowerCase()===t.toLowerCase():e===t}function eS(e,t,r){return{resolvedPath:e,originalPath:t,resolution:r}}function tS(e){const t=yc(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:vc(e)}}}async function rS(e,t){const r=(0,Zo.o1)(e,t);try{return eS(await(0,So.realpath)(r),r,{status:"resolved"})}catch(e){if("ENOENT"!==yc(e))return eS(r,r,tS(e));try{if((await(0,So.lstat)(r)).isSymbolicLink()){let e=null;try{e=await(0,So.readlink)(r)}catch{}return eS(r,r,{status:"danglingSymlink",symlinkTarget:e})}try{return eS(await(0,So.realpath)(r),r,{status:"resolved"})}catch(e){if("ENOENT"!==yc(e))return eS(r,r,tS(e))}return eS(r,r,{status:"unknownError",errno:"ENOENT",message:"realpath returned ENOENT but lstat found a non-symlink entry"})}catch(e){return"ENOENT"===yc(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,So.realpath)(t);return eS((0,s.join)(n,...r),e,{status:"newFile"})}catch(t){if("ENOENT"!==yc(t))return eS(e,e,tS(t))}r.unshift((0,s.basename)(t)),t=(0,s.dirname)(t)}return eS(e,e,{status:"newFile"})}(r):eS(r,r,tS(e))}}}function nS(e){return"resolved"===e.status||"newFile"===e.status}function oS(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 sS({realAbsolutePath:e,setting:t,resolvedWorkspaceRoots:r,resolvedAllowFolders:n,resolvedAllowGlobs:o}){return!("workspace"!==t.boundary||iS(e,r)||iS(e,n)||cS(e,t.allowPaths)||cS(e,o))}function iS(e,t){return t.some((t=>(0,Zo.BJ)(e,t)))}function aS(e){return e.flatMap((e=>{const t=(0,Zo.jl)(e.trim());return!t.includes("*")&&(0,s.isAbsolute)(t)?[(0,s.resolve)(t)]:[]}))}function cS(e,t){const r="win32"===process.platform?Zo.oL:e=>e,n=r(e);return t.some((e=>{const t=(0,Zo.jl)(e.trim());return!(!t.includes("*")&&(0,s.isAbsolute)(t))&&(0,hs.T)(r(t),n)}))}const lS={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 uS(e){const t=[];let r=!0,n=!1,o=e;for(;;){const e=lS[s.posix.basename(o.name)];if(void 0===e)return{command:o,wrapperForms:t,allowlistable:r,readsArguments:n};const i=dS(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||!gS(a))return{command:o,wrapperForms:t,allowlistable:!1,readsArguments:n};(o.name.includes("/")||o.args.slice(0,i).some((t=>hS(t,e)||pS(t.value,e))))&&(r=!1),n||=!0===e.readsArguments,t.push(o.fullText.trim()),o=new fe.Pv({name:a.value,args:c,fullText:[a.value,...c.map((e=>e.value))].join(" ")})}}function dS(e,t){let r=0;for(;r<e.length;){const n=e[r];if(hS(n,t))break;if(void 0===n||!gS(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=fS(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(mS))return"unreadable";for(r=n;r<e.length&&hS(e[r],t);)r++;return r<e.length?r:"none"}function hS(e,t){return!0===t.assignments&&/^[A-Za-z_][A-Za-z0-9_]*=/.test(e?.value??"")}function pS(e,t){return(t.directoryOptions??[]).some((t=>t.startsWith("--")?e===t||e.startsWith(`${t}=`):/^-[^-]/.test(e)&&e.includes(t.slice(1))))}function fS(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 mS(e){return"raw_string"===e.type||!/[$`]/.test(e.value)&&("string"===e.type||!/[*?[]|\{[^}]*(,|\.\.)/.test(e.value))}function gS(e){return("word"===e.type||"number"===e.type)&&!/[$`]/.test(e.value)}const wS=/(?<![\w-])(?:rm|rmdir|rd|del|erase|ri|remove-item)(?![\w-])/i,yS=/\s(?:-[dfiv]*r[dfiv]*|--recursive|-recurse|-recurs|-recur|-recu|-rec|-re)(?![\w-])/i;function vS(e,t,r){const n=t.exec(e);return null!==n&&r.test(e.slice(n.index+n[0].length))}var bS=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},SS=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 kS=(0,d.h)("permissions-service"),_S=(0,h.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"]}),CS=(0,h.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"]}),ES="Your team's MCP rules could not be checked for this MCP server, so this MCP tool can't run right now",xS=/[\p{Cc}\p{Bidi_Control}\p{Cs}]/gu,PS=/^[\p{M}\p{Cf}\p{Default_Ignorable_Code_Point}\s]+/u,RS=/[^\p{M}\p{Cf}\p{Default_Ignorable_Code_Point}\s\u2800]/u;function IS(e,t){for(const r of[e?.title,t?.title]){if("string"!=typeof r)continue;const e=qo(r,1024).replace(xS," ").replace(/\s+/g," ").replace(PS,"").trim(),t=qo(e,256).trimEnd();if(RS.test(t))return t}}function TS(e,t){return{toolTitle:IS(e,t),destructiveHint:"boolean"==typeof t?.destructiveHint?t.destructiveHint:void 0}}function AS(e){return Promise.all(e.map((async e=>{const t=await rS(e);return nS(t.resolution)?t.resolvedPath:(0,Zo.o1)(e)})))}function $S(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 MS(e){return[...new Set(e)]}function DS(){return{fdTargets:new Map([[0,"original-stdin"],[1,"original-stdout"],[2,"original-stderr"]])}}function OS({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 FS(e){return">"===e||">>"===e||">|"===e||"&>"===e||"&>>"===e}function NS(e){return"<"!==e.operator&&"<&"!==e.operator}function LS(e){if(void 0===e||e.trim()!==e)return;const t=Number(e);return Number.isInteger(t)&&t>=0?t:void 0}function jS(e){return"<<"===e.operator&&"heredoc_redirect"===e.targetNodeType&&1===e.destinationFds.length&&0===Number(e.destinationFds[0])&&void 0!==e.targetText}function US(e,t){return!(/^=|[~*?[{(#^`]/.test(e)||"\\"!==t.sep&&e.includes("\\"))}function BS(e){return"word"===e.type||"number"===e.type?US(e.value,i)?e.value:void 0:"raw_string"===e.type||"string"===e.type&&!/[$`\\]/.test(e.value)?e.value.slice(1,-1):void 0}function WS({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(BS);return t?[...r,void 0]:r}const HS=new Set(["cd","chdir","pushd"]),qS=new Set(["popd","eval","source",".","trap","set-location","sl","push-location","pop-location"]);function zS(e){const t=e.replace(/["'\\]/g,"");return t.slice(t.lastIndexOf("/")+1).toLowerCase()}function GS(e,t){return new fe.Pv({name:e,args:t,fullText:[e,...t.map((e=>e.value))].join(" ")})}function VS(e){let t=e;for(;;){const e=zS(t.name);if("command"===e){const e=GS("command",t.args),r=uS(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=BS(n);if(void 0===s||s.startsWith("-"))return"unreadable";t=GS(s,o)}}function KS(e,t){return!(!t.isAbsolute(e)||"/"!==t.sep&&/^[\\/]$/.test(t.parse(e).root))}async function JS({parsingResult:e,workingDirectory:t,resolvePathForPermissions:r,pathModule:n}){const o=[t];for(const t of e.executableCommands.map(uS)){const e=VS(t.command);if("unreadable"===e)return;const i=zS(e.name),a=e.args;if(qS.has(i)||/^cd\.\./.test(s=i)||/^[a-z]:$/.test(s))return;if(!HS.has(i))continue;const c=1===a.length&&void 0!==a[0]?BS(a[0]):void 0;if(void 0===c||!KS(c,n))return;const l=await r(c);if(!nS(l.resolution))return;o.push(l.resolvedPath)}var s;return o}async function ZS({targetText:e,workingDirectory:t,workingDirectories:r,...n}){const o=KS(e,n.pathModule)?[t]:r;if(void 0===o)return;let s;for(const t of o)if(s=await XS({...n,targetText:e,workingDirectory:t}),void 0===s)return;return s}async function XS({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(!nS(a.resolution))return;const c=[];for(const e of r){const t=await o(e);nS(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,$o.OK)(e,r).catch((()=>!0)))return!0;return!1}({targetPath:a.resolvedPath,rootPaths:c,pathModule:s})?void 0:c.some((e=>OS({basePath:e,targetPath:a.resolvedPath,pathModule:s})))?"workspace-file":n&&!(0,$o.dA)(a.originalPath)&&uk(a.resolvedPath,i)?"tmp-file":void 0}async function QS({parsingResult:e,workingDirectory:t,rootDirectories:r,allowTmpRedirects:n}){const s=await JS({parsingResult:e,workingDirectory:t,resolvePathForPermissions:rS,pathModule:i});for(const a of e.executableCommands.map(uS).flatMap(WS))if("/dev/null"!==a&&(void 0===a||!await ZS({targetText:a,workingDirectory:t,workingDirectories:s,rootDirectories:r,allowTmpRedirects:n,resolvePathForPermissions:rS,pathModule:i,tempPathOptions:{platform:process.platform,env:process.env,pathModule:i,homeDirectory:(0,o.homedir)()}})))return!1;return!0}function YS(e){return MS(e.map((e=>e.trim())).filter(Boolean))}function ek(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 tk(e,t){const r=t.trim();return!!r&&e.some((e=>e===r||e.startsWith(`${r} `)))}function rk(e){const t=e.name.trim(),r=e.arguments.map((e=>e.trim())).filter(Boolean).map((e=>new fe.r6({type:"word",value:e})));return new fe.Pv({name:t,args:r,fullText:[t,...r.map((e=>e.value))].join(" ").trim()})}function nk(e,t={}){return{type:e,...t}}function ok(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 sk(...e){return e.filter((e=>void 0!==e)).join(" • ")}function ik(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 ak(e,t){if("workspace"===e&&void 0!==t)return t}const ck={workspace:0,system:1};function lk(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 uk(e,{platform:t,env:r,pathModule:n,homeDirectory:o}){if((0,$o.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||!OS({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 dk(e,t){if("insecure_none"===t.type)return!0;if("insecure_none"===e.type)return!1;const r=(0,$o.$b)(e.networkPolicy),n=(0,$o.$b)(t.networkPolicy);if(r&&!n)return!1;const o=(0,$o._B)(e.networkPolicy),s=(0,$o._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!(ck[i]>ck[a])}function hk(e){return{wrapperForms:e.flatMap((e=>e.wrapperForms)),allowlistable:e.every((e=>e.allowlistable)),readsArguments:e.some((e=>e.readsArguments))}}function pk(e){return[...e.wrapperForms,e.command.fullText.trim()].filter(Boolean)}class fk{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&&dk(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||!dk(this.requestedPolicy,e)||(this.state="allowlisted")}deny(){this.state="denied"}isRunnable(){return"preapproved"===this.state||"allowlisted"===this.state}}function mk(e){return e?.type??"undefined"}const gk=["skills","skills-cursor","rules","plugins"],wk=["assets","agent-notes","agent-tools","swarm-agents"];async function yk(e,t,r){return e.shouldBlockFileRead?.(t,r)??e.shouldBlockRead(t,r)}function vk(e){const t=e.lastIndexOf("::mcpScope:");return-1===t?e:e.slice(0,t)}function bk({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 Sk=/^\s*Read\s*\((.*)\)\s*$/,kk=/^\s*Write\s*\((.*)\)\s*$/;class _k{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&&sS({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:ik(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 AS([...aS(e),...(0,$o.r5)()])}async resolvedReadAllowGlobs(e){const t=function(e){return e.flatMap((e=>{const t=(0,Zo.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 AS(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,yo.r_)(e)))),...gk.map((e=>(0,s.join)(t,e)))],n=this.rootDirectories.flatMap((e=>(0,$o.W1)(e)??[]));return AS([...this.rootDirectories,...r,...n,...void 0===this.projectDir?[]:[this.projectDir]])}async shouldBlockReadInternal(e,{cursorIgnoreChecked:t=!1},r){const n=(0,Zo.o1)(e),o=await Sc(n);if(null===o)return{type:"unsafeResolution",message:$S("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&&!jb(o)&&!Lb(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(iS(e,n))return!1;const[o,s]=await Promise.all([this.resolvedReadAllowFolders(r.allowPaths),this.resolvedReadAllowGlobs(r.allowPaths)]);return!!sS({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 rS(this.projectDir);return!!nS(r.resolution)&&Bb(r.resolvedPath,e,t)}async isFreelyWritableOutsideWorkspace(e,t){return function(e){return uk(e,{platform:process.platform,env:process.env,pathModule:i,homeDirectory:(0,o.homedir)()})}(e)||Ub(e,wk,{dataFolderName:t})||await this.isProjectDirInternalPath(e,wk)}async shouldBlockWrite(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{bS(n,(0,D.VI)(e.withName("InteractivePermissionsService.shouldBlockWrite")),!1).ctx;const i=await rS(t);if(!nS(i.resolution))return{type:"unsafeResolution",message:oS(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,$o.dA)(i.originalPath)||(0,$o.dA)(a))return{type:"permissionsConfig"};const d=await this.getPermissions();if(!jb(c)&&!Lb(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 Fi(a),e=!1}catch{e=!0}if(e)t=r;else{const e=e=>e.endsWith("\n")?e:`${e}\n`,{hunks:o}=(0,Tb.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 rS(e);if(nS(t.resolution)){if((0,Zo.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,Bs.$f)(o))return;const e=(0,s.join)(o,".git"),i=await(0,So.lstat)(e).catch(Qb);if(i?.isFile()){const s=await Kb(e);if(void 0!==s){const{commonDir:e}=s;if(Gb(o,t))return;if(t.some((t=>(0,Zo.BJ)(e,t))))return{root:o,commonDir:e};if(!await(r.isUntrustedExternalGitDir?.(e))&&(await(n??=Promise.all(t.map((e=>Vb(e)))),n)).some((t=>void 0!==t&&Yb(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,$o.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{SS(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 Sc(t.workingDirectory);if(null===o){if(!0!==t.skipUnsafeWorkingDirectoryBlock)return{kind:"block",reason:{type:"unsafeResolution",message:$S("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(kS.info(e,"Shell permissions: evaluating shell command",{toolCallId:r.toolCallId,approvalMode:a,userConfiguredPolicyType:mk(l),requestedPolicyType:mk(n),effectiveRequestedPolicyType:mk(n??l),smartAllowlistEnabled:!0===i.smartAllowlistEnabled,hasSmartModeApprovalReason:void 0!==r.smartModeApprovalReason,hasSmartModeApprovalRequestId:void 0!==r.smartModeApprovalRequestId,hookForcesPrompt:Io(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 kS.info(e,"Shell permissions: prompting for empty allowlist",{toolCallId:r.toolCallId,approvalMode:a,userConfiguredPolicyType:mk(l),requestedPolicyType:mk(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(uS),b=w?w.map(rk):v.map((e=>e.command)),S=void 0!==w?w.map(ek):b.map((e=>[e.fullText.trim()].filter(Boolean))),k=void 0!==g?g.commands.map(ek):v.map(pk);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,$o.$b)(l.networkPolicy)&&"insecure_none"!==n.type&&!(0,$o._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,$o.XX)(e.readBoundary,t.readBoundary),n="workspace"===r?(0,$o.wG)(ak(e.readBoundary,e.additionalReadPaths),ak(t.readBoundary,t.additionalReadPaths)):void 0;return{...e,readBoundary:r,additionalReadPaths:n}}({requestedPolicy:n,userConfiguredPolicy:l}),p&&kS.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=YS(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=>tk(r,e)))){const r=t[e];r&&P.push(r)}}P.length>0&&(kS.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)));kS.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=YS(s.flatMap((e=>function(e){const t=e.name.trim();if(!t)return[];if(db(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),YS(o)}(e)))),R=s.map((e=>e.suggestedAllowlistEntry)).filter((e=>"string"==typeof e)).filter((e=>x.includes(e))),x.length>0){const e=mb(x,R),t=e.length>0?e.join(", "):x.join(", ");E.push(`Not in allowlist: ${t}`)}_=o&&0===P.length,_&&kS.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=hk(v),$=b.map(((e,t)=>new fk(e,n,T,S[t],y?A:v[t])));if((0===b.length||h&&!y)&&!c){kS.info(e,"Shell permissions: prompting after parser miss",{toolCallId:r.toolCallId,approvalMode:a,requestedPolicyType:mk(n),userConfiguredPolicyType:mk(l),isSmartAllowlistActive:y,parsingFailed:h,parserCommandCount:b.length,hasSmartModeApprovalReason:void 0!==f,hasSmartModeApprovalRequestId:void 0!==m});const o={type:aw.Shell,toolCallId:r.toolCallId,details:{command:t,workingDirectory:r.workingDirectory,timeout:r.timeout,reason:sk(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 kS.info(e,"Shell permissions: blocked by readonly mode"),{kind:"block",reason:{type:"permissionsConfig",isReadonly:!0}};const j=Io(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&&wS.test(r)||vS(r,wS,yS)||vS(r,/(?<![\w-])(?:rmdir|rd|del|erase)(?![\w-])/i,/\/s(?![\w-])/i)||vS(r,/(?<![\w-])find(?![\w-])/i,/\s-delete\b/i))return!0;e||=vS(r,/(?<![\w-])(?:get-childitem|gci|ls|dir)(?![\w-])/i,yS)}}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&&kS.info(e,"Shell permissions: all commands allowed by sandbox policy");const t=await this.applyServerAndAdminPolicies(W);return kS.info(e,"Shell permissions: auto-approved shell command",{toolCallId:r.toolCallId,approvalMode:a,requestedPolicyType:mk(n),userConfiguredPolicyType:mk(l),autoApprovalPolicyType:mk(W),mergedPolicyType:mk(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=mb(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(", ");kS.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=sk(...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));kS.info(e,"Shell permissions: requesting shell approval",{toolCallId:r.toolCallId,approvalMode:a,requestedPolicyType:mk(n),userConfiguredPolicyType:mk(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:aw.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(uS),d=l?c.commands.map(rk):u.map((e=>e.command));if(0===d.length)return!1;const h=l?c.commands.map(ek):d.map((e=>[e.fullText.trim()].filter(Boolean))),p=void 0!==c?c.commands.map(ek):u.map(pk),f={type:"insecure_none"},m=hk(u),g=d.map(((e,t)=>new fk(e,f,void 0,h[t],l?m:u[t])));if(await this.hasHardDeny(n,g))return!1;const w=YS(o.smartAllowlistDenylist??[]);if(w.length>0)for(const e of p)if(e&&0!==e.length&&w.some((t=>tk(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,$o.resolveSandboxPolicyForWorkspace)(t,{perUser:c,perRepo:l});return function(e){return"insecure_none"===e.type?e:{...e,networkPolicy:(0,$o.Po)(),readBoundary:"workspace",additionalReadPaths:[]}}(e)}const d=void 0===u?void 0:nk(c.type,u),h=(0,$o._B)(e.networkPolicy)&&!ok(d?.networkPolicy),{policy:p}=await(0,$o.resolveSandboxPolicyForWorkspace)(t,{perUser:c,perRepo:l,teamAdmin:d});return h?{...p,networkPolicy:(0,$o.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,Bs.$f)(e))continue;const t=await rS(e);nS(t.resolution)&&!jb(t.resolvedPath)&&a.push(t.resolvedPath)}if(0===a.length)return;let c;if(!(0,Bs.$f)(t.workingDirectory)){const e=await rS(t.workingDirectory);nS(e.resolution)&&(c=e.resolvedPath)}return async function(e,t={}){if(0===e.length)return;const r=await Promise.all(e.map((e=>Vb(e)))),n=[];for(const o of r)void 0===o||n.some((e=>Yb(e,o)))||!e.some((e=>(0,Zo.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 zb((0,s.join)(r,"worktrees"),256),c=await(0,Fr.PH)(n,(e=>qb((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=>Yb(e,r)))||e.some((e=>(0,Zo.BJ)(r,e)))||Gb(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,$o.tv)(t,(0,o.homedir)());if(!r||"insecure_none"===r.type)return e;let n=(0,$o.fZ)(r.networkPolicy,e.networkPolicy);n&&void 0!==e.networkPolicy?.default&&(n={...n,default:e.networkPolicy.default});const s=(0,$o.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,$o.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,$o._B)(e.networkPolicy))return e;const r={default:"deny",allow:MS(t.allowlist)};return{...e,networkPolicy:(0,$o.fZ)(e.networkPolicy,r)}}async loadPerRepoFilePolicy(e,t){const r=await(0,$o.tv)((0,s.join)(t,".cursor","sandbox.json"),t);if(r){if("1"===process.env[vv.K4]){const n=(0,$o.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?nk(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:MS(i.allowlist)}:{},...i.denylist.length>0?{deny:MS(i.denylist)}:{}}:void 0:(0,$o.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,$o._B)(e.networkPolicy))return;const{teamAdminPolicy:t}=await this.getPermissions(),r=await this.resolveTeamAdminLayer(t);return function(e){if(ok(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,$o.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,s=e.parsingFailed,a=!0===e.allRedirectsAreDevNull,c=!(!n||a||s)&&await async function({parsingResult:e,workingDirectory:t,rootDirectories:r,allowTmpRedirects:n=!0,resolvePathForPermissions:s=rS,pathModule:a=i,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 JS({parsingResult:e,workingDirectory:t,resolvePathForPermissions:s,pathModule:a}),h=DS();for(const e of l){if(jS(e))continue;const o=u?DS():h,{operator:i,targetText:l}=e,f=e.destinationFds;if(">&"===i){const e=LS(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("<&"===i){const e=LS(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(!FS(i)||void 0===l||"word"===e.targetNodeType&&!US(l,a)){for(const e of f)o.fdTargets.set(e,"unsafe");return!1}const m=await ZS({targetText:l,workingDirectory:t,workingDirectories:d,rootDirectories:r,allowTmpRedirects:n,resolvePathForPermissions:s,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 QS({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(NS))}({parsingResult:e,hasRedirects:n,parsingFailed:s,allRedirectsAreAllowlistSafe:a,allRedirectsAreWorkspaceFileSafe:c})&&l;return{allowlistOfferSafe:(!n||a||c)&&l&&!s,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:aw.Shell,toolCallId:t.toolCallId,details:{command:e,workingDirectory:t.workingDirectory,timeout:t.timeout,reason:sk(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 QS({parsingResult:t,workingDirectory:e.workingDirectory,rootDirectories:this.rootDirectories,allowTmpRedirects:!0})?[]:this.generateAllowlistPatterns(t.executableCommands.map(uS))}async getAdminCommandDenylistBlock(e,t){const r=(await this.teamSettingsService.getAdminCommandDenylist()).rules;if(0===r.length)return;const n=ws({matchForms:t.parsingResult?ps({command:t.command,parsingResult:t.parsingResult}):[t.command],blockedCommands:r});return void 0!==n?(kS.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!==lk(e)}isPathEntry(e,t){return new RegExp(`^\\s*${e}\\s*\\(`).test(t)}matchesShell(e,t){const r=lk(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&&!db(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?Sk:kk}(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,hs.b)((0,Zo.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,Zo.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,hs.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{bS(o,(0,D.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:tb(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=bk({server:vk(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,...TS(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,...TS(r,l),providerIdentifier:a,args:c,canAllowlist:_,allowlistEntry:b,computerUseApp:S}}}catch(e){o.error=e,o.hasError=!0}finally{SS(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 CS.increment(e,1,{reason:"outside_limit"}),"Your team's admin limits this MCP tool";case"settings_unavailable":return CS.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 CS.increment(e,1,{reason:"unknown_server"}),ES;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 ab(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(vk(e.serverIdentifier||e.providerIdentifier),t);if(!1===n)return{kind:"notComputerUse"};const o=await async function(e,t){const r=Pb(e.meta?.["cursor/computerUseScope"])??Pb(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])=>xb(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&&Ib.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?Sb(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&&Ib.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:Sb(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 yb(t)?"Computer Use doesn't control Cursor itself, including its approval cards. Ask the user to do it instead.":vb.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.":bb.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=_b(o.app.bundleId)?void 0:bk({server:r.serverId,tool:Cb(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=vk(e);return!0===this.computerUse?.providerIdentifiers.has(t)}async isComputerUseDisabledByAdminFor(e){const t=this.computerUseAdminPolicy;return t?.providerIdentifiers.has(vk(e))?await t.isDisabledByAdmin():!!this.isComputerUseServer(e)&&!0===await(this.teamSettingsService.isComputerUseDisabledByAdmin?.())}allowComputerUseAppForSession({bundleId:e}){const t=void 0===this.computerUse||_b(e)?void 0:bk({server:this.computerUse.serverId,tool:Cb(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??tb(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=vk(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}){_S.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&&wv(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&&ab(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 Ck=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 Ek=65536,xk=1048576,Pk=(0,d.h)("LocalReadExecutor"),Rk=async(e,t,r,n)=>{const o=setTimeout((()=>{Pk.warn(e,`[watchdog, LocalReadExecutor] ${t} still not completed after ${r}ms`)}),r);try{return await n()}finally{clearTimeout(o)}};function Ik(e){return BigInt(Math.min(e,4294967295))}async function Tk(e,t){if(0===t)return(0,So.readFile)(e);if(t>2147483647)throw new RangeError(`File size (${t}) is greater than 2 GiB`);const r=await(0,So.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 Ak(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 $k(e){return e>=32&&e<=126||9===e||10===e||13===e}function Mk(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&&$k(t)&&r++,0===t&&$k(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 Dk=Buffer.from("\n---\n");function Ok(e,t){const r=e.length;if(r<2*Dk.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(Dk,r-Dk.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+Dk.length,r-4).toString("utf-8"))?o:r}const Fk=[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 Nk(e){return new wy.sV({result:{case:"invalidFile",value:new wy.cW({path:e,reason:"File content is binary data, not text"})}})}function Lk(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=jk(s,e),c=jk(i,e);return{applied:!0,start:a,end:Math.max(a,c)}}function jk(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 Uk(e){return-1===e.indexOf("\r\n")?e:e.replaceAll("\r\n","\n")}function Bk(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 Wk(e,t,r){const n=Bk((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 Hk(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=Uk(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=qo(c,o)),{text:c,truncated:l}}function qk(e,t,r,n){if(t>=r)return{text:"",truncated:!1};const o=Math.min(r,t+2*n+1);let s=Uk(e.slice(t,o));const i=s.length>n||o<r;return s.length>n&&(s=qo(s,n)),s.length<e.length&&(s=a_(s)),{text:s,truncated:i}}function zk(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+qo(t,n),truncated:!0}:{text:e.text+t,truncated:e.truncated}}function Gk(e,t){if(e.truncated)return e;const r=zk(e,t);return{text:r.text,truncated:r.truncated}}function Vk(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=zk(n,"\n")),n=zk(n,o.text),o.truncated&&(n={text:n.text,truncated:!0})})),n}function Kk(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 Jk(e){return void 0===e.maxChars||void 0!==e.offset||void 0!==e.limit?Hs:Math.min(Hs,e.maxChars+2)}function Zk(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 Xk extends Error{constructor(){super("Invalid UTF-8 while streaming read"),this.name="InvalidUtf8Error"}}function Qk(e){for(let t=1;t<=Math.min(3,e.length);t++){const r=e[e.length-t]??0;if(128!=(192&r))return Yk(r)>t?t:0}return 0}function Yk(e){return e>=240?4:e>=224?3:e>=192?2:1}class e_{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 Xk}validate(e){let t=e;if(this.carry.length>0){const r=Yk(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 Xk;t=e.subarray(r)}const r=Qk(t);if(!(0,n.isUtf8)(t.subarray(0,t.length-r)))throw new Xk;this.carry=Buffer.from(t.subarray(t.length-r))}}function t_(e,t){const r=function({file:e,stats:t,format:r},n){return Kk(n??Ji(e,t)??r.encoding)}(e,t),n=function(e){const t=Kk(e);return"utf8bom"===t?"utf8":t}(r);return"utf8"===n?{kind:"strictUtf8",cacheEncoding:"utf8"}:qs.encodingExists(n)?{kind:"iconv",decoderEncoding:n,cacheEncoding:r}:{kind:"strictUtf8",cacheEncoding:"utf8"}}function r_(e){const t=Ak(e),r=Ok(e,t);return"utf-8"!==Mk(e.subarray(t,r))?"other_encoding":function(e){if((0,n.isUtf8)(e))return"utf8_valid";const t=$l(e);return t>0&&(0,n.isUtf8)(e.subarray(0,e.length-t))?"utf8_cut":"utf8_invalid"}(e)}async function n_(e,t){const r=t>0?Math.min(t,xk):xk,o=await Tk(e,r);return o.length===t&&(0,n.isUtf8)(o)||si(new Ws.TextDecoder("utf-8",{fatal:!1}).decode(o,{stream:o.length===xk&&o.length!==t}))?{kind:"lossyUtf8",cacheEncoding:"utf8"}:{kind:"iconv",decoderEncoding:"latin1",cacheEncoding:"latin1"}}async function o_(e){const t=await(0,So.stat)(e),r=await Ui(e);if(r.isBinaryFile)return;const n=t_({file:e,stats:t,format:r},void 0);if("iconv"===n.kind)return n.decoderEncoding;const o=await n_(e,t.size);return"iconv"===o.kind?o.decoderEncoding:void 0}async function s_(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>=Hs,q=()=>v||w&&g>=Hs,z=(e,t)=>{if(H())return;const r=k.length>0?1:0;let n=Hs-C;if(r>0){if(n<=0)return void(E=!0);n--}const o=e.text.length>n?{line:{text:qo(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=Hs-g;if(r>0){if(n<=0)return void(w=!0);n--}const o=e.text.length>n?{line:{text:qo(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>Hs;)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-Qk(e));return Q=new e_(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 Ws.TextDecoder("utf-8",{fatal:"strictUtf8"===r.kind,ignoreBOM:!0}),i=(0,_o.createReadStream)(t,{highWaterMark:Ek,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 Xk;throw e}return}const i=(0,_o.createReadStream)(t,{highWaterMark:Ek,signal:e.signal,...s}).pipe(qs.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=Gk(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=Gk(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&&Zi(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)+Ek,ae=e=>e.text.length>ie?{text:qo(e.text,ie),truncated:!0}:e,ce=()=>Vk({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=Vk(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(Vk({text:"",truncated:E||se},k,re));return{content:le.text,totalLines:F,truncated:le.truncated,rangeApplied:!0}}class i_{constructor(e,t,r){this.permissionsService=e,this.workspacePath=t,this.terminalReads=new Ul,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,D.VI)(e.withName("LocalReadExecutor.execute")),!1);const o=t.path;if(""===o.trim())return new wy.sV({result:{case:"error",value:new wy.F_({path:o,error:Xo})}});const i=(0,Zo.o1)(o,this.workspacePath),a=await Rk(e,"permissionsService.shouldBlockFileRead",3e3,(()=>yk(this.permissionsService,i)));if(a){const r=await Rk(e,"resolveFileReadBlock",3e3,(()=>async function(e,t){return await Wu(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:aw.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 wy.sV({result:{case:"rejected",value:new wy.f4({path:i,reason:r.reason??""})}});if("denied"===r.kind)return new wy.sV({result:{case:"permissionDenied",value:new wy.lW({path:i})}})}void 0!==this.mcpStateAccessor&&py(e,this.mcpStateAccessor,i);try{const r=await Rk(e,"stat",3e3,(()=>(0,So.stat)(i)));if(r.isDirectory())return new wy.sV({result:{case:"invalidFile",value:new wy.cW({path:i,reason:"Path is a directory, not a file"})}});if(!r.isFile())return new wy.sV({result:{case:"invalidFile",value:new wy.cW({path:i,reason:"Path is neither a file nor a directory"})}});const o=function(e){return null!==function(e){const t=Ep(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=Ep(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 Rk(e,"getFormatForFile",3e3,(()=>Ui(i))),l=c.isImageFile,u=function(e){return".pdf"===(0,s.extname)(e).toLowerCase()}(i),d=Di(i);if(l){const t=await Rk(e,"prepareImageForModel",3e3,(async()=>(async e=>{let t;try{t=await av(e)}catch(t){const r=await cv(e);if("undecodable"===r.kind)return r;throw t}if(!0===t.reencoded)return{kind:"image",image:t};const r=await cv(t.data);return"undecodable"===r.kind?r:{kind:"image",image:t}})(await(0,So.readFile)(i))));return"undecodable"===t.kind?new wy.sV({result:{case:"invalidFile",value:new wy.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 wy.sV({result:{case:"success",value:new wy.mE({path:i,output:{case:"data",value:t.image.data},totalLines:0,fileSize:Ik(r.size),truncated:!1})}})}if(u){const t=await Rk(e,"readPdfBinary",3e3,(()=>(0,So.readFile)(i)));return new wy.sV({result:{case:"success",value:new wy.mE({path:i,output:{case:"data",value:t},totalLines:0,fileSize:Ik(r.size),truncated:!1})}})}if(c.isBinaryFile&&d){if(void 0!==t.maxVideoBytes&&r.size>t.maxVideoBytes)return new wy.sV({result:{case:"success",value:new wy.mE({path:i,totalLines:0,fileSize:Ik(r.size),truncated:!0})}});const n=await Rk(e,"readBinaryFile",3e3,(()=>(0,So.readFile)(i)));return new wy.sV({result:{case:"success",value:new wy.mE({path:i,output:{case:"data",value:n},totalLines:0,fileSize:Ik(r.size),truncated:!1})}})}if(c.isBinaryFile)return Nk(i);{const n=this.useStreamingRead,o=!n||await Rk(e,"useStreamingRead",3e3,(()=>n()));if(o||r.size>Hs){const n=await Rk(e,"readTextStreaming",7e3,(()=>async function(e,t,r,n){const o=t_(t,r.encodingHint);try{return{...await s_(e,t,r,o,n),decoder:o.kind}}catch(o){if(o instanceof Xk){const o=await n_(t.file,t.stats.size);return{...await s_(e,t,r,o,n),decoder:o.kind}}throw o}}(e,{file:i,stats:r,format:c},t,o))),s=Zk(n.content,n.truncated,t);return Tl(this.encodingSlices,e)&&this.recordStreamedRead(e,i,r.size,n,s),new wy.sV({result:{case:"success",value:new wy.mE({path:i,output:{case:"content",value:s},totalLines:n.totalLines,fileSize:Ik(r.size),truncated:n.truncated,rangeApplied:n.rangeApplied})}})}const s=await Rk(e,"readText",3e3,(()=>Fi(i,t.encodingHint))),a=await Rk(e,"countLines",3e3,(()=>Gs(s))),l=function(e,t,r){const n=Lk(t,""===e,r);return n.applied?n.start>=n.end?{content:"",rangeApplied:!0}:{content:Wk(e,n.start,n.end),rangeApplied:!0}:{content:e,rangeApplied:!1}}(s,a,t);let u=l.content,d=!1;const h=Jk(t);return u.length>h&&(u=Zk(u.substring(0,h),!0,t),d=!0),u.length<s.length&&(u=a_(u)),Hl(this.encodingSlices,e,{layer:"exec_read"},u),new wy.sV({result:{case:"success",value:new wy.mE({path:i,output:{case:"content",value:u},totalLines:a,fileSize:Ik(r.size),truncated:d,rangeApplied:l.rangeApplied})}})}}catch(e){const t=yc(e);return"ENOENT"===t?new wy.sV({result:{case:"fileNotFound",value:new wy.Ko({path:i})}}):"EACCES"===t||"EPERM"===t?new wy.sV({result:{case:"permissionDenied",value:new wy.lW({path:i})}}):new wy.sV({result:{case:"error",value:new wy.F_({path:i,error:e instanceof Error?e.message:"Unknown error occurred"})}})}}catch(e){r.error=e,r.hasError=!0}finally{Ck(r)}var n}async recordStreamedRead(e,t,r,o,s){try{const i=function(e){try{const t=new jl;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 Tk(e,t),!(0,n.isAscii)(r)&&(0,n.isUtf8)(r)?"utf8_as_other":"other_encoding"}catch{return"other_encoding"}var r}(t,r)),ql(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 Rk(e,"readTerminalFile",3e3,(()=>Tk(t,r.size)));if(o&&(i=s,Fk.some((e=>function(e,t){return e.length>=t.length&&e.subarray(0,t.length).equals(t)}(i,e)))))return Nk(t);var i;const a=function(e,t,r=8388608){if(0===e.length)return{content:"",totalLines:1,rangeApplied:!1,truncated:!1};const n=Ak(e),o=Ok(e,n);if("utf-8"!==Mk(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=Lk(o,n,t);if(!s.applied){const t=qk(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=Bk((t=>e.indexOf("\n",t)),e.length,(t=>e.charCodeAt(t-1)),s.start,s.end,!0),a=qk(e,i.from,i.to,r);return{content:a.text,totalLines:o,rangeApplied:!0,truncated:a.truncated}}(function(e){const t=Ak(e),r=t>0?e.subarray(0,t).toString("utf-8"):"",n=Ok(e,t),o=n<e.length?e.subarray(n).toString("utf-8"):"",s=e.subarray(t,n),i=Mk(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=Lk(s,o,r);if(!i.applied){if(o)return{content:"",totalLines:s,rangeApplied:!1,truncated:!1};const r=Hk(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=Bk((t=>e.indexOf(10,t)),e.length,(t=>e[t-1]??0),i.start,i.end,!0),c=Hk(e,a.from,a.to,t,n);return{content:c.text,totalLines:s,rangeApplied:!0,truncated:c.truncated}}(e,s,t,r)}(s,n,Jk(n)),c=Zk(a.content,a.truncated,n);return Tl(this.encodingSlices,e)&&(o||this.terminalReads.firstRead(n.toolCallId,t))&&Hl(this.encodingSlices,e,{layer:o?"exec_read":"exec_terminal_context",evidence:r_(s),partial:a.rangeApplied||a.truncated},c),new wy.sV({result:{case:"success",value:new wy.mE({path:t,output:{case:"content",value:c},totalLines:a.totalLines,fileSize:Ik(r.size),truncated:a.truncated,rangeApplied:a.rangeApplied})}})}}function a_(e){return Buffer.from(e,"utf16le").toString("utf16le")}var 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},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});function u_(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 d_(e){return`Path '${e}' is neither a file nor a directory`}async function h_(e){const t=await(0,So.stat)(e).catch((()=>{}));return void 0!==t&&!t.isFile()&&!t.isDirectory()}function p_(e,t,r){const n=function(e,t){let r;for(const n of t)(0,Zo.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 f_ extends Error{}function m_(e){const t=new AbortController,r=setTimeout((()=>t.abort()),e);return{signal:t.signal,clear:()=>clearTimeout(r)}}function g_(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 w_(e){switch(e){case"content":return new Kw.vD({result:{case:"content",value:new Kw.Zp({ripgrepTruncated:!0})}});case"files_with_matches":return new Kw.vD({result:{case:"files",value:new Kw.T7({ripgrepTruncated:!0})}});case"count":return new Kw.vD({result:{case:"count",value:new Kw.xA({ripgrepTruncated:!0})}});default:throw new Error(`Unknown output mode: ${String(e)}`)}}function y_(e){return"success"===e.result.case&&Object.values(e.result.value.workspaceResults).some((e=>!0===e.result.value?.clientTruncated))}function v_(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 b_(e){return/^(utf-?16|ucs-?2)/i.test(e)}const S_=(0,d.h)("local-exec/grep"),k_=(0,h.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"]}),__=(0,h.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"]}),C_=(0,h.v5)("local_exec.grep.rg.spawn_ms",{description:"Time to start the ripgrep process for one Grep or Glob search",labelNames:["sandboxed"]}),E_=(0,h.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 x_(e){return e instanceof Error&&e.message.includes("ENOENT")&&e.message.includes("spawn")}function P_(e){try{return(0,_o.existsSync)(e)}catch{return"check_failed"}}function R_(e){if("object"==typeof e&&null!==e&&"errno"in e){const t=e.errno;if("number"==typeof t)return t}}function I_(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 T_(e,t,r,n){return{...$_(e),...n,cwd:t,cwdExists:P_(t),errorMessage:vc(r),errorCode:yc(r),errno:R_(r),syscall:I_(r,"syscall"),errorPath:I_(r,"path")}}function A_(e){return new Error(`Path does not exist: ${e}`)}function $_(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,_o.existsSync)(e)}catch(e){t.rgPathExists=!1,t.rgPathExistsError=e instanceof Error?e.message:String(e)}try{const r=(0,_o.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,_o.existsSync)(r),t.parentDirExists&&(t.parentDirContents=(0,_o.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,_o.existsSync)(n),t.grandparentDirExists&&(t.grandparentDirContents=(0,_o.readdirSync)(n).slice(0,50))}catch(e){t.grandparentDirError=e instanceof Error?e.message:String(e)}if(t.rgPathExists)try{const r=(0,_o.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,_o.existsSync)(n)}catch{t.asarExists="check_failed"}const i=r.concat(o);try{if(t.asarUnpackedDirExists=(0,_o.existsSync)(i),t.asarUnpackedDirExists){const r=(0,s.dirname)((0,s.dirname)(e));t.ripgrepPkgDirExists=(0,_o.existsSync)(r)}}catch{t.asarUnpackedDirExists="check_failed"}}}return t}class M_{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,Zo.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,Zo.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,Zo.BJ)(t,e)))?void 0:[...new Set(r.map((({target:e})=>e)))]}searchTarget(e,t){if(!t.path)return".";const r=(0,Zo.o1)(t.path,this.singleWorkspacePath??e);return(0,Zo.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 ua(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,So.stat)(e)).isFile())return;const{encoding:t}=await Ui(e);return b_(t)?t.toLowerCase():void 0}catch{return}}((0,Zo.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,Zo.o1)(s.file,t),i=await Sc(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 gy(t,(e=>(0,Zo.o1)(n(e),r)));return s.statTimedOut&&(S_.info(e,"newest_first.stat_timeout_fallback",{toolCallId:o.toolCallId,execId:o.execId,outputMode:o.outputMode,fileCount:t.length}),__.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,M_.CLIENT_LIMIT_LINES)}async runFilesMode(e,t,r,n,o,s,i){const a={stack:[],error:void 0,hasError:!1};try{const d=c_(a,(0,D.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?M_.HARD_MAX_OUTPUT_LINES:M_.CLIENT_LIMIT_LINES,u=M_.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 Jw;let s=0,i=0,a=0;for(;Zw(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&&Zw(c,a,o);)l.push(c.slice(a,o.lineEnd)),a=o.nextStart;return{files:l,totalFiles:ey(s),clientTruncated:s>t,ripgrepTruncated:s>=r}}(c,l,u)),m=f.totalFiles>M_.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 Kw.T7({files:w,totalFiles:ey(f.totalFiles-y),clientTruncated:m,ripgrepTruncated:f.ripgrepTruncated||p.timedOut||p.stdoutByteCapped});return{result:new Kw.vD({result:{case:"files",value:v}}),timedOut:p.timedOut}}catch(e){a.error=e,a.hasError=!0}finally{l_(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=c_(a,(0,D.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?M_.HARD_MAX_OUTPUT_LINES:M_.CLIENT_LIMIT_LINES,u=M_.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 Jw;let i=0;for(;Zw(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:ey(a),totalMatches:ey(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 Kw.xA({counts:g.map((e=>new Kw.sS({file:e.file,count:ey(e.count)}))),totalFiles:ey(f.totalFiles-y),totalMatches:ey(f.totalMatches-v),clientTruncated:f.totalFiles>M_.CLIENT_LIMIT_LINES,ripgrepTruncated:f.ripgrepTruncated||p.timedOut||p.stdoutByteCapped});return{result:new Kw.vD({result:{case:"count",value:b}}),timedOut:p.timedOut}}catch(e){a.error=e,a.hasError=!0}finally{l_(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=c_(a,(0,D.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=M_.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 c_(o,(0,D.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 Jw;let a=0,c=0,l=0,u=0;for(;Zw(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:ey(l),totalMatchedLines:ey(a),totalFiles:ey(s.size),clientTruncated:c>=t,ripgrepTruncated:l>=r}}(e,t,r)}catch(e){o.error=e,o.hasError=!0}finally{l_(o)}}(p,M_.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 Kw.Zp({matches:C.map((e=>new Kw.uI({file:e.file,matches:e.matches.map((e=>new Kw.dx({lineNumber:e.lineNumber,content:e.content,isContextLine:e.isContextLine})))}))),totalLines:ey(m-k),totalMatchedLines:ey(g-_),clientTruncated:w,ripgrepTruncated:y||h.timedOut||h.stdoutByteCapped});return{result:new Kw.vD({result:{case:"content",value:E}}),timedOut:h.timedOut}}catch(e){a.error=e,a.hasError=!0}finally{l_(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=c_(s,(0,D.VI)(e.withName("LocalGrepExecutor.decodeLinesAsRead")),!1),c=function(e,t){const r=[],o=new Jw;let s=0,i=0,a=e.indexOf("�");for(;-1!==a&&Zw(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=Xw(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()+M_.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,Fr.wj)(o_((0,Zo.o1)(l[h],r)),e,"encoding detection timed out")}catch(e){if(e instanceof Fr.MU)break;continue}void 0===t||b_(t)||u.set(l[h],t)}return h<l.length&&S_.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),qs.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{l_(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 S_.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){S_.info(e,"ripgrep.deadline_reached",{toolCallId:t.toolCallId,execId:t.execId,outputMode:t.outputMode,...r}),k_.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(M_.INDEXED_GREP_CONTEXT_TIMEOUT_MS),i={phase:"provider"},a=performance.now();try{return await(0,Fr.wj)(this.grepProvider.executeIndexedGrep(o,t,r,i),M_.INDEXED_GREP_TIMEOUT_MS,`Indexed grep timed out after ${M_.INDEXED_GREP_TIMEOUT_MS/1e3}s`)}catch(t){if(t instanceof Fr.MU)return s(t),void S_.debug(e,"indexed_grep.timeout_fallback",{...n,totalMs:Math.round(performance.now()-a),...i});throw t}finally{s()}}static ripgrepTimeoutError(){return new f_(`Timed out after ${M_.MAIN_TIMEOUT_MS/1e3}s`)}async executeRg(e,t,r,n,o,s,i){const a=(0,D.VI)(e.withName("LocalGrepExecutor.executeRg")),c=8388608;return n=n??M_.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(M_.ripgrepTimeoutError());let f;const m="insecure_none"===s.type?"false":"true",g=performance.now();let w=g;try{const e=s;f=(0,$o.spawnInSandbox)((0,$o.Ko)(),r,{cwd:t},e),w=performance.now(),0}catch(r){if(p(),x_(r)){const n=(0,$o.Ko)();if(S_.error(e,"rg_diagnostics.spawn_throw",void 0,T_(n,t,r,i)),!1===P_(t))return u(A_(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=v_(y,!0,this.stdoutDecodes.get(i));""===e.stdout?u(M_.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(),x_(r)){const n=(0,$o.Ko)();if(S_.error(e,"rg_diagnostics.spawn_enoent",void 0,T_(n,t,r,i)),!1===P_(t))return void u(A_(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=v_(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}),C_.histogram(e,w-g,{sandboxed:m}),C||_||o.aborted||e.signal.aborted||0!==t&&1!==t||E_.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 Sc(t[0]);return null===r?{error:u_(e)}:await this.ignoreService.isCursorIgnored(r)?{error:`Path '${e}' is filtered out by .cursorignore`}:await h_(t[0])?{error:d_(e)}:{resolvedTarget:r}}async execute(e,t,r){if(!Tl(this.encodingSlices,e))return this.search(e,t,r,void 0);const n=new zl,o=await this.search(e,t,r,n);return"success"===o.result.case&&Hl(this.encodingSlices,e,{layer:"exec_grep",evidence:n.evidence(),partial:y_(o)},o),o}async search(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{const a=c_(o,(0,D.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=is(t.sandboxPolicy),p=this.grepProvider.getWorktreeGuardInfo?.(c);if((0,Zo.fl)({targetPath:t.path,workspacePaths:c,mainWorktreePath:p?.mainWorktreePath}))return new Kw.Ud({result:{case:"error",value:new Kw.ts({error:Zo.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 Kw.Ud({result:{case:"error",value:new Kw.ts({error:r.error})}});void 0!==this.mcpStateAccessor&&py(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,Zo.BJ)(s,o))continue;const i=await Sc(s);if(null!==i)if(await this.ignoreService.isCursorIgnored(i))r=!0;else{if(await h_(s))return new Kw.Ud({result:{case:"error",value:new Kw.ts({error:d_(m.path)})}});t.push(n),void 0!==this.mcpStateAccessor&&py(e,this.mcpStateAccessor,i)}}if(0===t.length){const e=r?`Path '${m.path}' is filtered out by .cursorignore`:u_(m.path);return new Kw.Ud({result:{case:"error",value:new Kw.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?m_(M_.MAIN_TIMEOUT_MS):void 0;let n=0,o=!1;try{for(const s of g){if(!0===t?.signal.aborted){r[s]=w_(u),n++,o=!0;continue}if(!1===P_(s))return new Kw.Ud({result:{case:"error",value:new Kw.ts({error:`Path does not exist: ${s}`})}});const i=t??m_(M_.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 f_))throw t;if(r[s]=w_(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(g_));if(this.reportDeadlineReached(a.ctx,d,{streaming:e,folderCount:g.length,stoppedFolderCount:n,outcome:t?"failed":"partial"}),t)throw M_.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=>p_(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 Kw.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 Kw.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 Kw.vD({result:{case:"count",value:s}});break}default:n[t]=o}}return n}(r,g),i=new Kw._0({pattern:m.pattern,path:void 0!==m.path&&this.isRootIndependentSearchPath(m.path)?(0,Zo.o1)(m.path):m.path,outputMode:u,workspaceResults:o});return new Kw.Ud({result:{case:"success",value:i}})}catch(e){if(m.path){const e=(0,Zo.o1)(m.path,this.singleWorkspacePath);try{await(0,So.stat)(e)}catch(t){return new Kw.Ud({result:{case:"error",value:new Kw.ts({error:`Path does not exist: ${e}`})}})}}return new Kw.Ud({result:{case:"error",value:new Kw.ts({error:e instanceof Error?e.message:String(e)})}})}}catch(e){o.error=e,o.hasError=!0}finally{l_(o)}var i}}M_.MAIN_TIMEOUT_MS=25e3,M_.INDEXED_GREP_TIMEOUT_MS=25e3,M_.INDEXED_GREP_CONTEXT_TIMEOUT_MS=M_.INDEXED_GREP_TIMEOUT_MS+100,M_.HARD_MAX_OUTPUT_LINES=1e4,M_.CLIENT_LIMIT_LINES=2e3,M_.LINE_ENCODING_TIMEOUT_MS=2e3,Be.object({record_v:Be.number().int().nullish(),pid:Be.number().int().nonnegative().nullish(),version:Be.string().nullish(),started_at:Be.number().nullish(),control_sock:Be.string().nullish(),runtime_dir:Be.string().nullish(),data_dir:Be.string().nullish(),config_path:Be.string().nullish(),log_path:Be.string().nullish(),metrics_addr:Be.string().nullish(),exe:Be.string().nullish()}),Be.object({mountpoint:Be.string().nullish(),capabilities:Be.array(Be.string()).nullish(),nfs_transport:Be.string().nullish(),bind_ignored:Be.object({active:Be.array(Be.string()).nullish()}).passthrough().nullish()});const D_=Be.object({daemon_alive:Be.boolean().nullish(),mounts:Be.array(Be.unknown()).nullish(),data_plane:Be.object({enabled:Be.boolean().nullish()}).passthrough().nullish()});Be.object({daemon_alive:Be.boolean().nullish(),daemon_version:Be.string().nullish(),capabilities:Be.array(Be.string()).nullish()}),D_.extend({memory:Be.object({anon_bytes:Be.number()}).nullish().catch(null)});const O_=Be.number().int().nonnegative(),F_=Be.object({line_no:Be.number().int().positive(),kind:Be.enum(["match","before","after"]),text:Be.string().optional(),bytes:Be.string().regex(/^(?:[0-9a-fA-F]{2})*$/).optional(),truncated:Be.boolean().default(!1)}).refine((e=>void 0!==e.text||void 0!==e.bytes));Be.object({type:Be.literal("file"),path:Be.string(),lines:Be.array(F_)}),Be.object({type:Be.literal("summary"),files_searched:O_,more:Be.boolean(),stop_reason:Be.string().nullable(),skipped:Be.object({over_size:O_,size_unknown:O_,budget_exhausted:O_,fetch_failed:O_,unreadable:O_})}),Be.object({type:Be.string()}),(0,d.h)("local-exec/grove-grep"),(0,h.Pu)("local_exec.grep.grove",{description:"Grep searches Grove served, or declined to ripgrep, by decline reason",labelNames:["outcome","reason"]}),(0,h.v5)("local_exec.grep.grove.served_ms",{description:"Time Grove took to answer a Grep search it served"});var N_=r("../proto/dist/generated/agent/v1/ls_exec_pb.js"),L_=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},j_=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 U_{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{L_(r,(0,D.VI)(e.withName("LocalLsExecutor.execute")),!1).ctx;const n=(0,Zo.o1)(t.path,this.workspacePath);try{let r;try{r=await(0,So.stat)(n)}catch(e){return"ENOENT"===yc(e)?function(e){const t=Ep(e,"terminals");return null!==t&&0===t.remainingPath.length}(n)?new N_.fv({result:{case:"error",value:new N_.uj({path:n,error:"No active terminals."})}}):new N_.fv({result:{case:"error",value:new N_.uj({path:n,error:`Path does not exist: ${n}`})}}):new N_.fv({result:{case:"error",value:new N_.uj({path:n,error:vc(e)})}})}if(!r.isDirectory())return new N_.fv({result:{case:"error",value:new N_.uj({path:n,error:`Path is not a directory: ${n}`})}});const o=is(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 N_.fv({result:{case:"timeout",value:new N_.ze({directoryTreeRoot:a})}}):new N_.fv({result:{case:"success",value:new N_.PC({directoryTreeRoot:a})}})}catch(e){return new N_.fv({result:{case:"error",value:new N_.uj({path:n,error:e instanceof Error?e.message:"Unknown error occurred"})}})}}catch(e){r.error=e,r.hasError=!0}finally{j_(r)}}async getDirectoryTree(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{return L_(o,(0,D.VI)(e.withName("LocalLsExecutor.getDirectoryTree")),!1),await this.buildTreeFromRipgrepStream(e,t,r,n,2500)}catch(e){o.error=e,o.hasError=!0}finally{j_(o)}}async buildTreeFromRipgrepStream(e,t,r,n,o){const i={stack:[],error:void 0,hasError:!1};try{L_(i,(0,D.VI)(e.withName("LocalLsExecutor.buildTreeFromRipgrepStream")),!1);const a=(0,s.resolve)(t),c=new N_.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}=pa(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 Sc(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{j_(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 N_.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]=ey(e.fullSubtreeExtensionCounts[i]+1),e.numFiles??=0,e.numFiles=ey(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 N_.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 B_ extends Error{constructor(e,t){super(`Tool ${e} not found, available tools: ${t.join(", ")}`),this.toolName=e,this.availableTools=t,this.name="McpToolNotFoundError"}}function W_(e){if(e instanceof B_)return!0;if(!(e instanceof Error)||"McpToolNotFoundError"!==e.name)return!1;const t=e;return"string"==typeof t.toolName&&Array.isArray(t.availableTools)}function H_(e){return!0===e.url?.startsWith("mcp-provider://")}function q_(e){const t=e?.trim();return void 0===t||0===t.length?void 0:t}function z_(e){const t=e?.trim();return void 0===t||0===t.length?void 0:t}function G_(e,t){return(t??[]).some((t=>{const r=q_(t.command),n=z_(t.serverUrl);if(void 0===r&&void 0===n)return!1;const o=void 0===r||void 0!==e.command&&(0,nb.mD)(r,e.command),s=void 0===n||void 0!==e.url&&(0,nb.eA)(n,e.url);return o&&s}))}function V_(e,t){if(H_(e))return!1;const r=t?.rules??[];return r.length>0&&G_(e,r)}var K_=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 J_ extends Error{constructor(e){super(`MCP server "${e}" is disabled`),this.name="McpServerDisabledError"}}class Z_ extends Error{constructor(e){super(`MCP server "${e}" has not been approved`),this.serverName=e,this.name="McpServerNotApprovedError"}}class X_ extends Error{constructor(e,t){super(`MCP server "${e}" is overridden by ${t}`),this.serverName=e,this.overridingConfigPath=t,this.name="McpServerOverriddenError"}}class Q_{constructor(e){this.disabledService=e}async load(e,t,r,n,o){if(await this.disabledService.isServerDisabled(t))throw new J_(t);return await o(e,r)}}class Y_{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,D.VI)(e.withName("ServerApprovalMiddleware.load")),!1),!await this.approvalService.isServerApproved(t,r,n))throw new Z_(t);return await o(e,r)}catch(e){s.error=e,s.hasError=!0}finally{K_(s)}}}class eC{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,wo.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,So.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,So.mkdir)(s.dirname(this.approvalsPath),{recursive:!0}),await(0,So.writeFile)(this.approvalsPath,JSON.stringify(e,null,2))}async saveApprovals(e){await this.saveApprovalsToFile(e),this.approvalsPromise=Promise.resolve(e)}}const tC=["https://api.cursor.com","https://api2.cursor.sh"],rC=["CURSOR_API_BASE_URL","CURSOR_BACKEND_URL"],nC=/^MCP server ".+" is blocked by \S/u;function oC(e){if(void 0!==e&&""!==e)try{return new URL(e).origin}catch{return}}function sC(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(tC);for(const e of rC){const r=oC(t[e]);void 0!==r&&n.add(r)}return n.has(r.origin)}function iC(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function aC(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 cC(e){if(!Array.isArray(e))return;const t=[];for(const r of e.slice(0,200)){const e=aC(r,200);void 0!==e&&t.push(e)}return t}function lC(e,t){const r=t.slice(0,20).join(", "),n=t.length-20;return n>0?` ${e}: ${r}, and ${n} more.`:` ${e}: ${r}.`}var uC=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},dC=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 hC{async load(e,t,r,n,o){const s=o(e,r);return new fC(e,t,s,r)}}function pC(e){let t;return e.then((e=>{t=e})).catch((()=>{})),t}class fC{constructor(e,t,r,n){this.serverName=t,this.clientPromise=r,this.config=n,this.clientPromiseTraceId=(0,D.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=uC(t,(0,D.VI)(e.withName("CachedMcpClient.getTools")),!1);r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("cacheTraceId",this.clientPromiseTraceId??"undefined");const n=pC(this.toolsPromise);return void 0!==n?n:await this.toolsPromise}catch(e){t.error=e,t.hasError=!0}finally{dC(t)}}async callTool(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{const i=uC(s,(0,D.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{dC(s)}}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{const r=uC(t,(0,D.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{dC(t)}}async getClient(e){const t={stack:[],error:void 0,hasError:!1};try{const r=uC(t,(0,D.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{dC(t)}}async listResources(e){const t={stack:[],error:void 0,hasError:!1};try{const r=uC(t,(0,D.VI)(e.withName("CachedMcpClient.listResources")),!1);r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("cacheTraceId",this.clientPromiseTraceId??"undefined");const n=pC(this.resourcesPromise);return void 0!==n?{resources:n}:{resources:await this.resourcesPromise}}catch(e){t.error=e,t.hasError=!0}finally{dC(t)}}async readResource(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=uC(r,(0,D.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{dC(r)}}async listPrompts(e){const t={stack:[],error:void 0,hasError:!1};try{const r=uC(t,(0,D.VI)(e.withName("CachedMcpClient.listPrompts")),!1);r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("cacheTraceId",this.clientPromiseTraceId??"undefined");const n=pC(this.promptsPromise);return void 0!==n?n:await this.promptsPromise}catch(e){t.error=e,t.hasError=!0}finally{dC(t)}}async getPrompt(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=uC(n,(0,D.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{dC(n)}}async getState(e){const t={stack:[],error:void 0,hasError:!1};try{const r=uC(t,(0,D.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{dC(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&&sC(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(!iC(n))return;const o=aC(n.error,700);return void 0!==o&&nC.test(o)?o:void 0}(e)}}async close(){try{const e=await this.clientPromise;await(e?.close?.())}catch{}}}function mC(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function gC(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 wC(e){return e?` (${gC(e,"")})`:""}function yC(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=yC(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=yC(n);if(void 0===e)return;r[t]=e}return r}function vC(e){const t=yC(e);if(null!=t&&"object"==typeof t&&!Array.isArray(t))return t}const bC=new TextDecoder("utf-8",{fatal:!0});function SC(e){return"string"==typeof e?e.split(";")[0]?.trim().toLowerCase()??"":""}function kC(e,t){const r=Buffer.from(t,"base64"),n=function(e){try{const t=bC.decode(e);return t.includes("\0")?void 0:t}catch{return}}(r)??(function(e){const t=SC(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: ${gC(e.uri,"unknown")} (${o}, ${r.byteLength} bytes). The file is not text, so its contents are not included.]`,binary:!0}}const _C=new Set(["image/png","image/jpeg","image/jpg","image/gif","image/webp"]);function CC(e){return"string"==typeof e.text&&e.text.length>0?e.text:void 0}function EC(e){if(!mC(e))return;const t=e.resource;return mC(t)&&void 0===CC(t)&&"string"==typeof t.blob&&_C.has(SC(t.mimeType))?t.blob:void 0}function xC(e){const t=e,r=t.resource;if(mC(r)){const e=CC(r);return void 0!==e?e:"string"==typeof r.blob?kC(r,r.blob).text:`Resource: ${gC(r.uri,"unknown")}${wC(r.name)}`}return t.uri?`Resource: ${gC(t.uri,"unknown")}${wC(t.name)}`:`Unsupported content type "${e.type}": ${JSON.stringify(e)}`}function PC(e){const t=vC(e);if(void 0!==t&&0!==Object.keys(t).length)try{return Buffer.byteLength(JSON.stringify(t))<=262144?t:void 0}catch{return}}var RC=r("zod/v4-mini");const IC=RC.object({CLIENT_ID:RC.string(),CLIENT_SECRET:RC.optional(RC.string()),scopes:RC.optional(RC.array(RC.string()))}),TC=RC.strictObject({caBundle:RC.string().check(RC.trim(),RC.minLength(1),RC.maxLength(131072))}),AC=RC.object({type:RC.optional(RC.literal("stdio")),command:RC.string(),args:RC.optional(RC.array(RC.string())),env:RC.optional(RC.record(RC.string(),RC.string())),envFile:RC.optional(RC.string()),cwd:RC.optional(RC.string()),enabledTools:RC.optional(RC.array(RC.string())),startupTimeoutSec:RC.catch(RC.optional(RC.number().check(RC.positive())),void 0)}),$C=RC.object({type:RC.optional(RC.enum(["http","sse"])),url:RC.string(),headers:RC.optional(RC.record(RC.string(),RC.string())),auth:RC.optional(IC),tls:RC.optional(TC),placement:RC.optional(RC.enum(["server","client"])),enabledTools:RC.optional(RC.array(RC.string()))}),MC=RC.union([AC,$C]),DC=RC.object({mcpServers:RC.record(RC.string(),MC)});Error;const OC=/\$\{(?:env:([A-Za-z_][A-Za-z0-9_]*)|([^:}]+)(?::-([^}]*))?)\}/g;function FC(e,t){if("string"==typeof e)return function(e,t){return e.replace(OC,((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=>FC(e,t)));if(null!==e&&"object"==typeof e){const r={};for(const[n,o]of Object.entries(e))r[n]=FC(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 NC(e){const t=Object.entries(e);return{jsonKeyOf:new Map(t.map((([e,t])=>[t,e]))),tomlKeyOf:new Map(t)}}const LC=NC({CLIENT_ID:"client_id",CLIENT_SECRET:"client_secret",scopes:"scopes"}),jC=NC({caBundle:"ca_bundle"}),UC=NC({type:"type",command:"command",args:"args",env:"env",envFile:"env_file",cwd:"cwd",enabledTools:"enabled_tools",startupTimeoutSec:"startup_timeout_sec"}),BC=NC({type:"type",url:"url",headers:"http_headers",auth:"auth",tls:"tls",placement:"placement",enabledTools:"enabled_tools"}),WC=(new Map([["auth",{keys:LC,unknownKeyIsError:!1}],["tls",{keys:jC,unknownKeyIsError:!0}]]),"enabled");new Set([...UC.jsonKeyOf.keys(),...BC.jsonKeyOf.keys(),WC]);Symbol("disabled");const HC=(0,d.h)("McpConfig");async function qC(e,t=e=>process.env[e]){try{const r=await(0,So.readFile)(e,"utf8"),n=FC((0,Uh.qg)(r),t);return DC.parse(n)}catch{return{mcpServers:{}}}}async function zC(e,t=e=>process.env[e]){const r={config:{mcpServers:{}},diagnostics:[]};return r}async function GC(e,t=e=>process.env[e]){const{config:r,diagnostics:n}=await zC(0,t);return n.length>0&&HC.warn((0,b.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.basename(e.file))))]}),r}const VC=["enterprise","project","user","env"];function KC(e){return"project"===e||"env"===e}const JC=["0.0.0.0/0","::/0"];function ZC(e){const t=(e??[]).filter((e=>e.trim().length>0)),r=t.flatMap((e=>{const t=(0,nb.bi)(e);return void 0===t?[]:[t]}));return{hasInvalidEntries:r.length!==t.length,entries:r}}function XC(e){const t=!0===e.enabled,r=ZC(e.mcpNetworkDenylist),n="deny_all"===e.mcpNetworkMode||r.entries.includes("*")||r.hasInvalidEntries,o=t?function(e){if("allow_all"===e.mcpNetworkMode)return[...JC];const t=ZC(e.mcpNetworkAllowlist);if("allowlist"===e.mcpNetworkMode)return t.entries.includes("*")?[...JC]:t.entries;if(!function(e){return(e.mcpNetworkAllowlist??[]).some((e=>e.trim().length>0))}(e))return[...JC];const r=(0,nb.b6)(e);return r.includes("*")?[...JC]:r}(e):[],s=t?n?["*"]:r.entries:[];return JSON.stringify({enabled:t,mode:e.mcpNetworkMode,allow:n?[]:o,deny:s})}class QC 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 YC=new Set(["invalid_auth","not_authed","account_inactive","token_revoked","token_expired"]);class eE extends Error{constructor(){super("Your organization admin only allows Slack workspaces your company manages. Connect your company Slack workspace instead."),this.name="SlackWorkspaceNotManagedError"}}class tE 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 rE(e){return URL.canParse(e)&&"mcp.slack.com"===new URL(e).hostname.toLowerCase()}function nE(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&&YC.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(!rE(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 tE;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 tE;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 eE;return e(i,a)}}function oE(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)&&pE(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=aE(e,n),s=dE(o,t,r);return Object.is(s,o)?[]:[[n,s]]})),a=Object.getOwnPropertyDescriptor(e,"cause"),c=void 0===a?void 0:aE(e,"cause"),l=dE(c,t,r),u=e instanceof AggregateError?aE(e,"errors"):void 0,d=function(e,t,r){if(!Array.isArray(e))return e;const n=e.map((e=>dE(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])=>iE(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(lE(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[cE];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=gE(e);return void 0!==g&&gE(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 sE(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 iE(e,t,r){const n=Object.getOwnPropertyDescriptor(e,t);return!0===n?.writable&&Reflect.defineProperty(e,t,{...n,value:r})}function aE(e,t){try{const r=Object.getOwnPropertyDescriptor(e,t);return void 0===r?.get?r?.value:r.get.call(e)}catch{return}}const cE=Symbol.for("nodejs.util.inspect.custom");function lE(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 uE(e,t,r,n){if("string"==typeof e)return t(e);if("object"!=typeof e||null===e)return e;if(e instanceof Error)return oE(e,t,n);if(Array.isArray(e)){if(r>=4)return;return e.slice(0,64).map((e=>uE(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:uE(a,t,r,n),writable:!0,enumerable:!0,configurable:!0})}catch{}return o}(e,t,r+1,n)}function dE(e,t,r){if(e instanceof Error)return oE(e,t,r);try{return pE(e,t)?uE(e,t,1,r):e}catch{return}}const hE=4096;function pE(e,t){const r=new Set,n=[e];for(let o=0;n.length>0;o++){if(o>=hE||n.length>hE)return fE(e,t);const s=n.pop();if("string"==typeof s){if(t(s)!==s)return!0}else if((mE(s)||s instanceof Error)&&!r.has(s)){r.add(s),s instanceof Error&&(n.push(aE(s,"message"),aE(s,"stack"),aE(s,"cause")),s instanceof AggregateError&&n.push(aE(s,"errors")));for(const e of Object.keys(s))n.push(aE(s,e))}}return!1}function fE(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,aE(n,e)]))),message:aE(n,"message"),stack:aE(n,"stack"),cause:aE(n,"cause"),...n instanceof AggregateError?{errors:aE(n,"errors")}:{}}):t);var n}))}catch{return!0}return void 0!==n&&t(n)!==n}function mE(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 gE(e){try{return"string"==typeof e.name?e.name:void 0}catch{return}}const wE=/spt_[A-Za-z0-9_]{6,}/g,yE=/[A-Z0-9]/;function vE(e){return function(e){return e.replace(wE,(e=>function(e){return e.slice(4).split("_").some((e=>e.length>=8&&yE.test(e)))}(e)?"[redacted Link shared payment token]":e))}(e)}var bE=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 SE=new Set([429,502,503,504]);function kE(e){return"object"==typeof e&&null!==e}function _E(e){const t=kE(e)?e.code:void 0,r=(e instanceof Error||kE(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&&SE.has(o)&&!SE.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 CE=8192;function EE(e){return void 0===e?"unknown":"url"in e&&e.url.length>0?void 0!==Rv(e.url)?"rest_mcp":"streamable_http":"command"in e?"stdio":"unknown"}new Set(["ENOENT","EACCES","ENOTDIR","EPERM"]);const xE=/\$\{[^}]*\}/;function PE(e){if(void 0!==function(e){if(void 0===e)return;const t=e.trim();return 0!==t.length&&xE.test(t)?t:void 0}(e))return;const t=e?.trim();return t&&t.length>0?t:void 0}const RE=new Map;async function IE(e,t=fetch){if(void 0===Rv(e))return;const r=new URL(e),n=`${r.origin}/.well-known/oauth-protected-resource${r.pathname.replace(/\/+$/,"")}`,o=RE.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 RE.set(n,{metadata:s,expiresAtMs:Date.now()+3e5}),s}(0,bs.J)((function(){RE.clear()}));const TE={info:()=>{},warn:()=>{},error:()=>{},debug:()=>{}};function AE(e){return TE}const $E=/^[\x21\x23-\x5B\x5D-\x7E]+$/,ME=["invalid_request","invalid_token","insufficient_scope"];function DE(e){return ME.some((t=>t===e))}function OE(e){const t=new Set;for(const r of e)r.length<=200&&$E.test(r)&&t.add(r);return[...t]}const FE=/[!#$%&'*+.^_`|~0-9A-Za-z-]+/y,NE=/"((?:[^"\\]|\\.)*)"?/y,LE=/[^\s,]*/y;function jE(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(FE);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(NE)?.[1]??"").replace(/\\(.)/g,"$1"):o(LE)?.[0]??"";if((void 0===r||"bearer"===r)&&s[0].toLowerCase()===t)return i}}const UE={stepUpScopes:[],signInMissing:[]};function BE(e){return Array.isArray(e)?e.filter((e=>"string"==typeof e&&e.length>0)):void 0}function WE(e){if("object"!=typeof e||null===e||Array.isArray(e))return UE;const t=BE("grantedScopes"in e?e.grantedScopes:void 0),r=BE("requestedScopes"in e?e.requestedScopes:void 0);return{...void 0!==t?{grantedScopes:t}:{},stepUpScopes:BE("stepUpScopes"in e?e.stepUpScopes:void 0)??[],signInMissing:BE("signInMissing"in e?e.signInMissing:void 0)??[],...void 0!==r?{requestedScopes:r}:{}}}function HE(e){return(e??"").split(/\s+/).filter((e=>e.length>0))}function qE(e,t){return e.filter((e=>!t.has(e)))}function zE(e){const t=Hv(e.serverUrl),r=e.connectorName??t?.displayName??e.accountKey,n=AE(e.accountKey);let o;const s=async()=>WE(await e.readRecord()),i=async t=>{if(void 0!==t.grantedScopes)return t.grantedScopes;const r=HE(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=jE(t,"error")?.toLowerCase(),n=jE(t,"resource_metadata");return{error:void 0===r||""===r?"none":DE(r)?r:"other",scopes:OE((jE(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 qv.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 OE(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:HE(t.searchParams.get("scope"))})}}},async recordTokens(t,{isRefresh:r}){const n=await e.readRecord();if(void 0===n)return;const o=WE(n),s=HE(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=qE(o.requestedScopes,c);await e.writeRecord({grantedScopes:i,stepUpScopes:qE(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}=WE(e);return t.length>0?{stepUpScopes:t,signInMissing:[]}:void 0}(await e.readRecord()):void 0)}}}function GE(e){const t=Hv(e.serverUrl);for(const r of e.scopes){const e=t?.stepUpScopes[r]?.action;if(void 0!==e)return e}return e.toolTitle}function VE(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:GE(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 KE extends Error{constructor(e,t,r){super(VE({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 VE({kind:this.decision.kind,serverUrl:this.serverUrl,connectorName:this.connectorName,scopes:this.decision.scopes,toolTitle:e??this.decision.toolName})}}function JE(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 ZE(e){return e instanceof Error&&/does not support dynamic client registration/i.test(e.message)}Error,Error;const XE=new Set(["UnauthorizedError","InvalidGrantError","InvalidTokenError","InvalidClientError","UnauthorizedClientError"]),QE=new Set(["invalid_grant","invalid_token","invalid_client","unauthorized_client"]),YE=[/\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 ex=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/types.js");const tx="2026-07-28",rx=-32022,nx="io.modelcontextprotocol/protocolVersion",ox="io.modelcontextprotocol/clientCapabilities",sx="io.modelcontextprotocol/clientInfo",ix="io.modelcontextprotocol/serverInfo",ax={name:"cursor",version:"1.0.0"},cx=new Map;function lx(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function ux(e){const t=new URL(String(e));return t.hash="",t.href}function dx(e,t){const r=cx.get(e);return!(void 0===r||r<=t()&&(cx.delete(e),1))}function hx(e,t){try{return ux(e)===t}catch{return!1}}function px(e){return(e.headers.get("content-type")??"").toLowerCase().includes("application/json")}const fx=new Set(["events/subscribe","events/unsubscribe","events/poll","events/stream"]);function mx(e,t,r,n,o=t.message){const s=new Headers(e?.headers);if(s.set("mcp-protocol-version",tx),s.set("mcp-method",r),s.delete("mcp-session-id"),!t.isRequest&&o===t.message)return{...e,headers:s};const i=lx(o.params)?o.params:{},a=lx(i._meta)?i._meta:{},c=function(e,t){const r="tools/call"===e||"prompts/get"===e||fx.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,[nx]:tx,[ox]:n.capabilities,[sx]:n.clientInfo}}});return{...e,headers:s,body:l}}function gx(e){return new Response(JSON.stringify({jsonrpc:"2.0",...e}),{status:200,headers:{"content-type":"application/json"}})}function wx(e,t){const r=ux(t.serverUrl),n=t.now??Date.now;let o={capabilities:{},clientInfo:{...ax}},s=!1;const i=()=>s||dx(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,mx(a,t,"server/discover",o,c)),d=await async function(e,t,r){if(!e.ok||!px(e))return e;let n;try{n=await e.clone().json()}catch{return e}if(!lx(n)||!lx(n.result))return e;const o=n.result,s=o.supportedVersions;if(!Array.isArray(s)||!s.includes(tx))return gx({id:t,error:{code:rx,message:"Unsupported protocol version",data:{requested:tx,supported:s??[]}}});const i=lx(o._meta)?o._meta:{},a=lx(i[ix])?i[ix]:{name:new URL(r).hostname,version:"unknown"};return gx({id:t,result:{protocolVersion:ex.aE,capabilities:lx(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){cx.set(e,t()+6e5)}(r,n)),d}return e(i,mx(a,t,c,o))};return async(t,c)=>{const l=function(e,t,r){if("POST"!==(t?.method??"GET").toUpperCase()||"string"!=typeof t?.body||!hx(e,r))return;let n;try{n=JSON.parse(t.body)}catch{return}if(!lx(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()&&hx(e,r)}(t,c,r)&&i()?new Response(null,{status:405}):e(t,c);if(l.isRequest&&"initialize"===l.method){const e=lx(l.message.params)?l.message.params:{};o={capabilities:lx(e.capabilities)?e.capabilities:{},clientInfo:lx(e.clientInfo)?e.clientInfo:o.clientInfo}}const u=l.isRequest&&"initialize"===l.method;if(u?dx(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||!px(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(!lx(r)||!lx(r.error))return!1;const n=r.error;if(n.code!==rx||!lx(n.data))return!1;const o=n.data.supported;return Array.isArray(o)&&o.includes(tx)}(d)){const e=await a(l,t,c);return s?e:d}return d}}function yx(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()===Pv));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()!==Pv))),cursorAuthHeaderValue:n[1],cursorAuthOrigin:o}}function vx(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(Pv,i),r(n,{...o,headers:a,redirect:"manual"})}}class bx{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 Sx=r("crypto");function kx(e){const t={};for(const[r,n]of Object.entries(e))void 0!==n&&(t[r]=n);return t}function _x(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 Cx(e,t){return _x(e,t)}function Ex(e){if(e)return(0,Sx.createHash)("sha256").update(e).digest("hex").slice(0,12)}function xx(e){if(e&&0!==e.length)return Ex(JSON.stringify([...e].sort()))}function Px(e){return{clientIdHash:Ex(e?.client_id),hasClientSecret:(e?.client_secret??"").length>0,redirectUrisHash:xx(e?.redirect_uris),redirectUriCount:e?.redirect_uris?.length??0}}function Rx(e){return"object"==typeof e&&null!==e}function Ix(e,t){let r=e;for(const e of t){if(!Rx(r)||!(e in r))return;r=r[e]}return r}function Tx(e,t){for(const r of t){const t=Ix(e,r.split("."));if("string"==typeof t)return t}}function Ax(e){if(!e||"object"!=typeof e)return;const t=e.errorCode;return"string"==typeof t?t:void 0}function $x(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 Mx=e=>e;function Dx(e,t){if(e instanceof Error){const r=e.message;return r&&r!==e.name?Bx(t(r)):void 0}if("string"==typeof e||"number"==typeof e||"boolean"==typeof e){const r=String(e);return r?Bx(t(r)):void 0}}function Ox(e){if(e&&"object"==typeof e)return Rx(e)?e.cause:void 0}function Fx(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(Bx(t(String(o)))):Rx(o)&&"string"==typeof o.message&&n.push(Bx(t(o.message)));break}{const e=Dx(o,t);n.push(e?`${o.name}: ${e}`:o.name),o=Ox(o)}}return n.length>1?n.join(" > "):void 0}const Nx="[REDACTED]",Lx=/(^|_|-)(token|secret|password|assertion|authorization|verifier|challenge|code)(_|-|$)/i;function jx(e){return e.replace(/(authorization[^:=\r\n]{0,32}[:=]\s*["']?)(?:[A-Za-z][\w.~+/-]*[ \t]+)?[^"',\s&}]+/gi,`$1${Nx}`).replace(/((?:access_token|refresh_token|id_token|client_secret|code|password|assertion|token|secret)[^:=\r\n]{0,32}[:=]\s*["']?)([^"',\s&}]+)/gi,`$1${Nx}`).replace(/(\bBearer\s+)([A-Za-z0-9\-._~+/]+=*)/gi,`$1${Nx}`)}function Ux(e,t=256){return e.length>t?`${e.slice(0,Math.max(0,t-3))}...`:e}function Bx(e,t){return Ux(jx(e),t?.maxLength)}function Wx(e,t=Mx){if("string"==typeof e)return Ux(jx(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")||Lx.test(t)}(e)?Nx:"string"==typeof r?jx(t(r)):r));if(!r)return;return Ux(r)}catch{return}}function Hx(e,t=Mx){const r=Ox(e),n=e instanceof Error?e.name:null!=e?typeof e:void 0,o=r instanceof Error?r.name:void 0,s=Dx(r,t),i=Dx(e,t)??s,a=Tx(e,["code","cause.code"]),c=Ax(e)??Ax(r)??Tx(e,["errorCode","error","cause.errorCode","cause.error","body.error","response.body.error"]),l=void 0===c?void 0:Bx(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=Ix(e,t.split("."));if("number"==typeof r&&Number.isFinite(r))return r}}(e)??$x(i)??$x(s),d=Wx(Ix(e,["response","body"])??Ix(e,["body"])??Ix(e,["data"])??Ix(e,["cause","body"])??Ix(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 kx({errorName:n,errorMessage:i,errorType:null!=e?typeof e:void 0,httpStatus:u,oauthErrorCode:l,errorResponseSummary:d,networkClassification:h,causeName:o,causeMessage:s,causeChain:Fx(e,t),sdkErrorKind:p})}const qx={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 zx(e){const t=e.message??qx[e.event],r={event:e.event,cursorMcp:{oauth:kx({...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 Gx=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]))),Vx=4096;function Kx(e){return"object"==typeof e&&null!==e&&"url"in e&&"string"==typeof e.url}function Jx(e){return"string"==typeof e?e:e instanceof URL?e.toString():e.url}function Zx(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Xx(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(Zx(e)){const t={};for(const[r,n]of Object.entries(e)){if("string"!=typeof n)return;t[r]=n}return t}}function Qx(e,t){const r=new Headers(Xx(Kx(e)?e.headers:void 0));return new Headers(Xx(t?.headers)).forEach(((e,t)=>{r.set(t,e)})),r}function Yx(e){const t=[];return e.forEach(((e,r)=>{t.push(r)})),t.sort()}function eP(e){if(null===e)return null;const t=Number.parseInt(e,10);return Number.isNaN(t)?null:t}function tP(e,t){if(null==e)return{kind:"none",bytes:0,contentLength:eP(t.get("content-length"))};if("string"==typeof e){const r=(new TextEncoder).encode(e).length;return{kind:"text",bytes:r,contentLength:eP(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:eP(t.get("content-length"))??n}}return e instanceof Blob?{kind:"blob",bytes:e.size,contentLength:eP(t.get("content-length"))??e.size}:e instanceof ArrayBuffer||ArrayBuffer.isView(e)?{kind:"binary",bytes:e.byteLength,contentLength:eP(t.get("content-length"))??e.byteLength}:"object"==typeof e&&null!==e&&("getReader"in e||Symbol.asyncIterator in e)?{kind:"stream",bytes:null,contentLength:eP(t.get("content-length"))}:{kind:"unknown",bytes:null,contentLength:eP(t.get("content-length"))}}function rP(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 nP(e){const{input:t,init:r}=e,n=_x(Jx(t)),o=Qx(t,r),s=Yx(o),i=o.get("content-type"),a=Ex(o.get("mcp-session-id")??void 0),c=function(e){if(!e)return null;const t=e.trim().split(/\s+/,1)[0]??"";return Gx.get(t.toLowerCase())??"unrecognized"}(o.get("authorization"));return{method:(r?.method??(Kx(t)?t.method:void 0)??"GET").toUpperCase(),url:n,headers:{names:s,count:s.length},contentType:i,body:tP(r?.body,o),sessionIdHash:a??null,authorizationScheme:c}}function oP(e,t){const r=Yx(e.headers),n=eP(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:Ex(e.headers.get("mcp-session-id")??void 0)??null,wwwAuthenticateHash:Ex(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:sP(e.headers,"retry-after"),slackRateLimitType:sP(e.headers,"x-slack-ratelimit-type")}}function sP(e,t){return e.get(t)?.slice(0,64)??null}function iP(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 aP(e,t){const r=nP({input:e,init:t});if(void 0!==rP(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 cP=e=>e,lP="REDACTED_SESSION_ID",uP=/\b00D[A-Za-z0-9]{12,15}![A-Za-z0-9._]{20,512}/g;async function dP(e,t,r){try{const n=r(await e.clone().text());return n.length>t?n.slice(0,t):n}catch{return}}async function hP(e){if(!aP(e.input,e.init))return;const t=await dP(e.response,Vx,e.redact);if(void 0!==t)try{return Wx(JSON.parse(t))}catch{return Bx(t,{maxLength:Vx})}}async function pP(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 dP(t,Vx,r);if(void 0===o)return;return function(e){if("/mcp"!==(t=_x(Jx(e.input)).path)&&!0!==t?.endsWith("/mcp"))return Bx(e.rawText,{maxLength:Vx});var t;try{const t=JSON.parse(e.rawText);return Zx(t)?function(e){const t=e.error;if("string"==typeof t)return JSON.stringify({error:t});if("object"!=typeof t||null===t)return;if(!Zx(t))return;const r=t,n="number"==typeof r.code||"string"==typeof r.code?r.code:void 0,o="string"==typeof r.message?Bx(r.message,{maxLength:Vx}):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 hP({input:e.input,response:e.response,init:e.init,redact:e.redact}):void 0}}function fP(e,t,r){try{e()}catch{t.warn?.("MCP HTTP exchange logging failed",{event:"mcp_http_exchange_logging_failure",phase:r})}}function mP(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=>mP(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,mP(n,t,r+1)])))}function gP(e,t){const r=e=>{const r=mP(e,t,0);return Zx(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 wP(e){const{fetch:t,logSuccessfulExchanges:r=!0,redactLogText:n}=e,o=void 0===n?e.logger:gP(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=Qx(e,t).get("mcp-session-id")?.trim()??"";return e=>{const t=n.length>=8?e.split(n).join(lP):e;return r(t.replace(uP,lP))}}(s,i,n??cP):n??cP;try{const e=await t(s,i),{responseErrorSummary:n,oauthTokenErrorBodySummary:u}=e.ok?{}:await pP({input:s,init:i,response:e,redact:l});return!r&&e.ok||fP((()=>{!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=nP({input:t,init:r}),l=rP(c.contentType,r?.body);return{event:"mcp_http_exchange",outcome:n.ok?"success":"http_error",durationMs:o,cursorMcp:{transport:{...s,request:c,response:oP(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")&&!aP(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(!Rx(e))return;const t=Rx(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 pP({input:s,init:i,response:r,redact:l}):{};throw fP((()=>{!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=Hx(n,e.redactLogText),u=nP({input:t,init:r}),d=rP(u.contentType,r?.body);return{event:"mcp_http_exchange",outcome:"error",durationMs:o,cursorMcp:{transport:{...s,request:u,response:void 0!==i?oP(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:iP(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 yP(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 vP(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 bP(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 SP=["PYTHONIOENCODING","PYTHONUTF8","PYTHONLEGACYWINDOWSSTDIO"],kP=[".exe",".cmd",".bat"],_P=/^pythonw?(?:\d+(?:\.\d+)*t?)?$/,CP=new Set(["py","pyw"]),EP=new Set(["--cache-dir","--color","--allow-insecure-host","--directory","--project","--config-file"]),xP=new Set;function PP(e){return SP.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 RP(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 IP(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 kP)if(t.endsWith(e))return t.slice(0,-e.length);return t}(e);if(_P.test(r)||CP.has(r)||"uvx"===r)return!0;if("uv"===r){const e=RP(t,EP);return"run"===e?.value||"tool"===e?.value&&"run"===RP(e.rest,EP)?.value}return"pipx"===r&&"run"===RP(t,xP)?.value}(n,o)?PP(i)||PP(r)?i:{...i,PYTHONIOENCODING:"utf-8:surrogateescape"}:i}async function TP(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 AP=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js"),$P=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/sse.js"),MP=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.js"),DP=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js");var OP=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js");function FP(e){return`${typeof e}:${String(e)}`}function NP(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(FP(e.id),r)}else if("notifications/cancelled"===e.method){const n=e.params?.requestId;if("string"!=typeof n&&"number"!=typeof n)return;const o=FP(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=FP(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 LP(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,wo.createHash)("sha256").update(JSON.stringify([e.url,t,e.accessToken??null])).digest("hex")}class jP{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,ex.vo)(e)&&(0,ex.eK)(e)){const t={jsonrpc:"2.0",id:e.id,result:this.initializeResult};queueMicrotask((()=>this.onmessage?.(t)))}else(0,ex.wU)(e)||await this.inner.send(e,t)}}const UP=Be.object({tools:Be.array(Be.unknown()),nextCursor:Be.unknown().optional(),_meta:Be.unknown().optional()}),BP={typeFilled:0,toolDropped:0,outputStripped:0};function WP(e){if(KP(e))return"string"==typeof e.name?e.name:void 0}function HP(e){return qP(e.issues.filter((e=>"outputSchema"===e.path[0])))}function qP(e){return e.map((e=>`${e.path.map(String).join(".")}: ${e.message}`))}function zP(e){if(!KP(e))return e;const t={...e};return delete t.outputSchema,t}function GP(e){return KP(e)&&!("type"in e)}function VP(e,t){return{...e,inputSchema:{type:"object",...t}}}function KP(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var JP=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/ajv-provider.js");const ZP=new class{constructor({maxSchemasPerCompiler:e=2048,createCompiler:t=()=>new JP.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,wo.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 XP{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>=CE}append(e){const t=CE-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}=Ko(e,Math.trunc(t));return r>=e.length?e:e.slice(0,r)}(e,t);this.captured+=r,this.capturedBytes=r.length<e.length?CE:this.capturedBytes+function(e){return Ko(e,1/0).written}(r)}}const QP=new WeakMap;var YP=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},eR=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 tR=(0,d.h)("McpSdkClient"),rR=(0,h.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 nR(e,t,r){try{rR.increment(e,1,function(e){const t=e.httpStatus??(void 0!==e.error?function(e){if(!e||"object"!=typeof e)return;const t=_E(e);if(void 0!==t)return t;const r=kE(e)?e.cause:void 0;return r&&"object"==typeof r?_E(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:EE(t),...r}))}catch{}}const oR=(0,h.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 sR(e){return void 0===e?"unknown":"url"in e?"http":"stdio"}const iR=["authorization_code","refresh_token"],aR=["code"];class cR{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=Bv(e);return void 0!==r&&function(e){return"https:"===e.protocol&&e.hostname===new URL(Iv).hostname}(r)?async()=>{}:void 0!==r&&function(e){return"https:"===e.protocol&&"setup.shopify.com"===e.hostname&&""===e.port&&"/mcp"===e.pathname}(r)?Wv:jv}(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,wo.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=Nv(e);return!0!==n?.pinsScopesOverConfiguredScopes?void 0!==t&&t.length>0||void 0===r?t:Hv(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=Nv(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 lR(e){const{serverName:t,config:n,tokenStorage:o}=e,s=await IE(n.url,e.fetchImpl),i=Yv({loopbackIpv4:s?.loopbackIpv4,redirectUrl:e.authRedirectUrl}),a=function(e,t){const r=PE(e?.CLIENT_ID);if(void 0!==r)return{client_id:r,...e?.CLIENT_SECRET?{client_secret:e.CLIENT_SECRET}:{},redirect_uris:eb(t),grant_types:[...iR],response_types:[...aR],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 cR({identifier:t,redirectUrl:i,serverUrl:n.url,restMcpProviderMetadata:s,gtmMcpMatch:e.gtmMcpMatch??{gtmApiOrigin:void 0},clientMetadata:{redirect_uris:eb(i),token_endpoint_auth_method:"none",grant_types:[...iR],response_types:[...aR],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:zE({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 uR=new Set;let dR=!1;function hR(){for(const e of uR)try{process.kill(e,"SIGKILL")}catch{}}function pR(e){return ZE(e)?new AP.D_:e}function fR(e,t){return wx(e??globalThis.fetch.bind(globalThis),{serverUrl:t})}function mR(e,t,r){const n=yx(e,t),o=r??(globalThis.fetch?globalThis.fetch.bind(globalThis):void 0),s=void 0!==n.cursorAuthHeaderValue&&void 0!==n.cursorAuthOrigin&&void 0!==o?vx((()=>n.cursorAuthHeaderValue),n.cursorAuthOrigin,o):o;return{transportHeaders:n.headers,baseFetch:s}}class gR{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 bx,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}})();zx({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 OP.K({name:"Cursor",version:"1.0.0"},{capabilities:t,jsonSchemaValidator:ZP})}setupElicitationHandler(){this.client.setRequestHandler(ex.$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??Jv;const f=await lR({serverName:e,config:t,tokenStorage:r,authRedirectUrl:o,fetchImpl:s,gtmMcpMatch:c,isScopePinGateEnabled:l,scopeChallengeStepUp:u}),m=f.tokens(),g=yx(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?vx((()=>g.cursorAuthHeaderValue),g.cursorAuthOrigin,v):v,S=e=>void 0===b||void 0===i?b:wP({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,AP.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:JE(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){AE(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 KE(n,o.serverUrl,o.scopeStepUp.connectorName)});var o},C=gR.createClient(h),E=e=>e instanceof AP.D_||function(e){if(null===e||"object"!=typeof e)return!1;const t=e.name;if("string"==typeof t&&XE.has(t))return!0;const r=e.errorCode;return!("string"!=typeof r||!QE.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&&YE.some((e=>e.test(n)))}(e)}(e)||ZE(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,AP.j2)(f,{serverUrl:p.toString(),authorizationCode:t,...void 0!==r?{resourceMetadataUrl:r}:{},...void 0!==b?{fetchFn:b}:{}}),a&&zx({logger:a,event:"mcp_oauth_callback_completion",metadata:{identifier:e,...Cx(p.toString()),...yP(f.tokens(),{expiresInIsFresh:!0})}})},P=r=>{const n=f.lastRedirectUrl?.toString?.()??"",o=new gR(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 $P.A(p,{authProvider:y,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...w??{}}},fetch:_(S("sse"))});try{return await C.connect(n),new gR(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&&zx({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),...Cx(p.toString()),...Hx(t,i?.redactLogText)}}),P();if(void 0!==r&&vP(t)&&t instanceof $P._)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 DP.j(p,{authProvider:y,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...w??{}}},fetch:_(fR(S("streamableHttp"),p))});try{await C.connect(I);const r=function(e,t=Date.now){return dx(ux(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:LP({url:t.url,headers:n,accessToken:f.tokens()?.access_token})}}(C,I);return new gR(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&&zx({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),...Cx(p.toString()),...Hx(t,i?.redactLogText)}}),P(I.sessionId);if(vP(t))return R(t);throw t}}static async fromStreamableHttpWithoutOAuth(e,t,r){const n=gR.createClient(),o=new DP.j(new URL(t.url),{requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...t.headers}},fetch:r});return await n.connect(o),new gR(e,n,{initialState:{kind:"ready"},sessionId:o.sessionId,protocolVersion:o.protocolVersion,config:t})}static async fromCachedSession(e,t,r,n,o,s=Jv,i,a,c,l,u){const d=new URL(t.url),h=await lR({serverName:e,config:t,tokenStorage:n,authRedirectUrl:s,fetchImpl:i,gtmMcpMatch:l,isScopePinGateEnabled:u}),{transportHeaders:p,baseFetch:f}=mR(t.url,o,i),m=new DP.j(d,{authProvider:h,sessionId:r.sessionId,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...p??{}}},fetch:void 0!==f&&void 0!==a?wP({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,wo.randomInt)(1048576,2146435072),e}(gR.createClient());return await g.connect(m),new gR(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=Jv,i,a,c,l){const u=await lR({serverName:e,config:t,tokenStorage:n,authRedirectUrl:s,fetchImpl:i,gtmMcpMatch:a,isScopePinGateEnabled:c});if(LP({url:t.url,headers:o,accessToken:u.tokens()?.access_token})!==r.credentialFingerprint)return;const{transportHeaders:d,baseFetch:h}=mR(t.url,o,i),p=new DP.j(new URL(t.url),{authProvider:u,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...d??{}}},fetch:h}),f=gR.createClient();return await f.connect(new jP(p,r.result)),new gR(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 DP.j&&await e.resumeStream("")}static async fromCommand(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{YP(s,(0,D.VI)(e.withName("McpSdkClient.fromCommand")),!1);const l=(c=o?.spawn,void 0!==c||"linux"!==process.platform?c:(e,t,r)=>(0,Jl.D9)(Kl.spawn,e,t,r)),u=r.args??[],d=new MP.oQ({command:r.command,args:u,env:bP(IP({command:r.command,args:u,env:n})),cwd:r.cwd,stderr:"pipe",...l&&{spawn:l}}),h=function(e){const t=new XP;let r=null===e;return null!==e&&(e.on("data",(e=>{t.full||t.push(e)})),e.once("end",(()=>{t.end(),r=!0}))),{read:()=>Bx(t.text.replace(/\s+/g," ").trim(),{maxLength:CE}),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=gR.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,uR.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,uR.add(i),dR||(dR=!0,process.on("exit",hR)));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}`,QP.set(r,t),r}(e,h.read())}finally{w=!1,void 0!==b&&clearTimeout(b)}return new gR(t,p,{initialState:{kind:"ready"},config:r,stdioServer:void 0!==m,serverSignals:NP(d)})}catch(e){s.error=e,s.hasError=!0}finally{eR(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 DP.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,Fr.wj)(n,t.timeoutMs)}catch(e){const t=Date.now()-r;return e instanceof Fr.MU?{outcome:"timeout",durationMs:t}:e instanceof DP.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=YP(t,(0,D.VI)(e.withName("McpSdkClient.getTools")),!1);if(r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("mcp.transport",sR(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 TP({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,...BP}}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}},UP),o=[];let s=0,i=0,a=0;for(const e of n.tools){let t=e;if(KP(e)){const r=e.inputSchema;GP(r)&&(t=VP(e,r),s++)}let n=ex.Dn.safeParse(t);if(!n.success&&(c=n.error).issues.some((e=>"outputSchema"===e.path[0]))){const o=ex.Dn.safeParse(zP(t));o.success&&(a++,r(WP(e),HP(n.error),"output_stripped"),n=o)}n.success?o.push(n.data):(i++,r(WP(e),qP(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(yR.has(n))return yR.delete(n),yR.add(n),!1;if(yR.add(n),yR.size>256){const e=yR.keys().next().value;void 0!==e&&yR.delete(e)}return!0})(n,this.serverName,e??"")&&tR.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,vR(r.ctx,"type_filled",n.typeFilled),vR(r.ctx,"tool_dropped",n.toolDropped),vR(r.ctx,"output_stripped",n.outputStripped),e??=function(e){if(!iC(e))return;const t=e.mcpAllowlist;if(!iC(t)||"string"!=typeof t.list)return;const r=aC(t.name,200),n=aC(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=cC(t.allowedServerNames)??cC(t.allowedServers);void 0!==s&&(o.allowedServers=s);const i=cC(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:yC(e.inputSchema),outputSchema:void 0===e.outputSchema?void 0:yC(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=pR(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 AP.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",{...Hx(t,this._redactLogText)}),this._stateEnteredAtMs=Date.now()}throw t}}catch(e){t.error=e,t.hasError=!0}finally{eR(t)}}async getAllowlistInUse(){return this._allowlistInUse}reportsCursorMcpAllowlist(){return void 0!==this.config&&"url"in this.config&&sC(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=ex.O4.MethodNotFound;if(t instanceof ex.Nh&&t.code===n&&void 0===this.client.getServerCapabilities()?.tools)return void this.noteToolListSuccess();if(t instanceof AP.D_||!this.toolListAttemptIsCurrent(r))return;const o=function(e){if(e instanceof ex.Nh)return{descriptor:`McpError ${e.code}`,errorClass:"McpError",jsonRpcCode:e.code};if(e instanceof DP.b||e instanceof $P._){const t=e instanceof DP.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&&tR.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=YP(s,(0,D.VI)(e.withName("McpSdkClient.callTool")),!1);a.span.setAttribute("toolName",t),a.span.setAttribute("serverName",this.serverName),a.span.setAttribute("mcp.transport",sR(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=YP(e,(0,D.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{eR(e)}}if("requires_authentication"===this.stateValue.kind)throw new AP.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=YP(n,(0,D.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),nR(e,this.config,{isError:!0===c.isError}),{content:c.content,isError:!0===c.isError,structuredContent:(i=c.structuredContent,vC(i)),_meta:PC(c._meta)}}catch(e){n.error=e,n.hasError=!0}finally{eR(n)}}catch(t){const r=pR(t);r instanceof KE?(nR(e,this.config,{error:r,httpStatus:r.decision.status}),function(e,t){try{oR.increment(e,1,{decision:t.decision.kind,dropped:String(t.decision.dropped.length>0)})}catch{}}(e,r)):nR(e,this.config,{error:r});const n=r instanceof KE&&"offer"===r.decision.kind&&void 0!==this._authProvider?.lastRedirectUrl&&this._authProvider.lastRedirectUrl!==u;if((r instanceof AP.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",{...Hx(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{eR(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},ex.TF,n):this.client.callTool(e,void 0,n)}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{if(YP(t,(0,D.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{eR(t)}}async listResources(e){const t={stack:[],error:void 0,hasError:!1};try{if(YP(t,(0,D.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 TP({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{eR(t)}}async readResource(e,t){const r={stack:[],error:void 0,hasError:!1};try{return YP(r,(0,D.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{eR(r)}}async listPrompts(e){const t={stack:[],error:void 0,hasError:!1};try{return YP(t,(0,D.VI)(e.withName("McpSdkClient.listPrompts")),!1),"requires_authentication"===this.stateValue.kind||"error"===this.stateValue.kind?[]:(this.client.getServerCapabilities()??{prompts:!1}).prompts?(await TP({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{eR(t)}}async getPrompt(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{return YP(n,(0,D.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{eR(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 wR=(0,h.Pu)("mcp_tool.schema",{description:"One MCP tool definition a tools/list repair touched",labelNames:["outcome"]}),yR=new Set;function vR(e,t,r){if(0!==r)try{wR.increment(e,r,{outcome:t})}catch{}}class bR 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 SR{constructor(e){this.tools=e}async execute(e,t,r,n){const o=this.tools[e];if(!o)throw new B_(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 B_(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 kR{async getClients(e){return{}}async getClient(e,t){}async getInstructions(e){return[]}async getToolSet(e){return new SR({})}async getTools(e){return[]}async getToolsForServers(e,t){return[]}}class _R{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=YP(t,(0,D.VI)(e.withName("ManagerMcpLease.getInstructions")),!1);return await this.manager.getInstructions(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{eR(t)}}async getToolSet(e){const t={stack:[],error:void 0,hasError:!1};try{const r=YP(t,(0,D.VI)(e.withName("ManagerMcpLease.getToolSet")),!1);return await this.manager.getToolSet(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{eR(t)}}async getTools(e){const t={stack:[],error:void 0,hasError:!1};try{const r=YP(t,(0,D.VI)(e.withName("ManagerMcpLease.getTools")),!1);return(await this.getToolSet(r.ctx)).getTools()}catch(e){t.error=e,t.hasError=!0}finally{eR(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 CR{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=YP(t,(0,D.VI)(e.withName("McpManager.getToolSet")),!1),n=YP(t,ER(this.listingDeadlineAt),!1),o=await(0,Fr.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 SR(a)}catch(e){t.error=e,t.hasError=!0}finally{eR(t)}}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{const r=YP(t,(0,D.VI)(e.withName("McpManager.getInstructions")),!1),n=YP(t,ER(this.listingDeadlineAt),!1),o=await(0,Fr.PH)(Object.entries(this.clients),(([e,t])=>n.within(t,r.ctx,(()=>t.getInstructions(r.ctx))).then((e=>e&&0!==e.trim().length?new gn.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{eR(t)}}}function ER(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 xR(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 PR{constructor(e){this.options=e,zx({logger:e.logger,event:"mcp_oauth_provider_initialized",metadata:this.baseMetadata})}get baseMetadata(){return{identifier:this.options.identifier,...this.options.serverUrl?{serverUrl:Cx(this.options.serverUrl)}:{}}}async loadTokens(){const e=await this.options.inner.loadTokens();return zx({logger:this.options.logger,event:"mcp_oauth_tokens_loaded",level:"debug",metadata:{...this.baseMetadata,...yP(e)}}),e}async saveTokens(e){await this.options.inner.saveTokens(e),zx({logger:this.options.logger,event:"mcp_oauth_tokens_saved",metadata:{...this.baseMetadata,...yP(e,{expiresInIsFresh:!0})}})}async prepareForRefresh(){zx({logger:this.options.logger,event:"mcp_oauth_refresh_prepare",metadata:this.baseMetadata}),await(this.options.inner.prepareForRefresh?.())}async releaseRefreshLeaseOnError(e){zx({logger:this.options.logger,event:"mcp_oauth_refresh_error_release",level:"warn",error:e,metadata:{...this.baseMetadata,...Hx(e,this.options.redactLogText)}}),await(this.options.inner.releaseRefreshLeaseOnError?.(e))}async loadClientInformation(){const e=await this.options.inner.loadClientInformation();return zx({logger:this.options.logger,event:"mcp_oauth_client_info_loaded",level:"debug",metadata:{...this.baseMetadata,...Px(e)}}),e}async saveClientInformation(e){await this.options.inner.saveClientInformation(e),zx({logger:this.options.logger,event:"mcp_oauth_client_info_saved",metadata:{...this.baseMetadata,...Px(e)}})}async invalidateCredentials(e){void 0!==this.options.inner.invalidateCredentials&&(zx({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 RR{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 IR{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 TR=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},AR=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 $R=(0,d.h)("DefinitionMcpLoader"),MR=(0,h.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 DR(e){const{filePath:t,baseDir:r}=e;return"~"===t||t.startsWith("~/")?s.join(o.homedir(),t.slice(1)):t.startsWith("./")||"."===t?s.resolve(r??process.cwd(),t):t}function OR(e){return"getManagedSlackWorkspaceLists"in e&&"function"==typeof e.getManagedSlackWorkspaceLists}function FR(e){return"getMcpNetworkControlsConfig"in e&&"function"==typeof e.getMcpNetworkControlsConfig}function NR(e){return e?.length??0}function LR(e){if(void 0!==e)return(0,wo.createHash)("sha256").update(XC(e)).digest("hex")}function jR(e){if(void 0===e)return;let t;return r=>(void 0===t&&(t=e(),queueMicrotask((()=>{t=void 0}))),t?vE(r):r)}async function UR(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=TR(u,(0,D.VI)(e.withName("mcp-agent-exec.loadServer")),!1);p.span.setAttribute("serverName",t);const f=!1!==l.mcpAppsUi;p.span.setAttribute("mcpAppsUi",f),$R.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=TR(s,(0,D.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(FR);return await async function(e,t,n,o,s={}){const i=n.cwd?DR({filePath:n.cwd}):void 0;let a,c;if(n.args&&n.args.length>0)a=DR({filePath:n.command,baseDir:i}),c=n.args.map((e=>DR({filePath:e,baseDir:i})));else{const e=(0,bE.A)(n.command);a=DR({filePath:e[0],baseDir:i}),c=e.slice(1).map((e=>DR({filePath:e,baseDir:i})))}const l=n.env??{},{startupTimeoutSec:u}=n,d=await(o?.getMcpNetworkControlsConfig?.({command:[n.command,...n.args??[]].join(" ")})),h=(0,nb.$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);$R.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=${NR(e.networkControlsConfig?.mcpNetworkAllowlist)}, mcpNetworkDenylistCount=${NR(e.networkControlsConfig?.mcpNetworkDenylist)}, localAgentNetworkAllowlistCount=${NR(e.networkControlsConfig?.localAgentNetworkAllowlist)}, sandboxPolicyHash=${LR(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:NR(e.networkControlsConfig?.mcpNetworkAllowlist),mcpNetworkDenylistCount:NR(e.networkControlsConfig?.mcpNetworkDenylist),localAgentNetworkAllowlistCount:NR(e.networkControlsConfig?.localAgentNetworkAllowlist),sandboxPolicyHash:LR(e.sandboxNetworkControlsConfig)}}({serverName:t,networkControlsConfig:d,sandboxNetworkControlsConfig:h}));try{return await gR.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 QC(t,e);throw e}}return!0===d?.enabled&&"no_sandbox"===d.mcpNetworkMode&&(!0===d.win32UserExtensionUnsandbox?$R.info(e,`Starting local MCP server "${t}" without MCP sandboxing`,{event:"mcp_stdio_win32_user_extension_unsandbox",serverName:t}):$R.info(e,`Starting local MCP server "${t}" without MCP sandboxing`)),gR.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=xR(e,$R),u=function(e,t,r){return{logger:{debug:(t,r)=>$R.debug(e,t,r),info:(t,r)=>$R.info(e,t,r),warn:(t,r)=>$R.warn(e,t,r),error:(t,r,n)=>$R.error(e,t,r,n)},metadata:{identifier:t,source:"mcp-agent-exec"},redactLogText:jR(r)}}(e,t,a),d=void 0!==s&&rE(r.url)?nE(globalThis.fetch.bind(globalThis),{managedSlackWorkspaceLists:()=>s.getManagedSlackWorkspaceLists()}):void 0;return gR.fromStreamableHttp(t,r,n,r.headers,o,d,u,l,void 0,void 0,i,!1,c)}(h,t,n,o,e,d.find(OR),a,c.isLinkSharedPaymentTokenLogRedactionEnabled,l)}throw new Error(`Invalid server: ${JSON.stringify(n)}`)}catch(e){s.error=e,s.hasError=!0}finally{AR(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=QP.get(e);void 0!==r&&QP.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=oE(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<hE;e++){const e=n.pop();if(!(e instanceof Error||mE(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=aE(e,r),s=sE(o,t);s!==o&&iE(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=QP.get(e);void 0!==r&&QP.set(t,r)}(e,r),r}(e,jR(c.isLinkSharedPaymentTokenLogRedactionEnabled))}}catch(e){u.error=e,u.hasError=!0}finally{AR(u)}}class BR{constructor(e,t=qC){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 WR{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{TR(r,(0,D.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,Fr.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=jR(n)??(e=>e),s=function(e){if("object"==typeof e&&null!==e)return QP.get(e)}(r);$R.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 CR(o,this.options.elicitationFactory)}catch(e){r.error=e,r.hasError=!0}finally{AR(r)}}clearClient(e){this.clientCache.delete(e)}clearAllMcpCaches(){this.clientCache.clear()}async evictClientsOnSandboxPolicyChange(e,t){const r=this.middlewares.find(FR);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,XC(t)]}))))}catch{return}const o=this.sandboxPolicyFingerprint;this.sandboxPolicyFingerprint=n,void 0!==o&&o!==n&&($R.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,Fr.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{TR(n,(0,D.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{AR(n)}}async loadDefinitionClient(e,t,r){const n=t.authStorageKey??t.identifier,o=new RR(this.tokenStorage,n),s=xR(e,$R),i=new PR({inner:o,logger:s,redactLogText:jR(this.options.isLinkSharedPaymentTokenLogRedactionEnabled),identifier:n,serverUrl:"url"in t.serverConfig?t.serverConfig.url:void 0}),a=r?new IR(i):i;return UR(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){$R.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 J_||e instanceof Z_||e instanceof X_||e instanceof HR}(r)}}class HR 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 qR=[1e3,3e3];class zR{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),MR.increment(e,1,{surface:"desktop",stage:"tool_call",reason:"server_not_allowed"})),new HR(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 eE)throw new HR(t,"teamPolicy",e.message);const r=e instanceof tE?qR[n]:void 0;if(void 0===r)throw e;await(0,Fr.cb)(r)}}}class GR extends WR{constructor(e,t,r=[],n={}){super(new BR(e),t,r,n),this.configPath=e}static init(e,t,r=[]){return new GR(t,e,r)}}function VR(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 KR=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth.js");function JR(e){const t=KR.VE.safeParse(e);return t.success?t.data:void 0}function ZR(e){const t=KR.H5.safeParse(e);return t.success?t.data:void 0}class XR{constructor(e){this.mcpAuthPath=e;const t=XR.mcpAuthPromises.get(e);if(t)this.mcpAuthPromise=t;else{const t=this.loadMcpAuth();this.mcpAuthPromise=t,XR.mcpAuthPromises.set(e,t),t.catch((()=>{XR.mcpAuthPromises.get(e)===t&&XR.mcpAuthPromises.delete(e)}))}XR.saveLocks.has(e)||XR.saveLocks.set(e,Promise.resolve())}async loadMcpAuth(){try{const e=await(0,So.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=JR(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?JR(n.tokens):void 0,clientInfo:"clientInfo"in n?ZR(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=XR.saveLocks.get(this.mcpAuthPath)??Promise.resolve();let r;XR.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,So.mkdir)(s.dirname(this.mcpAuthPath),{recursive:!0}),await(0,So.writeFile)(this.mcpAuthPath,JSON.stringify(e,null,2))}}XR.mcpAuthPromises=new Map,XR.saveLocks=new Map,(0,b.cF)(Symbol("execHookConversationId"),void 0),(0,b.cF)(Symbol("execHookGenerationId"),void 0),(0,b.cF)(Symbol("execHookModel"),void 0);const QR=(0,b.cF)(Symbol("execHookWorkspaceRoots"),void 0);var YR=r("../proto/dist/generated/agent/v1/write_exec_pb.js"),eI=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},tI=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 rI=(0,h.Pu)("mcp.filesystem.divergence",{description:"Divergence detected between MCP lease state and filesystem state",labelNames:["divergence_type","mcp_source","configured_servers","mcp_version"]}),nI=(0,h.Pu)("mcp.filesystem.sync_check",{description:"MCP filesystem sync check executed",labelNames:["synced","mcp_source","configured_servers","mcp_version"]}),oI=(0,h.wt)("mcp.filesystem.sync_check.expected_servers",{description:"Number of expected MCP servers at last sync check",labelNames:["mcp_source","mcp_version"]}),sI=(0,h.wt)("mcp.filesystem.sync_check.actual_servers",{description:"Number of actual MCP servers on disk at last sync check",labelNames:["mcp_source","mcp_version"]}),iI=(0,h.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"]}),aI=(0,h.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"]}),cI=(0,d.h)("McpFileSystemWriter"),lI="mcpFsStructuredLogOptIn";function uI(e,t){return t?.includeStructuredLogs?{...e??{},[lI]:!0}:e}const dI={debug(e,t,r,n){cI.debug(e,t,uI(r,n))},info(e,t,r,n){cI.info(e,t,uI(r,n))},warn(e,t,r,n){cI.warn(e,t,uI(r,n))},error(e,t,r,n,o){cI.error(e,t,r,uI(n,o))}},hI="mcps",pI="tools",fI="~staging",mI="~prev",gI=[25,50,100,200],wI=new Set(["EPERM","EBUSY","EACCES"]),yI=new Map;function vI(e){return e.slice(0,e.indexOf("~"))}function bI(e,t){return`${e}~${Date.now()}-${process.pid}-${(0,wo.randomBytes)(4).toString("hex")}${t}`}const SI=/~(\d+)-\d+-[0-9a-f]+~(?:staging|prev)$/;async function kI(e,t){const r=SI.exec(t),n=r?Number(r[1]):0;try{const{mtimeMs:r}=await(0,So.stat)((0,s.join)(e,t));return Date.now()-Math.max(n,r)>6e4}catch{return!1}}const _I="mcp_auth",CI="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.",EI="# >>> CURSOR MANAGED BLOCK >>>",xI="# <<< CURSOR MANAGED BLOCK <<<",PI=["# 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 RI(e,t,r=15e3){let n;return Promise.race([e.catch((()=>t)),new Promise((e=>{n=setTimeout((()=>e(t)),r)}))]).finally((()=>clearTimeout(n)))}function II(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_")}function TI(e){if(void 0===e)return;const t=e.trim();return t.length>0?t:void 0}function AI(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 $I(e){if(Array.isArray(e))return e.map((e=>$I(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,$I(t)]));return Object.fromEntries(t)}return e}function MI(e){return JSON.stringify($I(e))}function DI(e){const t=e.map((e=>({value:e,key:MI(e)})));return t.sort(((e,t)=>e.key<t.key?-1:e.key>t.key?1:0)),t.map((e=>e.value))}function OI(e){const t=DI(e.tools.map((e=>({name:e.toolName,description:e.description,inputSchema:e.inputSchema,outputSchema:e.outputSchema})))),r=DI(e.resources.map((e=>({uri:e.uri,name:e.name,description:e.description,mimeType:e.mimeType})))),n=DI(e.prompts.map((e=>({name:e.name,description:e.description,arguments:e.arguments}))));return MI({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 FI{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=>{dI.info(this.ctx,"Lease change event received",{serverIdentifiers:e?.serverIdentifiers,reason:e?.reason}),this.onLeaseChanged(this.ctx,e)})),dI.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=`${EI}\n${PI}\n${xI}\n`;let n;await(0,So.mkdir)(e,{recursive:!0});try{n=await(0,So.readFile)(t,"utf-8")}catch(e){if("ENOENT"!==yc(e))throw e}if(void 0===n)return void await(0,So.writeFile)(t,r);const o=n.indexOf(EI),i=n.indexOf(xI,o+30);if(-1===o||-1===i)await(0,So.writeFile)(t,r);else{const e=`${n.slice(0,o)}${r}${n.slice(i+30).replace(/^\n/,"")}`;e!==n&&await(0,So.writeFile)(t,e)}})((0,s.join)((0,o.homedir)(),".cursor")).catch((e=>{dI.warn(this.ctx,"Failed to ensure ~/.cursor/.gitignore",e)}))}async cleanupStaleStagingDirs(e){const t=this.getLogContext(e),r=(0,s.join)(this.projectDir,hI);try{const e=await(0,So.readdir)(r);await Promise.allSettled(e.filter((e=>e.endsWith(fI))).map((async e=>{await kI(r,e)&&await(0,So.rm)((0,s.join)(r,e),{recursive:!0,force:!0})})))}catch(e){"ENOENT"!==yc(e)&&dI.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:Xn(r)?{serverIdentifiers:void 0,reason:t?.reason??r?.reason}:void 0===t?r:Xn(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){dI.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,b.q6)();return e&&(t=t.with(d._O,e)),t}getLogContext(e){return e.with(d._O,this.ctx.get(d._O))}getMetricTags(e){return{...e,mcp_version:this.mcpVersion}}getMcpAuthToolDescription(){return TI(this.mcpAuthCopyOverrides?.authToolDescription)??CI}shouldExposeVirtualMcpAuthToolForStatus(e,t){return this.exposeVirtualMcpAuthTool&&Gn(e)&&(this.alwaysExposeVirtualMcpAuthTool||"needsAuth"===t)}getErrorStatusMessage(){return TI(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=TI(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:_I},t.replace(/\{serverIdentifier\}/g,r.serverIdentifier).replace(/\{authToolName\}/g,r.authToolName);var t,r}getNeedsAuthStatusMessageForWrite(e){return this.exposeVirtualMcpAuthTool&&Gn(e)?this.getNeedsAuthStatusMessage(e):TI(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){dI.warn(r,`getToolsForServers() threw, falling back to filtered getTools(): ${vc(n)}`);const o=await this.mcpLease.getTools(e).catch((e=>(dI.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 RI(r.getState(e),{kind:"error"}).then((r=>("error"!==r.kind||"message"in r||dI.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?RI(r.listResources(e),{resources:[]}):Promise.resolve({resources:[]}),s?RI(r.listPrompts(e),[]):Promise.resolve([]),s&&n?.fetchInstructions?RI(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:AI(o)}}buildServerDataMap(e,t,r){const n=new Map;for(const e of t){const t=ry(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,hI,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=ry(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,hI,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===_I))||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:_I,name:_I,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)?dI.warn(e,`Skipping server "${o.serverIdentifier}" — sanitizedId "${o.sanitizedId}" collides with another server`):(n.add(o.sanitizedId),r.push(o)):dI.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===_I))){const t=e.tools.find((e=>e.toolName===_I));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??[])];dI.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=>(dI.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 dI.warn(r,`getClient("${t}") threw during scoped refresh, preserving cached data: ${vc(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=>{dI.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):dI.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)),dI.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=ry(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{eI(r,(0,D.VI)(e.withName("McpFileSystemWriter.fetchAndWrite")),!1);const n=this.getLogContext(e);try{if(void 0!==this.cachedServerData&&void 0!==t&&!Xn(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=>(dI.warn(n,`getTools() threw, defaulting to []: ${e}`),[]))),this.mcpLease.getInstructions(e).catch((()=>[])),this.mcpLease.getClients(e).catch((e=>(dI.warn(n,`getClients() threw, defaulting to {}: ${e}`),{})))]),i=Object.keys(s);dI.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){dI.error(n,"Error fetching/writing MCP state",e)}}catch(e){r.error=e,r.hasError=!0}finally{tI(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,pI,`${II(t.toolName)}.json`)})))})));this.onDidWrite(t)}catch{}}async writeServerData(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{eI(n,(0,D.VI)(e.withName("McpFileSystemWriter.writeServerData")),!1);const o=this.getLogContext(e),i=(0,s.join)(this.projectDir,hI);await(0,So.mkdir)(i,{recursive:!0});const a=new Map;for(const e of t)try{a.set(e.serverIdentifier,OI(e))}catch(t){dI.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&&dI.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,So.stat)((0,s.join)(i,e.sanitizedId))}catch{dI.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??ry(e);r.has(n)?(dI.info(o,`Server "${e}" (sanitized="${n}") still in lease but excluded from write, preserving directory`),a.set(e,this.cachedFingerprints.get(e))):(dI.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,So.readdir)(i),t=new Set(e.filter((e=>!e.endsWith(fI)&&!e.endsWith(mI))));for(const r of e){const e=r.endsWith(fI),n=r.endsWith(mI);if((e||n)&&await kI(i,r))if(e)await(0,So.rm)((0,s.join)(i,r),{recursive:!0,force:!0});else{const e=vI(r);if(t.has(e))await(0,So.rm)((0,s.join)(i,r),{recursive:!0,force:!0});else try{await(0,So.rename)((0,s.join)(i,r),(0,s.join)(i,e)),t.add(e)}catch{await(0,So.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){dI.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})));dI.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,wo.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),dI.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,So.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];dI.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{tI(n)}}async writeServerAtomic(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{eI(n,(0,D.VI)(e.withName("McpFileSystemWriter.writeServerAtomic")),!1);const o=(0,s.join)(r,t.sanitizedId),i=yI.get(o),a=(async()=>{await(i?.catch((()=>{}))),await this.swapServerDirectory(e,t,r)})();yI.set(o,a);try{await a}finally{yI.get(o)===a&&yI.delete(o)}}catch(e){n.error=e,n.hasError=!0}finally{tI(n)}}async swapServerDirectory(e,t,r){const n=bI(t.sanitizedId,fI),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,So.rm)(o,{recursive:!0,force:!0}).catch((()=>{})),e}const a=(0,s.join)(r,bI(t.sanitizedId,mI));let c=!1;try{try{await this.renameWithRetry(i,a),c=!0}catch(e){if("ENOENT"!==yc(e))throw e}await this.renameWithRetry(o,i)}catch(r){if(dI.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,So.stat)(i).then((()=>!0),(()=>!1))&&await(0,So.rm)(a,{recursive:!0,force:!0}).catch((()=>{}))}throw await(0,So.rm)(o,{recursive:!0,force:!0}).catch((()=>{})),r}await(0,So.rm)(a,{recursive:!0,force:!0}).catch((()=>{}))}async renameWithRetry(e,t){for(let r=0;;r++)try{return void await(0,So.rename)(e,t)}catch(e){const t=yc(e);if(r>=gI.length||void 0===t||!wI.has(t))throw e;await(0,Fr.cb)(gI[r])}}async writeServerDirectory(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{eI(n,(0,D.VI)(e.withName("McpFileSystemWriter.writeServerDirectory")),!1);const o=(0,s.join)(r.basePath,r.dirName??t.sanitizedId);await(0,So.mkdir)(o,{recursive:!0});const i=[];if(t.tools.length>0){const e=(0,s.join)(o,pI);await(0,So.mkdir)(e,{recursive:!0});for(const r of t.tools){const t=II(r.toolName);i.push({path:(0,s.join)(e,`${t}.json`),content:JSON.stringify(Jn(r),null,2)})}}if(t.resources.length>0){const e=(0,s.join)(o,"resources");await(0,So.mkdir)(e,{recursive:!0});for(const r of t.resources){const t=II(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,So.mkdir)(e,{recursive:!0});for(const r of t.prompts){const t=II(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,So.writeFile)(e.path,e.content);return}const c=(await(0,Fr.up)(i,(e=>(0,So.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{tI(n)}}async getMcpFileSystemOptions(e,t){const r={stack:[],error:void 0,hasError:!1};try{if(this.disposed)return;eI(r,(0,D.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&&dI.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=II(t.toolName),n=(0,s.join)(e.folderPath,pI,`${r}.json`);return new gn.E$({toolName:t.toolName,definitionPath:n,...rb(t.annotations)})}));return new gn.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 gn.Is({enabled:!0,workspaceProjectDir:this.projectDir,mcpDescriptors:i})}catch(e){r.error=e,r.hasError=!0}finally{tI(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&&dI.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){dI.error(r,"Error waiting for pending write to complete",e)}finally{clearTimeout(e)}return n&&dI.warn(r,`getMcpFileSystemOptions timed out after ${t}ms waiting for write; returning stale cache`),n}try{await this.writePromise}catch(e){dI.error(r,"Error waiting for pending write to complete",e)}return!1}async buildOptionsFromSnapshots(e){const t={stack:[],error:void 0,hasError:!1};try{eI(t,(0,D.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,hI),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=ry(e.serverIdentifier),r=(0,s.join)(i,t),n=e.tools.map((e=>{const t=II(e.name);return new gn.E$({toolName:e.name,definitionPath:(0,s.join)(r,pI,`${t}.json`),...rb(e.annotations)})}));if(this.shouldExposeVirtualMcpAuthToolForStatus(e.serverIdentifier,e.status)&&!e.tools.some((e=>e.name===_I))){const e=II(_I);n.push(new gn.E$({toolName:_I,definitionPath:(0,s.join)(r,pI,`${e}.json`)}))}return new gn.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 dI.info(r,`buildOptionsFromSnapshots completed in ${Date.now()-n}ms: ${o.length} snapshots, ${a.length} descriptors, ${c} tools`),this.checkDescriptorsVsFilesystem(e,a,"snapshot"),new gn.Is({enabled:!0,workspaceProjectDir:this.projectDir,mcpDescriptors:a})}catch(e){t.error=e,t.hasError=!0}finally{tI(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<FI.DIVERGENCE_CHECK_COOLDOWN_MS||(this.lastDivergenceCheckMs=o,this._checkDescriptorsVsFilesystemAsync(e,t,r).catch((e=>{dI.warn(n,"Divergence check failed",e)})))}async _checkDescriptorsVsFilesystemAsync(e,t,r){const n=this.getLogContext(e),o=(0,s.join)(this.projectDir,hI),i=new Set,a=new Map;for(const e of t){const t=ry(e.serverIdentifier);i.add(t),a.set(t,e.tools.length)}let c=[];try{c=await(0,So.readdir)(o),c=c.filter((e=>!e.endsWith(fI)&&!e.endsWith(mI)))}catch(e){if("ENOENT"!==yc(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++,rI.increment(e,1,this.getMetricTags({divergence_type:"server_missing",mcp_source:r,configured_servers:f})),dI.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++,rI.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,pI);let h=0;try{h=(await(0,So.readdir)(d)).filter((e=>e.endsWith(".json"))).length}catch{}h!==c&&(u=!1,p++,rI.increment(e,1,this.getMetricTags({divergence_type:"tool_count_mismatch",mcp_source:r,configured_servers:f})),dI.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}))}nI.increment(e,1,this.getMetricTags({synced:String(u),mcp_source:r,configured_servers:f})),oI.gauge(e,i.size,this.getMetricTags({mcp_source:r})),sI.gauge(e,l.size,this.getMetricTags({mcp_source:r})),iI.gauge(e,d,this.getMetricTags({mcp_source:r})),aI.gauge(e,p,this.getMetricTags({mcp_source:r})),dI.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||dI.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())}}FI.DIVERGENCE_CHECK_COOLDOWN_MS=1e4;var NI=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},LI=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 jI(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 UI=(0,d.h)("local-exec:mcp");function BI(e,t){const r=s.relative(e,t);return""===r||!s.isAbsolute(r)&&".."!==r&&!r.startsWith(`..${s.sep}`)}function WI(e){return e instanceof Error&&"code"in e&&"string"==typeof e.code?e.code:void 0}function HI(e){return new Rc._Z({content:{case:"image",value:new Rc.do({data:e.data,mimeType:e.mimeType})}})}function qI(e){return new Rc._Z({content:{case:"text",value:new Rc.zN({text:e})}})}async function zI(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 Wu(n,{onNeedsApproval:async(e,n)=>{if("mcp"!==n.type)return new Rc.iz({result:{case:"error",value:new Rc.Nh({error:"Invalid approval details type for MCP execution"})}});const o=await r.pendingDecisionProvider.requestApproval({type:aw.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 Rc.iz({result:{case:"approved",value:new Rc.Ke}}):null:new Rc.iz({result:{case:"rejected",value:new Rc.xo({reason:`User rejected MCP: ${t.name}${o.reason?` - ${o.reason}`:""}`})}})},onUserRejected:e=>new Rc.iz({result:{case:"error",value:new Rc.Nh({error:`User rejected MCP: ${t.name}${e?` - ${e}`:""}`})}}),onPermissionDenied:(e,r)=>GI({name:t.name,reason:e,isReadonly:r?.isReadonly??!1})});return o??void 0}function GI({name:e,reason:t,isReadonly:r}){return new Rc.iz({result:{case:"permissionDenied",value:new Rc.HQ({error:`MCP tool execution blocked: ${e} - ${t}`,isReadonly:r})}})}class VI{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}}(Qn(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=NI(r,(0,D.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 Rc.iz({result:{case:"error",value:new Rc.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 zI(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 B_(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 UI.warn(o,"Refusing an MCP tool whose client was not judged",{toolName:t.toolName,toolSetNamesClients:void 0!==m.executeOn}),GI({name:t.name,reason:ES,isReadonly:!1});w=n}else w=await m.execute(e,r,t.toolCallId,this.elicitationFactory)}catch(e){let r=e;if(W_(r)&&t.providerIdentifier.length>0&&!a.some((e=>e.clientKey===t.providerIdentifier||e.providerIdentifier===t.providerIdentifier))&&(r=new bR(t.providerIdentifier,c)),r instanceof bR){const e=await this.describeDisconnectedServer(o,[i,t.providerIdentifier]);return void 0!==e?new Rc.iz({result:{case:"error",value:new Rc.Nh({error:e})}}):new Rc.iz({result:{case:"serverNotFound",value:new Rc.JL({name:r.serverName,availableServers:r.availableServers})}})}if(W_(r))return new Rc.iz({result:{case:"toolNotFound",value:new Rc.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(qI(e.text));else if("resource"===r){const r=EC(e),n=void 0===r?void 0:Buffer.from(r,"base64"),s=void 0===n?void 0:await av(n).then(HI,(e=>{UI.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??qI(xC(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 av(s)}catch(e){UI.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(qI(`[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(HI(i))}else if("image"!==r){const t=xC(e);y.push(qI(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 Rc._Z({content:{case:"text",value:new Rc.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.join(t,Ic),n=s.join(r,`${(0,wo.randomUUID)()}.txt`);await(0,So.mkdir)(s.dirname(n),{recursive:!0});const o=qo(e,Tc),i=Gs(o),a=Buffer.byteLength(o,"utf8");return await(0,So.writeFile)(n,o,"utf8"),new Ac.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)?ve.Struct.fromJson(w.structuredContent):void 0,S=new Rc.QW({content:v,isError:w.isError,structuredContent:b,resultMeta:void 0===w._meta?void 0:ve.Struct.fromJson(w._meta)});return new Rc.iz({result:{case:"success",value:S}})}catch(e){r.error=e,r.hasError=!0}finally{LI(r)}var n}}class KI{constructor(e,t){this.mcpLease=e,this.ensureMcpServersLoaded=t}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=NI(r,(0,D.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 Rc.kP({result:{case:"error",value:new Rc.w2({error:`Server "${t.server}" not found`})}});const o=await this.listResourcesFromClient(n,r,t.server,!0);return new Rc.kP({result:{case:"success",value:new Rc.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 Rc.kP({result:{case:"success",value:new Rc.T2({resources:s})}})}catch(e){const t=e instanceof Error?e.message:String(e);return new Rc.kP({result:{case:"error",value:new Rc.w2({error:`Failed to list MCP resources: ${t}`})}})}}catch(e){r.error=e,r.hasError=!0}finally{LI(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 Rc.X2({uri:e.uri,name:e.name,description:e.description,mimeType:e.mimeType,server:r,annotations:jI(e.annotations)}))):[]}}class JI{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(QR),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=NI(r,(0,D.VI)(e.withName("LocalReadMcpResourceExecutor.execute")),!1).ctx,o=t.smartModeApproval?.reason;if(void 0!==o){if(void 0===this.pendingDecisionProvider)return new Rc.ZD({result:{case:"error",value:new Rc.Jx({uri:t.uri,error:"Auto-review approval provider is not configured"})}});const e=await this.pendingDecisionProvider.requestApproval({type:aw.Mcp,details:{name:"FetchMcpResource",toolName:"FetchMcpResource",providerIdentifier:t.server,args:{server:ve.Value.fromJson(t.server),uri:ve.Value.fromJson(t.uri),...void 0!==t.downloadPath?{downloadPath:ve.Value.fromJson(t.downloadPath)}:{}},reason:"smartMode",canAllowlist:!1,smartModeApprovalReason:o,smartModeApprovalRequestId:t.smartModeApproval?.requestId},toolCallId:t.toolCallId});if(!e.approved)return new Rc.ZD({result:{case:"rejected",value:new Rc.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 Rc.ZD({result:{case:"error",value:new Rc.Jx({uri:t.uri,error:`Server "${t.server}" not found`})}});try{if("ready"!==(await a.getState(n)).kind)return new Rc.ZD({result:{case:"error",value:new Rc.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 Rc.ZD({result:{case:"notFound",value:new Rc.ov({uri:t.uri})}});const r=e.contents[0];if(t.downloadPath){const e=await async function(e,t){const r=s.resolve(e),n=await(0,So.realpath)(r),o=s.isAbsolute(t)?s.resolve(t):s.resolve(r,t),i=BI(r,o),a=s.isAbsolute(t)&&BI(n,o);if(!i&&!a)throw new Error("downloadPath must stay within the workspace");let c=s.dirname(o);for(;;)try{if(!BI(n,await(0,So.realpath)(c)))throw new Error("downloadPath must stay within the workspace");break}catch(e){if("ENOENT"!==WI(e))throw e;const t=s.dirname(c);if(t===c)throw e;c=t}try{if((await(0,So.lstat)(o)).isSymbolicLink())throw new Error("downloadPath must stay within the workspace")}catch(e){if("ENOENT"!==WI(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 YR.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 Rc.ZD({result:{case:"rejected",value:new Rc.Dh({uri:t.uri,reason:s.result.value.reason})}});if("success"!==s.result.case)return new Rc.ZD({result:{case:"error",value:new Rc.Jx({uri:t.uri,error:ZI(s)})}});o=s.result.value.path}return new Rc.ZD({result:{case:"success",value:new Rc.KZ({uri:t.uri,name:r.name,description:r.description,mimeType:r.mimeType,downloadPath:o})}})}if(r.text)return new Rc.ZD({result:{case:"success",value:new Rc.KZ({uri:t.uri,name:r.name,description:r.description,mimeType:r.mimeType,annotations:jI(r.annotations),metaJson:Kn(r._meta),content:{case:"text",value:r.text}})}});if(r.blob){const e=Buffer.from(r.blob,"base64");return new Rc.ZD({result:{case:"success",value:new Rc.KZ({uri:t.uri,name:r.name,description:r.description,mimeType:r.mimeType,annotations:jI(r.annotations),metaJson:Kn(r._meta),content:{case:"blob",value:e}})}})}return new Rc.ZD({result:{case:"error",value:new Rc.Jx({uri:t.uri,error:"Failed to read resource"})}})}catch(e){const r=e instanceof Error?e.message:String(e);return UI.warn(n,"LocalReadMcpResourceExecutor.execute failed",{server:t.server,hasDownloadPath:Boolean(t.downloadPath),errorName:e instanceof Error?e.name:typeof e,errorMessage:r}),new Rc.ZD({result:{case:"error",value:new Rc.Jx({uri:t.uri,error:`Failed to read MCP resource: ${r}`})}})}}catch(e){r.error=e,r.hasError=!0}finally{LI(r)}}}function ZI(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 XI=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 QI=1e4,YI=5e3,eT={PAGER:"cat",MANPAGER:"cat",LESS:"-R",PIP_PROGRESS_BAR:"off",TQDM_DISABLE:"1"};class tT{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<YI&&(this.outputHead=qo(this.outputHead+e,YI)),this.outputTail=zo(this.outputTail+e,YI),t<QI){const r=Math.min(e.length,QI-t);this.fullOutput+=e.slice(0,r)}this.totalChars>QI&&(this.fullOutput="")}getOutput(){return this.totalChars<=QI?this.fullOutput:void 0}getTruncation(){if(!(this.totalChars<=QI))return{outputHead:this.outputHead,outputTail:this.outputTail,elidedChars:this.totalChars-this.outputHead.length-this.outputTail.length}}}class rT{constructor(){this.kept="",this.full=!1}append(e){if(this.full)return;const t=Yo-this.kept.length;this.full=e.length>=t,this.kept+=qo(e,t)}get text(){return this.kept}}function nT(e,t){return null!==e?e:null===t?-1:-o.constants.signals[t]}class oT{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 fe.xC({...o,aborted:s,abortReason:r.abortReason})}:{case:"success",value:new fe.QR(o)};return new fe.W4({result:i,sandboxPolicy:as(n)})}async runProcess({ctx:e,args:t,workingDirectory:r,sandboxPolicy:n,timeoutMs:o}){const s=performance.now(),i=this.defaultCwd,a=(await(0,$o.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 tT,a=new rT,l=new rT;let u,d,h=!1,p=!1,f="",m=()=>{};const g=(0,$o.Qw)((0,$o.ue)((0,$o.Xw)({...process.env,...eT,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,Jl.D9)(Kl.spawn,y.executable,y.args,w):(0,$o.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:ty(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=fe.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=fe.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:nT(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,D.VI)(e.withName("LocalMiniSweAgentBashExecutor.execute")),!1).ctx;(0,D.HF)(n,"LocalMiniSweAgentBashExecutor.execute");const o=t.command,s=(0,Zo.o1)(t.workingDirectory||this.defaultCwd),i=t.timeout>0?t.timeout:3e4;if(!t.parsingResult)return new fe.W4({result:{case:"spawnError",value:new fe.mJ({command:o,workingDirectory:s,error:"Parsing result is required"})}});let a=t.requestedSandboxPolicy?is(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 fe.W4({result:{case:"permissionDenied",value:new fe.jn({command:o,workingDirectory:s,error:"Command blocked by permissions configuration",isReadonly:!0})}}):new fe.W4({result:{case:"rejected",value:new fe.pZ({command:o,workingDirectory:s,reason:Hu(c.reason)})}});a=c.policy,Is()&&(a=Os(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{XI(r)}}}const sT=G("shell-executor",(e=>new H(e,Q("shellArgs"),Y("shellResult"))),((e,t)=>{t.register(new A(e,te("shellArgs"),ee("shellResult")))})),iT=G("mini-swe-agent-bash-executor",(e=>new H(e,Q("miniSweAgentBashArgs"),Y("miniSweAgentBashResult"))),((e,t)=>{t.register(new A(e,te("miniSweAgentBashArgs"),ee("miniSweAgentBashResult")))}));function aT(e){return`${e} changed on disk after this tool call read it. Nothing was written. Read the file again and retry.`}function cT(e){return`${e} changed on disk after you last read or wrote it. Nothing was written. Read the file again and retry.`}(0,b.cF)(Symbol("optionalPendingPodWrite"),!1);const lT=G("write-executor",(e=>new H(e,Q("writeArgs"),Y("writeResult"))),((e,t)=>{t.register(new A(e,te("writeArgs"),ee("writeResult")))})),uT=G("delete-executor",(e=>new H(e,Q("deleteArgs"),Y("deleteResult"))),((e,t)=>{t.register(new A(e,te("deleteArgs"),ee("deleteResult")))})),dT=G("fetch-executor",(e=>new H(e,Q("fetchArgs"),Y("fetchResult"))),((e,t)=>{t.register(new A(e,te("fetchArgs"),ee("fetchResult")))})),hT=G("git-diff-executor",(e=>new H(e,Q("gitDiffRequest"),Y("gitDiffResponse"))),((e,t)=>{t.register(new A(e,te("gitDiffRequest"),ee("gitDiffResponse")))})),pT=G("grep-executor",(e=>new H(e,Q("grepArgs"),Y("grepResult"))),((e,t)=>{t.register(new A(e,te("grepArgs"),ee("grepResult")))})),fT="[REDACTED]",mT=new TextEncoder;async function gT(e){const t=mT.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 wT{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 gT(t.output.value),o=t.clone();return o.output={case:void 0},o.outputBlobId=void 0,o.sha256=r,o.sizeBytes=BigInt(n),new wy.sV({result:{case:"success",value:o}})}(await this.inner.execute(e,n,r))}}const yT=G("read-executor",(e=>new H(e,Q("readArgs"),Y("readResult"))),((e,t)=>{t.register(new A(e,te("readArgs"),ee("readResult")))})),vT=G("redacted-read-executor",(e=>new H(e,Q("redactedReadArgs"),Y("redactedReadResult"))),((e,t)=>{t.register(new A(e,te("redactedReadArgs"),ee("redactedReadResult")))})),bT=G("ls-executor",(e=>new H(e,Q("lsArgs"),Y("lsResult"))),((e,t)=>{t.register(new A(e,te("lsArgs"),ee("lsResult")))})),ST=G("diagnostics-executor",(e=>new H(e,Q("diagnosticsArgs"),Y("diagnosticsResult"))),((e,t)=>{t.register(new A(e,te("diagnosticsArgs"),ee("diagnosticsResult")))})),kT=G("canvas-diagnostics-executor",(e=>new H(e,Q("canvasDiagnosticsArgs"),Y("canvasDiagnosticsResult"))),((e,t)=>{t.register(new A(e,te("canvasDiagnosticsArgs"),ee("canvasDiagnosticsResult")))})),_T="$file:";const CT=(0,h.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"]}),ET=(0,h.v5)("mcp.symbolic_args.bytes",{description:"Total bytes substituted into one MCP tool call by $file:/abs/path arguments",labelNames:["route"]}),xT=(0,h.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"]}),PT=(0,h.v5)("mcp.symbolic_args.paths",{description:"Number of distinct $file:/abs/path arguments expanded in one MCP tool call",labelNames:["route"]});function RT(e,t,r){return{kind:e,message:`Could not resolve the symbolic argument "${_T}${t}": ${r} A string argument of the form "${_T}/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 IT={redacted:e=>`${e} contains a saved secret, and a saved secret is never sent through a "${_T}/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 "${fT}", 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 TT(e,t){return{kind:e,message:`Could not resolve the symbolic argument "${_T}${t}": ${IT[e](t)}`}}class AT extends Error{constructor(e){super(e.message),this.failure=e}}let $T;async function MT(e,t,r,n,o,{maxFileBytes:s=8388608,maxTotalBytes:i=16777216,refuseSavedSecrets:a=!1}){if(t.length>4)throw new AT(RT("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 AT(RT("no_read_executor",t[0]??"","this environment cannot read files on behalf of a tool call."));const l=await(0,Fr.xb)(t,(t=>async function(e,t,r,n,o){const s=await t.execute(e,new wy.a2({path:r,toolCallId:n,...o.digestOnly?{digestOnly:!0}:{}}));if("success"!==s.result.case)throw new AT(function(e,t,r){switch(e.result.case){case"fileNotFound":return RT("not_found",t,"the file does not exist.");case"permissionDenied":return RT("permission_denied",t,"reading it was not permitted.");case"rejected":return RT("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 RT("not_text",t,"the file cannot be read as text.");case"error":return r?{kind:"read_error",message:`Could not resolve the symbolic argument "${_T}${t}": ${e.result.value.error}`}:RT("read_error",t,e.result.value.error);default:return RT("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 AT(RT("not_text",r,"the file is not a text file."));if(n){if(xT.increment(e,1,{source:void 0!==o?"vm_digest":"outdated_executor"}),void 0===o)throw new AT(RT("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 gT(a??""),u={content:a,bytes:l,sha256:c};if(t.truncated||l>n)throw new AT(RT("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 AT(TT("redacted",r));if(void 0===e.redacted&&await async function(e){return void 0!==e.content?e.content.includes(fT):(await($T??=Promise.all([fT,`${fT}\n`,`${fT}\r\n`].map((async e=>(await gT(e)).sha256))).then((e=>new Set(e))),$T)).has(e.sha256)}(t))throw new AT(TT("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 AT(RT("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 DT(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=>(CT.increment(e,1,{route:r,outcome:t.kind}),{kind:"failed",failure:t,result:new Rc.iz({result:{case:"error",value:new Rc.Nh({error:t.message})}})});let c;try{c=await MT(e,i,n,t.toolCallId,!1,o)}catch(e){return a(function(e,t){return e instanceof AT?e.failure:RT("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(RT("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(_T))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,ve.Value.fromJson(t)]))),h.symbolicPathArguments=[],h.argumentsRepaired=!1,CT.increment(e,1,{route:r,outcome:"expanded"}),ET.record(e,l,{route:r}),PT.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 OT=/\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 FT(e,t,r,n){return OT.test(t)?(CT.increment(e,1,{route:n,outcome:"server_rejected_body"}),`${t}\n\nThe request carried ${r.bytes} bytes of file contents substituted from ${r.paths} "${_T}/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 NT(e){return e.files.map((e=>`"${_T}${e.path}" was replaced with the contents of ${e.path} (${e.bytes} bytes) before the call.`)).join("\n")}class LT{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 DT(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=FT(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 Rc._Z({content:{case:"text",value:new Rc.zN({text:NT(r)})}})):"error"===n.result.case&&(n.result.value.error=FT(e,n.result.value.error,r,"local")),n}(e,o,n.expansion)}}const jT=G("background-shell-executor",(e=>new H(e,Q("backgroundShellSpawnArgs"),Y("backgroundShellSpawnResult"))),((e,t)=>{t.register(new A(e,te("backgroundShellSpawnArgs"),ee("backgroundShellSpawnResult")))})),UT=G("write-background-shell-input-executor",(e=>new H(e,Q("writeShellStdinArgs"),Y("writeShellStdinResult"))),((e,t)=>{t.register(new A(e,te("writeShellStdinArgs"),ee("writeShellStdinResult")))})),BT=G("agent-store-conflict-executor",(e=>new H(e,Q("agentStoreConflictArgs"),Y("agentStoreConflictResult"))),((e,t)=>{t.register(new A(e,te("agentStoreConflictArgs"),ee("agentStoreConflictResult")))})),WT=G("shell-allowlist-precheck-executor",(e=>new H(e,Q("shellAllowlistPrecheckArgs"),Y("shellAllowlistPrecheckResult"))),((e,t)=>{t.register(new A(e,te("shellAllowlistPrecheckArgs"),ee("shellAllowlistPrecheckResult")))})),HT=G("mcp-allowlist-precheck-executor",(e=>new H(e,Q("mcpAllowlistPrecheckArgs"),Y("mcpAllowlistPrecheckResult"))),((e,t)=>{t.register(new A(e,te("mcpAllowlistPrecheckArgs"),ee("mcpAllowlistPrecheckResult")))})),qT=G("web-fetch-allowlist-precheck-executor",(e=>new H(e,Q("webFetchAllowlistPrecheckArgs"),Y("webFetchAllowlistPrecheckResult"))),((e,t)=>{t.register(new A(e,te("webFetchAllowlistPrecheckArgs"),ee("webFetchAllowlistPrecheckResult")))})),zT=G("force-background-shell-executor",(e=>new H(e,Q("forceBackgroundShellArgs"),Y("forceBackgroundShellResult"))),((e,t)=>{t.register(new A(e,te("forceBackgroundShellArgs"),ee("forceBackgroundShellResult")))})),GT=G("computer-use-executor",(e=>new H(e,Q("computerUseArgs"),Y("computerUseResult"))),((e,t)=>{t.register(new A(e,te("computerUseArgs"),ee("computerUseResult")))})),VT=G("record-screen-executor",(e=>new H(e,Q("recordScreenArgs"),Y("recordScreenResult"))),((e,t)=>{t.register(new A(e,te("recordScreenArgs"),ee("recordScreenResult")))}));var KT=r("../proto/dist/generated/agent/v1/agent_store_conflict_exec_pb.js");function JT(e){if(void 0!==e)return{journalEpoch:e.journalEpoch,seq:Number(e.seq),lastEventId:e.lastEventId}}class ZT{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:JT(t.cursor),advance:!1!==t.advance});return new KT.Ev({result:{case:"success",value:new KT.iS({events:e.events.map((e=>new KT.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 KT.LK({journalEpoch:r.journalEpoch,seq:BigInt(r.seq),lastEventId:r.lastEventId})),gap:e.gap})}})}catch(e){return new KT.Ev({result:{case:"error",value:new KT.h6({error:e instanceof Error?e.message:String(e)})}})}var r}}class XT{constructor(e){this.shellStdinWriter=e}async execute(e,t){const r=t.shellId;try{await this.shellStdinWriter(r,t.chars)}catch(e){return new Ao.nt({result:{case:"error",value:new Ao.Gv({error:`Failed to write to shell ${r} stdin: ${e instanceof Error?e.message:"Unknown error"}`})}})}return new Ao.nt({result:{case:"success",value:new Ao.tR({shellId:r,terminalFileLengthBeforeInputWritten:0})}})}}var QT=r("../proto/dist/generated/agent/v1/canvas_diagnostics_exec_pb.js"),YT=r("../proto/dist/generated/agent/v1/diagnostics_exec_pb.js");class eA{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"),tA(rA(t.path,"diagnostics unavailable"),await o)):(r(e.some((e=>1===e.severity))?"failed":"passed"),tA(new QT.GL({result:{case:"success",value:new QT.uX({path:t.path,diagnostics:e.map(nA)})}}),await o))}catch(e){return r("unavailable"),tA(rA(t.path,e instanceof Error?e.message:String(e)),await o)}}}function tA(e,t){return void 0===t||(e.saveState=t.saveState,e.canvasId=t.canvasId,e.title=t.title,e.saveDetail=t.saveDetail),e}function rA(e,t){return new QT.GL({result:{case:"error",value:new QT.HW({path:e,error:t})}})}function nA(e){return new YT.oQ({severity:oA(e.severity),range:new Ac.Q6({start:new Ac.yX({line:e.range.start.line+1,column:e.range.start.character+1}),end:new Ac.yX({line:e.range.end.line+1,column:e.range.end.character+1})}),message:e.message,source:"ts",code:e.code??""})}function oA(e){switch(e){case 1:return YT.h_.ERROR;case 2:return YT.h_.WARNING;case 3:return YT.h_.INFORMATION;case 4:return YT.h_.HINT;default:return YT.h_.UNSPECIFIED}}class sA{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 sA(e)}static fromUrl(e){if(!e.startsWith("file://"))throw new Error(`Expected file:// URL, got: ${e}`);return new sA(e)}static fromString(e){return new sA(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 iA=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 aA{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,D.VI)(e.withName("LocalDiagnosticsExecutor.execute")),!1),[e,n]=e.withTimeoutAndCancel(1e4);try{const r=(0,Zo.o1)(t.path,this.workspacePath);try{const e=await(0,So.stat)(r);if(!e.isFile()&&!e.isDirectory())return new YT.Ek({result:{case:"fileNotFound",value:new YT.Mu({path:t.path})}})}catch(e){if("ENOENT"===yc(e))return new YT.Ek({result:{case:"fileNotFound",value:new YT.Mu({path:t.path})}});if("EACCES"===yc(e))return new YT.Ek({result:{case:"permissionDenied",value:new YT.RP({path:t.path})}});throw e}const n=(0,Zo.o1)(r,this.workspacePath),o=new sA(n);await this.diagnosticsProvider.open(e,o);const s=(await this.diagnosticsProvider.getDiagnostics(e,o)).map((e=>this.convertDiagnostic(e)));return new YT.Ek({result:{case:"success",value:new YT.a1({path:t.path,diagnostics:s,totalDiagnostics:s.length})}})}catch(r){return e.canceled?new YT.Ek({result:{case:"error",value:new YT.Ho({path:t.path,error:"Request timed out after 10 seconds"})}}):new YT.Ek({result:{case:"error",value:new YT.Ho({path:t.path,error:r instanceof Error?r.message:String(r)})}})}finally{n()}}catch(e){r.error=e,r.hasError=!0}finally{iA(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 YT.oQ({severity:this.convertSeverity(e.severity),range:e.range?new Ac.Q6({start:new Ac.yX({line:e.range.start.line,column:e.range.start.character}),end:new Ac.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 YT.h_.ERROR;case 2:return YT.h_.WARNING;case 3:return YT.h_.INFORMATION;case 4:return YT.h_.HINT;default:return YT.h_.UNSPECIFIED}}}async function cA(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 Ww().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 lA(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 lA(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 lA{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 uA=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]=pA(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=mA(e)}],[/^\+\+\+\s/,e=>{u(),n.to=mA(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},dA=/(a|i|w|c|o|1|2)\/.*(?=["']? ["']?(b|i|w|c|o|1|2)\/)|(b|i|w|c|o|1|2)\/.*$/g,hA=/^(a|b|i|w|c|o|1|2)\//,pA=e=>{const t=e?.match(dA);return t?.map((e=>e.replace(hA,"").replace(/("|')$/,"")))},fA=/^\\?['"]|\\?['"]$/g,mA=e=>{let t=gA(e,"-+").trim();return t=yA(t),t.replace(fA,"").replace(hA,"")},gA=(e,t)=>{if(e=bA(e),!t&&String.prototype.trimLeft)return e.trimLeft();const r=vA(t);return e.replace(new RegExp(`^${r}+`),"")},wA=/\t.*|\d{4}-\d\d-\d\d\s\d\d:\d\d:\d\d(.\d+)?\s(\+|-)\d\d\d\d/,yA=e=>{const t=wA.exec(e);return t&&(e=e.substring(0,t.index).trim()),e},vA=e=>null==e?"\\s":e instanceof RegExp?e.source:`[${bA(e).replace(/([.*+?^=!:${}()|[\]/\\])/g,"\\$1")}]`,bA=e=>`${e??""}`,SA=(0,d.h)("local-mercurial-diff"),kA=5242880,_A="0000000000000000000000000000000000000000";let CA,EA;async function xA(e,t,r={}){const n=await async function(){if(void 0===CA&&(CA=await async function(e){const t="win32"===process.platform?["hg.com","hg.exe"]:["hg"];for(const r of e.split(s.delimiter))if(s.isAbsolute(r))for(const e of t){const t=s.join(r,e);try{if(!(await So.stat(t)).isFile())continue;return"win32"!==process.platform&&await So.access(t,_o.constants.X_OK),t}catch{}}}(process.env.PATH??"")??null),null===CA){const e=new Error("hg executable not found");throw e.code="ENOENT",e}return CA}(),o=await new Promise(((o,s)=>{const i=(0,Kl.spawn)(n,t,{cwd:e,env:{...process.env,HGPLAIN:"+strictflags",HGRCPATH:"",HGRCSKIPREPO:"1"},shell:!1}),a=new na.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 PA(e){const t=await async function(e){let t=s.resolve(e);for(;;){try{if((await So.stat(s.join(t,".hg"))).isDirectory())return!0}catch{}const e=s.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!==EA)return EA;const e=await So.mkdtemp(s.join((0,o.tmpdir)(),"hg-probe-"));try{const t=await xA(e,["help","environment"]);EA=/\bHGRCSKIPREPO\b/.test(t)?"skips-repo-config":"reads-repo-config"}catch(e){EA=function(e){return"object"==typeof e&&null!==e&&"code"in e&&"ENOENT"===e.code}(e)?"absent":"reads-repo-config"}finally{await So.rm(e,{recursive:!0,force:!0})}return EA}());if("not-mercurial"===r)return;if("unsafe"===r)throw new Error("MercurialClientUnsafe: hg would read repository config");let n;try{n=(await xA(e,["root"])).trim()}catch{return}if(0!==n.length)try{return(await So.stat(s.join(n,".hg"))).isDirectory()?n:void 0}catch{return}}function RA(e,t){return"win32"===process.platform?s.win32.normalize(e).toLowerCase()===s.win32.normalize(t).toLowerCase():s.resolve(e)===s.resolve(t)}function IA(e,t){const r=s.relative(s.resolve(t),s.resolve(e));return 0===r.length||!s.isAbsolute(r)&&!r.split(s.sep).includes("..")}async function TA(e){const t=s.resolve(e);try{return await So.realpath(t)}catch{return t}}function AA(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 $A(e){if(e.includes("\0")||/[\r\n]/.test(e))throw new Error("MercurialDiffFailed: base ref contains a newline")}async function MA({repositoryRoot:e,rev:t,filePath:r}){const n=await async function({repositoryRoot:e,rev:t,filePath:r}){let n;try{n=await xA(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>kA?"":xA(e,["cat","-r",t,"--",r])}async function DA(e,t,r){const n=function(e){switch(e){case Ue.ek.NAME_STATUS:return Ue.ek.NAME_STATUS;case Ue.ek.NAME_STATUS_AND_NUMSTAT:return Ue.ek.NAME_STATUS_AND_NUMSTAT;case Ue.ek.FILE_DIFFS:return Ue.ek.FILE_DIFFS;case Ue.ek.DIFFS_WITH_BEFORE_AND_AFTER:return Ue.ek.DIFFS_WITH_BEFORE_AND_AFTER;default:return Ue.ek.FILE_DIFFS}}(r.outputFormat),o=["root"],i=(await xA(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){$A(t),r.push("log");const n=(await xA(e,["log","-r",`ancestor(., (${t}))`,"-T","{node}"])).trim();if(0===n.length||n===_A)throw new Error("MercurialDiffFailed: base ref did not resolve");return n}r.push("log");const n=(await xA(e,["log","-r","max(::. and public())","-T","{node}"],{allowFailure:!0})).trim();if(n.length>0&&n!==_A)return n;const o=(await xA(e,["log","-r","ancestor(., default)","-T","{node}"],{allowFailure:!0})).trim();if(o.length>0&&o!==_A)return o;const s=(await xA(e,["log","-r",".","-T","{node}"],{allowFailure:!0})).trim();return s.length>0?s:_A}({cwd:t,baseRef:r.baseRef,commands:o});else if($A(r.baseRef),o.push("log"),a=(await xA(t,["log","-r",r.baseRef,"-T","{node}"])).trim(),0===a.length)throw new Error("MercurialDiffFailed: base ref did not resolve");r.ref.length>0&&($A(r.ref),o.push("log"),c=(await xA(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 xA(t,l),d=function(e){const t=e.replace(/\r\n/g,"\n");return new Ue.o$({diffs:uA(t).map((e=>function(e){const t=new Ue.QP({from:e.from,to:e.to,chunks:e.chunks.map((e=>new Ue.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:Ue.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 xA(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.join(t,e),n=await So.stat(r);if(n.size>kA){const t=await async function(e){const t=(0,wo.createHash)("sha256"),r=await So.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 So.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 Ue.QP({from:"/dev/null",to:e.path,chunks:[],added:0,removed:0});const t=AA(e.contents);if(0===t.length)return new Ue.QP({from:"/dev/null",to:e.path,chunks:[],added:0,removed:0});const r=t.length;return new Ue.QP({from:"/dev/null",to:e.path,chunks:[new Ue.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!==Ue.ek.FILE_DIFFS)for(const e of d.diffs)e.chunks=[];if(n===Ue.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 MA({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.join(i,t.to),r=await So.stat(e);t.afterFileContents=r.size>kA?"":await So.readFile(e,"utf8")}catch{t.afterFileContents=""}else try{t.afterFileContents=await MA({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=AA(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,wo.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 xA(t,["log","-r",".","-T","{node}"],{allowFailure:!0})).trim();m=e.length>0?e:_A,g=(await xA(t,["status","-0"])).length>0}SA.info(e,"Local mercurial diff commands",{sourceControl:"mercurial",commands:o});const w=new Ue.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 SA.info(e,"Local diff outcome",{sourceControl:"mercurial",outcome:"too_large"}),new Error(`GetDiffResponseTooLarge: ${t} bytes exceeds the ${y} byte limit`)}return SA.info(e,"Local diff outcome",{sourceControl:"mercurial",outcome:"ok",fileCount:d.diffs.length,patchIdPrefixed:!0===f?.startsWith("hg:")}),w}const OA=(0,d.h)("local-git-diff");function FA({exitCode:e,stderr:t}){return new Error(`Git command failed with code ${e}: ${t}`)}async function NA(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 FA(n);return!0===r.shouldNotTrimOutput?n.stdout:n.stdout.trim()}function LA(e){const t=uA(e);return new Ue.o$({diffs:t.map((e=>function(e){const t=new Ue.QP({from:e.from,to:e.to,chunks:e.chunks.map((e=>new Ue.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:Ue.Wf.UNSPECIFIED})}function jA(e){const t=[];for(const n of e){const e={body:`+${(r=n.contents).replaceAll("\n","\n+")}`,numLines:Gs(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 UA=["main","master","develop"];async function BA(e,t){const r=s.join(e,t),n=await So.lstat(r);if(n.isSymbolicLink())return{contents:await So.readlink(r),path:t,isSymlink:!0};if(!n.isFile())throw new Error("Not a regular file or symlink");return{contents:await So.readFile(r,"utf8"),path:t,isSymlink:!1}}async function WA(e,t,r){const n=Ww(),o=(e,r)=>n.run(t,e,r),i=await async function(e,t){let r;try{const e=(await NA(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 TA(t);let n=await TA(e);if(RA(n,r))return;let o=!1;for(;IA(n,r)&&!RA(n,r);){try{if((await So.stat(s.join(n,".hg"))).isDirectory()){o=!0;break}}catch{}const e=s.dirname(n);if(e===n)break;n=e}return o?PA(e):void 0}({cwd:e,gitRoot:r});return void 0!==t?"mercurial":"git"}return void 0===await PA(e)?"none":"mercurial"}(t,o);if(OA.info(e,"Local diff source control",{sourceControl:i}),"none"===i)throw OA.info(e,"Local diff outcome",{sourceControl:i,outcome:"no_version_control"}),new Error("NoVersionControl: no git or mercurial repository");if("mercurial"===i)return DA(e,t,r);const a=function(e){switch(e){case Ue.ek.NAME_STATUS:return Ue.ek.NAME_STATUS;case Ue.ek.NAME_STATUS_AND_NUMSTAT:return Ue.ek.NAME_STATUS_AND_NUMSTAT;case Ue.ek.FILE_DIFFS:return Ue.ek.FILE_DIFFS;case Ue.ek.DIFFS_WITH_BEFORE_AND_AFTER:return Ue.ek.DIFFS_WITH_BEFORE_AND_AFTER;default:return Ue.ek.FILE_DIFFS}}(r.outputFormat),c=await(async()=>{let e=r.baseRef.length>0?r.baseRef:await async function(e){try{const t=await NA(e,["symbolic-ref","--short","refs/remotes/origin/HEAD"]);if(t)return t.trim()}catch{}for(const t of UA){const r=`origin/${t}`;try{return await NA(e,["rev-parse","--verify",r]),r}catch{}}try{const t=(await NA(e,["branch","-r"])).split("\n").map((e=>e.trim())).find((e=>e.startsWith("origin/")));if(t)return t}catch{}try{const t=await NA(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 NA(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=LA(h);else{const t=FA(d);if(r.computePatchId||!await async function(e){return(await NA(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 NA(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 Ue.QP({from:"A"===t?"/dev/null":o,to:"D"===t?"/dev/null":o}))}return new Ue.o$({diffs:n,diffType:Ue.Wf.UNSPECIFIED,fileContentsOmitted:!0})}(o,u).catch((()=>{throw t})),OA.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 NA(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 BA(e,t)}catch{return}})))).filter((e=>void 0!==e))}(t,o,r.maxUntrackedFiles);for(const e of f){const t=e.isSymlink?`${jA([e])}\n\`:await NA(o,["diff","--no-color","--no-index","--","/dev/null",e.path],{ignoreErrors:!0,shouldNotTrimOutput:!0});p.diffs.push(...LA(t).diffs)}}if(a!==Ue.ek.FILE_DIFFS||!0===p.fileContentsOmitted)for(const e of p.diffs)e.chunks=[];if(a===Ue.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 NA(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 NA(o,["show","--end-of-options",`${n}:${s.to}`],{shouldNotTrimOutput:!0})}catch{s.afterFileContents=""}else try{s.afterFileContents=(await BA(t,s.to)).contents}catch{try{s.afterFileContents=await NA(o,["show","--end-of-options",`${n}:${s.to}`],{shouldNotTrimOutput:!0})}catch{s.afterFileContents=""}}else s.afterFileContents=""}catch(t){OA.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 cA({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 NA(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){OA.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,jA(f))):void 0,v=!0===r.returnHeadSha?(await NA(o,["rev-parse","HEAD"])).trim():void 0,b=!0===r.returnHeadSha?(await NA(o,["status","--porcelain=v1","--untracked-files=all"])).trim().length>0:void 0,S=new Ue.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 HA{async execute(e,t){return WA(e,t.cwd,t)}}var qA=r("../proto/dist/generated/agent/v1/mcp_allowlist_precheck_exec_pb.js");class zA{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 qA.M({allowlisted:r})}}var GA=r("../proto/dist/generated/agent/v1/record_screen_exec_pb.js"),VA=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function KA(e){return null!==e.exitCode||null!==e.signalCode||e.killed}function JA(e,t){return"object"==typeof e&&null!==e&&"code"in e&&e.code===t}function ZA(e){return e instanceof Error?e.message:String(e)}function XA(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: ${ZA(r)}`),o.length>0?`${e} (${o.join("; ")})`:e}const QA=(0,Ws.promisify)(Kl.execFile);class YA{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(!KA(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,Fr.wj)(Promise.all(e),YA.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 So.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 So.mkdir(this.stagingDir,{recursive:!0}),await So.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:GA.y.UNSPECIFIED}:t.includes("/")||t.includes("\\")?{success:!1,reason:GA.y.SLASHES_NOT_ALLOWED}:(t=t.replace(/[^a-zA-Z0-9 ._-]/g,"_"),t=t.trim(),0===t.length?{success:!1,reason:GA.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 So.rename(e,t)}catch(e){if(!JA(e,"EXDEV"))throw e}try{await So.copyFile(e,t)}catch(e){throw await So.rm(t,{force:!0}).catch((()=>{})),e}try{await So.unlink(e)}catch(e){throw await So.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 So.open(e,"wx");return await t.close(),e}catch(e){if(!JA(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,Jl.D9)(QA,"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,Jl.D9)(QA,"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:YA.PROXY_TARGET_FPS,includeBrandTag:!0}),await So.access(n,So.constants.R_OK)}catch(t){const r=(0,D.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,Jl.D9)(QA,"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 ${YA.PROXY_TARGET_FPS}fps`)}catch(e){console.warn(`[record-screen] Failed to read video framerate: ${e instanceof Error?e.message:String(e)}, defaulting to ${YA.PROXY_TARGET_FPS}fps`)}return YA.PROXY_TARGET_FPS}async startFfmpegRecording(e,t){const r=s.join(t,"recording");await So.mkdir(r,{recursive:!0});const n=s.join(r,"recording_render_proxy_1080p.mp4");let o;try{o=(await ug(this.display)).display.refreshRate}catch(e){console.warn(`[record-screen] Failed to detect refresh rate: ${e instanceof Error?e.message:String(e)}, using default ${YA.DEFAULT_REFRESH_RATE}Hz`),o=YA.DEFAULT_REFRESH_RATE}const i=["-video_size",e,"-framerate",String(o),"-draw_mouse","0","-f","x11grab","-i",this.display,"-vf",`scale=${YA.PROXY_TARGET_WIDTH}:-2:flags=lanczos,fps=${YA.PROXY_TARGET_FPS}`,"-c:v","libx264","-preset",YA.PROXY_PRESET,"-crf",String(YA.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,Jl.D9)(Kl.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,Jl.D9)(Kl.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 So.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(KA(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),JA(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{!KA(r.childProcess)&&r.childProcess.pid&&await this.stopFfmpegRecording(r)}catch(e){a=e,console.warn(`[record-screen] Failed to stop ffmpeg: ${ZA(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 So.access(d,So.constants.R_OK)}catch(e){await this.cleanupRecording(r),this.clearActiveRecordingIfCurrent(r);const t=JA(e,"ENOENT")?`Recording proxy not found at ${d}`:`Recording proxy at ${d} could not be validated: ${ZA(e)}`;return new GA.Tj({result:{case:"failure",value:new GA.yH({error:XA(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=ZA(e),o=t.includes(d)?t:`Recording proxy at ${d} could not be validated: ${t}`;return new GA.Tj({result:{case:"failure",value:new GA.yH({error:XA(o,r,a,n)})}})}const m={profileVersion:YA.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:YA.PROXY_TARGET_FPS,codec:"h264",profile:YA.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 So.copyFile(d,g);else{const t=await this.renderPolished(e,l);await this.movePolishedVideo(t,g)}}catch(e){throw await So.rm(g,{force:!0}).catch((()=>{})),e}try{await So.rm(l,{force:!0,recursive:!0})}catch(e){console.warn(`[record-screen] Failed to remove staging session ${l}: ${ZA(e)}`)}return this.clearActiveRecordingIfCurrent(r),new GA.Tj({result:{case:"saveSuccess",value:new GA.ol({path:g,recordingDurationMs:ve.protoInt64.parse(h.toString()),requestedFilePathRejectedReason:w})}})}catch(e){return await this.cleanupRecording(r),this.invokeStoppedCallbackIfCurrent(r),new GA.Tj({result:{case:"failure",value:new GA.yH({error:ZA(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,D.VI)(e.withName("LocalRecordScreenExecutor.execute")),!1);try{await this.ensureRecordingDirectoryExists()}catch(e){return new GA.Tj({result:{case:"failure",value:new GA.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===GA.$u.UNSPECIFIED)return new GA.Tj({result:{case:"failure",value:new GA.yH({error:"Mode must be one of START_RECORDING, SAVE_RECORDING, DISCARD_RECORDING"})}});switch(t.mode){case GA.$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 So.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 So.mkdir(o,{recursive:!0});const{resolutionString:s,resolution:i}=await ug(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 vg({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 GA.Tj({result:{case:"startSuccess",value:new GA.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 So.rm(o,{force:!0,recursive:!0}).catch((()=>{})),this.activeRecording=null,new GA.Tj({result:{case:"failure",value:new GA.yH({error:e instanceof Error?e.message:String(e)})}})}}case GA.$u.SAVE_RECORDING:{if(!this.activeRecording)return 1===this.inFlightSaves.length?await this.inFlightSaves[0].promise:new GA.Tj({result:{case:"failure",value:new GA.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 GA.$u.DISCARD_RECORDING:{if(!this.activeRecording)return new GA.Tj({result:{case:"failure",value:new GA.yH({error:"No active recording to discard"})}});const e=this.activeRecording;if(this.findInFlightSave(e))return new GA.Tj({result:{case:"failure",value:new GA.yH({error:"Save in progress for this recording; wait for it or start a new recording"})}});try{return await e.inputEventLogger.stop(),this.invokeStoppedCallbackOnce(),!KA(e.childProcess)&&e.childProcess.pid&&await this.stopFfmpegRecording(e),await So.rm(e.sessionDir,{force:!0,recursive:!0}),this.activeRecording=null,new GA.Tj({result:{case:"discardSuccess",value:new GA.N8}})}catch(t){await this.cleanupRecording(e),this.invokeStoppedCallbackOnce();const r=e.sessionDir;let n=!1;try{await So.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 GA.Tj({result:{case:"failure",value:new GA.yH({error:`Failed to discard recording: ${o}${s}`})}})}}default:{const e=t.mode;return new GA.Tj({result:{case:"failure",value:new GA.yH({error:`Unhandled recording mode: ${String(e)}`})}})}}}catch(e){r.error=e,r.hasError=!0}finally{VA(r)}}}async function e$(e){const t=await(0,So.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 e$(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 t$(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(...t$(t,e,s))}))}return n}async function r$(e){if(!await(0,So.access)(e,So.constants.R_OK).then((()=>!0),(()=>!1)))return"(No notes directory yet - will be created when you write your first note)";const t=await e$(e);return 0===t.length?"(Notes directory is empty)":t.flatMap(((e,r)=>t$(e,"",r===t.length-1))).join("\n")}async function n$(e,t){return r$(s.join(e,"agent-notes",t))}async function o$(e){return r$(s.join(e,"agent-notes","shared"))}YA.IN_FLIGHT_SAVE_DISPOSE_TIMEOUT_MS=3e4,YA.PROXY_TARGET_WIDTH=1920,YA.PROXY_TARGET_FPS=60,YA.PROXY_CRF=17,YA.PROXY_PRESET="veryfast",YA.PROXY_PROFILE_VERSION="render-proxy-h264-all-i-v1",YA.DEFAULT_REFRESH_RATE=60;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});const a$=3e3,c$=(0,d.h)("local-exec:request-context"),l$=Symbol("sectionLoadTimedOut");function u$(e,t){if(void 0===t)return e;let r;const n=new Promise((e=>{r=setTimeout((()=>e(l$)),t)}));return e.catch((()=>{})),Promise.race([e,n]).finally((()=>{clearTimeout(r)}))}class d${async read(e,t){const r=this.inFlight??this.begin(e),n=this.last;if(void 0===n)return r;const o=await u$(r,t).catch((()=>l$));return o===l$?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 h$(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{s$(o,(0,D.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{i$(o)}}async function p$(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 f$(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(h$(e,t,r,n)),o(p$(e,t,r,n))]);return{status:s,branchName:i}}async function m$(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.platform()} ${o.release()}`,k=(0,$o.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 u$(p(),3e3);e!==l$&&(M=e)}catch{M=void 0}return new Or.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:ve.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 g$={type:"object",properties:{},additionalProperties:!1};function w$(e,t){return{tools:(!0===t?.internalBrowserProvidersOnly?e.servers.filter((e=>Vn.has(e.serverIdentifier))):e.servers).flatMap((e=>e.tools)).map((e=>new gn.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?ve.Value.fromJson(e.inputSchema):void 0}}))),mcpInstructions:e.servers.flatMap((e=>e.instructions))}}function y$(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 gn.E$({toolName:e.toolName,...rb(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?ve.Value.fromJson(e.inputSchema):void 0}}})));return!Gn(e.serverIdentifier)||!0!==t?.alwaysExposeVirtualMcpAuthTool&&"needsAuth"!==e.status||o.some((e=>e.toolName===_I))||o.push(new gn.E$({toolName:_I,...r?{}:{description:CI,...!0===t?.inputSchemaJson?{inputSchemaJson:JSON.stringify(g$)}:{inputSchema:ve.Value.fromJson(g$)}}})),new gn.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 gn.U_({enabled:!0,mcpDescriptors:n})}function v$(e){const t=e?.trim();return t||void 0}function b$(e,t){const r=function(e){return v$(e.serverIdentifier)}(e);if(r)return r;const n=v$(e.serverName);return n?t.get(n)??n:void 0}class S${constructor(e){this.mcpLease=e}async getState(e){const[t,r]=await Promise.all([this.mcpLease.getTools(e).catch((t=>(c$.warn(e,"Error fetching MCP tools",{error:t}),[]))),this.mcpLease.getInstructions(e).catch((t=>(c$.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=>b$(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=>b$(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=>(c$.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:Qn(n),errorMessage:"error"===n.kind&&void 0!==n.message?n.message:void 0}]})));return new Map(n)}(e,this.mcpLease))}}function k$(e){return new Rc._W({result:{case:"success",value:new Rc.pv({servers:e.servers.map((e=>new Rc.XE({serverName:e.serverName,serverIdentifier:e.serverIdentifier,plugin:e.plugin,marketplace:e.marketplace,tools:e.tools.map((e=>new gn.gd({name:e.name,providerIdentifier:e.providerIdentifier,toolName:e.toolName,description:e.description,inputSchema:e.inputSchema?ve.Value.fromJson(e.inputSchema):void 0,metaJson:Kn(e._meta),...rb(e.annotations)}))),instructions:e.instructions,status:e.status,errorMessage:e.errorMessage})))})}})}class _${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!==Rc.ew.FORCE_IF_MISSING&&t.refreshPolicy!==Rc.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 k$({...r,servers:n})}return k$(r)}}class C${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 d$,this.reusedAgentSkills=new d$,this.reusedAdminCommandDenylist=new d$,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,b.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=s$(r,(0,D.VI)(e.withName("LocalRequestContextExecutor.warmWorkspaceCache")),!1),o=await Za(n.ctx,this.gitExecutor,t),s=o?await rc(n.ctx,this.gitExecutor,o):void 0,i={repoPath:o??void 0,remoteUrl:void 0!==s?nc(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((()=>f$((0,b.q6)(),this.gitExecutor,e,a$)))}}catch(e){r.error=e,r.hasError=!0}finally{i$(r)}}gitInfoSection(e){let t=this.reusedGitInfo.get(e);return void 0===t&&(t=new d$,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,b.q6)(),r=s$(e,(0,D.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{i$(e)}}async computeGlobalCache(e){const t={stack:[],error:void 0,hasError:!1};try{const r=s$(t,(0,D.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&&c$.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{i$(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=s$(r,(0,D.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 Or.DS({path:r.repoPath,status:a.gitStatus,branchName:a.gitBranchName,remoteUrl:r.remoteUrl,isOriginBacked:Ga(r.remoteUrl)});if(void 0===r.repoPath)return;const c=r.repoPath,{status:l,branchName:u}=void 0===this.freshSectionWaitMs?await f$(n.ctx,t.gitExecutor,c,a$):await this.gitInfoSection(c).read((()=>f$((0,b.q6)(),t.gitExecutor,c,a$)),this.freshSectionWaitMs);return void 0===l&&(i=!1),new Or.DS({path:r.repoPath,status:l,branchName:u,remoteUrl:r.remoteUrl,isOriginBacked:Ga(r.remoteUrl)})})))).filter((e=>void 0!==e)),gitRepoInfoComplete:s,gitStatusInfoComplete:s&&i}}catch(e){r.error=e,r.hasError=!0}finally{i$(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=s$(n,(0,D.VI)(e.withName("LocalRequestContextExecutor.computeCachedRequestContext")),!1),s=this.projectDir,i=async()=>{const e={stack:[],error:void 0,hasError:!1};try{const t=s$(e,(0,D.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{i$(e)}},a=performance.now(),c={},l=(e,t)=>{const r=performance.now();return t.finally((()=>{c[e]=Math.round(performance.now()-r)}))},u=e=>u$(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,b.q6)(),[m,g,w,{gitRepos:y,gitRepoInfoComplete:v,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",m$(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?n$(s,t.notesSessionId):Promise.resolve(void 0)),l("sharedNotes",this.agentNotesEnabled&&s?o$(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===l$,I=g===l$,T=x===l$,A=P===l$,$=R?this.lastGoodGlobalCache??{rules:[...this.additionalRules],cloudRule:null,codebaseReference:void 0,customSubagents:[]}:m,M=I?{servers:[]}:g,O=T?[]:x,F=A?void 0:P;(R||I||T||A)&&c$.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&&c$.warn(o.ctx,"computeCachedRequestContext: slow parallel data collection",{durationMs:Math.round(N),...c});const L=this.mcpMetaToolEnabled?y$(M,{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 Or.bb({rules:$.rules,env:w,gitRepos:y,gitRepoInfoComplete:v,repositoryInfo:$.codebaseReference?[{relativeWorkspacePath:$.codebaseReference.relativeWorkspacePath,repoName:$.codebaseReference.repoName,repoOwner:$.codebaseReference.repoOwner,isTracked:$.codebaseReference.isTracked,isLocal:$.codebaseReference.isLocal,orthogonalTransformSeed:$.codebaseReference.orthogonalTransformSeed,pathEncryptionKey:$.codebaseReference.pathEncryptionKey}]:[],...w$(M,{internalBrowserProvidersOnly:this.mcpMetaToolEnabled&&this.mcpMetaToolSlimDescriptors,inputSchemaJson:this.mcpInputSchemaJson}),conversationNotesListing:k,sharedNotesListing:_,customSubagents:$.customSubagents,mcpFileSystemOptions:C,mcpMetaToolOptions:L,supportsMcpAuth:!0,commitAttributionMessage:U?"enabled":void 0,prAttributionMessage:B?"enabled":void 0,agentSkills:O,adminCommandDenylist:F?.rules??[]});return null!==$.cloudRule&&void 0!==$.cloudRule&&(W.cloudRule=$.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{i$(n)}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{this.onRequestContext?.();const n=s$(r,(0,D.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 Or._G({result:{case:"success",value:new Or.yW({requestContext:r})}})}catch(e){return e instanceof Error||"string"==typeof e?n.span.recordException(e):n.span.recordException(vc(e)),new Or._G({result:{case:"error",value:new Or.nf({error:e instanceof Error?e.message:String(e)})}})}}catch(e){r.error=e,r.hasError=!0}finally{i$(r)}}}function E$(e){return 0!==e.timeout?e.timeout:e.isBackground||e.timeoutBehavior===fe._d.BACKGROUND||void 0!==e.hardTimeout&&e.hardTimeout>0?0:3e4}var x$=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class P${constructor(e,t,r,n){this.permissionsService=e,this.coreExecutor=t,this.ignoreService=r}buildResultFromExit(e){return 0===(e.exitCode??-1)?new fe.W4({result:{case:"success",value:new fe.QR({...e,stdout:e.outputLocation?"":e.stdout,stderr:e.outputLocation?"":e.stderr})},sandboxPolicy:as(e.sandboxPolicy)}):new fe.W4({result:{case:"failure",value:new fe.xC({...e,aborted:void 0!==e.abortReason,stdout:e.outputLocation?"":e.stdout,stderr:e.outputLocation?"":e.stderr})},sandboxPolicy:as(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?fe.Lv.TIMEOUT:fe.Lv.USER_ABORT:fe.Lv.UNSPECIFIED:void 0,u=ty(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 fe.W4({result:{case:"timeout",value:new fe.eG({command:t.command,workingDirectory:r,timeoutMs:n})},sandboxPolicy:as(o)}):e.signal.aborted?new fe.W4({result:{case:"rejected",value:new fe.pZ({command:t.command,workingDirectory:r,reason:"Command aborted"})},sandboxPolicy:as(o)}):new fe.W4({result:{case:"spawnError",value:new fe.mJ({command:t.command,workingDirectory:r,error:s instanceof Error?s.message:"Unknown error"})},sandboxPolicy:as(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,D.VI)(e.withName("LocalShellExecutor.execute")),!1).ctx;(0,D.HF)(n,"LocalShellExecutor.execute");const o=t.command,s=t.requestedSandboxPolicy?is(t.requestedSandboxPolicy):void 0,i=t.workingDirectory||await this.coreExecutor.getCwd(t.conversationId),a=E$(t),c=(0,Zo.o1)(i);if(!t.parsingResult)return new fe.W4({result:{case:"spawnError",value:new fe.mJ({command:o,workingDirectory:c,error:"Parsing result is required"})}});let l;if(To(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 fe.W4({result:qu(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:Ro(t)},s);if("block"===e.kind)return new fe.W4({result:qu(o,c,e.reason)});l=e.policy}return l=await Pc(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{x$(r)}}}var R$=r("../proto/dist/generated/agent/v1/shell_allowlist_precheck_exec_pb.js");class I${constructor(e){this.permissionsService=e}async execute(e,t){const r=t.parsingResult??new fe.HO,n=await this.permissionsService.isShellCommandFullyAllowlisted(e,t.command,{workingDirectory:t.workingDirectory,parsingResult:r,classifierResult:t.classifierResult,toolCallId:t.toolCallId});return new R$.e({allowlisted:n})}}class T${constructor(e){this.shellStreamExecutor=e}async execute(e,t,r){return""===t.toolCallId.trim()?new fe.jK({status:fe.iA.NOT_FOUND}):this.shellStreamExecutor.forceBackgroundByToolCallId(e,t.toolCallId)}}var A$=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 $$=(0,d.h)("local-exec:shell-stream");class M${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===fe.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:fe.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:fe.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 D$(){let e=()=>{};return{promise:new Promise((t=>{e=t})),resolve:e}}class O${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,b.uk)(r).then((()=>{}))])}finally{n()}}(e,r),o=n?.requestBackground();return o?new fe.jK({status:fe.iA.ACCEPTED,shellResult:o}):new fe.jK({status:fe.iA.NOT_FOUND})}pendingFrom(e){return{execute:(t,r,n)=>this.whilePending(r,(()=>e.get(re).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:D$()},""!==e.toolCallId&&e.timeoutBehavior===fe._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,D.VI)(e.withName("LocalShellStreamExecutor.execute")),!1);const o=t.command;let s=t.requestedSandboxPolicy?is(t.requestedSandboxPolicy):void 0;const i=t.workingDirectory||await this.coreExecutor.getCwd(t.conversationId),a=E$(t),c=(0,Zo.o1)(i),l=Date.now(),u=performance.now(),d=new fe.HO(jo(o).structured),h=vs({command:o,parsingResult:d,blockedCommands:t.adminCommandDenylist});if(void 0!==h)return void(yield new fe.FI({event:{case:"rejected",value:new fe.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:To(t)},s);if("block"===p.kind)return"permissionsConfig"===p.reason.type?void(yield new fe.FI({event:{case:"permissionDenied",value:new fe.jn({command:o,workingDirectory:c,error:"Command blocked by permissions configuration",isReadonly:p.reason.isReadonly??!1})}})):void(yield new fe.FI({event:{case:"rejected",value:new fe.pZ({command:o,workingDirectory:c,reason:Hu(p.reason)})}}));if($$.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}),To(t)){const r=p.policy??s;$$.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:Ro(t),onApprovalRequested:()=>{r.registered.resolve(void 0),r.registered=D$()}},s);if(r.awaitingApproval=!1,"block"===n.kind){if($$.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 fe.FI({event:{case:"permissionDenied",value:new fe.jn({command:o,workingDirectory:c,error:"Command blocked by permissions configuration",isReadonly:n.reason.isReadonly??!1})}}));const r=Hu(n.reason);return void(yield new fe.FI({event:{case:"rejected",value:new fe.pZ({command:o,workingDirectory:c,reason:r})}}))}s=n.policy,$$.info(e,"Shell stream: approval gate allowed command",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,effectivePolicyType:s.type})}s=await Pc(s,{command:o,workingDirectory:c,parsingResult:d,permissionsService:this.permissionsService,ignoreService:this.ignoreService}),yield new fe.FI({event:{case:"start",value:new fe.tD({sandboxPolicy:as(s)})}});const f=t.timeoutBehavior===fe._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 M$(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 fe.W4({result:{case:"success",value:new fe.QR({shellId:E,pid:C,command:o,workingDirectory:c,msToWait:ty(performance.now()-u),backgroundReason:fe.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 $;k&&e.signal&&(e.signal.aborted?A():e.signal.addEventListener("abort",A,{once:!0}));const M=t.hardTimeout;void 0!==M&&M>0&&($=setTimeout((()=>{void 0!==E?this.backgroundShellManager.abort(E)||g.abort():(P=!0,g.abort(),k?.abort())}),M));const O=k?.iterate()??b;try{for await(const r of O)if("stdout"===r.type)x+=r.data,yield new fe.FI({event:{case:"stdout",value:new fe.o0({data:r.data})}});else if("stderr"===r.type)x+=r.data,yield new fe.FI({event:{case:"stderr",value:new fe.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?fe.Lv.USER_ABORT:k?.timedOut||g.signal.aborted?fe.Lv.TIMEOUT:fe.Lv.USER_ABORT),yield new fe.FI({event:{case:"exit",value:new fe.vb({code:(r.code??-1)>>>0,cwd:await this.coreExecutor.getCwd(t.conversationId),outputLocation:r.outputLocation,aborted:r.aborted,abortReason:n,localExecutionTimeMs:ty(r.localExecutionTimeMs)})}})}}catch(r){if(!(r instanceof $o.SandboxUnsupportedError))throw r;const n=s?.type??"unknown";return $$.debug(e,"Shell stream: sandbox policy unsupported on this host",{toolCallId:t.toolCallId,policyType:n,reason:r.reason}),void(yield new fe.FI({event:{case:"sandboxUnsupported",value:new fe.rI({command:o,workingDirectory:c,sandboxPolicyType:n,reason:r.reason??r.message,isReadonly:"workspace_readonly"===n})}}))}finally{clearTimeout(S),k?.backgroundRequested||clearTimeout($),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===fe.Jg.USER_REQUEST?fe.Jg.USER_REQUEST:fe.Jg.TIMEOUT,s=n===fe.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($)}),yield new fe.FI({event:{case:"backgrounded",value:new fe.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($),yield new fe.FI({event:{case:"exit",value:new fe.vb({code:4294967295,cwd:await this.coreExecutor.getCwd(t.conversationId),aborted:!0,abortReason:fe.Lv.USER_ABORT})}})):clearTimeout($)}catch(e){n.error=e,n.hasError=!0}finally{A$(n)}}}const F$={kind:"absent"};class N${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 ko.q({max:1e3,ttl:6e4,ttlResolution:0,perf:e})}begin(e){this.entries.purgeStale();const t=++this.nextGeneration;return this.claims.set(q$(e),t),t}record(e,t,r){if(!this.claim(e,r))return;const n=q$(e);this.entries.set(n,{recorded:t,generation:r}),this.commitGeneration(n,r)}forget(e,t){if(!this.claim(e,t))return;const r=q$(e);this.entries.delete(r),this.commitGeneration(r,t)}end(e,t){this.claim(e,t)}take(e){const t=q$(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=q$(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=q$(e);return this.claims.get(r)===t&&(this.claims.delete(r),!0)}}class L${constructor(){this.views=new ko.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>Hs)return void this.views.delete(e);const r=(0,wo.createHash)("sha256").update(t).digest("hex");this.views.set(e,{kind:"fingerprint",byteLength:t.length,sha256:r})}recordDelete(e){this.views.set(e,F$)}}async function j$(e,t){if(void 0===e)return!1;try{if("absent"===e.kind)return await H$(t);const r=await W$(t);return void 0===r||r.byteLength!==e.byteLength||r.sha256!==e.sha256}catch{return!1}}async function U$(e,t){if("fingerprint"!==e?.kind)return!1;try{return!await H$(t)}catch{return!1}}class B${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,Zo.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,Zo.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 yk(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 W$(t)}catch{return}}(i,o.resolvedPath);return this.commit(o,s,i,a,n),i}try{a=await W$(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=F$: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 W$(e){try{const t=await(0,So.stat)(e);if(!t.isFile()||t.size>Hs)return}catch(e){return z$(e)}let t;try{t=await(0,So.open)(e,function(){const e=_o.constants;return e.O_RDONLY|(e.O_NONBLOCK??0)}());const r=await t.stat();if(!r.isFile()||r.size>Hs)return;const n=(0,wo.createHash)("sha256");let o=0;const s=Buffer.alloc(65536);for(;o<=Hs;){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>Hs)return;return{byteLength:o,sha256:n.digest("hex")}}catch(e){return z$(e)}finally{await(t?.close())}}async function H$(e){try{return await(0,So.stat)(e),!0}catch(e){if(G$(e))return!1;throw e}}function q$({toolCallId:e,resolvedPath:t}){return`${e}\0${t}`}function z$(e){if(!G$(e))throw e}function G$(e){const t=yc(e);return"ENOENT"===t||"ENOTDIR"===t}var V$=r("../proto/dist/generated/agent/v1/web_fetch_allowlist_precheck_exec_pb.js");class K${constructor(e){this.permissionsService=e}async execute(e,t){const r=await this.permissionsService.isWebFetchFullyAllowlisted(e,{url:t.url});return new V$.M({allowlisted:r})}}var J$=r("node:constants");const Z$=[".md",".markdown",".mdown",".mkd",".mkdn",".mdx"];function X$(e){const t=e.trim().toLowerCase();return Z$.some((e=>t.endsWith(e)))}function Q$(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 Y$="win32"===process.platform;process.platform;const eM="\\"===s.sep?"win32":"posix",tM={allowed:!1};class rM extends Error{constructor(e,t){super(t),this.name="SymlinkRefusedError",this.path=e}}function nM(e,{nonBlocking:t}){const r=_o.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 oM=[20,40,80],sM=new Set(["UNKNOWN","EBUSY"]);async function iM(e,t){try{const[r,n]=await Promise.all([t.stat({bigint:!0}),(0,So.lstat)(e,{bigint:!0})]);r.dev===n.dev&&r.ino===n.ino&&await(0,So.unlink)(e)}catch{}}async function aM(e,t,r,{removeOnRefusal:n=!1}={}){let o;try{o=await async function(e,t){try{return await(0,So.open)(e,nM(t,{nonBlocking:!0}),438)}catch(r){const n=yc(r);if(("EAGAIN"===n||"EWOULDBLOCK"===n)&&await async function(e){try{return(await(0,So.lstat)(e)).isFile()}catch{return!1}}(e))return await(0,So.open)(e,nM(t,{nonBlocking:!1}),438);throw r}}(e,t)}catch(t){if(function(e){const t=yc(e);return"ELOOP"===t||"EMLINK"===t||"EPERM"===t&&"number"==typeof _o.constants.O_NOFOLLOW}(t))throw new rM(e,`Refusing to ${r} through a symlink at ${e}`);throw t}try{let t;try{t=(0,_o.realpathSync)(e)}catch{throw new rM(e,`Cannot verify canonical path before ${r}: ${e}`)}if(t!==e)throw new rM(e,`Refusing ${r}: ${e} now resolves through a symlinked parent to ${t}`);const n=await o.stat();if(!n.isFile())throw new rM(e,`Refusing to ${r} non-regular file at ${e}`);return{fd:o,stats:n}}catch(t){throw n&&await iM(e,o),await o.close(),t}}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 lM=(0,d.h)("LocalWriteExecutor"),uM=(0,h.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"]}),dM=async(e,t,r,n)=>{const o=setTimeout((()=>{lM.warn(e,`[watchdog, LocalWriteExecutor] ${t} still not completed after ${r}ms`)}),r);try{return await n()}finally{clearTimeout(o)}};function hM(e){return new Error(`Could not create ${e}: directory creation exceeded the path depth and was stopped.`)}async function pM(e){try{return(await(0,So.stat)(e)).isDirectory()?"directory":"present"}catch(e){if("ENOENT"===yc(e))return"missing";throw e}}async function fM(e,t){const r=[];let n=e;for(let o=0;o<=t;o+=1){const t=await pM(n);if("directory"===t)return r.reverse(),r;if("present"===t)return await(0,So.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 hM(e)}class mM{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,md.fileURLToPath)(e),!1}catch{return!0}}(t.path))return new YR.v3({result:{case:"error",value:new YR.QM({path:t.path,error:`${t.path} is not a valid file URL. Use an absolute path instead.`})}});const n=(0,Zo.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 yM(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,D.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=Ub(r,d)||void 0!==this.projectDir&&!this.workspacePaths.some((e=>{return t=e,n=r,Y$&&(t=t.toLowerCase(),n=n.toLowerCase()),t===n||(t.charAt(t.length-1)!==s.sep&&(t+=s.sep),n.startsWith(t));var t,n}))&&Bb(this.projectDir,r,d);if((0,Zo.fl)({targetPath:r,workspacePaths:this.workspacePaths,mainWorktreePath:this.worktreeMainPath}))return new YR.v3({result:{case:"error",value:new YR.QM({path:r,error:Zo.PS})}});let p,f,m,g,w=!1;try{const e=await(0,So.stat)(r);if(g=511&e.mode,e.size<=es){const e=await dM(c,"readText before write",3e3,(()=>Ni(r,t.encodingHint)));p=e.text,f=e.encoding,m=lw(e)}else w=!0}catch(e){w="ENOENT"!==yc(e)}const y=await rS(r),v=y.resolvedPath;if(t.confineToWorkspace){let e=(await Promise.all(this.workspacePaths.map((e=>(0,So.realpath)(e).catch((()=>{})))))).filter((e=>void 0!==e));if(0===e.length&&void 0!==this.projectDir){const t=await(0,So.realpath)(this.projectDir).catch((()=>{}));void 0!==t&&(e=[t])}if(!e.some((e=>(0,Zo.BJ)(v,e))))return new YR.v3({result:{case:"error",value:new YR.QM({path:r,error:"downloadPath must stay within the workspace"})}})}const b=async()=>{return await j$(n,v)?aT(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 j$(o,v)?void 0:cT(r));var e,t},S=t.planMode?await dM(c,"checkPlanModeWriteTarget",3e3,(()=>async function(e,t){switch(t.resolution.status){case"resolved":case"newFile":return X$(t.resolvedPath)?{allowed:!0}:await async function(e,t){if(!(Q$(t.resolvedPath,eM)||Q$(e,eM)&&t.resolvedPath===await async function(e){const t=(0,s.dirname)((0,s.dirname)((0,s.dirname)((0,s.dirname)(e)))),r=await rS(t);if(nS(r.resolution))return(0,s.join)(r.resolvedPath,(0,s.relative)(t,e))}(e)))return tM;if("newFile"===t.resolution.status)return{allowed:!0,singleLink:{kind:"create"}};const r=await async function(e){try{const t=await(0,So.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?tM:{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,So.readlink)(t)}catch(e){const r=yc(e);return"ENOENT"===r||"EINVAL"===r?t:void 0}t=(0,s.resolve)((0,s.dirname)(t),e)}}(t.resolvedPath);return void 0!==e&&X$(e)?{allowed:!0}:tM}case"permissionDenied":case"symlinkLoop":case"unknownError":return tM;default:return t.resolution,tM}}(r,y))):void 0;if(void 0!==S&&!S.allowed)return new YR.v3({result:{case:"rejected",value:new YR.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 dM(c,"permissionsService.shouldBlockWrite",3e3,(()=>this.permissionsService.shouldBlockWrite(c,v,l)));if(k){const e=await dM(c,"handleBlockReason",3e3,(()=>Wu(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 gM(r,a);const c=await this.pendingDecisionProvider.requestApproval({type:aw.Write,details:{path:r,reason:e,isNewFile:o,diffString:s,before:p,after:l,blockReason:i},toolCallId:t.toolCallId});return c.approved?null:new YR.v3({result:{case:"rejected",value:new YR.en({path:r,reason:c.reason||""})}})},onUserRejected:e=>new YR.v3({result:{case:"rejected",value:new YR.en({path:r,reason:e||""})}}),onPermissionDenied:(e,t)=>new YR.v3({result:{case:"permissionDenied",value:new YR.U7({path:r,error:e,isReadonly:t?.isReadonly??!1})}})})));if(null!==e)return e}const _=await dM(c,"anotherSpellingRefusal",3e3,(()=>async function(e){const t=(0,s.basename)(e);let r;try{if(!(await(0,So.stat)(e)).isFile())return;const n=await(0,So.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 YR.v3({result:{case:"error",value:new YR.QM({path:r,error:_})}});const C=(0,s.dirname)(v);if(await U$(n,C))return gM(r,aT(r));if(await U$(o,C))return gM(r,cT(r));let E,x,P,R;try{E=await dM(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 fM(e,t),a=0;for(;a<i.length;){const c=i[a];if(n+=1,n>r)throw hM(e);try{await(0,So.mkdir)(c,{recursive:!1})}catch(r){const n=yc(r);if("EEXIST"===n){if("directory"!==await pM(c))throw r;a+=1;continue}if("ENOENT"===n){const n=(0,s.dirname)(c);if(n===c||"missing"!==await pM(n))throw r;i=await fM(e,t),a=0,o=0;continue}throw r}o+=1,a+=1}return o}(C)))}catch(e){const t=yc(e);return"EACCES"===t||"EPERM"===t?new YR.v3({result:{case:"permissionDenied",value:new YR.U7({path:r,directory:C,operation:"create_directory",error:"Permission denied"})}}):new YR.v3({result:{case:"error",value:new YR.QM({path:r,error:vc(e)})}})}if(void 0!==u)x=u,P=0;else{const e=await dM(c,"getBufferForWrite",3e3,(()=>ji(r,l,this.workspacePath,t.encodingHint)));x=e.buffer,P=e.lines,R=e.format.encoding}const I=()=>dM(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 aM(e,_o.constants.O_WRONLY|_o.constants.O_CREAT,"write"):await async function(e,t){const r="create"===t.kind,n=r?_o.constants.O_WRONLY|_o.constants.O_CREAT|_o.constants.O_EXCL:_o.constants.O_WRONLY;let o;try{o=await aM(e,n,"write",{removeOnRefusal:r})}catch(t){const r=yc(t);if("EEXIST"===r||"ENOENT"===r)throw new rM(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 rM(e,`Refusing to write: ${e} has ${r.nlink} hard links`);if("existing"===t.kind&&(r.dev!==t.dev||r.ino!==t.ino))throw new rM(e,`Refusing to write: ${e} was replaced after it was checked`);return o}catch(t){throw r&&await iM(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=yc(e);if(t>=oM.length||void 0===r||!sM.has(r))throw e;await(0,sg.setTimeout)(oM[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 Li(r,{buffer:x,encoding:R});try{t=await(0,So.open)((0,s.dirname)(v),J$.O_RDONLY),await t.sync()}catch{}finally{await(t?.close())}}));let T,A=!1;const $=async()=>{try{await I()}catch(e){throw T=e,A=!0,e}};try{void 0===this.writeFileMutationGuard?await I():await this.writeFileMutationGuard.runExclusive(v,$)}catch(e){if(void 0!==this.writeFileMutationGuard&&(!A||e!==T))return new YR.v3({result:{case:"error",value:new YR.QM({path:r,error:e instanceof Error?e.message:String(e)})}});if(e instanceof rM)return new YR.v3({result:{case:"permissionDenied",value:new YR.U7({path:r,directory:"",operation:"create_file",error:e.message})}});const t=yc(e);return"EACCES"===t||"EPERM"===t?new YR.v3({result:{case:"permissionDenied",value:new YR.U7({path:r,directory:"",operation:"create_file",error:"Permission denied"})}}):"ENOSPC"===yc(e)?new YR.v3({result:{case:"noSpace",value:new YR.bM({path:r})}}):"EDQUOT"===t?new YR.v3({result:{case:"error",value:new YR.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 YR.v3({result:{case:"error",value:new YR.QM({path:r,error:vc(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){lM.warn(c,"onWriteForAiTracking failed (write succeeded)",{path:r,error:e instanceof Error?e.message:String(e)})}}const M=x.byteLength;let O;if(void 0!==u||w||h||this.recordEncodingChecks(c,r,p,f,l),t.returnFileContentAfterWrite)try{O=await dM(c,"readText after write",3e3,(()=>Fi(r,t.encodingHint)))}catch{}return new YR.v3({result:{case:"success",value:new YR.j6({path:r,linesCreated:P,fileSize:M,...void 0!==O&&{fileContentAfterWrite:O}})}})}catch(e){a.error=e,a.hasError=!0}finally{cM(a)}}recordEncodingChecks(e,t,r,n,o){try{const i={path:t,encoding:n,pages:(s=iu.pages(),"failed"===s?"none":s)};for(const t of function(e,t,r){return[rl(e,t,r),nl(e,t,r)]}(r,n,o))uM.increment(e,1,ll(t,i))}catch(t){for(const t of Jc)uM.increment(e,1,{detector:t,outcome:"error",file:"unclassified"});lM.warn(e,"encoding check failed (write succeeded)",{error:t instanceof Error?t.message:String(t)})}var s}}function gM(e,t){return new YR.v3({result:{case:"error",value:new YR.QM({path:e,error:t})}})}class wM extends Error{constructor(e){super("stale write refusal"),this.result=e,this.name="StaleWriteRefusal"}}function yM(e){if("error"!==e.result.case)return!1;const{error:t,path:r}=e.result.value;return t===aT(r)||t===cT(r)}const vM=(0,d.h)("local-exec:provider"),bM=new Set,SM=new cd.AsyncLocalStorage;class kM extends Z{getMcpExecutionPolicyDeps(){return{permissionsService:this.permissionsService,pendingDecisionProvider:this.pendingDecisionStore}}static dropOwnedRequestContextCaches(){for(const e of bM)e.ownedRequestContextExecutor?.invalidateGlobalCache()}static rebuildRequestContextCachesFor(e){for(const t of bM)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,_o.readFileSync)(t,"utf-8"),n=JSON.parse(r),o=(0,$o.$6)(n);return(0,$o.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,$o.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 ju(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 Bu(c,this.askpassConfig)),this.shellManager&&(c=new Uu(c,this.shellManager));const l=e.overrideShellExecutor??(!0===e.suppressDefaultShellExecutor?void 0:new P$(this.permissionsService,c,this.ignoreService,this.pendingDecisionStore));void 0!==l&&this.register(sT,ng(l)),this.register(iT,ng(new oT(this.permissionsService,this.ignoreService,a??t??this.projectDir)));const u=new N$,d=new L$,h=e.overrideWriteExecutor??new mM(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(lT,function(e){const t=(r={execute:(t,r,n)=>e.execute(t,r,n).then((e=>{if(yM(e))throw new wM(e);return e}))},ng(r));var r;return{async execute(e,r,n){try{return await t.execute(e,r,n)}catch(e){if(e instanceof wM)return e.result;throw e}}}}(h));const p=e.overrideDeleteExecutor??new hw(this.pendingDecisionStore,this.fileChangeTracker,this.permissionsService,a,e.onDeleteForAiTracking,d);this.register(uT,ng(p)),this.register(dT,ng(new yw({encodingSlices:e.encodingSlices}))),this.register(hT,new HA);const f=this.mcpStateAccessor??new S$(this.mcpLease),m=e.overrideGrepExecutor??new M_(this.ignoreService,this.grepProvider,this.workspacePaths,{mcpStateAccessor:f,permissionsService:this.permissionsService,useStreamingGrep:e.useStreamingGrep,encodingSlices:e.encodingSlices});this.register(pT,ng(m));const g=e.overrideReadExecutor??new B$(new i_(this.permissionsService,a,{mcpStateAccessor:f,useStreamingRead:e.useStreamingRead,pendingDecisionProvider:this.pendingDecisionStore,encodingSlices:e.encodingSlices}),u,this.permissionsService,a,d),w=new wT(g);this.register(yT,w),e.registerRedactedReadExecutor&&this.register(vT,w);const y=e.overrideLsExecutor??new U_(this.permissionsService,this.ignoreService,a);this.register(bT,ng(y)),this.register(ST,ng(new aA(a,this.diagnosticsProvider))),e.getCanvasDiagnostics&&this.register(kT,ng(new eA(e.getCanvasDiagnostics,e.beginCanvasSave))),this.register(Yn,ng(new LT(Gl(new VI(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(yT))))),this.register(eo,ng(new KI(this.mcpLease,e.ensureMcpServersLoaded))),this.register(to,ng(Gl(new JI(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(ro,ng(new _$(f,e.ensureMcpServersLoaded,{filterToRequestedServers:this.mcpMetaToolEnabled&&this.mcpMetaToolSlimDescriptors})));const v=this.sharedRequestContextExecutor??this.createOwnedRequestContextExecutor(f,t,e),b=ng({execute:(e,t,r)=>{const n=SM.getStore();return void 0!==n&&(n.ran=!0),v.execute(e,t,r)}});this.register(Mr,{execute:async(t,r,n)=>{const o={ran:!1},s=await SM.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=w$(c,{internalBrowserProvidersOnly:this.mcpMetaToolEnabled&&this.mcpMetaToolSlimDescriptors,inputSchemaJson:this.mcpInputSchemaJson});if(a.tools=l.tools,a.mcpInstructions=l.mcpInstructions,a.mcpMetaToolOptions=this.mcpMetaToolEnabled?y$(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=[],vM.warn(t,"Failed to get mounted agent stores; continuing without prompt inventory")}return i}}),this.backgroundShellExecutor=new ad(this.permissionsService,c,this.ignoreService,this.projectDir,this.backgroundShellFactory,this.backgroundWorkRegistry,this.wakeupOwnerConversationId,e.backgroundShellManager),this.shellRedeliveryCaches=e.shellRedeliveryCaches??{backgroundShell:rg(),shellStream:rg(),writeStdin:rg()},this.register(jT,ng(this.backgroundShellExecutor,void 0,this.shellRedeliveryCaches.backgroundShell)),this.shellStreamExecutor=new O$(this.permissionsService,c,this.ignoreService,this.backgroundShellExecutor.getManager()),this.register(re,function(e,t,r=rg(t)){return{async*execute(t,n,o){if(!o?.execId)return void(yield*e.execute(t,n,o));const s=tg(o.execId,n),i=r.get(s);if(i)return void(yield*i.fork());const a=e.execute(t,n,o),c=new eg(a);r.set(s,c),yield*c.fork()}}}(this.shellStreamExecutor,void 0,this.shellRedeliveryCaches.shellStream)),void 0!==e.agentStoreConflictDrainer&&this.register(BT,new ZT(e.agentStoreConflictDrainer)),this.register(WT,new I$(this.permissionsService)),this.register(HT,new zA(this.permissionsService)),this.register(qT,new K$(this.permissionsService));const S=new T$(this.shellStreamExecutor);this.register(zT,ng(S));const k=!1===e.enableWriteBackgroundShellStdin?new XT((async()=>{throw new Error(e.writeBackgroundShellStdinDisabledReason??"write_shell_stdin is disabled for this session")})):new XT(((e,t)=>this.backgroundShellExecutor.writeStdin(e,t)));if(this.register(UT,ng(k,void 0,this.shellRedeliveryCaches.writeStdin)),e.computerUseExecutor&&(this.computerUseExecutor=e.computerUseExecutor,this.register(GT,ng(this.computerUseExecutor))),this.enableRecordScreen){if(!this.recordScreenArtifactsDir||!this.recordScreenDisplay)throw new Error("recordScreenArtifactsDir and recordScreenDisplay are required when enableRecordScreen is true");this.recordScreenExecutor=new YA({artifactsDir:this.recordScreenArtifactsDir,display:this.recordScreenDisplay,disablePolishedRendering:this.disableRecordScreenRendering,polishedRenderer:e.polishedRecordingRenderer}),this.register(VT,ng(this.recordScreenExecutor))}}createOwnedRequestContextExecutor(e,t,r){const n=new C$(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,Zo.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,bM.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 X(e,[K(re,this.shellStreamExecutor.pendingFrom(e))])}async dispose(){this.requestContextExecutorAwaitingWarmup=void 0,this.rebuildRequestContextOnRulesChange&&(bM.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 _M(e){return e.replace(/\\/g,"/")}function CM(e,t){for(const r of t){const t=_M(r);if(e===t||e.startsWith(`${t}/`))return!0}return!1}var EM;function xM(e,t,r){if(function(e){return Boolean(e.plugin?.trim()||e.pluginId?.trim()||e.marketplaceId?.trim())}(e))return EM.Plugin;const n=_M(e.fullPath);return CM(n,r.builtinDirs)?EM.Builtin:am(e.fullPath,t).inAgentStore?EM.UserStore:CM(n,r.userDirs)?EM.UserHome:(CM(n,r.workspaceDirs),EM.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"}(EM||(EM={}));var PM=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 RM=(0,Ws.debuglog)("merged-agent-skills"),IM=(0,d.h)("merged-agent-skills");class TM{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,D.VI)(e.withName("MergedAgentSkillsService.getAllAgentSkills")),!1),n=this.services.map((e=>e.getAllAgentSkills(r.ctx).catch((e=>(RM("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 IM.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=lm(c,l??sm);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(AM));var t})),void 0!==l?function(e,t){if(e.length<=1)return e;const r=function(e){const t=[Bf(e.userHomeDirectory).dirPath],r=Kf(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 Vf(t,!0))n.push(e.dirPath)}return{builtinDirs:t,userDirs:r,workspaceDirs:n}}(t),n=e.map(((e,n)=>({skill:e,index:n,tier:xM(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{PM(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()}),TM.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()}}TM.CHANGE_COALESCE_MS=1500;const AM=`/${Ff.configDir}/${Ff.subdir}/`;function $M(e,t){if((e.disabledEnvironments??[]).includes(t))return!1;const r=e.environments??[];return 0===r.length||r.includes(t)}const MM=(0,d.h)("skill-sync-manifest"),DM=".sync-manifest.json",OM=new Set(["EPERM","EBUSY"]),FM=[20,50,100],NM=new Map;async function LM(e,t){try{const r=await(0,So.readFile)((0,s.join)(e,DM),"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:(MM.warn(t,"Manifest failed schema validation, resetting",{skillDir:e}),{version:1,skills:{}})}catch(r){return r instanceof Error&&"ENOENT"===yc(r)||MM.debug(t,"Failed to read sync manifest, resetting",{skillDir:e,error:String(r)}),{version:1,skills:{}}}}function jM(e,t,r){e.skills[t]={lastSyncedAt:r}}function UM(e,t){delete e.skills[t]}var BM=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 WM=(0,d.h)("builtin-skills-sync");function HM(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function qM(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 zM(e){const t=qd(e.content),r=HM(t.data)?t.data:{};return zd(`${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={...HM(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 GM(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 VM(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,So.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,So.mkdtemp)((0,s.join)(e,`.${t.id}-staging-`)),o=`${n}-backup`;let i=!1;try{await(0,So.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,So.mkdir)((0,s.dirname)(t),{recursive:!0}),await(0,So.writeFile)(t,r,"utf-8")}try{await(0,So.rename)(r,o),i=!0}catch(e){if(!(e instanceof Error)||"ENOENT"!==yc(e))throw e}try{await(0,So.rename)(n,r)}catch(e){throw i&&(await(0,So.rename)(o,r),i=!1),e}i&&(await(0,So.rm)(o,{recursive:!0,force:!0}),i=!1)}finally{await(0,So.rm)(n,{recursive:!0,force:!0})}}(t,r),!0}try{if(await(0,So.readFile)(o,"utf-8")===i)return!1}catch(t){t instanceof Error&&"ENOENT"===yc(t)||WM.warn(e,"Unexpected error reading skill file",{skillId:r.id,error:String(t)})}return await(0,So.mkdir)(n,{recursive:!0}),await(0,So.writeFile)(o,i,"utf-8"),!0}async function VM(e,t=""){const r=t?(0,s.join)(e,...t.split("/")):e;let n;try{n=await(0,So.readdir)(r,{withFileTypes:!0})}catch(e){if(e instanceof Error&&"ENOENT"===yc(e))return[];throw e}const o=[];for(const r of n){const n=t?`${t}/${r.name}`:r.name;r.isDirectory()?o.push(...await VM(e,n)):r.isFile()&&r.name.endsWith(".md")&&"SKILL.md"!==n&&o.push(n)}return o}async function KM(e,t){try{return(await(0,So.readdir)(t,{withFileTypes:!0})).filter((e=>e.isDirectory()&&!e.name.startsWith("."))).map((e=>e.name))}catch(r){return r instanceof Error&&"ENOENT"===yc(r)||WM.warn(e,"Failed to list skills directory, skipping cleanup",{skillDir:t,error:String(r)}),[]}}async function JM(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,D.VI)(e.withName("syncBuiltinSkills")),!1).ctx,a=Date.now(),c=t.userHome??(0,o.homedir)(),l=t.skillDir??Bf(c).dirPath;await(0,So.mkdir)(l,{recursive:!0});const[u,d]=await Promise.all([LM(l,i),KM(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([ZM((0,s.join)(r,"SKILL.md")),"canvas"===e?ZM((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}})));WM.info(e,"managed_skills.startup_inventory",{skills_on_disk:o,manifest_present:Object.keys(n.skills).length>0})}catch(t){WM.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):WM.warn(i,"Skipping managed skill with unsafe id",{skillId:e.id});const f=void 0===t.canvasKit?void 0:Hf(c,t.canvasKit).dirPath,m=void 0!==f&&await ZM((0,s.join)(f,Wf)),g=new Set([...p.keys(),...d,...m?[Wf]:[]]),w=e=>void 0!==f&&e===Wf?f:l,y=e=>void 0!==f&&e===Wf?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&&$M(t,"local"),d=void 0!==t&&!c,h=void 0!==r||y(e),f=w(e);if(t&&!1!==t.enabled&&c)qM(t),f!==l&&await(0,So.mkdir)(f,{recursive:!0}),await GM(i,f,{id:e,fileContent:zM(t),resources:t.resources??{}})?v++:b++,jM(u,e,a);else if(!1===t?.enabled||d||o){const n=!1===t?.enabled?"enabled_false":d?"environment_ineligible":"grace_expired";await(0,So.rm)((0,s.join)(f,e),{recursive:!0,force:!0}),UM(u,e),h&&(S.push(e),WM.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||jM(u,e,a)}catch(t){WM.warn(i,"Failed to apply skill, will retry next sync",{skillId:e,error:String(t)})}try{await function(e,t){const r=(NM.get(e)??Promise.resolve()).then((()=>async function(e,t){const r=(0,s.join)(e,`${DM}.${process.pid}.${(0,wo.randomBytes)(6).toString("hex")}.tmp`);await(0,So.mkdir)(e,{recursive:!0});try{await(0,So.writeFile)(r,JSON.stringify(t,null,2),"utf-8"),await async function(e,t){for(let r=0;;r++)try{return void await(0,So.rename)(e,t)}catch(e){const t=yc(e),n=FM[r];if(void 0===n||void 0===t||!OM.has(t))throw e;await(0,Fr.cb)(n)}}(r,(0,s.join)(e,DM))}catch(e){throw await(0,So.rm)(r,{force:!0}).catch((()=>{})),e}}(e,t))),n=r.catch((()=>{}));return NM.set(e,n),n.then((()=>{NM.get(e)===n&&NM.delete(e)})),r}(l,u)}catch(e){!function(e){if(e instanceof Error&&"ENOENT"===yc(e))return!0;const t=String(e);return t.includes("ENOENT")||t.includes("no such file or directory")}(e)?WM.warn(i,"Failed to persist sync manifest",{skillDir:l,error:String(e)}):WM.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{BM(r)}var n}async function ZM(e){try{return await(0,So.stat)(e),!0}catch(e){const t=yc(e);if("ENOENT"===t||"ENOTDIR"===t)return!1;throw e}}const XM=(0,d.h)("managed-skills-sync");function QM(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 YM(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 eD{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(...QM(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=YM(n.url);r.has(e)||(r.add(e),t.push(n))}return t}(t)}}var tD=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 rD(e,t){return void 0===e?[]:(Array.isArray(e)?e:[e]).map((e=>({...e,userHomeDir:t})))}class nD{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??Gh,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: ${vc(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: ${vc(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(Pf));return this.plugins.filter((e=>"extension"!==e.identifier.source&&void 0===e.loadError&&e.installPath.length>0&&!t.has(Pf(e))))}async reloadPlugin(e){this.loadPromise&&await this.loadPromise;const t=rD(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 Ef({...l,log:l.log??this.pluginLogger,pluginFilter:r})}catch(t){this.pluginLogger.log("error",`reloadPlugin: source load failed for ${e.name}: ${vc(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,So.realpath)(r);if(!(await(0,So.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,So.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 Sf(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}: ${vc(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,b.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,D.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=rD(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??Gh,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(Cf(e,0,{userHomeDir:t.userHomeDir,onError:t.onError,log:r})),c&&a.length>0&&(d=Promise.allSettled(a.map((e=>Ef({...e,userHomeDir:e.userHomeDir??t.userHomeDir,log:e.log??r}))))),i&&l.push(async function(e={}){const t=e.log??Gh,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,So.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,So.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,So.realpath)(n)}catch(e){t.log("warn",`loadUserLocalPlugin ${r.name} rejected: failed to resolve symlink (${e instanceof Error?e.message:String(e)})`);continue}try{zp(a,e)}catch{t.log("warn",`loadUserLocalPlugin ${r.name} rejected: symlink target ${e} is outside ${o}`);continue}}if(!(await(0,So.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 Sf(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,So.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=xf(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=>xf(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: ${vc(e)}`),{plugins:[],failures:[],sourceUnavailable:!0}}}catch(t){e.error=t,e.hasError=!0}finally{tD(e)}}}var oD=r("../proto/dist/generated/aiserver/v1/dashboard_pb.js");const sD=BigInt(0),iD=BigInt(8),aD=BigInt(16),cD=BigInt(65535);function lD(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 uD(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 dD(e){const t=e.split(".");if(4!==t.length)return;let r=sD;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<<iD|BigInt(t)}return{version:4,value:r}}function hD(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=dD(n);if(!o)return;t.push(Number(o.value>>aD&cD)),t.push(Number(o.value&cD))}else{if(!/^[0-9a-f]{1,4}$/i.test(n))return;t.push(Number.parseInt(n,16))}}return t}function pD(e){return dD(e)??function(e){const t=uD(e);if(0===t.length||t.includes(":::"))return;const r=t.indexOf("::");if(-1===r){const e=hD(t);if(!e||8!==e.length)return;return{version:6,value:e.reduce(((e,t)=>e<<aD|BigInt(t)),sD)}}if(-1!==t.indexOf("::",r+1))return;const n=hD(t.slice(0,r)),o=hD(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<<aD|BigInt(t)),sD)}}(e)}function fD(e,t){const r=uD(e),n=uD(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=pD(t.slice(0,r)),o=pD(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 mD(e,t){if(!e.includes("*"))return e===t;const r=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${r}$`).test(t)}function gD(e,t){if(mD(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=uD(r.hostname);return!!fD(uD(n.hostname),o)&&mD(`${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=uD(t.slice(0,r));if(e.length>0)return`${e}/${t.slice(r+1).trim()}`}const n=lD(t);if(n)return uD(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=uD(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=lD(e);if(t)return uD(t.hostname);const r=uD(e);return r.length>0?r:void 0}(t);return!(!r||!n)&&fD(n,r)}async function wD(e){try{return await e.current()}catch{return}}function yD(e){try{const t=new URL(e);return`${t.protocol}//${t.host}${t.pathname}`}catch{return}}function vD({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||yv(t.url,n)?{blocked:!1}:{blocked:!0,reason:"teamNetworkAllowlist",message:"Not on the team network allowlist"}}function bD(e){const t=e?.trim();return t&&t.length>0?t:void 0}function SD(e,t,r){if(!0===r?.useCorePolicy)return!function(e,t){if(void 0===t)return!0;if(!0===t.disableAll)return!1;if(H_(e))return!0;if(V_(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=q_(t.command),n=z_(t.serverUrl);if(void 0===r&&void 0===n)return!1;const o=void 0===r||void 0!==e.command&&(0,nb.mD)(r,e.command),s=void 0===n||void 0!==e.url&&(0,nb.vc)(n,e.url);return o&&s}))}(e,t)}(e,r)||!0===t.allowUserOverrideMcpServers&&!G_(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=bD(e.command),n=bD(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&&gD(n,t.url);return o&&s}(t,e)))}class kD{constructor(e,t={}){this.dashboardClient=e,this.options=t}getTeamAdminSettings(){return this.dashboardClient.getTeamAdminSettingsOrEmptyIfNotInTeam(new oD.Byz(!0===this.options.supportsHostMcpBridgeExemption?{supportsHostMcpBridgeExemption:!0}:{}))}getTeamRepos(){return this.dashboardClient.getTeamReposOrEmptyIfNotInTeam(new oD.aYW({}))}}function _D(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 CD{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 ED{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 CD((()=>this.fetchSettings())),this.droppedReplies=new WeakSet,this.hostMcpBridgeClients=new WeakSet,this.mcpServerByClient=new WeakMap,this.teamRepos=new CD((()=>this.teamAdminSettingsProvider.getTeamRepos())),this.defaultAllowlist=new CD((()=>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 wD(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 wD(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 wD(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 wD(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(V_(e,r?.offMcpServerRules))return{blocked:!0,reason:"teamPolicy",message:"Blocked by team policy"};if(n){if(SD(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,nb.ME)(e.url,n);if(!o.allowed)return{blocked:!0,reason:"teamNetworkAllowlist",message:o.message};const s=vD({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?vD({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,nb._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=yD(t.url);return void 0!==n&&r.some((e=>yD(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,nb.rM)(e,t)));if(void 0!==r)return ib({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?"":ob(e.name);if(0===t.length)return[];const r=ib({mode:e.toolAllowlistMode,tools:e.toolAllowlist});return[{name:t,policy:r,flattened:cb(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===oD.h0i.WORKSPACE?"workspace":"system");var n;return{sandboxingDisabled:t?.sandboxing===oD.faf.DISABLED,networkingDisabled:t?.sandboxNetworking===oD._mX.ALWAYS_DISABLED,gitDisabled:t?.sandboxGit===oD.i24.ALWAYS_DISABLED,readBoundary:r,readAllowlistPaths:_D(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 xD=new Gw,PD={async resolveWorkspaceState(e){const t=e.workingDirectory??e.projectRoot??e.workspaceRoots?.[0],r=e.projectRoot??(void 0!==t?await Za((0,b.q6)(),xD,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?bo(r):void 0),workspaceRoots:n,createdAt:new Date}}},RD=(0,d.h)("ControlledConversationActionManager");class ID{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,f.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 c.QFf({action:{case:"cancelAction",value:new c.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 f.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 f.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 f.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 f.W2("ControlledConversationActionManager disposed");this.acceptsActions=!1,this.clientStream.close(),this.clientStream=(0,f.Jt)(),this.acceptsActions=!0,this.abortController=new AbortController,this.abortStarted=!1;for(const e of this.unprocessedUserMessages)this.clientStream.write(new c.QFf({action:{case:"userMessageAction",value:new c.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){RD.error(e,"Error writing conversation action",t)}}catch(e){if(!(e instanceof f.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 f.W2("ControlledConversationActionManager disposed")))}}var TD=r("../cursor-sdk-local-runtime/dist/utils/logger.js"),AD=r("../agent-kv/dist/agent-store.js");const $D="x-blob-encryption-key";function MD(e,t){const r={...t};return void 0!==r[$D]||(0,AD.TU)(e)&&(r[$D]=e),r}const DD=new Map;function OD(e){if("userMessageAction"===e.action.case)return e.action.value.userMessage?.text}function FD(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 ND(e){return new c.QFf({action:{case:"userMessageAction",value:new c.Vtf({userMessage:new c.RGk({text:e})})}})}function LD(e){return e instanceof DOMException&&"AbortError"===e.name||e instanceof Error&&("AbortError"===e.name||"The operation was aborted"===e.message)}function jD(e){e?.catch((e=>{TD.Jz.warn("[agent-session-runner] fire-and-forget hook failed:",e)}))}const UD=new Set(["mcp.slack.com","setup.shopify.com"]);async function BD(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?Rv(e):void 0}({serverUrl:i,restMcpHost:a}));var i,a;if(!UD.has(o)&&!s)return t;let c=await r.resolve(e);if(!c&&s){const t=(await IE(e,n))?.clientId;void 0!==t&&(c={CLIENT_ID:t})}return c?t?void 0===PE(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 WD{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 BD(e.serverConfig,this.resolver);return t===e.serverConfig?e:{...e,serverConfig:t}})))}clearCache(){this.inner.clearCache?.()}}class HD{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 qD{constructor(e,t){this.storage=e,this.prefix=t}async isServerApproved(e,t,r){return this.storage.isServerApproved(this.prefix+e,t,r)}}class zD{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 X_(t,n.configPath??"another config")}return await o(e,r)}}class GD{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 CR(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 VD{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 BR(e,"enterprise"===r||"env"===r?GC:void 0)}))),y=[];for(const{prefix:e,scope:o,fileSource:s}of w){const l=i?"":e,d=new HD(t,l),p=new qD(n,l),f=w.flatMap((e=>{return t=e.scope,r=o,VC.indexOf(t)<VC.indexOf(r)&&("enterprise"===t||"env"===r)?[e.fileSource]:[];var t,r})),m=[new hC,...KC(o)?[new Y_(p)]:[],new zR(r),...c?[new Q_(c)]:[],...f.length>0?[new zD(f)]:[]],g=new WR(u?new WD(s,u):s,d,m,{authRedirectUrlGenerator:a,isLinkSharedPaymentTokenLogRedactionEnabled:h});y.push({prefix:l,loader:g})}this.loader=new GD(y)}static init(e,t,r,n=!1,o,i={}){const a=new XR(s.join(r,"mcp-auth.json"));(async function(e){await(0,So.rm)(s.join(e,"mcp-cache.json"),{force:!0})})(r).catch((()=>{}));const c=n?{isServerApproved:()=>Promise.resolve(!0)}:new eC(s.join(r,"mcp-approvals.json"),t);return new VD(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 KD="cursor-plugins/local";function JD(e){var t;if(e)for(const r of e)if("object"==typeof(t=r)&&null!==t&&t.kind===KD)return r}class ZD extends _R{constructor(e){super(e),this.runtimeManager=e,this.disposed=!1}async dispose(){this.disposed||(this.disposed=!0,await this.runtimeManager.closeAllClients())}}class XD{constructor(e){this.storagePath=e}async isServerDisabled(e){try{const t=await(0,So.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,So.mkdir)((0,s.dirname)(this.storagePath),{recursive:!0}),await(0,So.writeFile)(this.storagePath,JSON.stringify(e,null,2))}}class QD{constructor(e,t){this.pluginMcpService=e,this.importThirdPartyPlugins=t}async getDefinitions(){let e;try{e=await this.pluginMcpService.getPluginMcpServers()}catch(e){return TD.Jz.warn("[cursor-config-mcp] Failed to enumerate plugin MCP servers:",e),[]}const t=[];for(const r of e){if(!this.importThirdPartyPlugins&&nO(r))continue;const e=VR(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}}):TD.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 YD{constructor(e){this.servers=e}async getDefinitions(){return Object.entries(this.servers).map((([e,t])=>({identifier:e,authStorageKey:`inline:${e}`,serverConfig:rO(e,t),source:"inline",metadata:{source:"cursor-sdk"}})))}}function eO(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 kR;const d=new XD((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 VD.init(t,r,n,i,a,{isLinkSharedPaymentTokenLogRedactionEnabled:u});if(!c&&!l)return;const d=new XR((0,s.join)(n,"mcp-auth.json")),h=i?{isServerApproved:()=>Promise.resolve(!0)}:new eC((0,s.join)(n,"mcp-approvals.json"),r),p=[new hC,new Y_(h),new zR(t),new Q_(a)],f=[];return c&&f.push({prefix:"",loader:new GR((0,s.join)(r,".cursor","mcp.json"),d,p,{isLinkSharedPaymentTokenLogRedactionEnabled:u})}),l&&f.push({prefix:"",loader:new GR((0,s.join)((0,o.homedir)(),".cursor","mcp.json"),d,p,{isLinkSharedPaymentTokenLogRedactionEnabled:u})}),tO(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 XR((0,s.join)(u,"mcp-auth.json")),r=[new hC,new zR(t)];p.push({prefix:"",loader:new WR(new YD(f),e,r,i)})}const m=JD(a.services.pluginBootstrapOutputs);if(m&&(e.includePluginMcp??1)){const e=new eC((0,s.join)(u,"mcp-approvals.json"),l),o=new XR((0,s.join)(u,"mcp-auth.json")),a=[new hC];r||a.push(new Y_(e)),a.push(new zR(t),new Q_(d));const c=new eD(m.pluginsService),h=new WR(new QD(c,n),o,a,i);p.push({prefix:"",loader:h})}if(h&&p.push({prefix:"",loader:h}),0===p.length)return new kR;const g=tO(p),w=await g.load(e.initializationCtx??(0,b.q6)(),e.cache);return new ZD(w)}}}function tO(e){return 1===e.length?e[0].loader:new GD(e)}function rO(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 nO(e){return"claude-plugin"===e.pluginSource}const oO=["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass"];function sO(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 iO(e){return e.slice(Math.max(e.lastIndexOf("\\"),e.lastIndexOf("/"))+1)}const aO=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 cO(e){const t=sO(e),r=iO(t);return!aO.has(r.toLowerCase())&&(!!/\.(exe|bat|cmd|com)$/i.test(r)||t===r&&/^[A-Za-z0-9_]+$/.test(r))}function lO(e){if(cO(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=sO(e),r=iO(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=sO(e);if(0===t.length||cO(e))return!1;const r=iO(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 uO=[".ps1",".exe",".bat",".cmd"];function dO(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 hO(e){return e?.enableClaudeNestedHookSpecificOutputCompatibility??!1}function pO(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function fO(e){if(!pO(e))return;const t=e.hookSpecificOutput;return pO(t)?t:void 0}function mO(e,t){if(!e)return!1;const r=e.hookEventName;return void 0===r||""===r||r===t}function gO(e,t,r){if(!pO(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(!hO(t))return n;const o=fO(e),s=mO(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 wO=e=>{const t=[];return yd(e)?bd(!0):(t.push("Expected an object"),bd(!1,t))},yO=e=>{const t=[],r=wO(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"),bd(0===t.length,t)};function vO(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 bO=new Set([gd.sessionStart,gd.beforeSubmitPrompt,gd.preToolUse,gd.postToolUse,gd.postToolUseFailure]);function SO(e){return"prompt"===e.type}function kO(e){return"command"===e.type||void 0===e.type}const _O={[gd.beforeShellExecution]:yO,[gd.beforeMCPExecution]:yO,[gd.afterShellExecution]:e=>{const t=wO(e);return t.isValid,t},[gd.afterMCPExecution]:e=>{const t=wO(e);return t.isValid,t},[gd.beforeReadFile]:e=>{const t=[],r=wO(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"),bd(0===t.length,t)},[gd.afterFileEdit]:e=>{const t=wO(e);return t.isValid,t},[gd.beforeTabFileRead]:e=>{const t=[],r=wO(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"),bd(0===t.length,t)},[gd.afterTabFileEdit]:e=>wO(e),[gd.beforeSubmitPrompt]:e=>{const t=wO(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||wd(e.additional_context)||r.push("additional_context must be a string if provided"),bd(0===r.length,r)},[gd.stop]:e=>{const t=wO(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"),bd(0===r.length,r)},[gd.afterAgentResponse]:e=>{const t=wO(e);return t.isValid,t},[gd.afterAgentThought]:e=>{const t=wO(e);return t.isValid,t},[gd.sessionStart]:e=>{const t=wO(e);if(!t.isValid)return t;const r=[];if(void 0!==e.env)if(yd(e.env))for(const[t,n]of Object.entries(e.env))wd(t)||r.push(`env key "${t}" must be a string`),wd(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||wd(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||wd(e.user_message)||r.push("user_message must be a string if provided"),bd(0===r.length,r)},[gd.sessionEnd]:e=>{const t=wO(e);return t.isValid?bd(!0,[]):t},[gd.preCompact]:e=>{const t=wO(e);if(!t.isValid)return t;if(null==e||0===Object.keys(e).length)return bd(!0,[]);const r=[];if(!vd(e))return r.push("PreCompact response must be an object"),bd(!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"),bd(0===r.length,r)},[gd.subagentStart]:e=>{const t=wO(e);if(!t.isValid)return t;if(!vd(e))return bd(!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||wd(n.user_message)||r.push("user_message must be a string if provided"),bd(0===r.length,r)},[gd.subagentStop]:e=>{const t=wO(e);if(!t.isValid)return t;const r=[];return vd(e)&&void 0!==e.followup_message&&"string"!=typeof e.followup_message&&r.push("followup_message must be a string if provided"),bd(0===r.length,r)},[gd.preToolUse]:e=>{const t=[],r=wO(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"),Sd(e.additional_context,"additional_context",t),bd(0===t.length,t)},[gd.postToolUse]:e=>{const t=[],r=wO(e);return r.isValid?(Sd(e.additional_context,"additional_context",t),bd(0===t.length,t)):r},[gd.postToolUseFailure]:e=>{const t=wO(e);if(!t.isValid)return t;const r=[];return Sd(e.additional_context,"additional_context",r),bd(0===r.length,r)},[gd.workspaceOpen]:e=>{const t=wO(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")),bd(0===r.length,r)}},CO=(e,t,r)=>{const n=function(e,t,r){let n;return n=e===gd.preToolUse?function(e,t){if(!pO(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(!hO(t))return r;const n=fO(e);if(!mO(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),pO(n.updatedInput)&&(o.updated_input=n.updatedInput,s=!0),s?o:r}(t,r):e===gd.stop?gO(t,r,"Stop"):e===gd.subagentStop?gO(t,r,"SubagentStop"):t,function(e,t,r,n){if(!bO.has(e)||!pO(r)||void 0!==r.additional_context)return r;const o=pO(t)?function(e){return"string"==typeof e.additionalContext?e.additionalContext:void 0}(t)??function(e,t,r){if(!hO(r))return;const n=xd[e];if(void 0===n)return;const o=fO(t);return mO(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,_O[e])(n);return o.isValid?{success:!0,data:n}:{success:!1,errors:o.errors}},EO=[gd.beforeShellExecution,gd.beforeMCPExecution,gd.beforeReadFile,gd.beforeTabFileRead,gd.subagentStart,gd.preToolUse],xO=[gd.workspaceOpen];function PO(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 RO(e,t){return{..."object"==typeof e&&null!==e?e:{},...t}}function IO(e){return EO.includes(e)}function TO({step:e,command:t,failClosed:r,kind:n}){const o=IO(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:$O(e,s),cause:r?"script_fail_closed":"permission_hook_invalid_output",reason:s,shouldNotifyUser:o&&!r}}function AO(e,t){return t}function $O(e,t){return IO(e)?AO(0,{permission:"deny",user_message:t}):e===gd.beforeSubmitPrompt||e===gd.sessionStart?AO(0,{continue:!1,user_message:t}):e===gd.stop?AO(0,{}):void 0}function MO(e){try{return{value:JSON.parse(e)}}catch{return}}function DO(e){if("object"!=typeof e||null===e)return!1;const t=e.event;return"backgrounded"===t?.case}function OO(e){if("object"!=typeof e||null===e)return;const t=e.path;return"string"==typeof t&&t.length>0?t:void 0}class FO{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>FO.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===lT.symbol||e===uT.symbol?{kind:"path"}:e===sT.symbol||e===re.symbol||e===jT.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=OO(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===re.symbol&&DO(r)){if(!t){u(o,n);const e=await f(n,l);t=!0,e.length>0&&(yield new fe.FI({event:{case:"hookContext",value:new fe.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===lT.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=OO(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,Fr.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 NO(e){return new RegExp(`<${e}(?:\\s[^>]*)?>[\\s\\S]*?</${e}>`,"gi")}FO.CARRIERS_BY_EXEC_ID_MAX=32,Error,Kl.execFileSync,new Map,_o.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 LO=["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(NO);function jO(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(UO,"\n\n"):r).trim()}(e,LO)}["system_reminder","system-reminder"].map(NO);const UO=/\n{3,}/g;function BO(e){const t=(0,yo.sh)(e.conversationId);if("subagent"===e.kind&&e.parentConversationId){const r=(0,yo.sh)(e.parentConversationId);return`${yo.O2}/${r}/subagents/${t}.${e.ext}`}return`${yo.O2}/${t}/${t}.${e.ext}`}function WO(e){const t=(0,yo.sh)(e.conversationId);return`${yo.O2}/${t}.${e.ext}`}function HO(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(BO({conversationId:e.conversationId,ext:n,kind:e.kind,parentConversationId:e.parentConversationId})),"subagent"===e.kind&&e.parentConversationId&&o(BO({conversationId:e.conversationId,ext:n,kind:"primary"})),r&&o(WO({conversationId:e.conversationId,ext:n}));return n}var qO;!function(e){e.INTERNAL="INTERNAL",e.EXTERNAL="EXTERNAL",e.NO_PREAMBLE="NO_PREAMBLE"}(qO||(qO={}));var zO=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},GO=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 VO(e){switch(e){case c.xyI.AGENT:return"agent";case c.xyI.ASK:return"ask";case c.xyI.PLAN:return"plan";case c.xyI.DEBUG:return"debug";case c.xyI.TRIAGE:return"triage";case c.xyI.MULTITASK:return"multitask";case c.xyI.CUSTOM:return"custom";case c.xyI.UNSPECIFIED:default:return"agent"}}function KO(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 JO(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 ZO=new TextEncoder,XO=new TextDecoder,QO=new class{serialize(e){const t=JSON.stringify(e,KO);return ZO.encode(t)}deserialize(e){const t=XO.decode(e);return t.includes('"__type":"Uint8Array"')?JSON.parse(t,JO):JSON.parse(t)}};function YO(e){const t=e.providerOptions;return!0===t?.cursor?.isSummary}function eF(e){return"system"!==e.role&&!YO(e)}function tF(e,t){return"user"===e.role&&"user"===t.role}async function rF(e,t,r){const n=await t.getBlob(e,r);return n?c.Anz.fromBinary(n).summarizedMessages:[]}async function nF(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=QO.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 oF(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 nF(e,t,o,n);r&&n.messages.push(r)}return n}async function sF(e,t,r,n,o){const s=[];let i=0;const a=()=>{const o=nF(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 iF(e,t){switch(e.type){case"text":return t?aF(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 aF(e){return jO(e)}const cF=/<think>[\s\S]*?<\/think>/gi,lF=/<thinking>[\s\S]*?<\/thinking>/gi,uF=/\n{3,}/g;function dF(e){let t=e;return t.includes("<")&&(t=t.replace(cF,"").replace(lF,"")),(t.includes("\n\n\n")?t.replace(uF,"\n\n"):t).trim()}function hF(e,t,r){if(void 0===e)return"";if("string"==typeof e){const n=t?aF(e):e;return r?dF(n):n}return e.map((e=>{if(r&&"text"===e.type){const r=dF(t?aF(e.text):e.text);return iF({...e,text:r},!1)}return iF(e,t)})).filter(Boolean).join("\n")}function pF(e,t){const r={role:e.role},n=e.content;if("string"==typeof n){const o=t?aF(n):n,s="assistant"===e.role?dF(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?aF(r.text):r.text,s="assistant"===e.role?dF(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 fF(e){return e.endsWith("\n")?e:`${e}\n`}function mF(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 gF(e){if("system"===e.role||YO(e))return;const t=pF(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 wF{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=BO({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=zO(o,(0,D.VI)(e.withName("writeFromState")),!1);try{const{overviewFactory:e}=n,o=mF(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=zO(n,(0,D.VI)(e.withName("hydrateSummaryArchives")),!1);let s=0;const i=(0,D.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 rF(i,t,e);return s+=r.length,await oF(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=zO(n,(0,D.VI)(e.withName("hydratePromptMessages")),!1),w=await oF(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(eF);return a.push(...y),a}catch(e){n.error=e,n.hasError=!0}finally{GO(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=hF(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=pF(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:VO(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&&tF(t[0],t[1])&&(t=t.slice(1));const r=[];for(const e of t){const t=gF(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"),fF(n))}return!0}catch(e){return console.error("[TranscriptStore] Failed to write transcript:",e),!1}}catch(e){o.error=e,o.hasError=!0}finally{GO(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 rF(e,t,s)}catch{continue}await sF(e,t,r,o,{skipFailedReads:!0,visit:n})}return await sF(e,t,r.rootPromptMessagesJson,o,{skipFailedReads:!1,visit:async e=>{eF(e)&&await n(e)}}),o}((0,D.OA)(e.ctx),this.blobStore,t.state,(async e=>{"system"!==e.role&&(d++,1!==d?(2===d&&u&&(tF(u,e)||await l(gF(u)),u=void 0),await l(gF(e))):u=e)}));u&&await l(gF(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=mF(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=zO(s,(0,D.VI)(e.withName("writeFromStateIncremental")),!1);if(i===n&&c)try{return await l(this.resolveFilePath(r,"jsonl"),fF(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 oF(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=gF(e);t&&s.push(t)}if(s.push(...a.jsonlLines),s.length>0){const e=fF(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{GO(s)}}}function yF(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 vF(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 bF(e){return`Tool blocked because this hook is configured to fail closed (block when it fails). ${e}`}function SF(e){return Object.values(gd).some((t=>t===e))}function kF(e){switch(e??(0,o.platform)()){case"darwin":return s.join("/Library","Application Support","Cursor","hooks.json");case"win32":return s.join("C:\\","ProgramData","Cursor","hooks.json");default:return s.join("/etc","cursor","hooks.json")}}function _F(e){return SO(e)?`prompt:${e.prompt}`:`command:${e.command}`}function CF(e){return(e.repoHooks??[]).flatMap((e=>[e.projectHooks,e.claudeProjectHooks,e.claudeProjectLocalHooks]))}class EF{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.dirname(s.dirname(n)):void 0,i=(e,t)=>{if(!e||!o)return;if(t)return o;const r=s.relative(s.resolve(o),s.resolve(e));return".."===r||r.startsWith(`..${s.sep}`)||s.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.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(_F(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=_F(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(!vd(e))return!1;if(!("hooks"in e))return!1;const r=e.hooks;if(!vd(r))return!1;const n=r;for(const[e,r]of Object.entries(n))if(e in Ed&&Array.isArray(r)){const n=!0===t.allowMatcherlessStop&&"Stop"===e;for(const e of r)if(vd(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=Bd(r,this.logger),o=Cd(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=Cd(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,...CF(e)];for(const e of r)if(e?.hooks)for(const r of Object.keys(e.hooks))SF(r)&&t.add(r);for(const r of e.pluginHooks??[])for(const e of Object.keys(r.config.hooks))SF(e)&&t.add(e);return t}}const xF="Read",PF="Write",RF="Delete",IF="List",TF="Grep",AF="Shell",$F="ReadLints";function MF(e,t){if("object"==typeof e&&null!==e)return Object.getOwnPropertyDescriptor(e,t)?.value}const DF=new Set([xF,PF,RF,IF,TF,$F]);function OF(e){const t=MF(e,"tool_name"),r=[MF(e,"file_path"),"string"==typeof t&&DF.has(t)?MF(MF(e,"tool_input"),"file_path"):void 0];for(const e of r)if("string"==typeof e&&e.length>0)return e}const FF=(0,d.h)("cli-hooks-executor");function NF(e){try{return(0,_o.statSync)(e).isFile()}catch{return!1}}const LF="\nJSON Parse Error: Error: Failed to parse hook stdout as JSON";function jF(e,t){for(const[r,n]of Object.entries(e))if(r===t)return n}function UF(e,t){const r=jF(e,t);if("string"==typeof r||null===r)return r}class BF{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,_p.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,yo.Rv)((0,o.homedir)(),this.workspacePath),r=this.transcriptParentConversationIdById.get(e),n=HO(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,So.access)(e),e}catch{}return null}catch{return null}}async getSubagentTranscriptPathIfExists(e){const{subagentId:t,parentConversationId:r}=e;try{const e=(0,yo.Rv)((0,o.homedir)(),this.workspacePath),n=HO({conversationId:t,kind:"subagent",parentConversationId:r}).map((t=>(0,s.join)(e,t)));for(const e of n)try{return await(0,So.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,...CF(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?vF(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?vF(n,t):n).some((e=>kO(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=jF(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 xO.includes(e)}(e),o=t,i=n?null:o.conversation_id?await this.getTranscriptPathIfExists(o.conversation_id):null;let a;if(e===gd.subagentStop){const e=UF(t,"subagent_id"),r=UF(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===gd.subagentStop&&{agent_transcript_path:a??null}},u=function(e,t){switch(e){case"beforeShellExecution":case"afterShellExecution":return yF(t,"command");case"beforeMCPExecution":case"afterMCPExecution":{const e=yF(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 yF(t,"subagent_type");case"preToolUse":case"postToolUse":case"postToolUseFailure":return yF(t,"tool_name");default:return}}(e,l),d=[],h=(e,t,n)=>{if(!e)return;const o=vF(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)SO(e)?this.promptHookClient&&d.push({type:"prompt",script:e,source:t}):kO(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,Zo.o1)(t,r),[o,i,a]=await Promise.all([(0,Zo.DN)(n),(0,Zo.DN)(s.dirname(n)),Promise.all(e.map((async e=>await(0,Zo.DN)(e.repoPath)??s.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.relative(o,t);(""===i||".."!==i&&!i.startsWith(`..${s.sep}`)&&!s.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.join(i,s.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:OF(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===gd.stop||e===gd.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 vF(n,u))kO(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=bF(`Hook execution failed: ${n}`),r=$O(e,t);if(r)return{success:!0,data:r,source:i,index:o}}return FF.warn((0,b.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||vd(n=r)&&vd(n.updated_input)&&0===Object.keys(n.updated_input).length))return r;var n;const o=EO.includes(e),s=e===gd.sessionStart,i=e===gd.workspaceOpen,a=bO.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]=PO(c[e],r):"continue"!==e||"boolean"!=typeof r?c[e]=s&&"env"===e&&"object"==typeof r&&null!==r?RO(c[e],r):r:void 0===c[e]?c[e]=r:c[e]=c[e]&&r:void 0===c[e]&&vd(r)&&Object.keys(r).length>0&&(c[e]=r):c[e]=PO(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=$O(e,bF(`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=$O(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=$O(e,bF(`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=$O(e,bF(`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=MO(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=MO(t.slice(e));if(void 0!==r)return r.value}}(g);if(void 0===w){const r=TO({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+LF}),{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+LF}),{success:!1,source:s,index:i})}const y=CO(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=TO({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,b.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 IO(e)?AO(0,{permission:"allow"}):e===gd.beforeSubmitPrompt||e===gd.sessionStart?AO(0,{continue:!0}):e===gd.stop?AO(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=$O(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=$O(e,bF(`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=uO.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:NF}):t.command;let w;if(m)w=e?dO(g):g;else if("windows_temp_file"===f){d=await(0,So.mkdtemp)((0,s.join)((0,o.tmpdir)(),"cursor-hooks-"));const e=(0,s.join)(d,"payload.json");await(0,So.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 | ${dO(t)} }`+lO(t)}(e,g)}else w=e?`@'\n${c.replace(/'/g,"''")}\n'@ | & ${g}`+lO(g):`${t.command} <<'CURSOR_HOOK_EOF'\n${c}\nCURSOR_HOOK_EOF`;const y=UF(n,"conversation_id")??void 0,v=UF(n,"session_id")??void 0,S=UF(n,"transcript_path"),k=void 0===y?void 0:this.activeSessionIdsByConversationId.get(y),_=void 0===v||v===y&&!this.sessionEnvById.has(v)?void 0===y?void 0:k?.at(-1)??y:v,C=this.buildHookEnvironment({transcriptPath:S,sessionId:_,conversationId:y,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,b.q6)(),P=new na.StringDecoder("utf8"),R=new na.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,So.rm)(d,{recursive:!0,force:!0})}catch{}}}}class WF{constructor(e){this.config=e,this.configuredSteps=EF.getConfiguredSteps(e)}getConfig(){return this.config}hasHookForStep(e){return this.configuredSteps.has(e)}getConfiguredSteps(){return new Set(this.configuredSteps)}}var HF=r("node:perf_hooks");const qF=(0,b.cF)(Symbol.for("@anysphere/agent-exec/toolCallHooks"),{kind:"none"});function zF(e){return"inExecute"!==e.get(qF).kind}function GF(e,t){const r=e.get(qF);return"inExecute"!==r.kind||!r.toolStepsInPreToolUse.includes(t)}(0,b.cF)(Symbol.for("@anysphere/agent-exec/hookAsk"),void 0),(0,b.cF)(Symbol.for("@anysphere/agent-exec/hookAllow"),void 0),new WeakMap,new WeakMap,(0,b.cF)(Symbol.for("@anysphere/agent-exec/toolCallRefusal"),void 0),new WeakMap,new WeakMap,new WeakMap,(0,b.cF)(Symbol.for("@anysphere/agent-exec/approvalWaits"),void 0),new WeakMap;const VF=(0,b.cF)(Symbol.for("@anysphere/agent-exec/hookStepTime"),void 0),KF=new cd.AsyncLocalStorage;function JF(e,t){return KF.run(e,t)}function ZF(e,t){void 0!==e&&t.length>0&&e.push(...t)}class XF 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 QF=r("../proto/dist/generated/agent/v1/hook_additional_context_pb.js");function YF({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 XF({hookEventName:e,actualLength:r.length,maxLength:1e4});return[new QF.C({hookEventName:e,content:r})]}Object.fromEntries(Array.from(bO).map((e=>{if(!function(e){return e===gd.sessionStart||e===gd.beforeSubmitPrompt||e===gd.preToolUse||e===gd.postToolUse||e===gd.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 eN="Agent note: Do not suggest workarounds to the blocked tool.";function tN(e){return e.includes(eN)?e:`${e}\n\n${eN}`}class rN extends Error{constructor(e){super(`Hook denied: ${e}`),this.failureType="permission_denied",this.name="HookDeniedError",this.reason=e}}class nN extends Error{constructor(e,t){super(`Hook failed (fail-closed): ${e}`),this.failureType="error",this.name="FailClosedError",this.reason=e,this.cause=t}}const oN="To view or modify configured hooks, go to Cursor Settings > Hooks.";function sN(e,t){return tN(`${t?`${e} was blocked by a hook: ${t}`:`${e} was blocked by a hook.`}\n\n${oN}`)}function iN(e){return function(e){return e instanceof rN}(e)||function(e){return e instanceof nN}(e)}const aN=(0,d.h)("generic-hooks");function cN(e,t,r,n){try{return YF({hookEventName:r,additionalContext:n})}catch(n){if(n instanceof XF)return aN.warn(e,`${r} additional_context exceeded max size; dropping carrier`,{toolName:t,hookEventName:r,actualLength:n.actualLength,maxLength:n.maxLength}),[];throw n}}const lN=e=>Math.round(1e3*e)/1e3;function uN(e,t,r,n,o,s){const i=n(e),a=o.getToolCallId?.(t)??(0,wo.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 JF(e.signal,(()=>t.executeHookForStep(gd.postToolUseFailure,{...a,tool_name:r,tool_input:o,error_message:l,failure_type:u,duration:n,tool_use_id:c,is_interrupt:d,...s})));ZF(i,cN(e,r,gd.postToolUseFailure,h?.additional_context))}catch(t){aN.warn(e,"postToolUseFailure hook error",{toolName:r,error:t instanceof Error?t.message:String(t)})}},fireSuccessAsync:async(n,l)=>{try{const u=await JF(e.signal,(()=>t.executeHookForStep(gd.postToolUse,{...a,tool_name:r,tool_input:o,tool_output:l,duration:n,tool_use_id:c,...s})));ZF(i,cN(e,r,gd.postToolUse,u?.additional_context))}catch(t){aN.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 dN(e,t,r,n,o,s,i,a){const{baseHookRequest:c,toolUseId:l,extraHookFields:u}=n;try{const a=await JF(e.signal,(()=>r.executeHookForStep(gd.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=tN(r);try{ZF(n.hookContextCollector,YF({hookEventName:gd.preToolUse,additionalContext:a.additional_context}))}catch(t){if(!(t instanceof XF))throw t;aN.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))),ZF(n.hookContextCollector,YF({hookEventName:gd.preToolUse,additionalContext:a?.additional_context}))}catch(n){const a=r.hasFailClosedHooksForStep?.(gd.preToolUse,s.toolName)??!1,c=n instanceof XF;if(a){const e=bF(`${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}}aN.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(iN(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 hN(e){return e.toolCallId}function pN(e,t,r,n){return{async execute(o,s,i){const a=mN(o,t),{hookContext:c,helpers:l}=uN(o,s,a,r,n,i);let u;try{u=await dN(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=HF.performance.now();try{const t=await e.execute(o,s,i),r=lN(HF.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(iN(e))return await l.fireFailureAsync(r,e.reason,e.failureType),n.runCleanup?.(c.toolUseId),n.createRejectedResult(s,e.reason);aN.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=lN(HF.performance.now()-d);throw await l.fireFailureAsync(t,e instanceof Error?e.message:String(e),"error"),n.runCleanup?.(c.toolUseId),e}}}}function*fN(e,t){const r=t.hookContextCollector;e.createHookContextEvent&&void 0!==r&&0!==r.length&&(yield e.createHookContextEvent(r))}function mN(e,t){const r=zF(e),n=e.get(VF);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===gd.preToolUse||e===gd.postToolUse||e===gd.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 gN(e){if("object"!=typeof e||null===e||!("code"in e))return!1;const t=e.code;return"ENOENT"===t||"ENOTDIR"===t}class wN{async readFile(e){try{return await So.readFile(e,"utf-8")}catch(e){if("ENOENT"===e?.code)return;throw e}}async exists(e){try{return await So.access(e),!0}catch{return!1}}async pathContainsSymlink(e,t){return async function(e,t){const r=function(e,t){const r=s.resolve(e),n=s.resolve(t),o=s.relative(n,r);if(0===o.length||".."===o||o.startsWith(`..${s.sep}`)||s.isAbsolute(o))return"unsafe";const i=o.split(s.sep).filter((e=>e.length>0)),a=[];let c=n;for(const e of i)c=s.join(c,e),a.push(c);return a}(e,t);if("unsafe"===r)return!0;for(const e of r)try{if((await(0,So.lstat)(e)).isSymbolicLink())return!0}catch(e){if(gN(e))return!0;throw e}return!1}(e,t)}}var yN=r("../proto/dist/generated/agent/v1/hooks_pb.js");const vN=G("hook-executor",(e=>new H(e,Q("executeHookArgs"),Y("executeHookResult"))),((e,t)=>{t.register(new A(e,te("executeHookArgs"),ee("executeHookResult")))})),bN=new Set(Object.values(gd));function SN(e){switch(e){case"completed":case"aborted":case"error":return e;default:return"error"}}function kN(e){switch(e){case"error":case"timeout":case"permission_denied":return e;default:return"error"}}function _N(e){const t=e?.toJson();return"object"!=typeof t||null===t||Array.isArray(t)?{}:t}class CN{constructor(e){this.hookExecutor=e}hasFailClosedHooksForStep(e,t){return!!function(e){return bN.has(e)}(e)&&(this.hookExecutor.hasFailClosedHooksForStep?.(e,t)??!1)}async execute(e,t){const r=t.request;if(!r)return new p.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??"",...vO(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(gd.preCompact,t);return new p.S1({response:new p.w5({response:{case:"preCompact",value:new yN.$_({userMessage:n?.user_message})}})})}case"subagentStart":{const e=r.request.value,t={conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...vO(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(gd.subagentStart,t);return new p.S1({response:new p.w5({response:{case:"subagentStart",value:new yN.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??"",...vO(e),subagent_id:e.subagentId,subagent_type:e.subagentType,status:SN(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(gd.subagentStop,t);return new p.S1({response:new p.w5({response:{case:"subagentStop",value:new yN.AH({followupMessage:n?.followup_message,additionalContext:n?.additional_context})}})})}case"beforeSubmitPrompt":{const e=r.request.value,t=await this.hookExecutor.executeHookForStep(gd.beforeSubmitPrompt,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...vO(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 p.S1({response:new p.w5({response:{case:"beforeSubmitPrompt",value:new yN.u1({continue:t?.continue,userMessage:t?.user_message,additionalContext:t?.additional_context})}})})}case"afterAgentResponse":{const e=r.request.value;return await this.hookExecutor.executeHookForStep(gd.afterAgentResponse,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...vO(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 p.S1({response:new p.w5({response:{case:"afterAgentResponse",value:new yN.FW}})})}case"afterAgentThought":{const e=r.request.value;return await this.hookExecutor.executeHookForStep(gd.afterAgentThought,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...vO(e),text:e.text,duration_ms:void 0!==e.durationMs?Number(e.durationMs):void 0}),new p.S1({response:new p.w5({response:{case:"afterAgentThought",value:new yN.H}})})}case"stop":{const e=r.request.value,t=await this.hookExecutor.executeHookForStep(gd.stop,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...vO(e),status:SN(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 p.S1({response:new p.w5({response:{case:"stop",value:new yN.rT({followupMessage:t?.followup_message})}})})}case"preToolUse":{if(!zF(e))return this.skipToolUseStep();const t=r.request.value,n=_N(t.toolInput),o={conversation_id:t.conversationId??"",generation_id:t.generationId??"",model:t.model??"",...vO(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(gd.preToolUse,o);return new p.S1({response:new p.w5({response:{case:"preToolUse",value:new yN.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(!zF(e))return this.skipToolUseStep();const t=r.request.value,n=_N(t.toolInput),o={conversation_id:t.conversationId??"",generation_id:t.generationId??"",model:t.model??"",...vO(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(gd.postToolUse,o);return new p.S1({response:new p.w5({response:{case:"postToolUse",value:new yN.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(!zF(e))return this.skipToolUseStep();const t=r.request.value,n=_N(t.toolInput),o={conversation_id:t.conversationId??"",generation_id:t.generationId??"",model:t.model??"",...vO(t),...t.parentToolCallId?{parent_tool_call_id:t.parentToolCallId}:{},tool_name:t.toolName,tool_input:n,error_message:t.errorMessage,failure_type:kN(t.failureType),duration:Number(t.durationMs),tool_use_id:t.toolUseId,is_interrupt:t.isInterrupt},s=await this.hookExecutor.executeHookForStep(gd.postToolUseFailure,o);return new p.S1({response:new p.w5({response:{case:"postToolUseFailure",value:new yN.U1({additionalContext:s?.additional_context})}})})}default:return new p.S1({response:void 0})}var n}async skipToolUseStep(){return await this.hookExecutor.whenConfigReady(),new p.S1({response:void 0})}}class EN{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 Or.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 Or.bb;return o&&(t.hooksAdditionalContext=o),s&&(t.hooksConfig=s),new Or._G({result:{case:"success",value:new Or.yW({requestContext:t,servedFromDiskCache:n.result.value.servedFromDiskCache})}})}return n}}function xN(e){return!!e&&e.type!==ts.vc.INSECURE_NONE&&e.type!==ts.vc.UNSPECIFIED}async function PN({hookExecutor:e,baseHookRequest:t,toolUseId:r,command:n,cwd:o,sandbox:s}){const i=await e.executeHookForStep(gd.beforeShellExecution,{...t,command:n,cwd:o,sandbox:s,tool_use_id:r});if("deny"===i?.permission){const e=sN("Command execution",i.user_message);throw new rN(e)}if("ask"===i?.permission)return a=i.user_message,new fe.In({kind:fe.b.FORCE_PROMPT,reason:a});var a}const RN={toolName:AF,getToolCallId:hN,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 Ao.Lt({result:{case:"rejected",value:new fe.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=xN(r.sandboxPolicy);GF(t,gd.beforeShellExecution)&&Po(r,await PN({hookExecutor:o,baseHookRequest:n,toolUseId:s,command:r.command,cwd:i,sandbox:a}))}};class IN{constructor(e,t,r){this.wrappedExecutor=pN(e,t,r,RN)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const TN={toolName:"WriteShellStdin",createToolInput:e=>({shell_id:e.shellId,chars_length:e.chars.length}),createRejectedResult:(e,t)=>new Ao.nt({result:{case:"error",value:new Ao.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 AN{constructor(e,t,r){this.wrappedExecutor=pN(e,t,r,TN)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const $N={toolName:"ComputerUse",getToolCallId:hN,createToolInput:e=>({actions_count:e.actions.length}),createRejectedResult:(e,t)=>new og.ks({result:{case:"error",value:new og.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 MN{constructor(e,t,r){this.wrappedExecutor=pN(e,t,r,$N)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const DN={toolName:RF,getToolCallId:hN,createToolInput:e=>({file_path:e.path}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new cw.Pi({result:{case:"rejected",value:new cw.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 ON{constructor(e,t,r){this.wrappedExecutor=pN(e,t,r,DN)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const FN={toolName:$F,getToolCallId:hN,createToolInput:e=>({file_path:e.path}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new YT.Ek({result:{case:"rejected",value:new YT.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 NN{constructor(e,t,r){this.wrappedExecutor=pN(e,t,r,FN)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const LN={toolName:"Fetch",getToolCallId:hN,createToolInput:e=>({url:e.url}),applyUpdatedInput:(e,t)=>{"string"==typeof t.url&&(e.url=t.url)},createRejectedResult:(e,t)=>new mw.uN({result:{case:"error",value:new mw.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 jN{constructor(e,t,r){this.wrappedExecutor=pN(e,t,r,LN)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const UN={toolName:TF,getToolCallId:hN,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 Kw.Ud({result:{case:"error",value:new Kw.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 BN{constructor(e,t,r){this.wrappedExecutor=pN(e,t,r,UN)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const WN={toolName:IF,getToolCallId:hN,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 N_.fv({result:{case:"rejected",value:new N_.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 HN{constructor(e,t,r){this.wrappedExecutor=pN(e,t,r,WN)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const qN=(0,d.h)("hooks-exec:mcp");function zN(e){return!!(null===e||"string"==typeof e||"boolean"==typeof e||"number"==typeof e&&Number.isFinite(e))||(Array.isArray(e)?e.every(zN):"object"==typeof e&&Object.values(e).every((e=>void 0!==e&&zN(e))))}function GN(e,t,r,n){try{return YF({hookEventName:r,additionalContext:n})}catch(n){if(n instanceof XF)return qN.warn(e,`${r} additional_context exceeded max size; dropping carrier`,{toolName:t,hookEventName:r,actualLength:n.actualLength,maxLength:n.maxLength}),[];throw n}}class VN{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(gd.preToolUse)||!0===this.hooksConfigLease?.hasHookForStep(gd.beforeMCPExecution)))return new Rc.iz({result:{case:"error",value:new Rc.Nh({error:`"${_T}" 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=mN(e,this.hookExecutor),o=this.baseHookRequestExtractor(e),s=(0,wo.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(gd.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{ZF(i,YF({hookEventName:gd.preToolUse,additionalContext:r.additional_context}))}catch(t){if(!(t instanceof XF))throw t;qN.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 Rc.iz({result:{case:"permissionDenied",value:new Rc.HQ({error:sN("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(!zN(n))throw new TypeError("updated_input value is not JSON");t.args[e]=ve.Value.fromJson(n)}a=Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t?.toJson()])))}catch(t){qN.warn(e,"Failed to merge updated_input for MCP",{error:t instanceof Error?t.message:String(t)})}ZF(i,YF({hookEventName:gd.preToolUse,additionalContext:r?.additional_context}))}catch(t){const r=n.hasFailClosedHooksForStep?.(gd.preToolUse,c)??!1,l=t instanceof XF;if(r){const r=bF(`${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 Rc.iz({result:{case:"permissionDenied",value:new Rc.HQ({error:sN("MCP tool execution",r),isReadonly:!1})}})}qN.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=GF(e,gd.beforeMCPExecution)?await n.executeHookForStep(gd.beforeMCPExecution,f):void 0;if("deny"===m?.permission){const t=sN("MCP tool execution",m.user_message);return await this.firePostToolUseFailureAsync(e,n,o,c,a,t,"permission_denied",0,s,!1,i),new Rc.iz({result:{case:"permissionDenied",value:new Rc.HQ({error:t,isReadonly:!1})}})}const g=HF.performance.now();try{const l=await this.innerExecutor.execute(e,t,r),u=lN(HF.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){qN.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(gd.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 Rc._Z({content:{case:"text",value:new Rc.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 Rc._Z({content:{case:"text",value:new Rc.zN({text:String(e.text)})}})):t.push(new Rc._Z({content:{case:"text",value:new Rc.zN({text:JSON.stringify(e)})}}))}else t.push(new Rc._Z({content:{case:"text",value:new Rc.zN({text:JSON.stringify(e)})}}));const r="object"==typeof e&&null!==e&&"isError"in e&&Boolean(e.isError);return new Rc.iz({result:{case:"success",value:new Rc.QW({content:t,isError:r})}})}catch(t){return qN.warn(e,"Failed to process updated_mcp_tool_output",{error:t instanceof Error?t.message:String(t)}),l}return l}catch(t){const r=lN(HF.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(gd.postToolUse,{...r,tool_name:n,tool_input:o,tool_output:s,duration:i,tool_use_id:a});return ZF(c,GN(e,n,gd.postToolUse,l?.additional_context)),l}catch(t){return void qN.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(gd.postToolUseFailure,{...r,tool_name:n,tool_input:o,error_message:s,failure_type:i,duration:a,tool_use_id:c,is_interrupt:l});ZF(u,GN(e,n,gd.postToolUseFailure,d?.additional_context))}catch(t){qN.warn(e,"postToolUseFailure hook error in MCP executor",{error:t instanceof Error?t.message:String(t)})}}}const KN={toolName:"ListMcpResources",createToolInput:e=>({server:e.server}),applyUpdatedInput:(e,t)=>{"string"==typeof t.server&&(e.server=t.server)},createRejectedResult:(e,t)=>new Rc.kP({result:{case:"error",value:new Rc.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 JN{constructor(e,t,r){this.wrappedExecutor=pN(e,t,r,KN)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const ZN={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 Rc.ZD({result:{case:"error",value:new Rc.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 XN{constructor(e,t,r){this.wrappedExecutor=pN(e,t,r,ZN)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const QN={toolName:xF,getToolCallId:hN,createToolInput:e=>({file_path:e.path}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new wy.sV({result:{case:"rejected",value:new wy.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?.(gd.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${oN}`}(t,e instanceof Error?e.message:String(e));throw new nN(r,e)}}((()=>o.executeHookForStep(gd.beforeReadFile,{...n,content:i,file_path:t.path,attachments:[],tool_use_id:s})),"File read");if("deny"===a?.permission){const e=sN("File read",a.user_message);throw new rN(e)}}};class YN{constructor(e,t,r){this.wrappedExecutor=new wT(pN(e,t,r,QN))}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const eL={toolName:"RecordScreen",getToolCallId:hN,createToolInput:e=>({mode:e.mode,save_as_filename:e.saveAsFilename}),createRejectedResult:(e,t)=>new GA.Tj({result:{case:"failure",value:new GA.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 tL{constructor(e,t,r){this.wrappedExecutor=pN(e,t,r,eL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}function rL(e){return"success"===e.result.case||"failure"===e.result.case?e.result.value.stdout+e.result.value.stderr:""}const nL={toolName:AF,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 fe.W4({result:{case:"rejected",value:new fe.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:rL(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||"";GF(t,gd.beforeShellExecution)&&Po(r,await PN({hookExecutor:o,baseHookRequest:n,toolUseId:s,command:r.command,cwd:i,sandbox:xN(r.requestedSandboxPolicy)}))},runPostExecutionHooks:async e=>{const{args:t,result:r,baseHookRequest:n,hookExecutor:o,executionDurationMs:s,toolUseId:i}=e,a=rL(r);await o.executeHookForStep(gd.afterShellExecution,{...n,command:t.command,output:a,duration:s,sandbox:xN(t.requestedSandboxPolicy),tool_use_id:i})}};class oL{constructor(e,t,r){this.wrappedExecutor=pN(e,t,r,nL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}class sL{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 iL={toolName:AF,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 fe.FI({event:{case:"rejected",value:new fe.pZ({command:e.command,workingDirectory:e.workingDirectory,reason:t})}}),createHookContextEvent:e=>new fe.FI({event:{case:"hookContext",value:new fe.Ng({hookAdditionalContexts:[...e]})}}),getExtraHookFields:e=>({cwd:e.workingDirectory||""}),createResultCollector:()=>new sL,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=xN(r.requestedSandboxPolicy);GF(t,gd.beforeShellExecution)&&Po(r,await PN({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=xN(t.requestedSandboxPolicy);await n.executeHookForStep(gd.afterShellExecution,{...r,command:t.command,output:o.getOutput(),duration:s,sandbox:a,tool_use_id:i})}};class aL{constructor(e,t,r){this.wrappedExecutor=function(e,t,r,n){return{async*execute(o,s,i){const a=mN(o,t),{hookContext:c,helpers:l}=uN(o,s,a,r,n,i),u=n.runPreExecutionHooks?async e=>{await n.runPreExecutionHooks(e)}:void 0,d=await dN(o,s,a,c,l,n,((e,t)=>n.createRejectedEvent(e,t)),u);if("rejected"===d.type){yield d.result;for(const e of fN(n,c))yield e;return}const h=HF.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=lN(HF.performance.now()-h),r=e instanceof Error?e.message:String(e);await l.fireFailureAsync(t,r,"error");for(const e of fN(n,c))yield e;throw e}const f=lN(HF.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){aN.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 fN(n,c))yield e}}}(e,t,r,iL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}class cL{constructor(e,t,r){const n=new Map;this.wrappedExecutor=pN(e,t,r,function(e){return{toolName:PF,getToolCallId:hN,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 YR.v3({result:{case:"error",value:new YR.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?.(gd.afterFileEdit))return;let s,i=!1;try{(await(0,So.stat)(r.path)).size>262144?i=!0:s=await Fi(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?.(gd.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,Tb.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(gd.afterFileEdit,d);if(r.returnFileContentAfterWrite&&void 0!==h){const e=n.result.value.path;try{const t=await Fi(e),r=Gs(t),o=Buffer.byteLength(t,"utf8");return new YR.v3({result:{case:"success",value:new YR.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 lL(e,t,r){return t===e.symbol}function uL(e,t,r){return lL(sT,e)?new oL(t,r.hookExecutor,r.baseHookRequestExtractor):lL(re,e)?new aL(t,r.hookExecutor,r.baseHookRequestExtractor):lL(lT,e)?new cL(t,r.hookExecutor,r.baseHookRequestExtractor):lL(Yn,e)?new VN(t,r.hookExecutor,r.baseHookRequestExtractor,r.mcpLease,r.hooksConfigLease):lL(yT,e)||lL(vT,e)?new YN(t,r.hookExecutor,r.baseHookRequestExtractor):lL(bT,e)?new HN(t,r.hookExecutor,r.baseHookRequestExtractor):lL(pT,e)?new BN(t,r.hookExecutor,r.baseHookRequestExtractor):lL(dT,e)?new jN(t,r.hookExecutor,r.baseHookRequestExtractor):lL(uT,e)?new ON(t,r.hookExecutor,r.baseHookRequestExtractor):lL(ST,e)?new NN(t,r.hookExecutor,r.baseHookRequestExtractor):lL(eo,e)?new JN(t,r.hookExecutor,r.baseHookRequestExtractor):lL(to,e)?new XN(t,r.hookExecutor,r.baseHookRequestExtractor):lL(jT,e)?new IN(t,r.hookExecutor,r.baseHookRequestExtractor):lL(UT,e)?new AN(t,r.hookExecutor,r.baseHookRequestExtractor):lL(GT,e)?new MN(t,r.hookExecutor,r.baseHookRequestExtractor):lL(VT,e)?new tL(t,r.hookExecutor,r.baseHookRequestExtractor):lL(Mr,e)&&(r.hooksAdditionalContextPromise||r.hooksConfigLease)?new EN(t,r.hooksAdditionalContextPromise??Promise.resolve(void 0),r.teamHooksReadyPromise,r.hooksConfigLease):void 0}class dL{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===vN.symbol)return new CN(t)}(e,this.hookExecutor);return void 0!==t?t:function(e,t,r){const n=uL(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=uL(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=vN;yield[e,new CN(this.hookExecutor)]}}const hL={cursor_version:process.env.AGENT_CLI_STATIC_VERSION??"1.0.0",user_email:null};function pL(e=process.cwd()){let t=e;const r={getCwd:async()=>t,clone:e=>pL(e??t),async*execute(e,r,n={}){const o=n.workingDirectory??t;t=o;const s=function(e){return"win32"===process.platform?{executable:(0,$o.oG)(),args:[...oO,"-Command",e]}:{executable:process.env.SHELL||"/bin/sh",args:["-lc",e]}}(r),i=(0,Kl.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 fL(e,t,...r){for(const n of r){const r=t(e[n]);if(void 0!==r)return r}}function mL(e){return"string"==typeof e&&e.length>0?e:void 0}function gL(e){return"object"==typeof e&&null!==e&&"string"==typeof e.id&&"string"==typeof e.value}function wL(e){if(Array.isArray(e)&&e.every(gL))return e.map((e=>({id:e.id,value:e.value})))}class yL{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 vL(e,t={}){const r=await new EF(new wN,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?kF():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 WF(r),i=function(e){return e.projectRoot??e.workingDirectory??e.workspaceRoots[0]??process.cwd()}(e),a=function(e){return Object.freeze({...hL,...e.globalContext??{}})}(t);return{projectDir:e.projectRoot,workspacePath:i,hooksConfig:r,hooksConfigLease:n,globalContext:a,createSessionRuntime(){const e=new BF(r,i,a,(t.createTerminalExecutor??pL)(),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 bL(e={}){return{createHooksRuntime:t=>vL(t.workspaceState,e)}}var SL=r("../proto/dist/generated/aiserver/v1/dashboard_service_connect.js");async function kL(e){(function(e){return"object"==typeof e&&null!==e&&"dispose"in e&&"function"==typeof e.dispose})(e)&&await e.dispose()}function _L(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 Gw,l=(0,o.homedir)(),u=Bf(l).dirPath;let d,h=!0;return{async prepareLocalExtensibility(){h=i&&await async function(e){if(!e)return!1;const t=(0,be.createClient)(SL.I,e);return"synced"===(await async function(e,t){try{const r=await t.getManagedSkills()??[],n=await JM(e,{managedSkills:[...r]});return{status:"synced",managedSkillsCount:r.length,syncResult:n}}catch(t){return XM.warn(e,"Failed to sync managed skills from source",{error:t}),{status:"fetch_failed",error:t}}}((0,b.q6)(),{getManagedSkills:async()=>(await t.getManagedSkills(new oD.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:TL(),getAgentSkills:async e=>[]};const p=(0,b.q6)(),f=e.loadNestedRules??!0,m=n?i.map((e=>new Nm(p,c,e,f,t,void 0))):[],g=function(e,t){const r=CL(t);return{getAllCursorRules:async t=>EL(await e.getAllCursorRules(t),r),reload(t){e.reload(t)},onDidChangeRules:t=>e.onDidChangeRules(t),dispose(){e.dispose()}}}(0===m.length?TL():1===m.length?m[0]:new Fm(m,(()=>sm)),{allowedRoots:n?i:[],excludedRoots:[]}),w=function(e,t){const r=CL(t);return{getAllCursorRules:async t=>EL(await e.getAllCursorRules(t),r),getAllAgentSkills:async t=>EL(await e.getAllAgentSkills(t),r),reload(t){e.reload(t)},onDidChangeRules:t=>e.onDidChangeRules(t),onDidChangeSkills:t=>e.onDidChangeSkills(t),dispose(){e.dispose()}}}(new jm(p,n?i:[],l,c,f,void 0,t,Promise.resolve(),"sdk"),{allowedRoots:[...n?i:[],...s?[l]:[],...h?[u]:[]],excludedRoots:h?[]:[u]}),y=n?i.map((e=>new Zm(e,t))):[],v=0===y.length?new qm:1===y.length?y[0]:new Qm(y),S=JD(o.services.pluginBootstrapOutputs),k=S&&a?new Bm(p,(()=>({importThirdPartyPlugins:r})),void 0,S.pluginsService):void 0,_=S&&a?new Ym((()=>({importThirdPartyPlugins:r})),S.pluginsService):void 0,C=new Fm([g,w,...k?[k]:[]],(()=>sm)),E=new TM([w,...k?[k]:[]],(()=>[]),(()=>({workspacePaths:n?i:[],userHomeDirectory:l,agentStoreSkillsDirs:[]}))),x=new Qm([v,..._?[_]:[]]);d={localRulesService:g,localSkillsService:w,localSubagentsService:v,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 kL(e)}catch(e){t??=e}if(void 0!==t)throw t}(e)}}}function CL(e){const t=Promise.all(e.allowedRoots.map(RL)),r=Promise.all(e.excludedRoots.map(RL));return async e=>{const[n,o,s]=await Promise.all([IL(e.fullPath),t,r]);return void 0!==n&&!s.some((e=>xL(n,e)))&&o.some((e=>xL(n,e)))}}async function EL(e,t){const r=await Promise.all(e.map(t));return e.filter(((e,t)=>r[t]))}function xL(e,t){if(e===t)return!0;const r=`${t}/`;return e.startsWith(r)}function PL(e){return e.replace(/\\/g,"/").replace(/\/+$/,"")}async function RL(e){try{return PL(await(0,So.realpath)(e))}catch{return PL(e)}}async function IL(e){try{return PL(await(0,So.realpath)(e))}catch{return}}function TL(){return{getAllCursorRules:async()=>[],reload(){},onDidChangeRules:()=>()=>{},dispose(){}}}function AL(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 $L=/^[a-z][a-z0-9+.-]*:\/\/([^/?#]*)/i,ML=/^(?:[^@/\s]+@)?([^:/\s\\]+):(?!\/\/)/,DL=/^([a-z][a-z0-9+.-]*)::(.*)$/i,OL=/^([a-z][a-z0-9+.-]*):\/\//i,FL=new Set(["file","git","http","https","ssh"]);function NL(e){if(/^(?:\\\\|\/\/)[^\\/]/.test(e))throw new Error("Cursor Orbit: plugin git remote could not be validated");const t=DL.exec(e);if(null!==t){const e=t[1].toLowerCase();if(!FL.has(e))throw new Error("Cursor Orbit: plugin git remote could not be validated");const r=t[2];if(!("http"!==e&&"https"!==e||null!==OL.exec(r)&&URL.canParse(r)))throw new Error("Cursor Orbit: plugin git remote could not be validated");const n=NL(r);if(0===n.length)throw new Error("Cursor Orbit: plugin git remote could not be validated");return n}const r=OL.exec(e)?.[1].toLowerCase();if(void 0!==r&&!FL.has(r))throw new Error("Cursor Orbit: plugin git remote could not be validated");const n=$L.exec(e)?.[1];if(void 0===n){const t=ML.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 LL(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(LL(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(LL(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(LL(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 LL(e){return e.trim().toLowerCase().replace(/^\[|\]$/g,"").replace(/\.+$/,"")}function jL(){const e=["-c","credential.interactive=false","-c","core.fsmonitor=false"];return"1"===process.env[vv.K4]&&e.push("-c","http.followRedirects=false"),"win32"===process.platform&&e.push("-c","core.longpaths=true"),e}function UL(e){return"function"==typeof e?e():e}async function BL(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[vv.K4])return;const r=(0,vv.H)(t[vv.Zf]);for(const t of e)for(const e of NL(t))if((0,vv.ad)(e,r))throw new Error(`Cursor Orbit: plugin git egress to ${e} is refused`)}(e),[...jL(),...e]}(e);try{return await Tw("git",n,{...r,...void 0!==t?.timeoutMs&&{timeout:t.timeoutMs,killSignal:"SIGTERM"}})}catch(e){if("1"===process.env[vv.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 WL=/^[0-9a-f]{7,40}$/i,HL=/^[0-9a-f]{40}$/i;function qL(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 zL(e,t,r){const n=t.trim();if(HL.test(n))return{fullSha:n.toLowerCase()};if(WL.test(n)){try{const t=await async function(e,t,r){const{stdout:n}=await BL(["ls-remote",e,`refs/heads/${t}`,`refs/tags/${t}`,`refs/tags/${t}^{}`],{sshBatchMode:r?.sshBatchMode,extraGitConfig:r?.extraGitConfig,timeoutMs:r?.timeoutMs});return qL(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 BL(["ls-remote","--symref",e,"HEAD"],{sshBatchMode:r?.sshBatchMode,extraGitConfig:r?.extraGitConfig,timeoutMs:r?.timeoutMs}),n=qL(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 BL(["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=qL(o);if(!s)throw new Error(`git ls-remote did not return a resolvable commit for ref "${n}" (${e})`);return{fullSha:s.toLowerCase()}}const GL=ah.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 VL;function KL(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 JL(e){const t=[];for(const r of e){const e=KL(r);if(null===e)return"all";t.push(e)}return t}async function ZL(e,t){const r="all"===e?"all":JL(e),n=t&&"all"!==r&&await(process.env.CURSOR_DISABLE_SPARSE_PLUGIN_CLONES?Promise.resolve(!1):(VL??=(async()=>{try{const{stdout:e}=await BL(["--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}})(),VL));return{materialize:r,sparse:n,sparseDirs:n?(o=r,[...new Set([...GL,...o])]):[]};var o}function XL(e){return e.toLowerCase().includes("filtering not recognized by server")}async function QL(e,t,r){await BL(["sparse-checkout","set","--cone","--",...t],{...r,cwd:e})}async function YL(e){try{await(0,So.access)((0,s.join)(e,".git","info","sparse-checkout"))}catch{return!1}try{const{stdout:t}=await BL(["config","--bool","--get","core.sparseCheckout"],{cwd:e});return"true"===t.trim()}catch{return!1}}async function ej(e,t,r){if("all"!==t&&0===t.length)return;if(!await YL(e))return;const n={...r,cwd:e,sshBatchMode:!0};if("all"===t)return void await BL(["sparse-checkout","disable"],n);const o=JL(t);"all"!==o?await BL(["sparse-checkout","add","--",...o],n):await BL(["sparse-checkout","disable"],n)}(0,bs.J)((function(){VL=void 0}));const tj=/\.git$/i,rj=new Set(["account","dashboard"]);function nj(e){return e.replace(tj,"")}function oj(e){let t;try{t=decodeURIComponent(e)}catch{return}return t.length>0&&!t.includes("/")?t:void 0}function sj(e){const t=e.toLowerCase();return"github.com"===t||t.endsWith(".github.com")}function ij(e){return e.toLowerCase().split(".").includes("gitlab")}function aj(e){const t=e.toLowerCase();return"bitbucket.org"===t||"www.bitbucket.org"===t}function cj(e){const t=e.toLowerCase();return ij(e)?"GitLab":t.includes("bitbucket")?"Bitbucket":t.includes("gitea")||t.includes("codeberg")?"Gitea/Codeberg":t.includes("azure")&&t.includes("dev")?"Azure DevOps":null}function lj(e){return sj(e)?"github":ij(e)?"gitlab":aj(e)?"bitbucket":function(e){const t=e.toLowerCase();return"dev.azure.com"===t||"www.dev.azure.com"===t}(e)?"azure_devops":"generic"}function uj(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);Ha(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=nj(r);return n?{owner:t,repo:n,hasSubpath:e.length>2}:void 0}(n);return void 0===s?null:{provider:lj(r),owner:s.owner,repo:s.repo,host:r}}function dj(e){const t=hj(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 hj(e){try{const t=e.startsWith("git@")?`ssh://${e.replace(":","/")}`:e;return new URL(t.includes("://")?t:`https://${t}`)}catch{return null}}function pj(e){const t=e.trim();if(""===t)return{error:"URL cannot be empty"};const r=uj(t);if(null===r)return{error:"Invalid URL format. Expected: github.com/owner/repo or gitlab.com/namespace/repo"};if(ij(r.host)){const e=hj(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=nj(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=hj(e.trim());if(null!==t&&aj(t.hostname))return function(e){const t=e[0],r=e[1];if(void 0===t||void 0===r)return;const n=oj(t),o=oj(r);if(void 0===n||void 0===o||rj.has(n.toLowerCase()))return;const s=nj(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=hj(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=nj(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!Ha(e.host)&&null===cj(e.host);case"gitlab":case"bitbucket":case"azure_devops":return!1;default:return e.provider,!1}}(r)){const e=mj(r.host.replace(/^www\./i,""));return{url:`https://${e}/${dj(t)?"scm/":""}${r.owner}/${r.repo}`,owner:r.owner,repo:r.repo,host:e,provider:"github"}}const n=cj(r.host);return{error:"Only GitHub, GitLab, Bitbucket, and Azure DevOps URLs are currently supported."+(null!==n?` ${n} is not supported yet.`:"")}}function fj(e){const t=pj(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 mj(e){return sj(e)?"github.com":e}function gj(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 wj(e){return/[\n\r:#[\]{}&*!|>'"%@`]/.test(e)||e.startsWith(" ")||e.endsWith(" ")?`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:e}const yj=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 vj(e){const t=xp(e).replace(/[. ]+$/g,"");return""===t||"."===t||".."===t?"_":yj.has(t.toLowerCase())?`_${t}`:t}const bj=18e5,Sj=6e5,kj={recursive:!0,force:!0,maxRetries:3},_j=["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"],Cj=["enotempty: directory not empty, rename","/_staging/"],Ej=["upload-pack: not our ref","server does not allow request for unadvertised object"];function xj(e){const t=String(e).toLowerCase().replaceAll("\\","/");return _j.some((e=>t.includes(e)))?"user_git_access":Cj.every((e=>t.includes(e)))?"local_cache_race":Ej.some((e=>t.includes(e)))?"stale_pinned_ref":"infrastructure"}function Pj(e){return"object"==typeof e&&null!==e&&(!0===e.killed||Pj(e.cause))}function Rj(e){return Pj(e)?"killed_by_budget":xj(e)}function Ij(e){const t=pj(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=uj(e);if(null===r)throw new Error(`Invalid git URL: ${e}`);return{host:mj(r.host.replace(/^www\./i,"")).toLowerCase(),pathSegments:[r.owner.toLowerCase(),r.repo.toLowerCase()]}}const Tj=new Map;class Aj{constructor(e,t){this.cacheRoot=e,this.options=t,this.manifestCache=new Map}get sparsePluginClones(){return this.options?.sparsePluginClones??!1}remoteTimeoutMs(){return this.sparsePluginClones?bj:void 0}localTimeoutMs(){return this.sparsePluginClones?Sj:void 0}lsRemoteTimeoutMs(){return this.sparsePluginClones?3e4:void 0}async cloneResolvedRef(e,t,r,n){const o={cwd:e,sshBatchMode:n?.sshBatchMode,extraGitConfig:{...UL(this.options?.extraGitConfig),"safe.directory":e}},{sparse:s,sparseDirs:i}=await ZL(n?.materialize??"all",this.sparsePluginClones);await BL(["init"],{...o,timeoutMs:this.localTimeoutMs()}),s&&await QL(e,i,{sshBatchMode:n?.sshBatchMode,extraGitConfig:UL(this.options?.extraGitConfig),timeoutMs:this.localTimeoutMs()});const{stderr:a}=await BL(["fetch","--depth","1",...s?["--filter=blob:none"]:[],t,r],{...o,timeoutMs:this.remoteTimeoutMs()});return await BL(["checkout","FETCH_HEAD"],{...o,timeoutMs:this.remoteTimeoutMs()}),{strategy:s?"sparse":"full",filterIgnoredByServer:s&&XL(a??"")}}async createStagingDir(){const e=(0,s.join)(this.cacheRoot,"_staging",(0,wo.randomUUID)());return await(0,So.mkdir)(e,{recursive:!0}),e}async moveToCanonicalDir(e,t){return await(0,So.mkdir)((0,s.dirname)(t),{recursive:!0}),await(0,So.rm)(t,kj),await(0,So.rename)(e,t),t}async cleanStaleStagingDirs(){const e=(0,s.join)(this.cacheRoot,"_staging");try{const t=await(0,So.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,So.stat)(n);r-o.mtimeMs>Aj.STALE_STAGING_THRESHOLD_MS&&await(0,So.rm)(n,kj)}catch{}})))}catch{}}getLegacyCloneDir(e,t){return(0,s.join)(this.cacheRoot,vj(e),vj(t))}getCanonicalCloneDir(e,t){const{host:r,pathSegments:n}=Ij(e);return(0,s.join)(this.cacheRoot,vj(r),...n.map(vj),vj(t))}getCanonicalRepoRootDir(e){const{host:t,pathSegments:r}=Ij(e);return(0,s.join)(this.cacheRoot,vj(t),...r.map(vj))}async pruneSiblingCloneDirs(e,t,r){const n=this.getCanonicalRepoRootDir(e),o=vj(t);try{const e=await(0,So.readdir)(n,{withFileTypes:!0});await Promise.all(e.filter((e=>e.isDirectory()&&e.name!==o)).map((e=>(0,So.rm)((0,s.join)(n,e.name),kj))))}catch{}if(void 0!==r)try{await(0,So.rm)(r,kj)}catch{}}async ensureCloned(e,t,r,n=Gh,o){const s=this.serializedOnRepo(this.getCanonicalRepoRootDir(t),(()=>this.ensureClonedImpl(e,t,r,n,o?.materialize??"all")));return this.sparsePluginClones?s:(0,Fr.wj)(s,3e4,`ensureCloned timed out after 30000ms for ${t} @ ${r}`)}async ensureMaterialized(e,t,r=Gh){const n=this.serializedOnRepo((0,s.dirname)(e),(async()=>{const n=performance.now();try{await ej(e,t,{extraGitConfig:UL(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:Rj(o)}),r.increment("marketplace_cache_manager.ensure_materialized.error",1,{error_category:Rj(o)}),r.distribution("marketplace_cache_manager.ensure_materialized.duration",performance.now()-n,{outcome:"error"}),o}}));return this.sparsePluginClones?n:(0,Fr.wj)(n,3e4,`ensureMaterialized timed out after 30000ms for ${e}`)}async serializedOnRepo(e,t){const r=`${this.cacheRoot}:${e}`,n=(Tj.get(r)??Promise.resolve()).catch((()=>{})).then(t);Tj.set(r,n);try{return await n}finally{Tj.get(r)===n&&Tj.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:fj(t);if(null!==a)try{i=(await zL(a,s,{sshBatchMode:!0,extraGitConfig:UL(this.options?.extraGitConfig),timeoutMs:this.lsRemoteTimeoutMs()})).fullSha}catch(e){if(this.sparsePluginClones&&Pj(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:xj(e)}),a=null,i=(await zL(t,s,{extraGitConfig:UL(this.options?.extraGitConfig),timeoutMs:this.lsRemoteTimeoutMs()})).fullSha}else i=(await zL(t,s,{extraGitConfig:UL(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 YL(c);return e&&await ej(c,o,{extraGitConfig:UL(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,So.utimes)(l,e,e).catch((()=>{}))}),Aj.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&&Pj(e))throw e;i.log("debug","Falling back to HTTPS clone due to SSH clone failure",{gitUrl:t,ref:s,error:String(e),errorCategory:Rj(e)}),await(0,So.rm)(l,kj),await(0,So.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=Rj(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,So.rm)(l,kj)}catch{}}}async isCloneComplete(e){try{if(!(await(0,So.stat)(e)).isDirectory())return!1;const t=await(0,So.readdir)(e);if(!t.includes(".git"))return!1;if(t.length>1)return!0;try{return(await(0,So.stat)((0,s.join)(e,".git","info","sparse-checkout"))).isFile()}catch{return!1}}catch{return!1}}getPluginDir(e,t){return zp(e,t)}async copyPluginToDir(e,t){await(0,So.mkdir)(t,{recursive:!0}),await(0,So.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 ah){const n=(0,s.join)(e,r);let o;try{o=await(0,So.readFile)(n,"utf-8")}catch{continue}const i=Fh(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=Lh(n.source,r.metadata?.pluginRoot);return o&&jh(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=Lh(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":jh(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):[]}}Aj.STALE_STAGING_THRESHOLD_MS=3e5,Aj.STAGING_HEARTBEAT_INTERVAL_MS=6e4;const $j=(0,Ws.debuglog)("cursor-plugins");function Mj(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Dj(e){return Mj(e)?e:void 0}function Oj(e){const t=e.name?.trim();return void 0!==t&&t.length>0?t:e.pluginId}function Fj(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 Nj(e,t){const r=t?.distributionGitUrl?.trim();return r?t?.gitUrl&&!Kj(e,t.gitUrl)?e:r:e}function Lj(e){return e?.distributionGitUrl?.trim()||e?.gitUrl}function jj(e,t){if(e.pinnedGitRef)return e.pinnedGitRef;if(e.plugin?.gitRef)return e.plugin.gitRef;const r=Fj(e.plugin,t),n=e.plugin?.gitUrl,o=r?.gitUrl;return n&&o&&n!==o||!r?.gitRef?"main":r.gitRef}const Uj="backend-git://";function Bj(e,t,r){const n=r?`#${encodeURIComponent(r)}`:"";return`${Uj}${encodeURIComponent(e)}@${encodeURIComponent(t)}${n}`}function Wj(e){if(!e.startsWith(Uj))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 Hj="backend-release://";function qj(e){const t=e.tag?`@${encodeURIComponent(e.tag)}`:"";return`${Hj}${encodeURIComponent(e.repo)}#${encodeURIComponent(e.asset)}${t}`}function zj(e){if(!e.startsWith(Hj))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 Gj=/^[0-9a-f]{7,40}$/i;function Vj(e){let t;try{t=Ij(e)}catch{return null}return`${t.host}\0${t.pathSegments.join("\0")}`}function Kj(e,t){if(e.trim()===t.trim())return!0;const r=Vj(e),n=Vj(t);return null!==r&&r===n}const Jj=104857600;async function Zj(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(!(Mj(d=u)&&Array.isArray(d.assets)&&d.assets.every((e=>Mj(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>Jj)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||!Xj(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||!Xj(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>Jj)throw new Error(`Release asset "${r}" actual download size exceeds maximum of 104857600 bytes (actual: ${g.byteLength})`);if(e.expectedSha256){const t=(0,wo.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,So.mkdir)(n,{recursive:!0});const u=await(0,So.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,So.writeFile)(d,c),await(0,So.mkdir)(h,{recursive:!0});let e=0,t=0;await Pp.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,So.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,So.readdir)(e)).some((e=>ih.includes(e)))&&(a=e)}const p=await(0,So.readdir)(a);await Promise.all(p.map((e=>(0,So.cp)((0,s.join)(a,e),(0,s.join)(n,e),{recursive:!0,verbatimSymlinks:!0}))))}finally{await(0,So.rm)(u,{recursive:!0,force:!0}).catch((()=>{}))}}function Xj(e,t){return!(e!==t&&!e.endsWith(".githubusercontent.com"))||("github.com"===t?"github.com"===e:e.endsWith(`.${t}`))}class Qj{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??Gh,this.extraGitConfig=s.extraGitConfig,this.awaitAuthReady=s.awaitAuthReady,this.githubToken=s.githubToken,this.sparsePluginClones=s.sparsePluginClones??!1,this.marketplaceCache=s.marketplaceCacheRoot?new Aj(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=UL(this.extraGitConfig),s=this.sparsePluginClones?3e4:void 0,i=e.startsWith("git@")||e.startsWith("ssh://")?null:fj(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 zL(e,t,n):await zL(e,t)).fullSha};if(null!==i)try{n=await c(i,!0)}catch(t){if(this.sparsePluginClones&&Pj(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=Fj(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=Oj({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,wo.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:Dj(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=Nj(c,r),d=jj(e,o),h=AL(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?qj({repo:h.releaseRepo,asset:h.releaseAsset,tag:h.releaseTag}):Bj(g,d,t.gitPath??void 0);const w=Lj(r);let y=w,v=r?.gitUrl,b=p;if(r?.gitUrl&&w){const e=Kj(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:Bj(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:Dj(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=Wj(e.downloadUrl);return!(!r||!Kj(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,So.mkdir)(t,{recursive:!0});const i={};if(o.rules&&o.rules.length>0){const e=(0,s.join)(t,"rules");await(0,So.mkdir)(e,{recursive:!0});const r=[];for(const t of o.rules){if(!t.content)continue;if(!1===t.isActive)continue;const n=`${xp(t.name)}.md`,o=[];o.push(`description: ${wj(t.name)}`),t.globs&&t.globs.length>0&&o.push(`globs: ${wj(t.globs.join(", "))}`),o.push(`alwaysApply: ${!0===t.isRequired}`);const i=`---\n${o.join("\n")}\n---\n\n`;await(0,So.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,So.mkdir)(e,{recursive:!0});const r=[];for(const t of o.commands){if(!t.content)continue;if(!1===t.isActive)continue;const n=`${xp(t.name)}.md`,o=t.description?`---\ndescription: ${wj(t.description)}\n---\n\n`:"";await(0,So.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,So.mkdir)(e,{recursive:!0});const r={};for(const e of o.hooks){const t=e.hookStep;t&&!1!==e.isActive&&gj(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,So.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,So.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,So.mkdir)(c,{recursive:!0}),await(0,So.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,So.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===zj(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)&&Pj(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=Gh,n,i){const a=i?.sparsePluginClones??!1,c=a?bj:void 0,l=zj(e.downloadUrl);if(l){if(e.gitPath){const r=await(0,So.mkdtemp)((0,s.join)((0,o.tmpdir)(),"release-plugin-"));try{await Zj(l.repo,l.asset,l.tag,r,i?.expectedReleaseAssetSha256,i?.githubToken);const n=zp(r,e.gitPath);await(0,So.mkdir)(t,{recursive:!0}),await(0,So.cp)(n,t,{recursive:!0,verbatimSymlinks:!0})}finally{await(0,So.rm)(r,{recursive:!0,force:!0}).catch((()=>{}))}}else await Zj(l.repo,l.asset,l.tag,t,i?.expectedReleaseAssetSha256,i?.githubToken);return}const u=Wj(e.downloadUrl);if(!u)throw new Error(`Invalid download URL format for plugin ${e.pluginId}: ${e.downloadUrl}`);const d=await(0,So.mkdtemp)((0,s.join)((0,o.tmpdir)(),"backend-plugin-"));try{let o;if(await async function(e,t,r,n=Gh,o,s="all",i=!1){const a=performance.now(),c=Gj.test(t),l="HEAD"===t.toUpperCase(),u={...o,"safe.directory":r},d=i?bj:void 0,h=i?Sj:void 0,{sparse:p,sparseDirs:f}=await ZL(s,i),m=p?["--filter=blob:none","--sparse"]:[],g=!!p||void 0,w=async e=>{p&&await QL(r,f,{extraGitConfig:u,timeoutMs:e,sshBatchMode:!0})},y=async(e,n)=>{let o;return l?(({stderr:o}=await BL(["clone","--depth","1",...m,e,r],{extraGitConfig:u,timeoutMs:d,sshBatchMode:n})),await w(d)):c?(await BL(["init"],{cwd:r,extraGitConfig:u,timeoutMs:h}),await BL(["remote","add","origin",e],{cwd:r,extraGitConfig:u,timeoutMs:h}),await w(h),({stderr:o}=await BL(["fetch","--depth","1",...p?["--filter=blob:none"]:[],"origin",t],{cwd:r,extraGitConfig:u,timeoutMs:d,sshBatchMode:n})),await BL(["checkout","FETCH_HEAD"],{cwd:r,extraGitConfig:u,timeoutMs:d,sshBatchMode:n})):(({stderr:o}=await BL(["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:fj(e);let b;if(null!==v)try{b=await y(v,!0)}catch(t){if(i&&Pj(t))throw t;await(0,So.rm)(r,{recursive:!0,force:!0}),await(0,So.mkdir)(r,{recursive:!0}),b=await y(e,g)}else b=await y(e,g);p&&XL(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);$j("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?JL([u.gitPath]):[],a),u.gitPath)o=zp(d,u.gitPath);else{const t=await async function(e,t){for(const r of ah){const n=(0,s.join)(e,r);let o;try{o=await(0,So.readFile)(n,"utf-8")}catch{continue}const i=Fh(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=Lh(c.source,a.metadata?.pluginRoot);return l&&jh(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 ej(d,JL([t.gitPath]),{extraGitConfig:n,timeoutMs:c}),o=zp(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 ej(d,"all",{extraGitConfig:n,timeoutMs:c}),o=d}}await(0,So.mkdir)(t,{recursive:!0}),await(0,So.cp)(o,t,{recursive:!0,verbatimSymlinks:!0})}finally{await(0,So.rm)(d,{recursive:!0,force:!0}).catch((()=>{}))}}(e,t,this.pluginLogger,UL(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=JL(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?JL([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,JL([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 Yj(e,t,r,n,o){return new Qj(e,t,r,n,o)}function eU(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 tU extends Error{constructor(e){super(e),this.name="SettingsParseError"}}function rU(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function nU(e){return 65279===e.charCodeAt(0)?e.slice(1):e}async function oU(e){try{return nU(await(0,So.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 sU(e){const t=await oU(e);return void 0===t?[]:function(e){const t=function(e){const t=nU(e);if(0===t.trim().length)return{};const r=[],n=(0,Uh.qg)(t,r,{allowTrailingComma:!0});if(r.length>0){const e=r.slice(0,3).map((e=>`${(0,Uh._n)(e.error)} at offset ${e.offset}`)).join("; ");throw new tU(`.cursor/settings.json contains syntax errors: ${e}`)}if(!rU(n))return{};const o=n.plugins;if(void 0===o)return{};if(!rU(o))return{};const s={};for(const[e,t]of Object.entries(o))rU(t)&&(s[e]=t);return{plugins:s}}(e);return t.plugins?Object.entries(t.plugins).filter((([,e])=>!0===e.enabled)).filter((([,e])=>!e.gitUrl||eU(e.gitUrl))).map((([e,t])=>({key:e,entry:t}))):[]}(t)}function iU(e){const t=e.indexOf("/");return-1===t?{name:e}:{name:e.slice(t+1),marketplaceName:e.slice(0,t)}}function aU(e={}){const t=e.userHomeDirectory??(0,o.homedir)(),r=e.importThirdPartyPlugins??!1,n=e.pluginLogger??{log(e,t,r){switch(e){case"warn":TD.Jz.warn("[local-plugins-bootstrap]",t,r??{});break;case"error":TD.Jz.error("[local-plugins-bootstrap]",t,r??{})}},increment(){},distribution(){},captureException(e,t){TD.Jz.error("[local-plugins-bootstrap] Unexpected plugin exception:",e,t??{})}},i=cU(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 sU(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,be.createClient)(SL.I,e.dashboardTransport),n=Yj((async()=>{try{return await r.getEffectiveUserPlugins(new oD.EwF({}))}catch{return{plugins:[]}}}),t,void 0,void 0,{allowedMarketplaceNames:["cursor-public"]}),o=e.workspacePath,i=Yj((async()=>{if(void 0===o)return{plugins:[]};try{const e=await sU(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||eU(t)})).map((({key:e,entry:t})=>{const r=iU(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=iU(e.key);return new oD.vwy({name:t.name,marketplaceName:t.marketplaceName})})),t=await r.resolvePluginsByRef(new oD.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 $p(e.userHomeDirectory),pruneOldVersions:!0},{client:i,userId:"",cacheManager:new $p(e.userHomeDirectory),pruneOldVersions:!0}]}({dashboardTransport:e.dashboardTransport,workspacePath:i,userHomeDirectory:t}):void 0),h=cU(d),p=new nD(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:KD,discoveredEntries:l,loadedPlugins:f,loadFailures:p.getLoadFailures(),bootstrapFailures:m,pluginsService:p,async dispose(){}};for(const e of m)TD.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)TD.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 cU(e){return void 0!==e&&(!Array.isArray(e)||e.length>0)}class lU{async getAllCursorRules(e){return[]}reload(e){}dispose(){}onDidChangeRules(e){return()=>{}}}const uU=["projectFolder","terminalsFolder","agentSharedNotesFolder","agentConversationNotesFolder","agentTranscriptsFolder","processWorkingDirectory","artifactsFolder"];function dU(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 hU(e){const t=dU(e).replaceAll("\\","/");return/^[A-Za-z]:\/$/.test(t)?t.slice(0,-1):t}function pU(e){const t=dU(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 fU(e){const t=hU(e.value),r=e.roots.filter((e=>e.host.length>0)).sort(((e,t)=>hU(t.host).length-hU(e.host).length));for(const e of r){const r=hU(e.host);if(t===r)return pU({reportedWorkspacePath:e.reported,suffix:""});const n="/"===r?"/":`${r}/`;if(t.startsWith(n)){const n="/"===r?t:t.slice(r.length);return pU({reportedWorkspacePath:e.reported,suffix:n})}}}const mU={powershellUtf8Console:!1,powershellUtf8ChildEnv:!1};class gU extends kM{constructor(e,t){super(e),this.sessionMcpLease=t}async dispose(){try{await super.dispose()}finally{await kL(this.sessionMcpLease)}}}function wU(e){const t=new Gw;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 lU,s=r.workspaceServices.subagentsService??new qm,i=r.workspaceServices.mcpLease??new kR,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 kR:void 0:void 0,l=(u=c??i,0===(d=r.options.extraMcpTools??[]).length?u:"onDidChange"in(h=u)&&"function"==typeof h.onDidChange?new fw(u,d):new pw(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 mU;try{const t=await e();return{powershellUtf8Console:t.powershellUtf8Console,powershellUtf8ChildEnv:t.powershellUtf8ChildEnv}}catch{return mU}}(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 kM(u):new gU(u,c);return void 0===r.options.reportedWorkspacePath&&void 0===r.options.reportedProjectFolder||function(e,t){const r=e.get(Mr);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(Mr,{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=>fU({value:e,roots:o})??e));for(const e of uU){const t=n[e];if(void 0===t||""===t)continue;const r=fU({value:t,roots:o});n[e]="processWorkingDirectory"===e&&void 0!==s?r??dU(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 kL(c),e}}}}const yU=["cursorRulesService","getAgentSkills","subagentsService"],vU=new WeakSet;function bU(e){("object"==typeof e&&null!==e||"function"==typeof e)&&vU.add(e)}function SU(e){return("object"==typeof e&&null!==e||"function"==typeof e)&&vU.has(e)}function kU(e,t){const r=Object.keys(t).filter((e=>!yU.includes(e)));if(r.length>0)throw new Error(`Workspace service contributors may only provide ${yU.join(", ")}. Received unsupported service keys: ${r.join(", ")}.`);for(const r of yU)Object.hasOwn(t,r)&&(e[r]=t[r])}async function _U(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&&(bU(s.cursorRulesService),bU(s.subagentsService),Object.assign(n,s));for(const t of e.workspaceServicesContributors??[]){const e=await t.contributeServices(o());void 0!==e&&kU(n,e)}return n}catch(t){try{await CU(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 CU(e,t){const r=t?.preserveSharedContributorsFrom;let n;const o=async e=>{try{await kL(e)}catch(e){n??=e}};if(e.subagentsService===r?.subagentsService||SU(e.subagentsService)||await o(e.subagentsService),e.cursorRulesService===r?.cursorRulesService||SU(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 kL(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 EU=["project","user","team","mdm","plugins"],xU=new Set([...EU,"all"]);function PU(e){if(void 0===e||0===e.length)return IU([]);for(const t of e)if(!xU.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{...IU(EU),all:!0}}return IU(e.filter((e=>"all"!==e)))}function RU(e,t){return e[t]}function IU(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 TU=Object.freeze({}),AU=Object.freeze({allowMcpServers:!0,allowPlugins:!0,allowBackgroundSessions:!0,requireMcpApproval:!1,maxParallelSessions:void 0,sandboxMode:void 0,metadata:TU});async function $U(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 kL(o)}catch(e){r??=e}}}if(void 0!==r)throw r}async function MU(e={}){const t=function(e={}){return{workspace:e.workspace??PD,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({...AU.metadata,...e.metadata}),r={...AU,...e,metadata:t};return{name:"permissive-sdk-local",resolvePolicy:()=>r}}(),{workspaceState:r});let o=await _U(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,ye.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 $U(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 $U(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 _U(t,r,n);s?await CU(i,{disposeLocalExtensibility:l}):(o=i,await CU(e,{preserveSharedContributorsFrom:i,disposeLocalExtensibility:l}),await(t.lifecycle?.onWorkspaceReload?.(r)))}))},async dispose(){s||(s=!0,await a((async()=>{try{await CU(o,{disposeLocalExtensibility:l})}finally{await(t.lifecycle?.dispose())}})))}}}class DU{async requestApproval(e){return{approved:!0}}}class OU{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 FU{async open(e,t){}async getDiagnostics(e,t){return[]}}class NU{async getCodebaseReference(e,t){}}class LU{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 TD.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){TD.Jz.warn("[sdk-mcp-state] Could not read the MCP allowlist in use:",e)}}}class jU{constructor(e){this.subagents=e.map((e=>new Wm.zz({fullPath:`sdk-inline://${e.name}`,name:e.name,description:e.description,tools:[],model:e.model,prompt:e.prompt,permissionMode:Wm.b$.DEFAULT,isBackground:!1,source:"sdk"})))}async getAllSubagents(){return this.subagents}async reload(){return this.subagents}}class UU{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 BU(e){return"string"==typeof e&&e.trim().length>0}function WU(e,t){return new fe.jn({command:t.command??"",workingDirectory:t.workingDirectory??"",error:e,isReadonly:!0})}function HU(e){return{execute:async(t,r)=>new YR.v3({result:{case:"permissionDenied",value:new YR.U7({path:r.path,error:e,isReadonly:!0})}})}}function qU(e){return{execute:async(t,r)=>new cw.Pi({result:{case:"permissionDenied",value:new cw.QG({path:r.path,clientVisibleError:e,isReadonly:!0})}})}}function zU(e){return{execute:async(t,r)=>new Rc.iz({result:{case:"permissionDenied",value:new Rc.HQ({error:`${e} Tool: ${r.name}`,isReadonly:!0})}})}}var GU=r("../agent-kv/dist/subagent-states.js");let VU;function KU(e){const t=process.env.CURSOR_DATA_DIR;if(t?.trim())return bo(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,yo.r_)(e.workspacePath)):void 0!==e.homeDir&&function(e){if(""===e.trim())return!1;try{return!!(0,_o.statSync)(e).isDirectory()&&((0,_o.accessSync)(e,_o.constants.W_OK),!0)}catch{return!1}}(e.homeDir)?(0,s.join)(e.homeDir,".cursor","projects",(0,yo.r_)(e.workspacePath)):(0,s.join)(e.ensureFallbackRoot(e.tempDir),(0,yo.r_)(e.workspacePath))}({workspacePath:e,homeDir:r,tempDir:(0,o.tmpdir)(),ensureFallbackRoot:e=>(void 0===VU&&(VU=function(e){return(0,_o.mkdtempSync)((0,s.join)(e,"cursor-transcripts-"))}(e)),VU)})}async function JU(e,t){const r=(0,s.dirname)(e);await(0,So.mkdir)(r,{recursive:!0}),await(0,So.writeFile)(e,t,"utf-8")}class ZU{constructor(e){this.writeChain=Promise.resolve(),this.workspacePath=e.workspacePath,this.conversationId=e.conversationId,this.parentConversationId=e.parentConversationId,this.blobStore=e.blobStore,this.projectDir=KU(this.workspacePath);const t=this.parentConversationId?(e,t)=>{const r=BO({conversationId:e,ext:t,kind:"subagent",parentConversationId:this.parentConversationId});return(0,s.join)(this.projectDir,r)}:void 0;this.transcriptStore=new wF(this.projectDir,e.blobStore,JU,{writeText:!1,writeJsonl:!0,...t?{pathResolver:t}:{}}),this.nestedSubagentTranscriptStore=new wF(this.projectDir,e.blobStore,JU,{writeText:!1,writeJsonl:!0,pathResolver:(e,t)=>{const r=BO({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){TD.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,GU.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=BO({conversationId:this.conversationId,ext:"jsonl",kind:"subagent",parentConversationId:this.parentConversationId});return(0,s.join)(this.projectDir,e)}return function(e,t){const r=BO({conversationId:t,ext:"jsonl",kind:"primary"});return(0,s.join)(KU(e),r)}(this.workspacePath,this.conversationId)}getProjectDir(){return this.projectDir}}const XU=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,QU="User aborted/interrupted manually.";class YU{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,ye.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 UU}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(!XU.test(e))throw new Error(`Invalid resumeAgentId format: ${e}`)}(r),r&&!t.prompt)return r;if(r&&BU(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,ye.C)(),o=function(e){const t=new oe.We,r=(0,AD.sh)(e),n=new AD.pH(new oe.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 ZU({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:Wm.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:Wm.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 no.a3({status:no.jh.ACCEPTED}):new no.a3({status:no.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){TD.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 no.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 no.Pw({...r,runInBackground:!1}):new no.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,ye.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,ye.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,ye.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,i=0;const a=new c.QFf({action:{case:"userMessageAction",value:new c.Vtf({userMessage:new c.RGk({text:r.prompt})})}}),l=new c.Gmx({modelId:r.modelId,displayModelId:r.modelId,displayName:r.modelId});void 0!==r.credentials.case&&(l.credentials=r.credentials);const u=new ID,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&&i++,"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 pr(e.id,"Web search is not supported in local subagent");case"webFetchRequestQuery":return mr(e.id,"Web fetch is not supported in local subagent");case"switchModeRequestQuery":return yr(e.id,"Subagent mode switches are not supported in local subagent");case"askQuestionInteractionQuery":{const t=new er.tz({result:{case:"rejected",value:new er.ox({reason:"Interactive questions are not supported in local subagent mode"})}});return gr(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 c=r.rootParentConversationId?.trim(),p=r.parentConversationId?.trim(),f=void 0!==c&&""!==c?c:void 0!==p&&""!==p?p:t,m=await this.getResources({agentId:t,parentAgentId:r.parentConversationId}),g=r.readonly?new X(m,function(e){const t=[K(lT,HU(e.errorMessage)),K(uT,qU(e.errorMessage)),K(Yn,zU(e.errorMessage))];return e.wrapShell&&t.push(K(sT,function(e){return{execute:async(t,r)=>new fe.W4({result:{case:"permissionDenied",value:WU(e,r)}})}}(e.errorMessage)),K(re,function(e){return{async*execute(t,r){yield new fe.FI({event:{case:"permissionDenied",value:WU(e,r)}})}}}(e.errorMessage)),K(jT,function(e){return{execute:async(t,r)=>new Ao.Lt({result:{case:"permissionDenied",value:WU(e,r)}})}}(e.errorMessage))),e.includeWriteBackgroundShellStdin&&t.push(K(UT,function(e){return{execute:async(t,r)=>new Ao.nt({result:{case:"error",value:new Ao.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(),a,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:MD(n.agentStore.getMetadata("blobEncryptionKey"),this.headers),endlessRetries:this.endlessRetries,subagentModelOverrides:[]}),await n.transcriptWriter.writeTurnEndedFromState(e,n.agentStore.getConversationStateStructure(),e.signal.aborted?{status:"aborted",error:QU}:{status:"success"}),{status:"completed",finalMessage:s,toolCallCount:i}}catch(r){const o=r instanceof Error?r.message:String(r);return TD.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:QU}:{status:"error",error:o}}}getTurnEndedFromError(e,t){return e.signal.aborted?{status:"aborted",error:QU}:{status:"error",error:t}}isAwaitBackgroundMode(e){if(!Boolean(e.resumeAgentId&&!BU(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 no.zJ({result:{case:"stillRunning",value:new no.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 no.zJ({result:{case:"complete",value:new no.bE({agentId:r,finalMessage:e.finalMessage,toolCallCount:e.toolCallCount??0})}}):new no.zJ({result:{case:"error",value:new no.Y({agentId:r,error:e.finalMessage||"Subagent was aborted"})}}):this.isBackgroundRunBusy(r)?new no.zJ({result:{case:"stillRunning",value:new no.L5({agentId:r})}}):new no.zJ({result:{case:"notFound",value:new no.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 no.zJ({result:{case:"stillRunning",value:new no.L5({agentId:r})}}):(this.takeQueuedChildCompletion(r,n.runId),"completed"===i.status?new no.zJ({result:{case:"complete",value:new no.bE({agentId:r,finalMessage:i.finalMessage,toolCallCount:i.toolCallCount??0})}}):new no.zJ({result:{case:"error",value:new no.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 eB=r("../proto/dist/generated/agent/v1/agent_service_connect.js"),tB=r("../proto/dist/generated/agent/v1/requested_model_pb.js"),rB=r("../proto/dist/generated/agent/v1/selected_context_pb.js"),nB=r("./src/agent/analytics.ts"),oB=r("../proto/dist/generated/agent/v1/todo_tool_pb.js");const sB={[og.w3.UNSPECIFIED]:"unspecified",[og.w3.LEFT]:"left",[og.w3.RIGHT]:"right",[og.w3.MIDDLE]:"middle",[og.w3.BACK]:"back",[og.w3.FORWARD]:"forward"},iB={[og.Dh.UNSPECIFIED]:"unspecified",[og.Dh.UP]:"up",[og.Dh.DOWN]:"down",[og.Dh.LEFT]:"left",[og.Dh.RIGHT]:"right"},aB={[og.EB.UNSPECIFIED]:"unspecified",[og.EB.TAP]:"tap",[og.EB.DOWN]:"down",[og.EB.UP]:"up"};function cB(e){return sB[e]??"unspecified"}function lB(e){return void 0===e?void 0:{x:e.x,y:e.y}}function uB({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:lB(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 dB(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 hB("tool-call-started",e.message.value);case"partialToolCall":return hB("partial-tool-call",e.message.value);case"toolCallCompleted":return hB("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=dB(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 hB(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:yB(r)}:{}}:null}case"deleteToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"delete",args:{path:t.path},...r?{result:vB(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:bB(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:SB(r)}:{}}:null}case"readToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"read",args:{path:t.path},...r?{result:_B(r)}:{}}:null}case"editToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"edit",args:{path:t.path},...r?{result:CB(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:EB(r)}:{}}:null}case"readLintsToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"readLints",args:{paths:t.paths},...r?{result:PB(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:RB(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:TB(r)}:{}}:null}case"recordScreenToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"recordScreen",args:{mode:AB(t.mode)},...r?{result:$B(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:IB(r)}:{}}:null}case"createPlanToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"createPlan",args:{plan:t.plan},...r?{result:MB(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:OB(e.status)})))},...r?{result:DB(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:lB(e.value.coordinate)};case"click":return{type:"click",coordinate:lB(e.value.coordinate),button:cB(e.value.button),count:e.value.count,modifierKeys:e.value.modifierKeys};case"mouseDown":case"mouseUp":return{type:e.case,button:cB(e.value.button)};case"drag":return{type:"drag",path:e.value.path.map((e=>({x:e.x,y:e.y}))),button:cB(e.value.button),modifierKeys:e.value.modifierKeys};case"scroll":return{type:"scroll",coordinate:lB(e.value.coordinate),direction:iB[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:aB[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?uB(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:pB(t),...r?{result:gB(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 pB(e){return{description:e.description??"",prompt:e.prompt??"",...e.subagentType?{subagentType:fB(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:mB(e.mode)}:{},...e.respondingToMessageIds&&e.respondingToMessageIds.length>0?{respondingToMessageIds:e.respondingToMessageIds}:{}}}function fB(e){const t=e.type.case;return t?"custom"===t?{kind:t,name:e.type.value.name}:{kind:t}:{kind:"unspecified"}}function mB(e){switch(e){case Wm.FL.AGENT:return"agent";case Wm.FL.PLAN:return"plan";default:return"unspecified"}}function gB(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:wB(t.backgroundReason),...t.transcriptPath?{transcriptPath:t.transcriptPath}:{}}}}case"error":return{status:"error",error:{message:e.result.value.error??"Task failed"}};default:return}}function wB(e){switch(e){case Wm.qL.AGENT_REQUEST:return"agentRequest";case Wm.qL.USER_REQUEST:return"userRequest";case Wm.qL.QUEUED_FOLLOW_UP:return"queuedFollowUp";default:return"unspecified"}}function yB(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 vB(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 bB(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 SB(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]=kB(n);return{status:"success",value:{...Object.keys(r).length>0?{workspaceResults:r}:{},...t.activeEditorResult?{activeEditorResult:kB(t.activeEditorResult)}:{}}}}return{status:"error",error:{message:e.result.value.error??e.result.case}}}}function kB(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 _B(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 CB(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 EB(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{directoryTreeRoot:xB(e.result.value.directoryTreeRoot)}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function xB(e){if(e)return{absPath:e.absPath??"",childrenDirs:e.childrenDirs?.map(xB)??[],childrenFiles:e.childrenFiles?.map((e=>({name:e.name})))??[],childrenWereProcessed:e.childrenWereProcessed??!1,fullSubtreeExtensionCounts:e.fullSubtreeExtensionCounts??{},numFiles:e.numFiles??0}}function PB(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:FB(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 RB(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 IB(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 TB(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 AB(e){switch(e){case GA.$u.START_RECORDING:return"START_RECORDING";case GA.$u.SAVE_RECORDING:return"SAVE_RECORDING";case GA.$u.DISCARD_RECORDING:return"DISCARD_RECORDING";default:throw new Error(`Unknown RecordingMode: ${e}`)}}function $B(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 MB(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 DB(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{todos:e.result.value.todos?.map((e=>({content:e.content,status:OB(e.status)})))??[],totalCount:e.result.value.totalCount??0}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function OB(e){switch(e){case oB.Vj.UNSPECIFIED:case oB.Vj.PENDING:return"pending";case oB.Vj.IN_PROGRESS:return"inProgress";case oB.Vj.COMPLETED:return"completed";case oB.Vj.CANCELLED:return"cancelled";default:return"pending"}}function FB(e){switch(e){case YT.h_.UNSPECIFIED:case YT.h_.ERROR:return"error";case YT.h_.WARNING:return"warning";case YT.h_.INFORMATION:return"information";case YT.h_.HINT:return"hint";default:return"error"}}const NB={type:"object",properties:{},additionalProperties:!0};function LB(e){const t={};for(const[r,n]of Object.entries(e))t[r]=n;return t}function jB(e){return"text"===e.type?new Rc._Z({content:{case:"text",value:new Rc.zN({text:e.text})}}):new Rc._Z({content:{case:"image",value:new Rc.do({data:n.Buffer.from(e.data,"base64"),mimeType:e.mimeType??""})}})}function UB(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var BB=r("./src/agent/errors.ts");const WB="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 HB(e){return{async execute(){throw new Error(e)}}}function qB(e){var t;e.register(sT,HB(WB)),e.register(re,(t=WB,{async*execute(){throw new Error(t)}})),e.register(jT,HB(WB)),e.register(zT,HB(WB)),e.register(UT,HB(WB)),e.register(iT,HB(WB)),e.register(ST,HB("ReadLints is not available when local.fs is set: lint diagnostics come from a host language service, not the FileSystem.")),e.register(hT,HB("Git is not available when local.fs is set: the agent's files live in a FileSystem, not a host git checkout."))}var zB=r("./src/agent/filesystem/executors.ts"),GB=r("./src/agent/filesystem/compose.ts"),VB=r("./src/agent/filesystem/trees.ts"),KB=r("./src/agent/filesystem/walk.ts");const JB="/tmp",ZB=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.txt$/i;function XB(e){const{write:t,hostProjectDir:r}=e;return{async execute(e,n,o){const s=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,KB.eI)(e.hostProjectDir),r=(0,KB.eI)(e.writePath);return"/"!==t&&(0,KB.hJ)({path:r,prefix:t})?r.slice(t.length):void 0}(e),n=void 0===r?(0,KB.eI)(e.writePath):(0,KB.eI)(`${JB}/${r}`);if(!(0,KB.hJ)({path:n,prefix:JB}))return;const o=a().posix.basename(n),s=a().posix.join(JB,Ic);return a().posix.dirname(n)===s&&ZB.test(o)?a().posix.join(JB,o):n}({writePath:n.path,hostProjectDir:r});if(void 0===s||s===n.path)return await t.execute(e,n,o);const i=n.clone();i.path=s;const c=await t.execute(e,i,o);return"success"===c.result.case&&(c.result.value.path=s),c}}}class QB{constructor(e,t="/"){this.fs=e,this.listeners=new Set,this.workspace=(0,KB.eI)(t)}getAllCursorRules(e){return this.rules??=async function(e,t){const[r,n]=await Promise.all([YB(e,s.posix.join(t,".cursor/rules")),eW(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 YB(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,Fr.PH)(r,(async t=>{const r=await tW(e,t),n=void 0===r?null:Yr(r);if(null!==n)return Om({path:t,body:n.body,frontmatter:n.frontmatter,rawFrontmatter:n.rawFrontmatter})}),{max:8})).filter((e=>void 0!==e))}async function eW(e,t){const r=await tW(e,t);if(void 0!==r)return Om({path:t,body:Xr({content:r,filename:"AGENTS.md"}),frontmatter:{alwaysApply:!0}})}async function tW(e,t){try{const r=await e.read(t);return"string"==typeof r?r:(new TextDecoder).decode(r)}catch{return}}const rW={getAllCursorRules:async()=>[],reload(){},onDidChangeRules:()=>()=>{},dispose(){}},nW={async exec(){throw new Error("git is not available in a FileSystem session")}},oW={isIgnoredByAny:async()=>!1,isGitIgnored:async()=>!1,isCursorIgnored:async()=>!1,isRepoBlocked:async()=>!1,listCursorIgnoreFilesByRoot:async()=>[],getCursorIgnoreMapping:async()=>({}),getShellSandboxIgnoreMapping:async()=>({}),getGitIgnoreMapping:async()=>({}),getRepoBlockExcludeGlobs:async()=>[]};function sW(e){return{cursorRulesService:!0===e.includeProjectRules?new QB(e.fs,e.workspace):rW,getAgentSkills:async()=>[],subagentsService:e.subagentsService??new qm,gitExecutor:nW,ignoreService:oW,requestContextIsWorkingDirHomeDir:!1,reportProcessWorkingDirectory:!1}}function iW(e,t){const r=t.workspace??"/",n=(0,zB.c9)(e,{workspace:r});return{localResourceProviderOptions:{overrideReadExecutor:n.read,overrideWriteExecutor:XB({write:n.write,hostProjectDir:t.hostProjectDir}),overrideGrepExecutor:n.grep,overrideLsExecutor:n.ls,overrideDeleteExecutor:n.delete,suppressDefaultShellExecutor:!0,...sW({...t.settings,fs:e,workspace:r})},reportedWorkspacePath:r,reportedProjectFolder:JB,excludeHooks:!0,excludeProjectMcp:!0}}var aW=r("./src/agent/executor-common.ts");class cW{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 lW{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 uW=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.":lC("Allowed servers",r)}${t=e.blockedServers,void 0===t||0===t.length?"":lC("Blocked",t)}`;var t,r}(e.allowlist)}`}(e))}catch{}}}}};var dW=r("./src/agent/native/vendored-tree-sitter.ts"),hW=r("./src/agent/platform-package-locator.ts"),pW=r("./src/agent/sdk-config.ts"),fW=r("../../node_modules/.pnpm/@statsig+js-client@3.31.0/node_modules/@statsig/js-client/src/index.js"),mW=r("./src/agent/utils/logger.ts");const gW={checkFeatureGate:()=>!1,getDynamicConfigValue:({defaultValue:e})=>e},wW=new Map;async function yW(e){try{const t=await async function(e){const t=await(0,aW.dC)(e,aW.EV);if(!t)return;const r=aW.EV.endsWith("/")?aW.EV.slice(0,-1):aW.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,aW.tF)(),"x-ghost-mode":(0,aW.U)(e)},body:JSON.stringify({})});if(!n.ok)return void mW.v.log(`Failed to bootstrap SDK Statsig: ${n.status} ${n.statusText}`);const o=await n.json();return vW(o)&&"string"==typeof o.config&&o.config.length>0?o.config:void 0}(e);if(!t)return gW;const r=new fW.StatsigClient("client-Bm4HJ0aDjXHQVsoACMREyLNxm5p6zzuzhO50MgtoT5D",function(e){try{const r=JSON.parse(e);if(vW(r)&&"object"==typeof(t=r.user)&&null!==t&&!Array.isArray(t))return{...r.user,custom:{...r.user.custom,clientType:"sdk",clientVersion:(0,aW.tF)()}}}catch(e){mW.v.log(`Failed to parse SDK Statsig bootstrap user: ${e instanceof Error?e.message:String(e)}`)}var t;return{custom:{clientType:"sdk",clientVersion:(0,aW.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 mW.v.log(`Failed to initialize SDK Statsig: ${e instanceof Error?e.message:String(e)}`),gW}}function vW(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function bW(e){let t;return e?.then((e=>{t=e}),(()=>{})),()=>t?.checkFeatureGate("grok_bot_mcp_app_payment_token_filter",{disableExposureLog:!0})??!1}var SW=r("./src/agent/tools-option.ts");class kW{async requestApproval(){return{approved:!0}}}function _W(e,t){if(!function(e){return void 0!==e&&Object.keys(e).length>0}(t))return;const r=e.resources.base;if(!(r instanceof kM))throw new BB.j1("SDK custom tools require the default local workspace resource provider.",{isRetryable:!1});const n=r.getMcpExecutionPolicyDeps(),o=r.get(Yn),s=function(e,t){return{async execute(r,n,o){const s=n.toolName||function(e){const t=`${qn}-`;return e.startsWith(t)?e.slice(t.length):e}(n.name),i=e[s];if(void 0===i)return new Rc.iz({result:{case:"error",value:new Rc.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:UB(e)?e:void 0};var t}(e),r=void 0!==t.structuredContent?ve.Struct.fromJson(t.structuredContent):void 0;return new Rc.iz({result:{case:"success",value:new Rc.QW({content:t.content.map(jB),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 Rc.iz({result:{case:"error",value:new Rc.Nh({error:e instanceof Error?e.message:String(e)})}})}}}}(t,e.state.sessionId),i=new kW;e.resources.base.register(Yn,{async execute(e,t,r){if(function(e){return e.providerIdentifier===qn}(t)){const o=await zI(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 CW=new Set(["127.0.0.1","localhost","[::1]"]);function EW(e){if(void 0===e)return{};const t=e.resourceProviderOptions;return{...void 0!==t?{localResourceProviderOptions:t}:{},...void 0!==e.reportedWorkspacePath?{reportedWorkspacePath:e.reportedWorkspacePath}:{}}}function xW(){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 PW={warn(){},error(){}},RW={log(){}};class IW{async requestApproval(e){return{approved:!1,reason:`Local SDK runs cannot request interactive approval for ${TW(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 TW(e){switch(e.type){case aw.Shell:return"this shell command";case aw.Mcp:return"this MCP tool call";case aw.Write:return"this file edit";case aw.Delete:return"this file deletion";default:return"this operation"}}function AW(e){return void 0!==e&&"insecure_none"!==e.type}async function $W(e,t){const r="string"==typeof e||void 0===e?{workingDirectory:e,apiKey:t}:e,i=(0,b.q6)().with(d._O,RW),a=PU(r.settingSources),l=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&&CW.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}`);ma=e}((0,pW.Mu)()),/:\/\/(localhost|127\.0\.0\.1)/.test(aW.EV)&&(process.env.NODE_TLS_REJECT_UNAUTHORIZED="0");const u=performance.now();let h=0;if(r.apiKey){const e=performance.now();await Promise.all([(0,aW.ly)(r.apiKey),(0,aW.mU)(r.apiKey)]),h=performance.now()-e}const p=r.workingDirectory||process.cwd();(0,dW.configureVendoredTreeSitterWorkspaceDir)(p);for(const e of r.dirs??[])(0,dW.configureVendoredTreeSitterWorkspaceDir)(e);const f=(0,yo.Rv)((0,o.homedir)(),p),m={hostProjectDir:f,settings:{includeProjectRules:RU(a,"project"),subagentsService:new jU(r.customSubagents??[])}};let g;const w="win32"===process.platform?"rg.exe":"rg",y=process.env.CURSOR_RIPGREP_PATH;g=y&&(0,s.isAbsolute)(y)?y:(0,hW.hQ)({binaryName:w,excludedWorkspaceDir:p}),g||(g=(0,$o.xS)()),g&&(0,$o.J)(g);let v,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{v=(0,aW.KU)(r.apiKey,r.teamId);const e=(0,be.createClient)(SL.I,v),t=function(e){let t=wW.get(e);return t||(t=yW(e),wW.set(e,t),t.then((r=>{r===gW&&wW.get(e)===t&&wW.delete(e)}),(()=>{wW.get(e)===t&&wW.delete(e)}))),t}(r.apiKey);S=t;const n={getDefaultNetworkAllowlist:async()=>(await t).getDynamicConfigValue({configName:"sandbox_default_network_allowlist",paramName:"allowlist",defaultValue:[]})};k=new ED(new kD(e,{supportsHostMcpBridgeExemption:!0}),n,{...void 0===l?{}:{hostMcpBridgeUrls:l},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){mW.v.log(`Failed to initialize authenticated dashboard services: ${e instanceof Error?e.message:String(e)}`)}const _=performance.now(),C=r.apiKey?await(0,$o.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=AW(r)?r:!0===n?.enabled?function(e,t={}){return{type:e,...t}}("workspace_readwrite",{networkPolicy:(0,$o.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,hW.hQ)({binaryName:t,excludedWorkspaceDir:e});r&&(0,$o.St)({sandboxBinaryPath:r})}(t),!(0,$o.K3)(void 0,{ctx:e.initializationCtx}))throw new BB.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,$o.resolveSandboxPolicyForWorkspace)(t,s);return{defaultSandboxPolicy:i,defaultSandboxPolicySources:s}}({cwd:p,perUserSandboxPolicy:C,sandboxOptions:r.sandboxOptions,initializationCtx:i}):void 0,x=performance.now()-_,P=E?.defaultSandboxPolicy,R=E?.defaultSandboxPolicySources,I=AW(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})(),$={powershellUtf8Console:!1,powershellUtf8ChildEnv:!1},M=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=PU(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,$o.K3)(c,{ctx:e.initializationCtx})),u=e.getSandboxEnabled??(()=>"insecure_none"!==c.type&&l()),d=new Gw,h=new _c(d,a,n),p=new FU,f=new NU,m=e.getSmartModeClassifierAutoModeEnabled?.(),g=new OU(m?"allowlist":e.approvalMode??"unrestricted",c,a,e.respectAdminControls??!1),w=e.pendingDecisionProvider,y={executeIndexedGrep:void 0},v=()=>!0,b=RU(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=_||RU(i,"project")||RU(i,"user")||b,x=RU(i,"project")||RU(i,"user")||RU(i,"mdm"),P=RU(i,"team"),R=P&&void 0!==e.dashboardTransport,I=RU(i,"project")||RU(i,"user")||P||R||b,T={teamSettingsService:a,initializationCtx:e.initializationCtx,importThirdPartyPlugins:S,ignoreApprovals:!0,includeProjectMcp:RU(i,"project"),includeUserMcp:RU(i,"user"),includePluginMcp:b,isLinkSharedPaymentTokenLogRedactionEnabled:e.isLinkSharedPaymentTokenLogRedactionEnabled},A=s=>MU({workingDirectory:t,...void 0!==o?{workspaceRoots:o}:{},adapters:{...s.includeMcp?{mcp:eO({...T,inlineMcpServers:e.mcpServers})}:{},...b?{pluginBootstrap:aU({importThirdPartyPlugins:S,dashboardTransport:e.dashboardTransport})}:{},...x?{hooks:bL({includeProjectHooks:RU(i,"project"),includeUserHooks:RU(i,"user"),includeEnterpriseHooks:RU(i,"mdm"),useCommandHookStdinTransport:e.useCommandHookStdinTransport})}:{},...I?{localExtensibility:_L({includeProjectExtensibility:RU(i,"project"),includeUserExtensibility:RU(i,"user"),includeManagedSkills:R,includeTeamExtensibility:P,includePluginExtensibility:b,teamSettingsService:a,getThirdPartyExtensibilityEnabled:v,dashboardTransport:e.dashboardTransport,importThirdPartyPlugins:S})}:{},resourceFactory:wU({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 LU(new S$(e),void 0===t?.onMcpAllowlistInUse&&void 0===t?.onMcpServerBlockedByAllowlist?void 0:{mcpLease:e,onMcpAllowlistInUse:t.onMcpAllowlistInUse,onMcpServerBlockedByAllowlist:t.onMcpServerBlockedByAllowlist}),createSessionMcpLease:(t,r)=>eO({...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 DU;return{pendingDecisionStore:n,fileChangeTracker:new uw(t),permissionsService:new _k(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 yL(new dL(e.resources,n.hookExecutor,(()=>function(e,t){const r=fL(t,mL,"conversationId","conversation_id")??e.sessionId??"";return{conversation_id:r,generation_id:fL(t,mL,"generationId","generation_id")??r,model:fL(t,mL,"model")??"unknown",...vO({modelId:fL(t,mL,"modelId","model_id"),modelParams:fL(t,wL,"modelParams","model_params")})}}(e.sessionState,e.metadata)),e.workspaceServices.mcpLease,void 0,void 0,t.hooksConfigLease),n)}}]:[],...C?{workspaceServicesContributors:[{contributeServices:t=>{const r=new jU(e.customSubagents??[]),n=t.services.subagentsService;return{subagentsService:void 0===n?r:new Qm([r,n])}}}]}:{}}});if(!E)return A({includeMcp:!1});try{return await A({includeMcp:!0})}catch(e){return TD.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:i,dashboardTransport:v,settingSources:r.settingSources,mcpServers:r.mcpServers,customSubagents:r.customSubagents,defaultSandboxPolicy:P,defaultSandboxPolicySources:R,approvalMode:I?"allowlist":void 0,pendingDecisionProvider:I||!0===r.autoReview?new IW: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,$o.tv)(i,t);if(a&&"insecure_none"!==a.type&&a.networkPolicy?.allow&&s.push(...a.networkPolicy.allow),"1"!==process.env[vv.K4]&&r){const e=await(0,$o.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:xW,getPowershellUtf8Options:async()=>{if(void 0===S)return $;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 $}},isLinkSharedPaymentTokenLogRedactionEnabled:bW(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,nB.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()-u)}),{run:async(e,t,o)=>(0,TD.ni)(PW,(async()=>{const s=(0,D.VI)((0,b.q6)().withName("sdk.run").with(d._O,RW)),[i,a]=s.ctx.withCancel(),l=t.sessionId??(0,ye.C)(),u=t.mcpServersOverride,h=void 0===(f=t.customTools)?[]:Object.entries(f).map((([e,t])=>({clientKey:qn,providerIdentifier:qn,toolName:e,name:`${qn}-${e}`,description:t.description??"",inputSchema:t.inputSchema??NB,...void 0===t.outputSchema?{}:{outputSchema:t.outputSchema},...void 0===t.annotations?{}:{annotations:LB(t.annotations)},source:"internal"})));var f;let g;const w={...m,workspace:t.fileSystemWorkspace},y=void 0===t.fileSystem?void 0:(_=await async function(e,t){return"function"==typeof e?await e(t):e}(t.fileSystem,{agentId:l,sessionId:l}),C=_,(0,GB.VL)({"/":C,[JB]:(0,VB.Om)()})),v=void 0===t.onMcpAdminToolLimitCounts?void 0:new cW,S=()=>{for(const e of v?.take()??[])try{t.onMcpAdminToolLimitCounts?.(e)}catch{}},k=new lW;var _,C;g=await M.createSessionRuntime({sessionId:l,mcpServersOverride:u,extraMcpTools:h,onMcpAdminToolLimitCheck:v?.record,onMcpAllowlistInUse:uW.report,onMcpServerBlockedByAllowlist:k.report,...void 0===y?EW(t.sessionResources):iW(y,w)});const E=new Map;try{const s=g.resources.wrapped;_W(g,t.customTools),void 0!==y&&qB(g.resources.base);const d=t.blobStore??new oe.ve;let f=t.initialState??new c.Y9z({});const m=void 0!==t.model?new tB.G4({modelId:t.model.id,...!0===t.model.maxMode?{maxMode:!0}:{},parameters:(t.model.params??[]).map((e=>new tB.SR({id:e.id,value:e.value})))}):void 0,b=!0===e.summarize?void 0:e.images,_=Array.isArray(b)?b.map((e=>{const t=(0,ye.C)(),r=new Uint8Array(n.Buffer.from(e.data,"base64")),o=(0,aW.v8)(r);return new rB.d({uuid:t,...o?{mimeType:o}:{},dataOrBlobId:{case:"data",value:r}})})):[],C=_.length>0?new rB.xv({selectedImages:_}):void 0,R=function(e){switch(e){case"agent":return c.xyI.AGENT;case"plan":return c.xyI.PLAN;default:return}}(t.mode),I=!0===e.summarize?new c.QFf({action:{case:"summarizeAction",value:new c.Scs}}):new c.QFf({action:{case:"userMessageAction",value:new c.Vtf({userMessage:new c.RGk({text:e.text,selectedContext:C,...void 0!==R?{mode:R}:{}})})}}),T={sendUpdate:async(e,t)=>{const r=dB(t,l);null!==r&&await o.sendUpdate(r)},query:async(e,t)=>function(e){switch(e.query.case){case"webSearchRequestQuery":return hr(e.id);case"webFetchRequestQuery":return fr(e.id);case"switchModeRequestQuery":return wr(e.id);case"askQuestionInteractionQuery":return gr(e.id,new er.tz({result:{case:"rejected",value:new er.ox({reason:"Interactive questions are not supported in local SDK runs"})}}));case"createPlanRequestQuery":return vr(e.id,new tr.bK({result:{case:"success",value:new tr.Jo},planUri:""}));case"setupVmEnvironmentArgs":return br(e.id,new or.r$({result:{case:"success",value:new or.JH}}));case"replaceEnvArgs":return Sr(e.id,new nr.dV({result:{case:"failure",value:new nr.uq({errorMessage:"Environment replacement is not supported in local SDK runs",setupLogs:""})}}));case"prManagementRequestQuery":return kr(e.id,new rr.HL({result:{case:"error",value:new rr.K$({error:"PR management is only available in cloud agents"})}}));case"mcpAuthRequestQuery":return _r(e.id,"MCP authentication is not supported in local SDK runs");case"connectScmRequestQuery":return Cr(e.id,"Connecting GitHub is not supported in local SDK runs");case"generateImageRequestQuery":return Er(e.id,e.query.value.args?.description);case void 0:throw new BB.j1("Missing interaction query type",{isRetryable:!1});default:throw e.query,new BB.j1("Unhandled interaction query type",{isRetryable:!1})}}(t)};if(N!==t.apiKey||!L){await Promise.all([(0,aW.ly)(t.apiKey),(0,aW.mU)(t.apiKey)]);const e=(0,aW.KU)(t.apiKey,r.teamId),n=go((0,be.createClient)(eB.N,e),{injectTraceHeaders:!0});L=new Bn(n),N=t.apiKey}const A=(0,aW.Vh)(L,(()=>{const e=(0,aW.KU)(t.apiKey,r.teamId),n=go((0,be.createClient)(eB.N,e),{injectTraceHeaders:!0}),o=new Bn(n);return L=o,N=t.apiKey,o})),$=function(e){return{...void 0!==e.allowedTools?{[SW.$$]:e.allowedTools.join(",")}:{},...void 0!==e.disallowedTools&&e.disallowedTools.length>0?{[SW.VJ]:e.disallowedTools.join(",")}:{}}}(t),D=new YU({agentClient:A,rootRequestId:t.requestId,getResources:async({agentId:e})=>{let r=E.get(e);return r||(r=await M.createSessionRuntime({sessionId:e,mcpServersOverride:u,extraMcpTools:h,onMcpAdminToolLimitCheck:v?.record,onMcpAllowlistInUse:uW.report,onMcpServerBlockedByAllowlist:k.report,...void 0===y?EW(t.subagentInherit):iW(y,w)}),_W(r,t.customTools),void 0!==y&&qB(r.resources.base),r.resources.base.register(so,O),r.resources.base.register(io,F),r.resources.base.register(ao,j),E.set(e,r)),r.resources.wrapped},mcpTools:h,workspacePath:p,parentConversationId:l,...(void 0!==t.subagentInherit||void 0!==y)&&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 no.vS({result:{case:"error",value:new no.od({agentId:o,error:s.error})}}):"aborted"===s.status?new no.vS({result:{case:"error",value:new no.od({agentId:o,error:s.error??"Subagent was aborted by the user"})}}):"background"===s.status?new no.vS({result:{case:"success",value:new no.HJ({agentId:o,finalMessage:s.finalMessage,toolCallCount:s.toolCallCount??0,backgroundReason:s.backgroundReason,transcriptPath:s.transcriptPath})}}):new no.vS({result:{case:"success",value:new no.HJ({agentId:o,finalMessage:s.finalMessage,toolCallCount:s.toolCallCount??0})}})}catch(t){if(o&&e.releaseSession&&e.releaseSession(o),t instanceof dr)throw t;const n=t instanceof Error?t.message:String(t),s=o??function(e){return e instanceof oo&&e.agentId||e&&"object"==typeof e&&"agentId"in e&&"string"==typeof e.agentId?e.agentId:void 0}(t)??r.resumeAgentId;return new no.vS({result:{case:"error",value:new no.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}}}(D),F=(P=D,{execute:(e,t)=>P.awaitBackgroundRunBounded(e,t)}),j=function(e){return{execute:async(t,r)=>e.forceBackgroundByToolCallId(r.toolCallId)}}(D);g.resources.base.register(so,O),g.resources.base.register(io,F),g.resources.base.register(ao,j);const U=M.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===y&&!0!==e.summarize?function(e){const{workspaceRuntime:t}=e;if(!(t.hooksConfigLease.hasHookForStep(gd.sessionStart)||t.hooksConfigLease.hasHookForStep(gd.sessionEnd)||t.hooksConfigLease.hasHookForStep(gd.stop)||t.hooksConfigLease.hasHookForStep(gd.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(gd.sessionStart))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...vO(e),is_background_agent:!1},r=await n.executeHookForStep(gd.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){TD.Jz.warn("[hooks-adapter] sessionStart hook failed:",e)}},async onSessionEnd(e,t){if(n.hasHooksForStep(gd.sessionEnd))try{const r={conversation_id:o?.conversationId??"",generation_id:o?.generationId??"",model:o?.model??"unknown",...o?vO(o):{},reason:e,duration_ms:t,is_background_agent:!1,final_status:e};await n.executeHookForStep(gd.sessionEnd,r)}catch(e){TD.Jz.warn("[hooks-adapter] sessionEnd hook failed:",e)}finally{n.clearSessionEnvironment()}else n.clearSessionEnvironment()},async onBeforeSubmitPrompt(e){if(n.hasHooksForStep(gd.beforeSubmitPrompt))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...vO(e),prompt:e.promptText??"",attachments:[]};await n.executeHookForStep(gd.beforeSubmitPrompt,t)}catch(e){TD.Jz.warn("[hooks-adapter] beforeSubmitPrompt hook failed:",e)}},async onTurnCompleted(e){if(!n.hasHooksForStep(gd.stop))return;const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...vO(e),status:"completed",loop_count:e.loopCount},r=await n.executeHookForStep(gd.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(gd.stop))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...vO(e),status:"error",loop_count:e.loopCount};await n.executeHookForStep(gd.stop,t)}catch(e){TD.Jz.warn("[hooks-adapter] onTurnError stop hook failed:",e)}},async onTurnAborted(e){if(n.hasHooksForStep(gd.stop))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...vO(e),status:"aborted",loop_count:e.loopCount};await n.executeHookForStep(gd.stop,t)}catch(e){TD.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 ZU({workspacePath:p,conversationId:l,blobStore:d}),q=function(e,t,r){const{hooks:n}=r,[o,s]=e.withCancel(),i=new ID;let a;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"),ND(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=MD(function(e,t){if((0,AD.TU)(t))return t;const r=DD.get(e);if(void 0!==r)return r;const n=(0,AD.sh)(e).blobEncryptionKey;if(void 0===n)throw new Error("getDefaultAgentMetadata did not seed a blobEncryptionKey");return DD.set(e,n),n}(r.conversationId,r.blobEncryptionKey),r.runOptions?.headers);return{done:(async()=>{const e=FD(r,0,OD(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;TD.Jz.warn("[agent-session-runner] sessionStart hook failed:",e)}let s=t,c=0;for(;s;){const e=FD(r,c,OD(s));try{await(n?.onBeforeSubmitPrompt?.(e))}catch(e){TD.Jz.warn("[agent-session-runner] beforeSubmitPrompt hook failed:",e)}a=r.runOptions?.generationUUID??(0,ye.C)();try{await r.agentClient.run(o,w,s,void 0,g,r.resources,r.blobStore,i,y,r.mcpTools??[],{conversationId:r.conversationId,...r.runOptions,generationUUID:a,headers:S,subagentModelOverrides:r.runOptions?.subagentModelOverrides??[]})}catch(t){throw v=LD(t)?"aborted":"error",jD("aborted"===v?n?.onTurnAborted?.(e):n?.onTurnError?.(e)),t}finally{a=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=ND(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||LD(r)?"aborted":"error",jD("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?(c+=1,i.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){TD.Jz.warn("[agent-session-runner] sessionEnd hook failed:",e)}try{await(n?.dispose?.())}catch(e){TD.Jz.warn("[agent-session-runner] hooks dispose failed:",e)}})),abort(){s()},async steer(e){if(""===e.trim())return"revert_to_followup";const t=a;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,ye.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 i.submitConversationAction(new c.QFf({action:{case:"injectContextAction",value:new c.hGJ({injectionId:r,expectedRunId:t,payload:{case:"userContext",value:new c.oW$({userMessage:new c.RGk({messageId:(0,ye.C)(),text:e})})}})}})),await n}catch(e){return u(r,"revert_to_followup"),TD.Jz.warn("[agent-session-runner] context injection failed:",e),"revert_to_followup"}}}}(i,I,{agentClient:A,interactionListener:T,resources:s,blobStore:d,initialState:f,conversationId:l,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 D.waitForBackgroundCompletions(l,t);return r.length>0?function(e){return new c.QFf({action:{case:"backgroundTaskCompletionAction",value:new c.Kwc({completions:e.map((e=>new c.KFq({taskId:e.agentId,kind:c.aZc.SUBAGENT,status:"success"===e.status?c.uHL.SUCCESS:"aborted"===e.status?c.uHL.ABORTED:c.uHL.ERROR,...e.finalMessage.length>0?{detail:e.finalMessage}:{}})))})}})}(r):void 0},async onCheckpoint(e){f=e,H.writeFromState(i,e),await(t.onCheckpoint?.(e))}}),z=q.done.finally((async()=>{try{await D.awaitBackgroundWorkers()}finally{await H.waitForPendingWrites().catch((()=>{}));for(const e of E.values())try{await e.dispose()}catch(e){mW.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(),a()},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 M.reload()},async dispose(){await M.dispose()}}}},"./src/agent/native/tree-sitter-bash.webpack.cjs"(e,t,r){const{loadVendoredTreeSitterModule:n}=r("./src/agent/native/vendored-tree-sitter.ts"),o=n({packageName:"tree-sitter-bash",nativeRequire:require});e.exports=o.available?o.module:{}},"./src/agent/native/tree-sitter.webpack.cjs"(e,t,r){const{createUnavailableParserClass:n,loadVendoredTreeSitterModule:o}=r("./src/agent/native/vendored-tree-sitter.ts"),s=o({packageName:"tree-sitter",nativeRequire:require});e.exports=s.available?s.module:n(s.reason)},"../constants/dist/commercial-cursor-hosts.js"(e,t,r){"use strict";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){"use strict";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){"use strict";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){"use strict";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"),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.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.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.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.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.normalize(e),r=t[0]?.toLowerCase();return r&&":"===t[1]&&t[2]===m.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.resolve(t)===m.resolve(this.cwd)&&(this.cwd=void 0===r||m.resolve(r)===m.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.join(q.tmpdir(),"cursor-bash-state-")),g=m.join(f,"state-in"),w=m.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.Writable?D:null,j=O instanceof Ir.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.Writable?E:null,R=x instanceof Ir.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.Writable?x:null,I=P instanceof Ir.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.win32.basename(t).toLowerCase();return"bash.exe"===r?t:"bin"===r?m.win32.join(t,"bash.exe"):m.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){"use strict";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){"use strict";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){"use strict";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){"use strict";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"),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.resolve(e),E(r));return void 0!==n&&C(n.fstype)}function R(e){const t=a.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.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.parse(e),o=e.slice(n.length).split(a.sep);let s=n;for(const[e,n]of o.entries()){s=a.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.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.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.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){"use strict";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){"use strict";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){"use strict";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}))})}}}};