@cursor/sdk 1.4.0 → 1.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bundled/index.js +565 -532
- package/dist/bundled/sqlite.js +1 -1
- package/dist/cjs/144.js +206 -0
- package/dist/cjs/730.js +1 -1
- package/dist/cjs/index.js +1 -1
- package/dist/cjs/local-executor.d.ts.map +1 -1
- package/dist/cjs/mcp-allowlist-notice.d.ts +30 -0
- package/dist/cjs/mcp-allowlist-notice.d.ts.map +1 -0
- package/dist/esm/144.js +206 -0
- package/dist/esm/730.js +1 -1
- package/dist/esm/index.js +1 -1
- package/dist/esm/local-executor.d.ts.map +1 -1
- package/dist/esm/mcp-allowlist-notice.d.ts +30 -0
- package/dist/esm/mcp-allowlist-notice.d.ts.map +1 -0
- package/package.json +6 -6
- package/dist/cjs/993.js +0 -211
- package/dist/esm/993.js +0 -211
package/dist/cjs/993.js
DELETED
|
@@ -1,211 +0,0 @@
|
|
|
1
|
-
exports.id=993,exports.ids=[993],exports.modules={"./src/agent/local-executor.ts"(e,t,r){"use strict";r.d(t,{createLocalExecutor:()=>dB});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"]}),I={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 R extends Error{constructor(e){super(e),this.name="ControlledExecDisposedError"}}function T(e){return e instanceof R?"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:I[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=Re(e)?e.content:void 0;if(!Array.isArray(n))continue;const o=n;for(const e of o)Re(e)&&"tool-call"===e.type&&"string"==typeof e.toolCallId&&t.add(e.toolCallId)}return t}function Ie(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 Re(t)&&"string"==typeof t.toolCallId&&""!==t.toolCallId?t.toolCallId:void 0}function Re(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)?Ie(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 It(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 Rt=/^(?: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:Ie(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(Pn),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(Pn);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 Ir=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 Rr=(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=>{Rr.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{Ir(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 Rr.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=>{Rr.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(It(f()),{countAsTransportError:!0});const e=p((()=>It(f())),(()=>It({...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(Rt.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;async function Sn(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 kn(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 _n(e){const{connectCode:t,connectCodeName:r,...n}=e;return void 0===r?n:{...n,connectCode:r}}async function Cn(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 Sn(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 Sn(u,o,void 0===d?void 0:e=>d({error:a,delayMs:u,waitEnded:e}))};let d,h,p,f,m,g=e.state,w=e.action,y=0,v=o,b=0,S=0,k=!1,_=0;const C=()=>{k&&(n.onConnectionStateChange?.({state:"connected"}),k=!1)},E=e=>()=>{e===y&&(m=!0,C())},x=e=>({handleCheckpoint:async(t,n,o)=>{e===y&&(m=!0),await r.handleCheckpoint(t,n,o),e===y&&(d=n,h=o?.resumeEligibility??"eligible",C())},getLatestCheckpoint:()=>r.getLatestCheckpoint()});for(;;){if(t.canceled)throw i.toCancelledError(void 0,v);if(d=void 0,h=void 0,m=!1,s.beginAttempt?.({attempt:y,originalRequestId:a}),y>0?(v=(0,ye.C)(),await(n.onRetryStarting?.(y,{actionCase:w.action.case,conversationState:g,isResume:"resumeAction"===w.action.case,attemptRequestId:v})),e.logging&&yn.info(t,`[${e.logging.tag}] Retrying attempt ${y}`,{attempt:y,actionCase:w.action.case,requestId:v,originalRequestId:a}),"resumeAction"===w.action.case&&(await(n.onRetryResuming?.({checkpointState:g,nextAttempt:y,reason:"resume_action"})),e.logging&&yn.info(t,`[${e.logging.tag}] Resuming from checkpoint`,{nextAttempt:y,reason:"resume_action"}))):(e.logging&&yn.info(t,`[${e.logging.tag}] Initial request`,{attempt:y,actionCase:w.action.case,requestId:v}),!0===e.notifyInitialResume&&"resumeAction"===w.action.case&&(await(n.onRetryResuming?.({checkpointState:g,nextAttempt:y,reason:"resume_action"})),e.logging&&yn.info(t,`[${e.logging.tag}] Resuming from checkpoint`,{nextAttempt:y,reason:"resume_action"}))),t.canceled)throw i.toCancelledError(void 0,v);try{return await s.runAttempt({state:g,action:w,checkpointHandler:x(y),attempt:y,attemptRequestId:v,notifyConnected:C,notifyApplicationProgress:E(y)}),C(),void(e.logging&&yn.info(t,`[${e.logging.tag}] Request successful`,{attempt:y,actionCase:w.action.case,requestId:v,originalRequestId:a}))}catch(r){if(!0===i.shortCircuit?.(r))throw i.toCancelledError(r,v);const o=!0===n.endlessRetries?.(),C=e.nowMs?.()??Date.now();m&&(p=void 0,f=void 0);const E=void 0===p?void 0:C-p,x=void 0===f?void 0:C-f;let R=s.classify(r,{attempt:y,attemptRequestId:v,originalRequestId:a,serverErrorRetries:b,transportErrorRetries:S,stallRetryElapsedMs:E,rateLimitRetryElapsedMs:x,endlessRetries:o});if("retry"===R.action){const n="resumeAction"===w.action.case||!0===e.noProgressGuardCountsReplays&&y>0;void 0!==d?_=0:n&&m&&(_++,_>=2&&(e.logging&&yn.warn(t,`[${e.logging.tag}] Resume attempts are streaming but not producing checkpoints; stopping automatic resume`,{noProgressResumeFailures:_,attempt:y,requestId:v,originalRequestId:a,errorName:r instanceof Error?r.name:typeof r}),R={action:"throw",error:new Ge("Agent turn stopped after repeated resume attempts made no progress",{cause:r instanceof Error?r:void 0,requestId:v,displayInfo:{title:"Agent stopped retrying",detail:"The connection was interrupted repeatedly without saving progress, so the agent stopped to avoid repeating the same work. Retry to continue from the last saved state.",isRetryable:!0}}),transportFailureKind:R.transportFailureKind}))}const T={...void 0===R.transportFailureKind?{}:{transportFailureKind:R.transportFailureKind},...void 0===e.loop?{}:{loop:e.loop}},A=e.logging?.diagnostics?.(r);if(e.logging){const e="retry"===R.action?`RETRY (countAsServerError=${R.countAsServerError}, countAsTransportError=${R.countAsTransportError})`:`THROW ${R.error.kind}`;yn.warn(t,`[AGENT_ERROR_DIAGNOSTICS] requestId=${v} originalRequestId=${a} decision=${e}`,{decision:e,willRetry:"retry"===R.action,enableAgentRetries:n.enableAgentRetries??!1,endlessRetries:o,isRunningInTest:n.isRunningInTest??!1,serverErrorRetries:b,transportErrorRetries:S,attempt:y,requestId:v,originalRequestId:a,...T,...A})}if("throw"===R.action){if(0===y){const r={attempt:0,actionCase:w.action.case,error:R.error,requestId:v,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:v,originalRequestId:a})}}throw e.logging&&yn.warn(t,`[${e.logging.tag}] Error not retryable`,{...T,...A,attempt:y,actionCase:w.action.case,requestId:v,originalRequestId:a,errorName:R.error.name,...!0===e.logging.includeErrorObjects?{error:R.error}:{},serverErrorRetries:b,transportErrorRetries:S}),R.error}const $=y+1;if("ineligible_terminal_turn"===h)return void(e.logging&&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!==R.immediate&&(n.onConnectionStateChange?.({state:"reconnecting",attempt:$,trigger:{...T,...s.reconnectTrigger?.(r,R,{originalRequestId:a,failedAttemptRequestId:v,nextAttempt:$})??{originatingRequestId:a,attemptRequestId:v}}}),k=!0),R.countAsServerError&&b++,R.countAsTransportError&&S++,!0===R.stall?p??=C:p=void 0,!0===R.rateLimit?f??=C:f=void 0,y=$,void 0!==d&&(I=d,kn((P=g).turns,I.turns)&&kn(P.rootPromptMessagesJson,I.rootPromptMessagesJson)||(l=vn),g=d,w=new c.QFf({action:{case:"resumeAction",value:new c.qKo}})),s.onRetryCommitted?.(),!0===R.immediate||!0===R.noBackoff&&void 0===R.retryAfterMs||await u(y,t.signal,o,R,r)}}var P,I}new Set(["textDelta","thinkingDelta","thinkingCompleted","partialToolCall","toolCallDelta","toolCallStarted","toolCallCompleted","tokenDelta"]);var En=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},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});const Pn=(0,b.cF)(Symbol("agentStreamMetadata"),void 0),In=(0,d.h)("@anysphere/agent-client:abort"),Rn=(0,d.h)("@anysphere/agent-client:retry"),Tn=(0,d.h)("@anysphere/agent-client:request-context-blob");async function An({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,Tn.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 $n=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 Mn(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 Dn(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 On(e){return e instanceof Error?e.name:void 0}class Fn{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:On(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=On(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 I={networkPhaseStartedAt:performance.now()};try{d.onNetworkPhaseStart?.()}catch(t){Rn.warn(e,"onNetworkPhaseStart callback failed",{error:String(t)})}const R=En(h,(0,D.VI)(e.withName("networkPhase")),!1);e=R.ctx,await(0,D.MG)(R.span,(()=>Cn({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,..._n(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})=>{const d=function(e,t,r){return{sendUpdate:async(n,o)=>{if(t===r())return e.sendUpdate(n,o);"toolCallCompleted"===o.message?.case&&Rn.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,d,y,b,a,o,l,v,i,S,k,C,c,u,s,I)},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{xn(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 _={stack:[],error:void 0,hasError:!1};try{const x=e;e=this.options.prepareAttemptContext?.(e,{attempt:b,attemptRequestId:h,originalRequestId:m,runOptions:d})??e;const P=En(_,(0,D.VI)(e.withName(k)),!1);P.span.setAttribute("agent.attempt",b),P.span.setAttribute("agent.request_id",h),P.span.setAttribute("agent.original_request_id",m),e=P.ctx,e=(0,D.Mf)(e,"agent.request_id",h),e=(e=(0,D.Mf)(e,"agent.original_request_id",m)).with(Pn,{requestId:h,rootParentRequestId:d.rootParentRequestId,modelDetails:n});const I=new Set(w.sources);let R=void 0!==w.abortReasonName||void 0!==w.abortReasonMessage;const T=(t,r)=>{if(I.has(t))return;I.add(t),w.sources=[...I];const n=(e=>{const t="string"==typeof e?.abortReasonName?e.abortReasonName:void 0,r="string"==typeof e?.abortReasonMessage?e.abortReasonMessage:void 0;if(void 0!==t||void 0!==r)return{abortReasonName:t,abortReasonMessage:r}})(r);R||void 0===n||(R=!0,w.abortReasonName=n.abortReasonName,w.abortReasonMessage=n.abortReasonMessage),In.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;T("ctx_signal_abort",he(t))}else e.signal.addEventListener("abort",(()=>{const t=e.signal.reason;T("ctx_signal_abort",he(t))}),{once:!0});const[A,$]=e.withCancel();if(a.signal?.aborted){const e=a.signal?.reason;T("conversation_action_abort",he(e)),$()}else a.signal?.addEventListener("abort",(()=>{const e=a.signal?.reason;T("conversation_action_abort",he(e)),$()}),{once:!0});if(e.canceled||A.canceled){const t={ctxCanceled:e.canceled,softCancel:A.canceled};throw T("pre_run_cancel",t),new Ze("User aborted request")}const O=(0,D.VI)(e.withName("createControlledExecManager")),F=M.fromResources(s);O[Symbol.dispose]();const[N,L]=e.withCancel(),j=new Kt,{failThresholdMs:U,advisoryThresholdMs:B}=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 W;const H=En(_,new Jt(N,{thresholdMs:U,advisoryThresholdMs:B,loop:this.options.loop,transportMode:()=>W,onStall:e=>{T("stall_detector",{thresholdMs:U,advisoryThresholdMs:B}),L(e)},onStallCallback:d.onStall,handlerTracker:j}),!1);let q,z,G;const V=(0,Se.Jt)(),K=new f.F8(V,(e=>(H.reset("outbound_write",$n(e)),e))),J=En(_,(0,D.VI)(e.withName("writeInitialRequest")),!1);let Z;const X=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),Q=d.requestContextBlobTransportMode??"legacy",Y=0===b&&"userMessageAction"===r.action.case&&0===t.turns.length,ee="ref_only"===Q&&Y?"dual":Q,[,te]=await Promise.all([An({ctx:e,action:r,resources:s,blobStore:i,options:d,source:"run_request",transportMode:ee,notifyBytes:0===b}),void 0===d.mintLlmGatewayCredential?Promise.resolve(void 0):$r(d.mintLlmGatewayCredential,{signal:A.signal,isCanceled:()=>A.canceled,requestId:h})]),ne={action:r,headers:d.headers??{}},oe=this.options.decorateAttempt?.(ne,d)??ne,se=new c.Mpn({conversationState:t,action:oe.action,modelDetails:n,requestedModel:d.requestedModel,clientLlmGatewayCredential:te,mcpTools:X,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(Z=K.write(new pe.KS({message:{case:"runRequest",value:se}})),A.canceled){const t={ctxCanceled:e.canceled,softCancel:A.canceled};throw T("post_write_cancel",t),J[Symbol.dispose](),new Ze("User aborted request")}const ie={...oe.headers,"x-request-id":h,"x-original-request-id":m,...Oe(d),...Ne()};q=(0,D.VI)(e.withName("handshakeEstablishment")),q.span.setAttribute("handshake.firstStreamOnClient",!this.hasStartedStream),this.hasStartedStream=!0;const ae=function(e){return e?.get(wn)}(e)?.startTransportRun(),ce=void 0===ae?q.ctx:function(e,t){return e.with(wn,t)}(q.ctx,ae),le=0===b&&void 0!==d.onTtftBreakdown?S?.networkPhaseStartedAt:void 0;let ue;const me=void 0===ae&&void 0===le?V:(C=V,E=()=>{ue=performance.now(),ae?.markFirstRequestSent(ue)},{[Symbol.asyncIterator](){const e=C[Symbol.asyncIterator]();let t=!1;const r={next:()=>(t||(t=!0,E()),e.next())};return void 0!==e.return&&(r.return=t=>e.return(t)),void 0!==e.throw&&(r.throw=t=>e.throw(t)),r}}),ge=this.client.run(ce,me,{signal:N.signal,headers:ie,onHeader:e=>{W=e.get("x-cursor-agent-transport-mode")??void 0,d.onHeader?.(e)},onNetworkStarted:()=>{void 0===z&&(z=performance.now(),0===b&&(G=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)}}()))}}),ye=performance.now();let be;const ke=t=>{q&&(q.span.setAttribute("handshake.firstMessageHeartbeat",t),void 0!==z&&q.span.setAttribute("handshake.preNetworkMs",z-ye),q[Symbol.dispose](),q=void 0),y();const r=performance.now();be=r,d.onFirstMessage?.(r-ye),void 0!==z&&(d.onFirstMessageNetwork?.(r-z),void 0!==G&&(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:W,firstMessageNetworkMs:r-z,reading:G.stop()}),G=void 0))},Ce=()=>{v(),d.onFirstNonHeartbeatResponse?.(performance.now()-ye,b)},xe=d.onTtftBreakdown?e=>{const t=performance.now(),r=void 0===le||void 0===ue||"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:le,transportRunCalledAt:ye,firstRequestTakenAt:ue,firstMessageAt:be??t,firstOutputAt:t,firstOutputAtEpochMs:Date.now()});d.onTtftBreakdown(void 0===r?e:{...e,transit:r},b)}: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,ge,{action:oe.action,state:t},void 0===this.options.onExecHeldForCheckpoint?{}:{onHeld:this.options.onExecHeldForCheckpoint}):ge,Re=!0===this.options.execAfterCheckpointStored||!0===this.options.execCheckpointGate?new Ee(void 0===this.options.onExecHeldForCheckpointStore?{}:{onExecHeld:this.options.onExecHeldForCheckpointStore}):void 0,{interactionStream:Ae,execStream:De,checkpointStream:Fe,kvStream:Le,done:je}=function(e,t,r,n,o,s,i,a,c){const l=(0,Se.Jt)(),u=(0,Se.Jt)(),d=(0,Se.Jt)(),h=(0,Se.Jt)();let p=!1,f=!1;return{interactionStream:l,execStream:u,checkpointStream:d,kvStream:h,done:async function(){let m,g,w=!1,y=!1;try{for await(const o of t){if(void 0!==o.ttftBreakdown){const t=o.ttftBreakdown;try{a?.({serverFirstTokenMs:t.serverFirstTokenMs,preStreamSetupMs:t.preStreamSetupMs,waitForFirstEventMs:t.waitForFirstEventMs,providerTtftMs:t.providerTtftMs,slowPoolWaitMs:t.slowPoolWaitMs,...void 0===t.clientPrepMs?{}:{clientPrepMs:t.clientPrepMs},...void 0===t.clientPrepLegs?{}:{clientPrepLegs:we(t.clientPrepLegs)},...void 0===t.preHandlerMs?{}:{preHandlerMs:t.preHandlerMs},clock:t.clientClock?"client":"server"})}catch(t){Rn.warn(e,"onTtftBreakdown callback failed",{error:String(t)})}}const t="interactionUpdate"===o.message.case&&"heartbeat"===o.message.value.message.case;if(p||(p=!0,n(t)),t)r.onServerSentHeartbeat(),r.reset("inbound_message","heartbeat");else{if(!f){f=!0;try{i?.()}catch(t){Rn.warn(e,"onFirstNonHeartbeatMessage callback failed",{error:String(t)})}}r.reset("inbound_message",$n(o))}if("interactionUpdate"===o.message.case&&"turnEnded"===o.message.value.message.case&&(w=!0),"interactionUpdate"!==o.message.case&&"interactionQuery"!==o.message.case||await l.write(o.message).catch((()=>{})),"execServerMessage"!==o.message.case&&"execServerControlMessage"!==o.message.case||await u.write(o.message.value),"conversationCheckpointUpdate"===o.message.case){const e=w?"ineligible_terminal_turn":"eligible";"ineligible_terminal_turn"===e&&(y=!0);const t=c?.noteRouted(o.message.value);try{await d.write({checkpoint:o.message.value,metadata:{resumeEligibility:e},...void 0===t?{}:{onSettled:t}})}catch(e){throw t?.(),e}}"kvServerMessage"===o.message.case&&await h.write(o.message.value)}r.onStreamEnded()}catch(e){m=e}finally{if(g=m,w&&y&&void 0!==m&&!o?.aborted&&!s?.aborted&&function(e){const t=e instanceof 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)}(m)&&(Rn.debug(e,"Ignoring transport close after terminal agent stream",{caughtError:m instanceof Error?`${m.name}: ${m.message}`:String(m)}),r.onStreamEnded(),g=void 0),w||o?.aborted||s?.aborted){if(!w&&!o?.aborted){const t=`Stream ended without turnEnded, abort signals: signal.aborted=${o?.aborted}, parentSignal.aborted=${s?.aborted}; firstMessageFired=${p}`;Rn.warn(e,t)}}else{const t="Stream ended without turnEnded — connection likely dropped mid-stream";void 0===m?(Rn.warn(e,t),g=new Ge(t,{isTransport:!0})):m instanceof Error&&"[aborted] aborted"===m.message?(Rn.warn(e,`${t}; retrying caught [aborted] aborted error`),g=new Ge(t,{cause:m,isTransport:!0})):Rn.warn(e,`${t}; caught non-retriable stream error, rethrowing as-is`,{caughtError:Mn(m)})}l.close(),u.close(),d.close(),h.close()}if(void 0!==g)throw g}()}}(e,Ie,H,ke,A.signal,e.signal,Ce,xe,Re);let Ue;const Be={handleCheckpoint:async(e,t,r)=>{await l.handleCheckpoint(e,t,r),Ue=r?.resumeEligibility??"eligible"},getLatestCheckpoint:()=>l.getLatestCheckpoint()};J[Symbol.dispose]();const We=5e3;let He;const qe=()=>{He=setTimeout((()=>{K.write(new pe.KS({message:{case:"clientHeartbeat",value:new pe.kA}})).then((()=>H.onClientSentHeartbeat()),(()=>{})),qe()}),We)},Ve=()=>{void 0!==He&&(clearTimeout(He),He=void 0)};qe();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(Ae,o,new f.F8(K,(e=>new pe.KS({message:{case:"interactionResponse",value:e}}))),H);t={run:async e=>{await Promise.all([j.track("handleShellStream",Dn(e,a,o)),j.track("interactionController",c.run(e))])}}}else{const e=new Ar(Ae,o,new f.F8(K,(e=>new pe.KS({message:{case:"interactionResponse",value:e}}))),H);t={run:async t=>{await j.track("interactionController",e.run(t))}}}void 0!==Z&&await Promise.race([Z,je.catch((()=>{}))]);const c=new f.F8(K,(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(De,c,F,Re),b=new de(Le,new f.F8(K,(e=>new pe.KS({message:{case:"kvClientMessage",value:e}}))),i,{beforeGetBlob:async(e,t)=>i.persistForRemoteRead(e,t)}),S=new _e(Fe,Be,e);let k,_;const C={promise:new Promise(((e,t)=>{k=e,_=t})),resolve:k,reject:_};A.canceled?(C.resolve(),Ae.close()):A.signal.addEventListener("abort",(()=>{C.resolve(),Ae.close()}),{once:!0}),l.run(A).then(C.resolve).catch(C.reject);const E=Promise.allSettled([j.track("streamSplitter",je.finally((()=>{Ve(),a.close(),c.close()}))),j.track("execHandler",C.promise),t.run(e),j.track("checkpointController",S.run()),j.track("kvHandler",b.run(e)),j.track("conversationActionManager",a.run(e,{write:async t=>{await An({ctx:e,action:t,resources:s,blobStore:i,options:d,source:"queued_action"}),await K.write(new pe.KS({message:{case:"conversationAction",value:t}}))}}))]);let P,I;const R={promise:new Promise(((e,t)=>{P=e,I=t})),resolve:P,reject:I};E.then(R.resolve).catch(R.reject),e.canceled?R.reject(new Ze("User aborted request")):e.signal.addEventListener("abort",(()=>R.reject(new Ze("User aborted request"))),{once:!0});const T=()=>{e.signal.aborted?L():function(e){const t=e.lingerMs??6e3;return new Promise((r=>{let n=!1;const o=e=>{n||(n=!0,clearTimeout(s),r(e))},s=setTimeout((()=>o("linger_timed_out")),t);e.done.then((()=>o("stream_ended")),(()=>o("stream_ended")))}))}({done:je,lingerMs:d.softCancelLingerMs}).then((t=>{Rn.info(e,"Soft-cancel transport linger finished",{outcome:t,requestId:h}),L()}))};A.canceled?(T(),R.reject(new Ze("User aborted request"))):A.signal.addEventListener("abort",(()=>{T(),R.reject(new Ze("User aborted request"))}),{once:!0});const $=await R.promise,M=$[0],D=$[1],O=$[3],N=e=>e.reason instanceof Error?`${e.reason.name}: ${e.reason.message}`:String(e.reason);if("rejected"===O.status)throw new Ke("Checkpoint persistence failed",{cause:O.reason instanceof Error?O.reason:void 0,requestId:h,displayInfo:{title:"Checkpoint persistence failed",detail:N(O),isRetryable:!1}});const U="ineligible_terminal_turn"===Ue;if(U){const t={..."rejected"===M.status?{streamSplitter:N(M)}:{},..."rejected"===D.status?{execHandler:N(D)}:{}};Object.keys(t).length>0&&Rn.debug(e,"Ignoring handler errors after terminal checkpoint",t)}if("rejected"===M.status&&!U)throw M.reason;if("rejected"===D.status&&!U)throw D.reason;A.canceled||await this.processUnprocessedMessages(x,a,Be,n,o,s,i,u,d,h,m,g,w,H,y,v)}finally{Ve(),G?.stop(),G=void 0,q&&(q[Symbol.dispose](),q=void 0)}}catch(e){_.error=e,_.hasError=!0}finally{xn(_)}var C,E}async processUnprocessedMessages(e,t,r,n,o,s,i,a,l,u,d,h,p,f,m,g){if(!t.hasUnprocessedMessages())return;const w=t.getUnprocessedUserMessages(),y=r.getLatestCheckpoint();if(!y||0===w.length)return;const v=w[0];t.markMessageAsProcessed(v),t.resetStream(),f[Symbol.dispose]();const b=r.getLatestCheckpoint();try{await this.runInternal(e,y,new c.QFf({action:{case:"userMessageAction",value:new c.Vtf({userMessage:v})}}),n,o,s,i,t,r,a,l,u,d,h,p,m,g,0,void 0,"agent.request.queuedMessage")}catch(e){throw b===r.getLatestCheckpoint()&&t.requeueMessage(v),e}}}const Nn="cursor-ide-browser",Ln="cursor-dev-control",jn="custom-user-tools",Un=new Set(["cursor-app-control","cursor-backend-control","cursor-browser-extension",Nn,Ln,jn,"fsd","cursor-subscriptions","cursor-cloud","suggestions","Cursor Slack Tools","Cursor Automation Tools"]);function Bn(e){return!Un.has(e)}const Wn=new Set([Ln,Nn]);function Hn(e){if(void 0!==e&&0!==Object.keys(e).length)try{return JSON.stringify(e)}catch{return}}function qn(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 Gn(e){return void 0===e||void 0===e.serverIdentifiers}function Vn(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 Kn=G("mcp-executor",(e=>new H(e,Q("mcpArgs"),Y("mcpResult"))),((e,t)=>{t.register(new A(e,te("mcpArgs"),ee("mcpResult")))})),Jn=G("list-mcp-resources-executor",(e=>new H(e,Q("listMcpResourcesExecArgs"),Y("listMcpResourcesExecResult"))),((e,t)=>{t.register(new A(e,te("listMcpResourcesExecArgs"),ee("listMcpResourcesExecResult")))})),Zn=G("read-mcp-resource-executor",(e=>new H(e,Q("readMcpResourceExecArgs"),Y("readMcpResourceExecResult"))),((e,t)=>{t.register(new A(e,te("readMcpResourceExecArgs"),ee("readMcpResourceExecResult")))})),Xn=G("mcp-state-executor",(e=>new H(e,Q("mcpStateExecArgs"),Y("mcpStateExecResult"))),((e,t)=>{t.register(new A(e,te("mcpStateExecArgs"),ee("mcpStateExecResult")))}));var Qn=r("../proto/dist/generated/agent/v1/subagent_exec_pb.js");(0,b.cF)(Symbol("pendingSubagentReplay"),void 0);class Yn extends Error{constructor(e,t){super(e),this.name="SubagentHostError",this.agentId=t?.agentId,this.cause=t?.cause}}const eo=G("subagent-executor",(e=>new H(e,Q("subagentArgs"),Y("subagentResult"))),((e,t)=>{t.register(new A(e,te("subagentArgs"),ee("subagentResult")))})),to=G("subagent-await-executor",(e=>new H(e,Q("subagentAwaitArgs"),Y("subagentAwaitResult"))),((e,t)=>{t.register(new A(e,te("subagentAwaitArgs"),ee("subagentAwaitResult")))})),ro=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 no=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/status.js"),oo=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/span_kind.js");const so=(0,be.createContextKey)(void 0,{description:"anysphere.callerContext"});function io(e){return null!==e&&"object"==typeof e&&Symbol.asyncIterator in e}function ao(e){return e instanceof Error?e:new Error(String(e))}function co(e,t,r){return{[Symbol.asyncIterator](){const n=e[Symbol.asyncIterator]();let o=!1;const s=e=>{o||(o=!0,e?(t?.recordException(ao(e)),t?.setStatus({code:no.s.ERROR,message:e instanceof Error?e.message:"Stream failed"})):t?.setStatus({code:no.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 lo(...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 uo(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:oo.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=lo(o,e))}const i=lo(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(so,l),g={...c,headers:i,signal:p,contextValues:m},w=s.call(e,a,g);return io(w)?co(w,u,d):null!==(h=w)&&"object"==typeof h&&"then"in h&&"function"==typeof h.then?Promise.resolve(w).then((e=>io(e)?co(e,u,d):(u?.setStatus({code:no.s.OK}),u?.end(),d?.(),e))).catch((e=>{throw u?.recordException(ao(e)),u?.setStatus({code:no.s.ERROR,message:e instanceof Error?e.message:"RPC call failed"}),u?.end(),d?.(),e})):(u?.setStatus({code:no.s.OK}),u?.end(),d?.(),w)}catch(e){throw u?.recordException(ao(e)),u?.setStatus({code:no.s.ERROR,message:e instanceof Error?e.message:"RPC call failed"}),u?.end(),d?.(),e}var h}}})}var ho=r("node:crypto"),po=r("../utils/dist/workspace-paths.js");function fo(){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 mo(e){return(0,s.join)(fo(),(0,po.r_)(e))}var go=r("node:fs/promises"),wo=r("../../node_modules/.pnpm/lru-cache@11.2.5/node_modules/lru-cache/dist/esm/index.js"),yo=r("node:fs");const vo="local";function bo(e,t){return`${e}:task_progress:${t}`}function So(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 ko(e,t){e.hookApprovalRequirement=void 0!==t?new fe.In(t):void 0}function _o(e){return e.hookApprovalRequirement}function Co(e){return e?.kind===fe.b.FORCE_PROMPT}function Eo(e){return!(!e.skipApproval||e.smartModeClassifierAllowed&&Co(e.hookApprovalRequirement))}var xo=r("../proto/dist/generated/agent/v1/background_shell_exec_pb.js"),Po=r("../shell-exec/dist/api/index.js"),Io=r("./src/agent/native/tree-sitter.webpack.cjs"),Ro=r("./src/agent/native/tree-sitter-bash.webpack.cjs");const To=function(e,t=console.warn){let r;return()=>{if(void 0!==r)return r;try{const t=e();t.setLanguage(Ro),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 Io)),Ao=new Set(["file_redirect","heredoc_redirect","herestring_redirect","heredoc","here_string","redirect","redirection"]),$o=new Set(["<",">",">>",">|","<>","<&",">&","&>","&>>"]);function Mo(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=>$o.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)Ao.has(r.type)&&h(r,t)})(t),Ao.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 Do(e){return Mo(To(),e)}function Oo(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 Fo(e,t){return t>0?t>=e.length?e.length:Math.trunc(t):0}function No(e,t){const r=Fo(e,t);return Oo(e,r)?r-1:r}function Lo(e,t){const r=Fo(e,t);return Oo(e,r)?r+1:r}function jo(e,t){return t>0?e.length<=t?e:e.slice(0,No(e,t)):""}function Uo(e,t){return t>0?e.length<=t?e:e.slice(Lo(e,e.length-Math.trunc(t))):""}let Bo,Wo;function Ho(e,t){Bo??=new TextEncoder,Wo??=new Uint8Array(65536);let r=0,n=0;for(;r<e.length&&n<t;){const o=Math.min(t-n,Wo.length),s=e.slice(r,r+o),i=Bo.encodeInto(s,Wo.subarray(0,o));if(0===i.read)break;r+=i.read,n+=i.written}return{read:r,written:n}}var qo=r("../../node_modules/.pnpm/re2js@1.2.2/node_modules/re2js/build/index.esm.js"),zo=r("../utils/dist/path-utils.js");const Go="path is empty or only whitespace",Vo=async e=>{const t=(0,zo.o1)(e);try{return await(0,go.realpath)(t)}catch{return t}},Ko=1048576,Jo=52428800;var Zo=r("../proto/dist/generated/agent/v1/sandbox_pb.js");function Xo(e){if(!e)return;let t;return"allow"===e.default?t=Zo.h1.ALLOW:"deny"===e.default&&(t=Zo.h1.DENY),new Zo.RB({version:e.version,defaultAction:t,deny:e.deny??[],allow:e.allow??[],logging:e.logging?(r=e.logging,new Zo.Qq({decisionLogPath:r.decisionLogPath,logFormat:r.logFormat})):void 0});var r}function Qo(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 Zo.h1.ALLOW:t.default="allow";break;case Zo.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,Po.T6)():(0,Po.Po)())}function Yo(e){switch(e){case"system":return Zo.Sz.SYSTEM;case"workspace":return Zo.Sz.WORKSPACE;default:return Zo.Sz.UNSPECIFIED}}function es(e){const t=function(e){switch(e){case Zo.Sz.SYSTEM:return"system";case Zo.Sz.WORKSPACE:return"workspace";case Zo.Sz.UNSPECIFIED:default:return}}(e.readBoundary),r=e.additionalReadPaths??[];return{readBoundary:t,additionalReadPaths:"workspace"===t&&r.length>0?r:void 0}}function ts(e){if(!e)return{type:"insecure_none"};switch(e.type){case Zo.vc.INSECURE_NONE:case Zo.vc.UNSPECIFIED:return{type:"insecure_none",allowlistEscalated:e.allowlistEscalated,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies};case Zo.vc.WORKSPACE_READWRITE:return{type:"workspace_readwrite",networkPolicy:Qo(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,...es(e)};case Zo.vc.WORKSPACE_READONLY:return{type:"workspace_readonly",networkPolicy:Qo(e),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadonlyPaths:e.additionalReadonlyPaths,disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicyStrict:e.networkPolicyStrict,...es(e)};default:return{type:"insecure_none"}}}function rs(e){if(e)return"insecure_none"===e.type?new Zo.Mw({type:Zo.vc.INSECURE_NONE,allowlistEscalated:e.allowlistEscalated,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies}):"workspace_readwrite"===e.type?new Zo.Mw({type:Zo.vc.WORKSPACE_READWRITE,networkAccess:(0,Po.$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:Xo(e.networkPolicy),networkPolicyStrict:e.networkPolicyStrict,readBoundary:Yo(e.readBoundary),additionalReadPaths:"workspace"===e.readBoundary?e.additionalReadPaths??[]:[]}):"workspace_readonly"===e.type?new Zo.Mw({type:Zo.vc.WORKSPACE_READONLY,networkAccess:(0,Po.$b)(e.networkPolicy),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadonlyPaths:e.additionalReadonlyPaths??[],disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicy:Xo(e.networkPolicy),networkPolicyStrict:e.networkPolicyStrict,readBoundary:Yo(e.readBoundary),additionalReadPaths:"workspace"===e.readBoundary?e.additionalReadPaths??[]:[]}):new Zo.Mw({type:Zo.vc.INSECURE_NONE})}function ns(e){return" "===e||"\t"===e||"\n"===e||"\r"===e||" "===e||""===e||""===e||""===e||"\ufeff"===e}function os(e){let t="",r=!1;for(const n of e)ns(n)?r=!0:(r&&t.length>0&&(t+=" "),r=!1,t+=n);return t}function ss(e){if(0===e.length)return!1;for(let t=0;t<e.length;t++)if("*"!==e[t])return!1;return!0}function is(e){const t=e.indexOf(":");if(t<=0)return;const r=e.slice(0,t).trim();for(let e=0;e<r.length;e++){const t=r[e];if(void 0!==t&&0===t.trim().length)return}return{executablePattern:r,argsPattern:e.slice(t+1).trim()}}function as(e){const t=e.trim();return{trimmedPattern:t,regexSource:`^${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\\\*/g,".*")}$`}}function cs(e,t){const{trimmedPattern:r,regexSource:n}=as(e);try{return new RegExp(n).test(t)}catch{return r===t}}function ls({command:e,parsingResult:t}){return[...new Set([e,...t.executableCommands.map((e=>e.fullText))])]}const us={a:"",b:"\b",e:"",E:"",f:"\f",n:"\n",r:"\r",t:"\t",v:"\v","\\":"\\","'":"'",'"':'"',"?":"?"};function ds(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=us[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 os(t)}function hs({rule:e,command:t}){const r=os(e).trim();return 0!==r.length&&(null!==function(e){const t=os(e).trim();if(0===t.length)return"Rule cannot be empty";if(t.length>512)return"Rule cannot exceed 512 characters";if(ss(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=is(t);if(void 0!==r){const{executablePattern:e,argsPattern:t}=r;if(ss(e)&&(0===t.length||ss(t)))return"Rule cannot match every command; narrow the executable or argument pattern"}return null}(r)||[t.trim(),os(t).trim(),ds(t).trim()].some((e=>function(e,t){const r=is(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(cs(e,s)&&cs(n,i))return!0}return e.includes("*")?cs(e,t):t===e||t.startsWith(`${e} `)}(r,e))))}function ps({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=>hs({rule:e,command:t}))))return e}function fs(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 ms({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=ps({matchForms:ls({command:e,parsingResult:t}),blockedCommands:r});return void 0===n?void 0:fs(n)}var gs=r("../utils/dist/test-resets.js");const ws="CURSOR_FORCED_SHELL_EGRESS_NETWORK_DEFAULT",ys="CURSOR_FORCED_SHELL_EGRESS_DEPENDENCY_DENY_DOMAINS",vs=/\$\(|`|<\(|>\(/,bs=/[;&|]/;let Ss,ks,_s,Cs;function Es(){if(void 0===Ss){const e=(process.env.CURSOR_FORCED_SHELL_EGRESS??"").trim().toLowerCase();Ss=""!==e&&"0"!==e&&"false"!==e&&"off"!==e}return Ss}function xs(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 Ps(e){return(process.env[e]??"").split(",").map((e=>e.trim())).filter((e=>e.length>0))}function Is(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 Rs(){if(void 0===Cs){const e=(process.env[ws]??"").trim().toLowerCase();let t="deny";"allow"===e||"deny"===e?t=e:""!==e&&console.error(`[forced-egress] ignoring invalid value in ${ws} (expected "allow" or "deny"); using "deny".`);const r=Ps("CURSOR_FORCED_SHELL_EGRESS_DENY_DOMAINS"),n=(process.env[ys]??"").trim();let o=r;"none"===n.toLowerCase()?o=[]:""!==n&&(o=Ps(ys)),Cs={networkDefault:t,denyDomains:r,dependencyDenyDomains:o,allowDomains:Ps("CURSOR_FORCED_SHELL_EGRESS_ALLOW_DOMAINS"),writablePaths:Is("CURSOR_FORCED_SHELL_EGRESS_WRITABLE_PATHS")}}return Cs}function Ts(e,t,r={}){const n=[xs(e),xs(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 As(e,t){const r=function(){const e=Rs();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===ks&&(ks=Ts("CURSOR_FORCED_SHELL_EGRESS_DEPENDENCY_REGEX","CURSOR_FORCED_SHELL_EGRESS_EXTRA_DEPENDENCY_REGEX",{anchorToExecutable:!0})),ks);if(null===n)return r;const o=t?.executableCommands??[];if(t?.parsingFailed||0===o.length)return r;if(vs.test(e))return r;const s=(void 0===_s&&(_s=Ts("CURSOR_FORCED_SHELL_EGRESS_SOURCE_REGEX","CURSOR_FORCED_SHELL_EGRESS_EXTRA_SOURCE_REGEX")),_s);for(const e of o){const t=e.fullText?.trim()||e.name?.trim()||"";if(!t||s?.test(t)||bs.test(t))return r}return o.every((e=>n.test(e.fullText?.trim()||e.name?.trim()||"")))?function(){const e=Rs();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,gs.J)((function(){Ss=void 0,ks=void 0,_s=void 0,Cs=void 0}));var $s=r("../utils/dist/lru-cache.js");const Ms=["Desktop","Documents","Downloads","Music","Movies","Pictures","Library",".Trash"],Ds="/Volumes";function Os(e){const t=e.replace(/\/{2,}/g,"/");return t.length>1&&t.endsWith("/")?t.slice(0,-1):t}function Fs(e,t){if("darwin"!==t.platform)return[];const r=Os(e),n=r.toLowerCase(),o=Os(t.homeDirectory),s="/"===r?1:r.split("/").length;return[...Ms.map((e=>`${o}/${e}`)),Ds].filter((e=>{return(t=e.toLowerCase())!==(r=n)&&t.startsWith(r.endsWith("/")?r:`${r}/`);var t,r})).map((e=>{const t=e.split("/").slice(s).join("/");return`${"/"===r?"":r}/${t}`}))}var Ns=r("../utils/dist/safe-spawn-cwd.js"),Ls=r("node:util");const js=8388608;var Us=r("../../node_modules/.pnpm/iconv-lite@0.7.0/node_modules/iconv-lite/lib/index.js"),Bs=r("../../node_modules/.pnpm/jschardet@3.1.4/node_modules/jschardet/index.js");function Ws(e){let t=1,r=0;for(;;){const n=e.indexOf("\n",r);if(-1===n)return t;t++,r=n+1}}const Hs="utf8",qs="utf8bom",zs="latin1",Gs={"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 Vs(e){return Gs[e]||e}function Ks(e){return e.startsWith("\ufeff")?e.slice(1):e}function Js(e){const t=e.toLowerCase();return"latin-1"===t?zs:"utf-8"===t?Hs:"utf-8-bom"===t||"utf-8 bom"===t?qs:t}function Zs(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 Xs=new Ls.TextDecoder("utf-8",{fatal:!1}),Qs=new Ls.TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),Ys="�";function ei(e){return Xs.decode(e)}function ti(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 ri(e,t=1/0){let r=0,n=0;for(;r<t;){const t=e.indexOf(Ys,n);if(-1===t)break;r++,n=t+1}return r}function ni(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 oi(e){return e<128?1:e<2048?2:e<65536?3:4}var si;!function(e){e.CRLF="CRLF",e.LF="LF"}(si||(si={}));const ii=[".mp4",".webm",".mov",".avi",".mkv",".wmv",".flv",".m4v"],ai=new Set(ii),ci=new Ls.TextDecoder("utf-8",{fatal:!0}),li=new Ls.TextDecoder("latin1"),ui=Buffer.from([239,187,191]),di={utf16le:Buffer.from([255,254]),utf16be:Buffer.from([254,255]),utf32le:Buffer.from([255,254,0,0]),utf32be:Buffer.from([0,0,254,255])},hi=8192,pi="UTF-8",fi="windows-1252",mi=/[^\u0000-\u007f\ufffd]/u,gi=/(?:\p{Script=Cyrillic}\p{M}*){3,}/gu,wi=/(?:\p{Script=Greek}\p{M}*){3,}/gu,yi=/(?:\p{Script=Hebrew}\p{M}*){3,}/gu,vi=new Map([["windows-1251",gi],["ISO-8859-5",gi],["KOI8-R",gi],["x-mac-cyrillic",gi],["IBM866",gi],["IBM855",gi],["ISO-8859-7",wi],["windows-1253",wi],["windows-1255",yi],["ISO-8859-8",yi],["TIS-620",/(?:\p{Script=Thai}\p{M}*){3,}/gu]]),bi=/\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,Si=/[\p{L}\p{M}]+/gu,ki=String.raw`[\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u00FF\u0152\u0153\u0160\u0161\u017D\u017E\u0178]`,_i=new RegExp(`[A-Za-z]${ki}{1,2}(?!${ki})|^${ki}{1,2}[A-Za-z]`,"u"),Ci=new Map,Ei=new Set([".png",".jpg",".jpeg",".gif",".webp",".ico",".bmp",".pdf",".zip",".tar",".gz",".exe",".dll",".so",".dylib",".bin",...ii]),xi=/\.(png|jpg|jpeg|gif|webp|ico|bmp)$/i,Pi=new Set([".ps1",".psm1",".psd1"]),Ii=/[^\u0000-\u007f]/u;function Ri(e){const t=e.toLowerCase(),r=t.lastIndexOf(".");return-1===r?"":t.substring(r)}function Ti(e){const t=Ri(e);return ai.has(t)}function Ai(e){const t=Ri(e);return{encoding:"binary",lineEnding:si.LF,isBinaryFile:!0,isImageFile:xi.test(t),isVideoFile:ai.has(t)}}async function $i(e,t){return(await Mi(e,t)).text}async function Mi(e,t){const{stamp:r,buf:n}=await async function(e){const t=await(0,go.open)(e,"r");try{return{stamp:await t.stat(),buf:await t.readFile()}}finally{await t.close()}}(e),o=Ni(n);if(o.isBinaryFile)throw new Error("Binary file cannot be decoded as text");const s=zi(e,r);let i;i=t||s||o.encoding;const{text:a,encoding:c}=Ki(n,i),l=Ks(a),u=c===Hs&&Ji(n)?qs:c;Gi(e,r,u);const d=function(e,t){if(t===qs)return Ji(e);const r=di[Vs(Js(t))];return void 0!==r&&e.subarray(0,r.length).equals(r)}(n,u);if(o.lineEnding===si.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 Di(e,t){if("binary"===t.encoding)return void qi(e);let r;try{r=await(0,go.stat)(e)}catch{return void qi(e)}r.size===t.buffer.byteLength?Gi(e,r,t.encoding):qi(e)}async function Oi(e,t,r,o){let s,i;try{s=r?await async function(e,t){try{return await Fi(e)}catch{}const r=Ri(e);if(Ei.has(r))return Ai(e);try{return await async function(e){const t=new Map;let r=0;for await(const n of Wi(e)){if(r>=100)break;try{const e=await Fi(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:Hi()}(t)}catch{return Hi()}}(e,r):await Fi(e)}catch{const t=Ri(e);s=Ei.has(t)?Ai(e):Hi()}const a=()=>i??=async function(e){try{const t=await(0,go.stat)(e);if(!t.isFile()||t.size>js)return;return await(0,go.readFile)(e)}catch{return}}(e),c=zi(e,await async function(e){try{return await(0,go.stat)(e)}catch{return}}(e));let l;if(!s.isBinaryFile){let r;o?r=Js(o):c?r=Js(c):(r=Js(s.encoding),r!==Hs&&r!==qs||(r=await async function(e,t){const r=await t();return void 0===r||(0,n.isUtf8)(r)?e:Vi(r).encoding===zs?zs:e}(r,a))),r===Hs&&!o&&function(e,t){return"win32"===process.platform&&Pi.has(Ri(e))&&Ii.test(t)&&!t.startsWith("#!")}(e,t)&&(await async function(e){try{return await(0,go.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=qs);const i=r===qs||r===Hs&&!o&&await Zi(e,ui),u=di[Vs(r)];i?l=ui:u&&await Zi(e,u)&&(l=u),s={...s,encoding:i?qs:r}}const u=Ws(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=Ks(Ki(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=Zs(t),o=Zs(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===si.CRLF?"\r\n":"\n"}):s.lineEnding===si.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?Ks(t):t,p=s.encoding===qs?Hs:s.encoding,f=p===Hs?await async function(e,t){if(!t.includes(Ys))return;const r=await e();return void 0===r?void 0:function(e,t){if(!e.includes(Ys)||(0,n.isUtf8)(t))return;const r=function(e){const t=[];let r=0;for(const n of Qs.decode(e)){const o=n.codePointAt(0)??0;if(65533!==o){r+=oi(o);continue}const s=ni(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(Ys);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(Ys,"utf8"));return Buffer.concat(s)}(t,r)}(a,h):void 0,m=f??Us.encode(h,p,{defaultEncoding:Hs});return{lines:u,buffer:l?Buffer.concat([l,m]):m,format:s}}async function Fi(e){const t=Ni((r=await Bi(e)).length===hi?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:Ti(e)}:{...t,isVideoFile:!1}}function Ni(e){if(0===e.length)return Hi();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:ji(Us.decode(e.subarray(0,hi),Vs(Js(t)))),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1};if(!function(e){const t=Math.min(hi,e.length);if(0===t)return!0;for(let r=0;r<t;r++)if(0===e[r])return!1;let r=0;for(let n=0;n<t;n++){const t=e[n];t<32&&9!==t&&10!==t&&13!==t&&r++}return r/t*100<5}(e))return{encoding:"binary",lineEnding:si.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:pi,lineEnding:Li(e),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1};if(!(0,n.isUtf8)(e)&&(o=ei(e),s=e.length,ti(o)||1024*ri(o)<=s&&!mi.test(o)))return{encoding:pi,lineEnding:Li(e),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1};const i=Bs.detect(e);let a=i.confidence>.7?i.encoding:"utf-8";"ascii"===a&&(a="utf-8");const c=vi.get(a);return void 0!==c&&(a=function(e,t,r){const n=Vs(Js(t));if(!Us.encodingExists(n))return t;const o=Us.decode(e,n);return bi.test(o)&&function(e,t,r){const n=t.match(r)?.length??0;let o=0;for(const[t]of Us.decode(e,fi).matchAll(Si))_i.test(t)&&o++;return o>n}(e,o,r)?fi:t}(e,a,c)),a!==fi||function(e,t){const r=Vs(Js(t));return!Us.getDecoder(r).write(e).includes(Ys)}(e,a)||(a="utf-8"),{encoding:a??"utf-8",lineEnding:Li(e),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1}}function Li(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 Ui(t,r)}function ji(e){const t=e.match(/\n/g)?.length??0,r=e.match(/\r\n/g)?.length??0;return Ui(r,t-r)}function Ui(e,t){return 0===e&&0===t?si.LF:e/(e+t)*100>=5?si.CRLF:si.LF}async function Bi(e){const t=await(0,go.open)(e,"r");try{const e=Buffer.allocUnsafe(hi),{bytesRead:r}=await t.read(e,0,hi,0);return e.subarray(0,r)}finally{await t.close()}}async function*Wi(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,go.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*Wi(r)):n.isFile()&&(yield r)}}catch(e){return}}function Hi(){return{encoding:Hs,lineEnding:"win32"===process.platform?si.CRLF:si.LF,isBinaryFile:!1,isImageFile:!1,isVideoFile:!1}}function qi(e){Ci.delete(e)}function zi(e,t){const r=Ci.get(e);if(void 0!==r)return void 0!==t&&r.size===t.size&&r.mtimeMs===t.mtimeMs?r.encoding:void Ci.delete(e)}function Gi(e,t,r){if(Ci.has(e)&&Ci.delete(e),Ci.set(e,{encoding:r,size:t.size,mtimeMs:t.mtimeMs}),Ci.size<=100)return;const n=Ci.keys().next().value;void 0!==n&&Ci.delete(n)}function Vi(e){try{return{text:ci.decode(e),encoding:Hs}}catch{const t=ei(e);return ti(t)?{text:t,encoding:Hs}:{text:li.decode(e),encoding:zs}}}function Ki(e,t){const r=Js(t);if(r===Hs||r===qs||"ascii"===r){const t=Vi(e);return r===qs&&t.encoding===Hs?{text:t.text,encoding:qs}:t}if(r===zs)return{text:li.decode(e),encoding:zs};try{const t=Vs(r);if(Us.encodingExists(t))return{text:Us.decode(e,t),encoding:r}}catch{}return Vi(e)}function Ji(e){return e.length>=ui.length&&e[0]===ui[0]&&e[1]===ui[1]&&e[2]===ui[2]}async function Zi(e,t){try{return(await Bi(e)).subarray(0,t.length).equals(t)}catch{return!1}}var Xi=r("../../node_modules/.pnpm/ignore@7.0.5/node_modules/ignore/index.js");class Qi{constructor({ttlMs:e,now:t=Date.now}){this.entries=new Map,this.nextSweepAtMs=0,this.ttlMs="function"==typeof e?e:Qi.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 Yi=r("node:string_decoder");const ea=new Map,ta=new Map;let ra;function na(e){return(0,ho.createHash)("sha256").update(e).digest("hex").slice(0,16)}async function oa(e){try{return await(0,go.access)(e),!0}catch{return!1}}async function sa(e){const t=await(0,go.stat)(e),r=ea.get(e);if(void 0!==r&&r.mtimeMs===t.mtimeMs&&r.size===t.size&&(r.ripgrepPath===e||await oa(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=Ni(t);return r.isBinaryFile?ei(t):Ks(Ki(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(ra??=(0,go.mkdtemp)((0,s.join)((0,o.tmpdir)(),"cursorignore-utf8-")).then((e=>(process.once("exit",(()=>{try{(0,yo.rmSync)(e,{recursive:!0,force:!0})}catch{}})),e))),ra),n=(0,s.join)(r,`cursorignore-${na(e)}-${na(t)}.txt`);if(await oa(n))return n;const i=`${n}.${process.pid}.${Date.now()}.tmp`;return await(0,go.writeFile)(i,t,"utf8"),await(0,go.rename)(i,n),n}(e,r)}(e,await(0,go.readFile)(e));return ea.set(e,{mtimeMs:t.mtimeMs,size:t.size,ripgrepPath:i}),i}function ia(e){return Promise.all(e.map((e=>async function(e){const t=ta.get(e);if(void 0!==t)return t;const r=sa(e).catch((()=>e)).finally((()=>{ta.delete(e)}));return ta.set(e,r),r}(e))))}(0,gs.J)((function(){ea.clear(),ta.clear()}));var aa=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 ca(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 la(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 ia(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,Po.spawnInSandbox)((0,Po.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=ca(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 Yi.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{aa(r)}}(),didTimeout:w}}var ua=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 da;function ha(e=process.env){if(void 0!==da)return da;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 pa({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 fa{constructor(e=()=>ha()){this.cache=new Qi({ttlMs:e})}get size(){return this.cache.size}clear(){this.cache.clear()}delete(e){this.cache.delete(pa(e))}walk(e,t){const r=pa(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,ca(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{ua(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=la(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 ma=[{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 ga(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 wa(e,t){const r=ga(t);return r?`${e}${r}`.toLowerCase():""}new Map(ma.map((e=>[e.gitHost,e.apiHost]))),new Map(ma.map((e=>[e.gitHost,e.gitCdnHost]))),new Map(ma.map((e=>[e.gitHost,e.cloneKitS3Host]))),new Map(ma.map((e=>[e.gitHost,e.rawUserContentHost]))),new Map(ma.map((e=>[e.apiHost,e.gitHost]))),new Map(ma.map((e=>[e.apiHost,e.internalHost])));const ya=new Map;function va(e){const t=ya.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 wa(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 wa(n.includes("@")?n.slice(n.lastIndexOf("@")+1):n,o)}}(e);return ya.size>=16384&&ya.clear(),ya.set(e,r),r}function ba(e){return/^origin(-[a-z0-9]+)?\.cursor\.com$/i.test(e)}(function(e){const t=ma.find((t=>t.stage===e));if(void 0===t)throw new Error(`unknown Origin stage: ${e}`);return t})("prod").gitHost;const Sa=new Map;function ka(e){if(void 0===e)return;if(Sa.has(e))return Sa.get(e);const t=function(e){const t=e?function(e){let t=e.trim();if(""!==t){t.startsWith("git@")?t=`https://${t.slice(4).replace(":","/")}`:/^[a-z][a-z0-9+.-]*:\/\//i.test(t)&&!/^https?:\/\//i.test(t)?t=t.replace(/^[a-z][a-z0-9+.-]*:\/\//i,"https://"):/^https?:\/\//i.test(t)||(t=`https://${t}`);try{return new URL(t)}catch{return}}}(e):void 0;if(void 0===t||!ba(t.hostname))return;const r=ga(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 Sa.size>=16384&&Sa.clear(),Sa.set(e,t),t}function _a(e){return void 0!==function(e){const t=ka(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 Ca=new WeakMap;function Ea(e,t,r){const n=performance.now();let o=Ca.get(t);void 0===o&&(o=new Map,Ca.set(t,o));const s=o.get(r);if(void 0!==s&&n-s.startedAt<5e3)return s.root;for(const[e,t]of o)n-t.startedAt>=5e3&&o.delete(e);const i=async function(e,t,r){try{return(await t.exec(e,r,["rev-parse","--show-toplevel"],{caller:"findGitRoot"})).stdout.trim()}catch{return null}}(e,t,r);return o.set(r,{startedAt:n,root:i}),i}async function xa(e,t,r){try{return(await t.exec(e,r,["config","--get","remote.origin.url"],{caller:"getGitRemoteUrl"})).stdout.trim()}catch{return}}function Pa(e){const t=e.trim();if(""===t)return t;try{const e=new URL(t);return""===e.host?Ra(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=Ia.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)??Ra(t)??t}}const Ia=new Set(["ftp","file","http","https","ws","wss"]);function Ra(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 Ta=["**/node_modules/**","**/.git/**","**/.turbo/**","**/.next/**","**/.cache/**","**/.pnpm/**","**/.yarn/**","**/dist/**","**/build/**","**/out/**","**/target/**","**/.vscode/**","**/.idea/**","**/venv/**","**/__pycache__/**","**/logs/**","**/tmp/**","**/temp/**"];function Aa(e,t){return Fs(e,t).map((t=>`/${s.posix.relative(e,t)}`))}var $a=r("../../node_modules/.pnpm/picomatch@4.0.5/node_modules/picomatch/index.js");function Ma(e,t){return e.some((e=>{return"*"===e.url.trim()?(e.patterns??[]).some((e=>Fa(e.pattern,t))):!((r=e.url).includes("://")||r.includes("github.com")||r.includes("gitlab.com")||r.includes("bitbucket.org")||r.includes("@"))&&Fa(e.url,t);var r}))}function Da(e,t,r){return Oa(e.url,t)&&(e.patterns??[]).some((e=>Fa(e.pattern,r)))}function Oa(e,t){return e.includes("*")?"*"===e.trim()||function(e,t){const r=e.trim();return!!Fa(r,t)||!!r.startsWith("*/")&&Fa(`**/${r.slice(2)}`,t)}(Ba(e),Ba(t)):Ba(e)===Ba(t)}function Fa(e,t){const r=e.trim();return!("."!==t&&""!==t||"**"!==r&&"**/*"!==r)||function(e){const t=ja.get(e);if(void 0!==t)return t;let r;try{const t=$a(e,{dot:!0});r=r=>{try{return t(r)}catch{return e===r}}}catch{r=t=>e===t}return Ua(ja,Na,e,r)}(r)(t)}const Na=2048,La=new Map,ja=new Map;function Ua(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 Ba(e){const t=La.get(e);if(void 0!==t)return t;const r=(function(e){const t=ka(e);if(void 0!==t)return`${t.hostname}/git/${t.owner}/${t.name}`.toLowerCase()}(n=e)??va(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 Ua(La,2048,e,r)}function Wa(e){if("object"==typeof e&&null!==e&&"code"in e){const t=e.code;if("string"==typeof t)return t}}function Ha(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,gs.J)((function(){La.clear(),ja.clear()}));const qa=[".gitignore",".cursorignore"];async function za(e){if(!(0,s.isAbsolute)(e))return null;const t=await(0,zo.DN)(e);return null===t?null:t}function Ga(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 Va{constructor(e,t,r,n={}){this.disposeRequested=!1,this.initIgnoreService=()=>Za.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 Ka=Math.min(8,Math.max(1,Math.floor(o.availableParallelism()/2)));class Ja{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=Xi().add(t),this.instances.set(e,r)),r}delete(e){this.instances.delete(e)}clear(){this.instances.clear(),this.lookups=0}}class Za{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 $s.q({max:2e3}),this.cursorIgnoreCache=new $s.q({max:2e3}),this.gitRootCache=new $s.q({max:1e4}),this.gitRemoteUrlCache=new $s.q({max:200}),this.hasGitDirCache=new $s.q({max:1e3}),this.gitParsedIgnoreCache=new Ja(1e4),this.cursorParsedIgnoreCache=new Ja(1e4),this.ignoreMappingsHaveEntries=!1,this.directoryWalkPlacementCache=new $s.q({max:1e4}),this.extraRootCursorIgnoreCache=new $s.q({max:32}),this.extraGitRepoMappingCache=new $s.q({max:32}),this.unwalkedFolders=o.flatMap((e=>Fs(e,s)))}static getRipwalkCache(){return Za.ripwalkCache??=new fa,Za.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=>{const n=await Ea(e,t,r);return null!==n&&Fs(n,i).length>0?r:n}))).filter((e=>null!==e));return u.length>0&&await Promise.all([Za.initializeIgnoreMapping(u,".gitignore",c,i),Za.initializeIgnoreMapping(a,".cursorignore",l,i)]),new Za(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 Za.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,go.access)(n,go.constants.F_OK);const t=await $i(n),o=Za.parseIgnoreRules(t);r[e]=o}catch(o){"ENOENT"===Wa(o)||console.error(`Error reading ${t} file at ${n}:`,o),r[e]=[]}}static async initializeIgnoreMapping(e,t,r,n){try{const o=Za.deduplicateRootDirectories(e),i=await Za.promiseQueue.enqueueList(o,(e=>Za.findFilesWithRipgrep(e,t,n))),a=Array.from(i.values()).flat();await Promise.all(a.map((async e=>{try{const t=await $i(e),n=Za.parseIgnoreRules(t),o=(0,s.dirname)(e);r[o]=n}catch(r){console.error(`Error processing ${t} file at ${e}:`,r)}})));const c=new Set;for(const e of o)await Za.preloadHierarchy(e,t,r,c)}catch(e){console.error(`Error initializing ignore mapping for ${t}:`,e)}}static async findFilesWithRipgrep(e,t,r){const n=(0,b.q6)(),o=[],i={root:e,includeGlobs:qa.map((e=>`**/${e}`)),excludeGlobs:[...Ta,...Aa(e,r)],source:"ignore_scan"},a=Za.getRipwalkCache().walk(n,i);for await(const r of a.lines)(0,s.basename)(r)===t&&o.push((0,s.join)(e,r));return o}async handleManualLookupWhenNoWorkspaceDirs(e,t,r){const n={};let o=(0,s.dirname)(e);const i=(0,s.parse)(o).root;for(;;){let e=r?.get(o);if(void 0===e){try{e=Za.parseIgnoreRules(await $i((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)=>Xi().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 Za.promiseQueue.enqueueList(o,(e=>Za.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,go.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,Ns.$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 go.stat(e).catch((e=>{if(void 0===Wa(e))throw e}));n?.isDirectory()&&r.push(e)}const n=Date.now();for(const e of r){let r=this.extraRootCursorIgnoreCache.get(e);if(void 0===r||r.expiresAt<=n){const t={};await Za.initializeIgnoreMapping([e],".cursorignore",t,this.scanEnvironment),r={mapping:t,expiresAt:n+ha()},this.extraRootCursorIgnoreCache.set(e,r)}for(const[e,n]of Object.entries(r.mapping))t[e]=Ga(t[e],n)}for(const e of[...this.rootDirectories,...r]){const r=await this.getRepoBlockExcludeGlobs(e);0!==r.length&&(t[e]=Ga(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 $s.q({max:1}),this.cursorIgnoreCache=new $s.q({max:1}),this.gitRootCache=new $s.q({max:1}),this.gitRemoteUrlCache=new $s.q({max:1}),this.hasGitDirCache=new $s.q({max:1}),this.directoryWalkPlacementCache=new $s.q({max:1}),this.extraRootCursorIgnoreCache=new $s.q({max:1}),this.extraGitRepoMappingCache=new $s.q({max:1}),this.gitParsedIgnoreCache.clear(),this.cursorParsedIgnoreCache.clear(),this.gitRepoMappingPromise=void 0}async handleCursorIgnoreCreated(e){const t=(0,s.dirname)(e),r=await $i(e),n=Za.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 $i(e),n=Za.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,go.access)((0,s.join)(e,".git"),go.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&&!Ma(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=>Da(e,o,s))))return!0;e.allowed.length>0&&!n&&(n=!0,r=e.allowed.some((e=>Da(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 xa((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=>Oa(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,go.access)((0,s.join)(e,".git"),go.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,go.access)((0,s.join)(i,".git"),go.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,...Aa(e,this.scanEnvironment)],noIgnoreVcs:!0,source:"ignore_scan"},i=Za.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 xa(o,this.gitExecutor,e);t.set(e,r)}catch{t.set(e,void 0)}}))),t}}async function Xa(e,t){let r=e;if(Es()&&(r=As(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]=Ga(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,Po.s9)(r.additionalReadwritePaths,[...n.roots,...n.commonDirs]);return{...r,additionalReadwritePaths:e.length>0?e:void 0,ignoreMapping:o}}return{...r,ignoreMapping:o}}Za.promiseQueue=new Fr.TJ({max:Ka});var Qa=r("../proto/dist/generated/agent/v1/mcp_exec_pb.js");const Ya="agent-tools",ec=51380224;var tc=r("../proto/dist/generated/agent/v1/utils_pb.js");const rc=new Ls.TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}),nc=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]]),oc=new Set([194,195,226,239]),sc=/\p{Lu}/u,ic=new Set([" ","","«","»","‹","›","‘","’","“","”","•","–","—","…","™"]),ac=new Set(["¿","¡"]),cc=new Map([[215,new Set(["¹","²","³","¼","½","¾","°","±","€","¢","£","¤","¥"])],[216,new Set(["¹","²","³","¼","½","¾","°","±","€","¢","£","¤","¥"])],[197,new Set(["¹","²","³"])],[205,ac],[209,ac],[211,ac],[218,ac],[220,ac]]),lc=new Set(["ƒ","Š","Œ","Ž","š","œ","ž","Ÿ"]),uc=/[\p{Cc}\p{Cn}\p{Cs}\p{Co}]/u;function dc(e){if(void 0===e)return;const t=e.charCodeAt(0);return t>=128&&t<=191?t:nc.get(e)}function hc(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=dc(e[t+r]);if(void 0===n)return;o[r]=n}const s=e[t+1];if(oc.has(r)){if(195===r&&ic.has(s)&&t>0&&sc.test(e[t-1]))return}else{if(ic.has(s))return;if(!0===cc.get(r)?.has(s))return;if(3===n&&lc.has(s)&&ic.has(e[t+2]))return}let i;try{i=rc.decode(o)}catch{return}return uc.test(i)?void 0:{index:t,text:e.slice(t,t+n),repaired:i}}function pc(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=hc(e,n);void 0!==o?(r.push(o),n+=o.text.length):n++}return r}const fc=`[\\u00c2-\\u00f0][\\u0080-\\u00bf${[...nc.keys()].join("")}]`,mc=new RegExp(fc),gc=/\p{L}/u;function wc(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||!nc.has(e[t+r])))return 0}return n}function yc(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||!sc.test(e[t.index-1]))return!0;const n=t.index+t.text.length;return n<e.length&&gc.test(e[n])}const vc=["mojibake","replacement_chars"];function bc(e){return e<=1?"1":e<6?"2-5":"6+"}function Sc(e){return e<=0?"0":bc(e)}function kc(e,t,r){if(void 0===e)return"new";if(t>0)return"damaged";const n=Ic(r);return"utf8"!==n&&"utf8_bom"!==n?"other_encoding":"intact"}function _c(e,t){return e<=t?"existing_only":"new_damage"}function Cc(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(pc(t,1).length>0)return!0;t=""}t+=n.repaired,r=n.index+n.text.length}return pc(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 Ec(e){return{detector:e,outcome:"clean",afterCount:0,beforeCount:0}}function xc(e,t,r){const n=pc(r,1e3);if(0===n.length)return Ec("mojibake");const o=void 0===e?[]:pc(e,Math.max(n.length,6));return{detector:"mojibake",outcome:_c(n.length,o.length),file:kc(e,o.length,t),afterCount:n.length,beforeCount:o.length,pattern:Cc(n,o)}}function Pc(e,t,r){const n=ri(r);if(0===n)return Ec("replacement_chars");const o=void 0===e?0:ri(e);return{detector:"replacement_chars",outcome:_c(n,o),file:kc(e,o,t),afterCount:n,beforeCount:o}}function Ic(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 Rc=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 Tc(e){const t=(0,s.extname)(e).slice(1).toLowerCase();return""===t?"none":Rc.get(t)??"other"}const Ac=new Map([[1252,"1252"],[1250,"1250"],[1251,"1251"],[874,"874"],[932,"932"],[936,"936"],[949,"949"],[950,"950"],[65001,"65001"]]);function $c(e){if("string"==typeof e)return e;const t=void 0===e.acp?void 0:Ac.get(e.acp);return void 0===t?"other":e.oemcp===e.acp?t:`${t}_split`}function Mc(e,t){if("clean"===e.outcome)return{detector:e.detector,outcome:"clean",file:"unclassified"};const r={outcome:e.outcome,file:e.file,ext:Tc(t.path),encoding:Ic(t.encoding),code_page:$c(t.pages),run_count:bc(e.afterCount),delta:(n=e.afterCount-e.beforeCount,n<0?"neg":Sc(n)),before_count:Sc(e.beforeCount)};var n;return"mojibake"===e.detector?{detector:"mojibake",pattern:e.pattern,...r}:{detector:"replacement_chars",...r}}class Dc{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+ri(t,6-r))}labels(e,t){const r=$c(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:Sc(o),branch:e[t],stream:t,code_page:r})}return n}}const Oc=/[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/,Fc=Object.getOwnPropertyDescriptor(String.prototype,"isWellFormed")?.value;const Nc=["replacement","lone_surrogate","mojibake_high","mojibake_medium","utf16","c1","clean"],Lc=/\0[^\0]\0/,jc=/[\u0080-\u009f]/,Uc=new RegExp(`[\\u0080-\\u009f]|${fc}`),Bc="\\u0000",Wc=/\\u(?:[dD][89a-fA-F]|0000)/,Hc=/\\u[dD](?:([89abAB])|[c-fC-F])[0-9a-fA-F]{2}/g,qc=/\\u[dD][c-fC-F][0-9a-fA-F]{2}/y;function zc(e,t){let r=0;for(;r<t&&92===e.charCodeAt(t-1-r);)r++;return r%2==0}function Gc(e,t){return 92!==e.charCodeAt(t)?1:117===e.charCodeAt(t+1)?6:2}function Vc(e,t={}){const r=n.Buffer.byteLength(e,"utf8")===e.length;if(!r&&e.includes("�"))return"replacement";const o=!0===t.jsonEscaped&&Wc.test(e);if(!r&&function(e){return"function"!=typeof Fc?function(e){return Oc.test(e)}(e):!0!==Reflect.apply(Fc,e,[])}(e)||o&&function(e){Hc.lastIndex=0;for(let t=Hc.exec(e);null!==t;t=Hc.exec(e))if(zc(e,t.index)){if(void 0===t[1])return!0;if(qc.lastIndex=t.index+6,!qc.test(e))return!0;Hc.lastIndex=t.index+12}return!1}(e))return"lone_surrogate";if(function(e,t){return!(!e.includes("\0")||!Lc.test(e))||t&&function(e){for(let t=e.indexOf(Bc);-1!==t;t=e.indexOf(Bc,t+6)){if(!zc(e,t))continue;const r=t+6;if(!(r>=e.length||e.startsWith(Bc,r))&&e.startsWith(Bc,r+Gc(e,r)))return!0}return!1}(e)}(e,o))return"utf16";if(r)return"clean";if(!Uc.test(e))return"clean";const s=function(e){if(!mc.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?hc(e,o):void 0;if(void 0!==i){if(t++,r=yc(e,i),o+=i.text.length,!n||!r&&t>=256)return"medium";continue}const a=n?wc(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":jc.test(e)?"c1":"clean"}const Kc=/^v?(\d{1,9})\.(\d{1,9})(?:\.\d{1,9})?(?:[-+][0-9A-Za-z.+-]*)?$/,Jc=["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}]})),Zc=Jc[0].major,Xc=Jc[0].minor;function Qc(e){if(null==e)return"unknown";const t=e.trim();if(0===t.length||t.length>128)return"unknown";const r=Kc.exec(t);if(null===r)return"unknown";const n=Number(r[1]),o=Number(r[2]);if(n!==Zc)return"other";const s=Jc.find((e=>e.minor===o));return void 0!==s?s.bucket:o<Xc?"older":"newer"}const Yc=(0,d.h)("local-exec:encoding-slices");function el(e,t){if(void 0===e)return!1;try{const{enabled:r}=e;return"function"==typeof r?r(t):r}catch{return!1}}function tl(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 rl(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 nl{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=rl(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 ol=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"})),sl=(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"]}),il=Nc[0],al=new Map(Nc.map(((e,t)=>[e,t])));function cl(e){return al.get(e)??Nc.length}class ll{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===il}noteText(e){if(0===e.length)return;const t=e.length>this.remaining?jo(e,this.remaining):e;this.remaining-=Math.max(t.length,1);const r=Vc(t);cl(r)<cl(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 dl(e,t,r,n){const o={layer:r.layer,kind:n,origin:tl(n,r.evidence??"unseen",!0===r.partial),source:r.source??r.layer,version_bucket:Qc(e.clientVersion)};void 0!==r.codePageLookup&&(o.code_page_lookup=r.codePageLookup),void 0!==r.shellKind&&(o.shell_kind=r.shellKind),sl.increment(t,1,o)}function hl(e,t){Yc.warn(e,"encoding slice was not counted (result unaffected)",{error:t instanceof Error?t.name:"unknown"})}function pl(e,t,r,n){if(void 0!==e&&el(e,t))try{const o=new ll;o.note(n),dl(e,t,r,o.kind())}catch(e){hl(t,e)}}function fl(e,t,r,n){if(void 0!==e&&el(e,t))try{dl(e,t,r,n)}catch(e){hl(t,e)}}class ml{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(el(t,o))try{n(a)&&pl(t,o,{layer:r},a)}catch(e){hl(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 wl{constructor(){this.text={stdout:new ll,stderr:new ll},this.bytes={stdout:new nl,stderr:new nl},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":ol.get(e)??"unknown"}(e)}record(e,t,r,n){for(const o of["stdout","stderr"])this.produced[o]&&fl(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 yl=r("node:child_process"),vl=r("../utils/dist/workload-spawn.js");const bl=(0,d.h)("local-exec:shell-output-encoding"),Sl=(0,Ls.promisify)(yl.execFile),kl=/^\s*OEMCP\s+REG_\w+\s+(\d+)\s*$/m,_l=/^\s*ACP\s+REG_\w+\s+(\d+)\s*$/m;function Cl(e,t){const r=t.exec(e);return null===r?void 0:Number(r[1])}const El="㐀-䶿一-鿿豈-",xl=" -〿㈀-㏿︰--",Pl="‐-※←-⇿─-◿★☆",Il="-ヿ",Rl=new Map([["cp932",{script:new RegExp(`[${El}${xl}${Pl}${Il}]`),doubleByte:!0}],["cp936",{script:new RegExp(`[${El}${xl}${Pl}${Il}-ㄯ]`),doubleByte:!0}],["cp949",{script:new RegExp(`[${El}${xl}${Pl}${Il}-가-]`),doubleByte:!0}],["cp950",{script:new RegExp(`[${El}${xl}${Pl}-ㄯ]`),doubleByte:!0}],["cp874",{script:new RegExp("[-]"),doubleByte:!1}]]);const Tl=function(e){let t,r,n,o,s=!1,i=0;const a=()=>{i+=1;const e=i;n=async function(){const{stdout:e}=await(0,vl.D9)(Sl,"\\\\.\\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=Cl(t,kl),o=Cl(t,_l);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 Us.encodingExists(t)?t:void 0}(t);return void 0!==n&&Rl.has(n)?n:void 0}(i),r=i,s=!0,n=void 0,o=void 0===i.oemcp&&void 0===i.acp?"unparsed":"answered",bl.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),bl.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),Al=Buffer.alloc(0),$l=/[\u0080-\uffff]/;function Ml(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 Dl(){const e=new Yi.StringDecoder("utf8");return{write:t=>e.write(t),end:()=>e.end()}}function Ol(e,t){return Us.decode(t,e,{stripBOM:!1})}const Fl=/[\xe0-\xef][\x80-\xbf]\?/;const Nl=10,Ll=Buffer.alloc(0),jl=new Set([7,8,9,10,11,12,13,27]);function Ul(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&&!jl.has(r))return!1}return!0}function Bl(e,t,r=0,n){if("utf8"===t){const t=e.indexOf(Nl);return-1===t?-1:t+1}const[o,s]="utf16le"===t?[Nl,0]:[0,Nl];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 Wl(e){const t=new Yi.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 Hl={encoding:"utf8",skip:0};function ql(e){const t=e();let r="utf8";const n={};let o=!1;const s=()=>"utf8"===r?t:n[r]??=Wl(r),i=e=>("utf8"!==r&&e.length>0&&(o=!0),e);let a,c=!0,l=Ll,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?Hl:void 0;const r=0===e[0]?"utf16be":0===e[1]?"utf16le":void 0;if(void 0===r)return Hl;const n=Bl(e,r);if(-1!==n)return Ul(e,r,n)?{encoding:r,skip:0}:Hl;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)&&Ul(e,r,o)?{encoding:r,skip:0}:Hl}const o={encoding:r,skip:0},s=e.indexOf(0),i=e.indexOf(Nl);if(-1!==s&&(-1===i||s<i)){const n=s-s%2+2;return n>e.length?t?o:void 0:Ul(e,r,n)?o:Hl}if(-1===i)return t?Hl:void 0;if("utf16le"===r&&i%2==0){if(i+1>=e.length)return t?Hl:void 0;if(0===e[i+1])return o}return Hl},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]===Nl,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=Ll}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(Nl),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]===Nl&&(l=Buffer.of(Nl),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=Bl(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):Wl(t.encoding).write(n)},end(){const e=m(Ll,!0)+i(s().end());return c=!0,l=Ll,u=!1,d=0,a=void 0,e},branch:()=>!0===t.usedCodePage?.()?"code_page":o?"utf16":"utf8"}}var zl=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},Gl=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 Vl=(0,d.h)("local-exec:shell-core"),Kl=(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"]}),Jl="win32"===process.platform,Zl=["CURSOR_CONVERSATION_ID","CURSOR_REQUEST_ID","CURSOR_AGENT_STORE_FILES_DIR","CURSOR_AGENT_STORE_SHARED_PATHS"];function Xl(e){return`'${e.replace(/'/g,"'\\''")}'`}const Ql=["eval-cursorbench","cursorbench","sand-eval","eval-harness"];function Yl(e){return Ql.some((t=>e.includes(t)))?(0,ho.createHash)("sha256").update(e).digest("hex"):e}function eu(e,t){return e[t]??process.env[t]}const tu=/^[A-Za-z_][A-Za-z0-9_]*$/,ru=/CURSOR_SANDBOX/i;function nu(e){return tu.test(e)&&!ru.test(e)}function ou(e){return"function"==typeof e?e():e}function su(e,t){const r=void 0===e?[]:[...e];return r.includes(t)||r.push(t),r}function iu(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 au extends Error{constructor(e){super(`working directory does not exist: ${e}; the command did not run`),this.name="WorkingDirectoryMissingError"}}class cu{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{zl(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,Ns.$f)(c)&&(0,Ns.A)(c)||await async function(e){try{return(await(0,go.stat)(e)).isDirectory()}catch(e){const t=Wa(e);if("ENOENT"===t||"ENOTDIR"===t)return!1;throw e}}(c))){if(c!==(0,zo.o1)(await i.getCwd(),this.workspacePath))throw new au(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,po.sh)(t.conversationId)),t.requestId&&(w.CURSOR_REQUEST_ID=t.requestId),this.projectDir&&(w.AGENT_TRANSCRIPTS=s.join(this.projectDir,po.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&&nu(e)&&(w[e]=t);const b=w.CURSOR_REQUEST_ID;void 0!==b&&(w.CURSOR_REQUEST_ID=Yl(b)),function(e,t){const r=Zl,n=Object.keys(t).filter((e=>nu(e)&&!r.includes(e))),o=`builtin unset ${[...Zl,...n].join(" ")} 2>/dev/null || true`,s=[];for(const t of Zl){const r=eu(e,t);void 0!==r&&s.push(`builtin export ${t}=${Xl(r)}`)}for(const e of n){const r=t[e];void 0!==r&&s.push(`builtin export ${e}=${Xl(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=Yl(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=eu(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[]}}(eu(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=su(i.additionalReadonlyPaths,a):i.additionalReadwritePaths=su(i.additionalReadwritePaths,a));for(const e of n)e.readOnly||"workspace_readwrite"!==i.type?i.additionalReadonlyPaths=su(i.additionalReadonlyPaths,e.path):i.additionalReadwritePaths=su(i.additionalReadwritePaths,e.path);return{...e,perUser:i}}(t.sandboxPolicy,w),k=(0,Po.CG)(S??Po.BM);let _,C,E,x;S&&(yield{type:"start",sandboxed:"workspace_readonly"===k||"workspace_readwrite"===k}),t.askpassConfig&&!Jl&&(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??Tl,I=(this.options.outputFallbackEncoding??(()=>P.current()))(),R=()=>function(e){if(void 0===e)return Dl();const t=Rl.get(e);return void 0!==t&&Us.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=$l.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&&Fl.test(a.toString("latin1")),o=t.test(i[i.length-1])}},isUtf8Text:()=>s,reset(){n=!1,o=!1,s=!1}}}(t);let s=Al,i=0,a="utf8",c=!1;const l=()=>{a="utf8",o.reset(),i=0},u=(t,n)=>{const s=n?Ml(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=Ol(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=Ol(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=$l.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=Al,"utf8"===a){const e=t.subarray(0,t.length-Ml(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?Ml(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=Al;const t=0===e.length?"":"utf8"===a?e.toString("utf8"):u(e,!1).text;return l(),t},usedCodePage:()=>c}}(e,t):Dl()}(I),T={stdout:ql(R),stderr:ql(R)},A=new Dc,$=el(this.options.encodingSlices,e)?new wl: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()))Kl.increment(e,1,r);$?.record(this.options.encodingSlices,e,t,P.lastOutcome())}catch(t){Vl.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+_<=Ko,f=void 0!==l&&!0!==l.truncated&&l.size+_<=ec;"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+_>ec)l.truncated=!0;else if(f&&void 0!==l)if(l.size+=_,l.lineCount+=iu(r.data),l.file)l.file.write(C);else if(l.buffer+=C,l.size>l.threshold){const e=s.join(this.projectDir,Ya);l.path=s.join(e,`${(0,ho.randomUUID)()}.txt`);try{await(0,go.mkdir)(e,{recursive:!0}),l.file=(0,yo.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:Po.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+=Ws(e)-1}const e=await new Promise((e=>l.file.end(e)));u??=e??void 0,u?await(0,go.rm)(l.path,{force:!0}):t=new tc.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"===Wa(t)&&(0,Ns.$f)(c))try{Vl.warn(e,"shell failed with ENOENT in an agent store working directory",{...await(0,Ns.KZ)(c)})}catch{}throw t}finally{O()}}catch(e){r.error=e,r.hasError=!0}finally{Gl(r)}}async getCwd(e){return this.executorFor(e).getCwd()}getWorkspacePath(){if(!this.workspacePath)throw new Error("Workspace path is not configured");return this.workspacePath}}class lu{constructor(e,t){this.innerExecutor=e,this.shellManager=t}async*execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{zl(r,(0,D.VI)(e.withName("ManagedShellCoreExecutor.execute")),!1),Vl.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{Gl(r)}}async getCwd(e){return this.innerExecutor.getCwd(e)}getWorkspacePath(){return this.innerExecutor.getWorkspacePath()}}class uu{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 du(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(fs(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 fs(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 pu(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 fu=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 mu=(0,d.h)("local-exec:background-shell");function gu(e,t,r){return new xo.Lt({result:pu(e,t,r)})}class wu{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 yu(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 vu(e){e().catch((()=>{}))}class bu{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=qo.L3.compile(e.config.pattern,qo.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=No(e,n+t);o<=n&&(o=Lo(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=Uo(r,1024)}finish(){this.finished||(this.finished=!0,this.flushPendingBatch("finish"),this.clearFlushTimer(),0===this.matchedOccurrences&&this.recordWatchOutcome("silent",{silent_ms:_u(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:_u(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=bo(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:`${jo(i,500)}...`),detail:o,outputPath:this.args.outputPath,reason:"task_progress"}})}emitLimitReachedNotification(){this.emittedNotifications+=1;const e=this.args.config.pattern,t=bo(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&&mu.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 Su{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 bu({shellId:t,outputPath:i,config:o,conversationId:r??vo,toolCallId:n,registry:this.backgroundWorkRegistry,ctx:e})}catch(r){return void(void 0!==e&&mu.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 ku{async spawn(e,t){const r=new AbortController,n=new wu(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 Po.SandboxUnsupportedError||e instanceof au)throw e}return vu((()=>yu(n,o))),n}async adopt(e){const t=new wu(e.shellId,e.abortController);return t.stdin=e.stdin,t.pid=e.pid,vu((()=>yu(t,e.eventIterator))),t}}function _u(e){return Math.round(performance.now()-e)}function Cu(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`}function Eu(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: ${Cu(e.cwd)}\n`,n+=`command: ${Cu(e.command)}\n`,void 0!==e.title&&e.title.trim().length>0&&(n+=`title: ${Cu(e.title)}\n`),n+=`status: ${r}\n`,n+=`started_at: ${e.startedAt}\n`,n+=`running_for_ms: ${t}\n`,n+="---\n",n}function xu(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 Pu{constructor(e,t){this.innerFactory=e,this.projectDir=t}async spawn(e,t){const r=s.join(this.projectDir,"terminals");await(0,go.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=_u(g),r=Eu({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=_u(g),n=Eu({pid:e,cwd:t.workingDirectory,command:t.command,title:t.description,status:y,startedAt:m,runningForMs:r});await(0,go.writeFile)(_,n,"utf8"),l=setInterval((()=>{E()}),5e3)},I=async()=>{a||(a=await yo.promises.open(_,"r+")),c||(c=await yo.promises.open(_,"a"))},R=async(e,t)=>{if(!v){if(v=!0,x(),p||await P(),await I(),void 0!==t){const e=_u(g),r=`\n---\n${t}\n`+(i.showElapsedTime?`elapsed_ms: ${e}\n`:"")+`ended_at: ${(new Date).toISOString()}\n---\n`;await S(r)}y=e,await E()}};try{for await(const r of o(e,i)){if("stdout"===r.type)p||(await P(),await I()),await S(r.data);else if("stderr"===r.type)p||(await P(),await I()),await S(r.data);else if("stdout_trimmed"!==r.type||d)if("stderr_trimmed"!==r.type||h)if("stdin_ready"!==r.type||u)"exit"===r.type&&await R(r.aborted?"aborted":0===r.code?"succeeded":"failed",`exit_code: ${r.code??"unknown"}`);else{u=!0,p||(await P(r.pid),await I());const e=r.stdin;if(e&&!0!==t.suppressStdinLogging){const t=e=>{if(null==e)return;const t="string"==typeof e?e:n.Buffer.isBuffer(e)||e instanceof Uint8Array?n.Buffer.from(e).toString():"";if(!t)return;const r=t.endsWith("\n")?t:`${t}\n`;S(`[stdin] ${r}`)},r=e.write.bind(e);if(e.write=(e,n,o)=>(t(e),r(e,n,o)),"function"==typeof e.end){const r=e.end.bind(e);e.end=(e,n,o)=>(void 0!==e&&t(e),r(e,n,o))}}}else h=!0,p||await P(),await I(),await S(xu("stderr"));else d=!0,p||await P(),await I(),await S(xu("stdout"));yield r}if(!v){const e=i.signal?.aborted??!1;await R(e?"aborted":"failed")}}catch(e){const t=i.signal?.aborted??!1,r=Cu(e instanceof Error?e.message:"Unknown error");if(await R(t?"aborted":"failed",t?void 0:`error: ${r}`),!t)throw e}finally{if(x(),await b,a)try{await a.close()}catch{}if(c)try{await c.close()}catch{}}}}}async adopt(e){const t=s.join(this.projectDir,"terminals");await(0,go.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=_u(i),l=Eu({pid:e.pid,cwd:e.workingDirectory,command:e.command,title:e.description,status:a,startedAt:o,runningForMs:c})+(e.initialOutput??"");await(0,go.writeFile)(r,l,"utf8");const u=await yo.promises.open(r,"r+");let d;try{d=await yo.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=_u(i),r=Eu({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=_u(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(xu("stderr"))):(f=!0,await k(xu("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 Iu{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:So(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??vo,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:_u(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 Ru{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 Tu{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 Ru(s,i):s,l=o??function(e){const t=new ku;return new Pu(t,e)}(n),u=new Su(l,n,c);this.backgroundShellManager=new Iu(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?ts(t.sandboxPolicy):void 0,s=t.workingDirectory||await this.coreExecutor.getCwd(t.conversationId),i=(0,zo.o1)(s),a=new fe.HO(Do(n).structured),c=ms({command:n,parsingResult:a,blockedCommands:t.adminCommandDenylist});if(void 0!==c)return new xo.Lt({result:{case:"rejected",value:new fe.pZ({command:n,workingDirectory:i,reason:c})}});let l;if(mu.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}),Eo(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 mu.info(e,"Background shell: invariant blocked command",{toolCallId:t.toolCallId,blockReasonType:r.reason.type,skipApproval:t.skipApproval}),gu(n,i,r.reason);l=r.policy??o,mu.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:_o(t)},o);if("block"===r.kind)return mu.info(e,"Background shell: approval gate blocked command",{toolCallId:t.toolCallId,blockReasonType:r.reason.type,hasSmartModeApproval:void 0!==t.smartModeApproval,skipApproval:t.skipApproval}),gu(n,i,r.reason);l=r.policy,mu.info(e,"Background shell: approval gate allowed command",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,effectivePolicyType:l.type})}l=await Xa(l,{command:n,workingDirectory:i,parsingResult:a,permissionsService:this.permissionsService,ignoreService:this.ignoreService});try{const r=this.backgroundShellManager.generateShellId(),o=l?{perRepo:l}:void 0,s={ctx:e,command:n,workingDirectory:i,toolCallId:t.toolCallId,conversationId:t.conversationId,requestId:t.requestId,secretScopeId:t.secretScopeId,sandboxPolicy:o,shellId:r,enableWriteShellStdinTool:t.enableWriteShellStdinTool,suppressStdinLogging:t.suppressStdinLogging,description:t.description,outputNotification:t.outputNotification},a=await this.backgroundShellManager.spawn(s,this.coreExecutor);return new xo.Lt({result:{case:"success",value:new xo.Po({shellId:r,command:n,workingDirectory:i,pid:a.pid})}})}catch(r){if(r instanceof Po.SandboxUnsupportedError){const o=l?.type??"unknown";return mu.debug(e,"Background shell: sandbox policy unsupported on this host",{toolCallId:t.toolCallId,policyType:o,reason:r.reason}),new xo.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 xo.Lt({result:{case:"error",value:new xo.Of({command:n,workingDirectory:i,error:r instanceof Error?r.message:"Unknown error"})}})}}catch(e){r.error=e,r.hasError=!0}finally{fu(r)}}writeStdin(e,t){return this.backgroundShellManager.writeStdin(e,t)}}var Au=r("node:async_hooks");r("../../node_modules/.pnpm/minimatch@10.2.5/node_modules/minimatch/dist/esm/index.js");function $u(e){return e instanceof Error?e.message:String(e)}function Mu(e){return"Failed to read skill file: "+$u(e)}function Du(e){return"Invalid skill frontmatter: "+$u(e)}function Ou(e,t){return e||t?void 0:"Description is required"}new Set(["EACCES","EPERM","ENOENT","ENOTDIR","EISDIR","ELOOP","ENAMETOOLONG"]);const Fu=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function Nu(e){return e.toLocaleString("en-US")}var Lu=r("node:url");const ju={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"},Uu=e=>"string"==typeof e,Bu=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),Wu=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),Hu=(e,t=[])=>({isValid:e,errors:t});function qu(e,t,r){void 0===e||Uu(e)||r.push(`${t} must be a string if provided`)}const zu=e=>{const t=[];if(!Bu(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)"),Hu(!1,t);const r=e.type;return"prompt"===r?((e,t)=>{Uu(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&&(Uu(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)=>{Uu(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(Uu(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),Hu(0===t.length,t)},Gu=(e,t)=>{const r=[];if(!Array.isArray(e))return r.push(`${t} must be an array of hook scripts`),Hu(!1,r);for(let n=0;n<e.length;n++){const o=zu(e[n]);o.isValid||r.push(`${t}[${n}]: ${o.errors.join(", ")}`)}return Hu(0===r.length,r)},Vu=e=>{const t=[];if(!Bu(e))return t.push("Hooks config must be an object"),Hu(!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"),!Bu(e.hooks))return t.push("Config hooks must be an object"),Hu(!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(ju),n=e.hooks;for(const[e,o]of Object.entries(n))if(r.includes(e)){if(void 0!==o){const r=Gu(o,e);r.isValid||t.push(...r.errors)}}else t.push(`Unknown hook type: ${e}. Valid types are: ${r.join(", ")}`);return Hu(0===t.length,t)},Ku={PreToolUse:ju.preToolUse,PermissionRequest:null,PostToolUse:ju.postToolUse,UserPromptSubmit:ju.beforeSubmitPrompt,Stop:ju.stop,SubagentStop:ju.subagentStop,SessionStart:ju.sessionStart,SessionEnd:ju.sessionEnd,PreCompact:ju.preCompact,Notification:null},Ju=Object.fromEntries(Object.entries(Ku).filter((e=>Zu(e[0])&&null!==e[1])).map((([e,t])=>[t,e])));function Zu(e){return Object.prototype.hasOwnProperty.call(Ku,e)}const Xu={Bash:"Shell",Read:"Read",Write:"Write",Edit:"Write",Glob:null,Grep:"Grep",WebFetch:"WebFetch",WebSearch:"WebSearch",Task:"Task"},Qu=["Glob"],Yu=["Notification","PermissionRequest"],ed=/^[A-Za-z0-9_./:=+-]+$/,td=/^=|^-.*\./,rd=/\$\{(?:CLAUDE_PROJECT_DIR|CURSOR_PROJECT_DIR|CLAUDE_PLUGIN_ROOT|CURSOR_PLUGIN_ROOT)\}/g,nd=/^[^\p{Cc}$`"]*$/u,od=/\\(?:[$`"\\]|$)/;function sd(e){return`'${e.replace(/'/g,"'\\''")}'`}function id(e){if(ed.test(e)&&!td.test(e))return e;const t=e.replace(rd,"");if((t!==e||e.includes("'"))&&nd.test(t)&&!od.test(e))return`"${e}"`;const r=[];let n=0;for(const t of e.matchAll(rd))t.index>n&&r.push(sd(e.slice(n,t.index))),r.push(`"${t[0]}"`),n=t.index+t[0].length;return(n<e.length||0===r.length)&&r.push(sd(e.slice(n))),r.join("")}const ad={warn:()=>{},info:()=>{}};function cd(e,t,r=ad){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(id).join(" ")}(r,n):(t.warn(`Hook "${r}" has invalid "args" (expected an array of strings), skipping`),null));var o}(e,r);return null===o?null:{type:"command",command:o,...n}}function ld(e,t,r=ad){const n=[];let o;if("PreToolUse"===t||"PostToolUse"===t){const t=function(e,t=ad){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=Xu[t];null!==r?void 0!==r?n.includes(r)||n.push(r):n.push(t):Qu.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=cd(t,o,r);e&&n.push(e)}return n}function ud(e,t=ad){const r={};for(const[n,o]of Object.entries(e)){if(!Zu(n)){t.warn(`Unknown Claude Code event "${n}", skipping`);continue}if(Yu.includes(n)){t.warn(`Claude Code event "${n}" is not supported in Cursor and will be ignored`);continue}const e=Ku[n];if(!e){t.warn(`Unknown Claude Code event "${n}", skipping`);continue}const s=[];if(Array.isArray(o))for(const e of o){const r=ld(e,n,t);s.push(...r)}else void 0!==o&&t.warn(`Claude Code event "${n}" has invalid value (expected array), skipping`);if(s.length>0){const t=r[e]||[];r[e]=[...t,...s]}}return{version:1,hooks:r}}var dd=r("../../node_modules/.pnpm/gray-matter@4.0.3/node_modules/gray-matter/index.js");const hd=()=>({});function pd(e,t){return dd(e,{...t,engines:{...t?.engines,js:hd,javascript:hd}})}function fd(e,t,r){return dd.stringify({content:e,data:{}},t,r)}function md(e){return e.replace(/\\/g,"/").replace(/\/+$/,"")||"/"}function gd(e,t){if(Object.hasOwn(e,t))return e[t]}function wd(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?md(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===gd(i,e))continue;let r;void 0!==a&&(r=t.find((t=>!("project"!==t.scope&&"local"!==t.scope||!t.projectPath)&&(md(t.projectPath)===a&&!0===gd(i,e))))),r||!0!==gd(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 yd=r("../../node_modules/.pnpm/js-yaml@4.3.1/node_modules/js-yaml/dist/js-yaml.mjs");const vd=Be.enum(["canvas"]),bd=Be.array(vd).transform((e=>[...new Set(e)].sort())),Sd=new Set(["https://agent-plugins.org/schemas/1.0.0/plugin.schema.json","https://agent-plugins.org/schemas/1.0.0/mcp.schema.json"]),kd=/^v?(\d+\.\d+(?:\.\d+)?)$/;function _d(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 Cd(e){let t;try{t=new URL(e).pathname.split("/")}catch{t=e.split("/")}for(const e of t){const t=kd.exec(e);if(null!==t)return t[1]}}function Ed(e){return void 0===e?{kind:"absent"}:Sd.has(e)?{kind:"supported",id:e,version:Cd(e)??e}:{kind:"unsupported",id:e}}const xd=10485760,Pd=/^[a-z0-9]([a-z0-9.-]*[a-z0-9])?$/,Id=[".cursor-plugin/plugin.json",".claude-plugin/plugin.json","plugin.json"],Rd=[".cursor-plugin",".claude-plugin"],Td=[".cursor-plugin/marketplace.json",".claude-plugin/marketplace.json"],Ad=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()}),$d=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()}),Md=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()}),Dd=Be.union([Be.string(),Ad,$d,Md]),Od=/^(\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?|never)$/,Fd='Must be a semver version (X.Y.Z) or "never"',Nd=Be.object({cursor:Be.string().regex(Od,Fd).optional(),sand:Be.string().regex(Od,Fd).optional(),sandMobile:Be.string().regex(Od,Fd).optional()}),Ld=Be.object({name:Be.string().min(1,"Author name is required"),email:Be.string().email().optional()}),jd=Be.enum(["string","number","integer","boolean","object","array","null"]),Ud=Be.union([jd,Be.array(jd).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 Bd(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 Wd=Be.lazy((()=>Be.object({type:Ud.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(),Wd).optional(),required:Be.array(Be.string()).optional(),additionalProperties:Be.union([Be.boolean(),Wd]).optional(),items:Be.union([Wd,Be.array(Wd)]).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(Bd)));function Hd(e){const t=Wd.superRefine(((e,t)=>{Gd(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?Vd(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 qd=Be.unknown().superRefine(((e,t)=>{const r=Hd(e);if(!r.success)for(const e of r.error.issues)t.addIssue({code:"custom",message:e.message,path:e.path})})).transform((e=>{if(!Vd(e))throw new Error('Plugin variable schema must declare type "object"');return e})),zd=(Be.object({name:Be.string().min(1).transform((e=>e.toLowerCase())).refine((e=>Pd.test(e)),"Name must be kebab-case (lowercase alphanumeric with hyphens and periods)"),displayName:Be.string().optional(),source:Dd,description:Be.string().optional(),version:Be.string().optional(),author:Ld.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:bd.optional(),logo:Be.string().optional(),category:Be.string().optional(),tags:Be.array(Be.string()).optional(),minClientVersions:Nd.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:qd.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(Pd,"Name must be kebab-case (lowercase alphanumeric with hyphens and periods)"),displayName:Be.string().optional(),description:Be.string().optional(),version:Be.string().optional(),author:Ld.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:bd.optional(),minClientVersions:Nd.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:qd.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 Gd(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Vd(e){return Gd(e)&&"object"===e.type}function Kd(e){return e.trim().toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")}function Jd(e,t){if(Gd(e)&&"string"==typeof e.name){const t=Kd(e.name);if(t.length>0)return t}return function(e){const t=void 0!==e.repoName?Kd(e.repoName):"";return t.length>0?t:`cursor-marketplace-${e.fallbackId??(0,ho.randomUUID)()}`}(t)}function Zd(e){if(Gd(e)&&Gd(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 Xd(e){return"string"==typeof e?e:void 0}function Qd(e){if(!Array.isArray(e))return;const t=e.filter((e=>"string"==typeof e));return t.length>0?t:void 0}function Yd(e){return"string"==typeof e?e:Qd(e)}function eh(e){if(!Gd(e)||!Gd(e.metadata))return;const t={description:Xd(e.metadata.description),version:Xd(e.metadata.version),pluginRoot:Xd(e.metadata.pluginRoot)};return void 0!==t.description||void 0!==t.version||void 0!==t.pluginRoot?t:void 0}function th(e){if(!Gd(e))return;const t=Xd(e.name);if(void 0===t||0===t.length)return;const r=Xd(e.email);return{name:t,...void 0!==r?{email:r}:{}}}function rh(e){if("string"==typeof e||Gd(e))return e;if(Array.isArray(e)){const t=e.filter((e=>"string"==typeof e||Gd(e)));return t.length>0?t:void 0}}function nh(e){if("string"==typeof e||Gd(e))return e}function oh(e){if(void 0===e)return;const t=Hd(e);return t.success?t.data:void 0}function sh(e,t={}){if(e.length>xd)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(!Gd(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(!Gd(e))return{skippedEntry:{index:t,error:`Plugin entry at index ${t} is not an object`}};const r="string"==typeof(n=e.source)?n:Gd(n)?"github"===n.source&&"string"==typeof n.repo&&n.repo.length>0?{source:"github",repo:n.repo,ref:Xd(n.ref),sha:Xd(n.sha)}:("url"===n.source||void 0===n.source)&&"string"==typeof n.url&&n.url.length>0?{source:"url",url:n.url,ref:Xd(n.ref),sha:Xd(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:Xd(n.ref),sha:Xd(n.sha)}:"string"==typeof n.repo&&n.repo.length>0?{source:"github",repo:n.repo,ref:Xd(n.ref),sha:Xd(n.sha)}:void 0:void 0;var n;if(void 0===r){const r=Xd(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?Kd(e.name):"")||function(e){if("string"==typeof e){const t=Kd((0,s.basename)(e));return t.length>0?t:void 0}if("github"===e.source){const t=Kd(e.repo.split("/").at(-1)??"");return t.length>0?t:void 0}if("git-subdir"===e.source){const t=Kd((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=Kd((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=bd.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=Nd.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:Xd(e.displayName),source:r,description:Xd(e.description),version:Xd(e.version),author:th(e.author),publisher:Xd(e.publisher),homepage:Xd(e.homepage),repository:Xd(e.repository),license:Xd(e.license),keywords:Qd(e.keywords),logo:Xd(e.logo),category:Xd(e.category),tags:Qd(e.tags),strict:"boolean"!=typeof e.strict||e.strict,commands:Yd(e.commands),agents:Yd(e.agents),skills:Yd(e.skills),rules:Yd(e.rules),hooks:nh(e.hooks),variables:oh(e.variables),mcpServers:rh(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:Jd(r,t),owner:Zd(r),description:Xd(r.description),plugins:n,metadata:eh(r),skippedPluginEntries:o}}}function ih(e){if(e.length>xd)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=Ed(_d(t)),n=zd.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 ah(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 ch(e){return!e.includes("..")&&!(0,s.isAbsolute)(e)&&!e.includes("://")}var lh=r("../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/main.js");const uh=/\$\{(?:env:([A-Za-z_][A-Za-z0-9_]*)|([^:}]+)(?::-([^}]*))?)\}/g,dh=/\$%7B([^%/?#]+?)%7D/gi;function hh(e,t){return ph(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 ph(e,t){if("string"==typeof e)return function(e,t){return e.replace(dh,"${$1}").replace(uh,((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=>ph(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]=ph(o,t);return r}return e}function fh(e,t){return e.replace(/\$\{CLAUDE_PLUGIN_ROOT\}/g,(()=>t)).replace(/\$\{CURSOR_PLUGIN_ROOT\}/g,(()=>t))}const mh={log:()=>{},increment:()=>{},distribution:()=>{},captureException:()=>{}},gh=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()}),wh=Be.object({mcpServers:Be.record(Be.string(),gh).optional()}),yh=[".mcp.json","mcp.json"],vh=new Set(["author","owner","source","metadata"].map((e=>e.toLowerCase())));function bh(e,t){if(!function(e){return vh.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 Sh(e){return"object"==typeof e&&null!==e&&("command"in e||"url"in e)}function kh(e){const t=void 0!==e&&e.length>0?e.replace(/\/+$/,""):void 0;return yh.map((e=>void 0!==t?`${t}/${e}`:e))}function _h(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=fh(o.command,t)),Array.isArray(o.args)&&(e.args=o.args.map((e=>"string"==typeof e?fh(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?fh(n,t):n;e.env=r}"string"==typeof o.cwd&&(e.cwd=fh(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 Ch(e,t,r){try{const n=(0,lh.qg)(e),o=_d(n);if(void 0!==o){const e=r?.log??mh;"unsupported"===Ed(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=Cd(e),n=Cd(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=wh.safeParse(n),i=!0===r?.skipExpansion;if(s.success&&s.data.mcpServers&&Object.keys(s.data.mcpServers).length>0)return i?s.data:_h(s.data,t,r);const a={};for(const[e,t]of Object.entries(n))"mcpServers"!==e&&!bh(e,t)&&Sh(t)&&(a[e]=t);if(Object.keys(a).length>0){const e=wh.safeParse({mcpServers:a});if(e.success)return i?e.data:_h(e.data,t,r)}return null}catch{return null}}function Eh(e,t,r){for(const[n,o]of Object.entries(t))e.mcpServers[n]=o,e.mcpServerSourcePaths[n]=r}async function xh(e,t,r,n={}){const o=n.toSourcePath??(e=>e),s=n.installPathForExpansion??"",i=n.fallbackFileNames??yh,a=n.manifestPrecedence??"override",c={},l={};for(const t of i){const r=await e(t);if(null===r)continue;const i=Ch(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(!ch(i))return;const a=await t(i);if(null===a)return;const c=Ch(a,o,r.parserOptions);c?.mcpServers&&Object.keys(c.mcpServers).length>0&&Eh(s,c.mcpServers,n(i))},a=e=>{const t=Ch(JSON.stringify(e),o,r.parserOptions);t?.mcpServers&&Object.keys(t.mcpServers).length>0&&Eh(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 Ph=new Set(["CREDENTIAL","CREDENTIALS","KEY","PASSPHRASE","PASSWORD","SECRET","TOKEN"]);function Ih(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=>Ph.has(e)))}const Rh=/\$\{(?:env:([A-Z][A-Z0-9_]*)|([A-Z][A-Z0-9_]*)(?::-([^}]*))?)\}/g,Th=new Set(["CURSOR_PLUGIN_ROOT","CLAUDE_PLUGIN_ROOT"]),Ah=new Set(["api","aws","db","dd","gcp","http","https","id","mcp","ssl","tls","uri","url"]);function $h(e){return e.split("_").filter((e=>e.length>0)).map((e=>{const t=e.toLowerCase();return Ah.has(t)?e.toUpperCase():e.charAt(0).toUpperCase()+t.slice(1)})).join(" ")}function Mh(e,t){if("string"!=typeof e){if(Array.isArray(e))for(const r of e)Mh(r,t);else if(null!==e&&"object"==typeof e)for(const r of Object.values(e))Mh(r,t)}else for(const[,r,n,o]of e.matchAll(Rh)){const e=r??n;if(void 0===e||Th.has(e)||t.has(e))continue;const s=void 0===r?`\${${e}}`:`\${env:${e}}`;t.set(e,{reference:s,defaultValue:o})}}function Dh(e){if(void 0===e?.mcpServers)return;const t=new Map;if(Mh(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:$h(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.`,...Ih(e)?{writeOnly:!0}:{}}}return{type:"object",properties:r}}const Oh=[".md",".mdc",".markdown"],Fh=[...Oh,".txt"],Nh=/^---\s*\n([\s\S]*?)\n---/;function Lh(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function jh(e){return e.trim().toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9.-]/g,"")}function Uh(e){const t=e.match(Nh);if(!t)return{};try{const e=yd.Ay.load(t[1],{schema:yd.Ay.JSON_SCHEMA});if(!Lh(e))return{};const r=Lh(e.metadata)?e.metadata:void 0,n=Bh(e.environments??r?.environments);return{disabledEnvironments:Bh(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 Bh(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 Wh(e){return jh((0,s.basename)(e).replace(/\.(md|mdc|markdown|txt)$/i,""))}function Hh(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 qh{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=yh.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,Oh):s.has("skills")?this.discoverSkills(`${r}skills`):Promise.resolve([]),void 0!==n?.agents?this.discoverFromManifestPaths(r,n.agents,!1,Oh):s.has("agents")?this.discoverMarkdownComponents(`${r}agents`,Oh):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,Fh):s.has("commands")?this.discoverMarkdownComponents(`${r}commands`,Fh):Promise.resolve([]),void 0!==n?.rules?this.discoverFromManifestPaths(r,n.rules,!1,Oh):s.has("rules")?this.discoverMarkdownComponents(`${r}rules`,Oh):Promise.resolve([]),this.discoverMcpServers(r,n?.mcpServers,i)]);return{skills:Hh(c?[c,...l]:l),agents:Hh(u),hooks:d,commands:Hh(h),rules:Hh(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 Lh(r)&&Lh(r.hooks)?Object.keys(r.hooks).map((t=>({name:jh(t),path:e,description:`Hook: ${t}`}))):[]}catch{return[]}}async discoverHooksFromManifest(e,t){if("string"==typeof t){if(!ch(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:jh(e),path:"manifest",description:`Hook: ${e}`})))}async discoverFromManifestPaths(e,t,r=!1,n=Oh){if("string"==typeof t){if(!ch(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(!ch(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=Wh(t.endsWith("SKILL.md")?t.slice(0,-8).replace(/\/$/,""):t);const{content:n}=await this.fetcher.fetchFile(e),s=Uh(n);if(r=s.name??r,r){const t={disabledEnvironments:s.disabledEnvironments,environments:s.environments,name:jh(r),path:e};void 0!==s.description&&(t.description=s.description),o.push(t)}}else{if(!await this.fetcher.fileExists(t))continue;let e=Wh(t);const{content:r}=await this.fetcher.fetchFile(t),n=Uh(r);e=n.name??e;const s=n.description;if(e){const r={name:jh(e),path:t};void 0!==s&&(r.description=s),o.push(r)}}}catch{}return o}async discoverMarkdownComponents(e,t=Oh,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=Wh(e.name);const{content:r}=await this.fetcher.fetchFile(e.path),n=Uh(r);t=n.name?jh(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=jh((0,s.basename)(e.replace(/[\\/]+$/,"")));const{content:n}=await this.fetcher.fetchFile(t),o=Uh(n);if(r=o.name?jh(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=Uh(r),o=n.name?jh(n.name):jh(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=>xh(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:jh(e),path:i.mcpServerSourcePaths?.[e]??"manifest"}))),variables:Dh(a??i),configs:l}}}var zh=r("node:stream"),Gh=r("node:stream/promises"),Vh=r("node:zlib");function Kh(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 Jh(e){return e.replace(/[^a-zA-Z0-9._-]/g,"_")}var Zh=r("../../node_modules/.pnpm/tar@7.5.21/node_modules/tar/dist/esm/index.min.js");const Xh=".cache-complete";function Qh(e){return Jh(e)}function Yh(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 ep(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?Qh(t.version):void 0)}class tp{constructor(e,t){const r=e??process.env.HOME??"";this.cacheRoot=t?.cacheRoot??(0,s.join)(r,".cursor","plugins/cache")}getCacheDir(e){return ep(this.cacheRoot,e)}async isCached(e){const t=this.getCacheDir(e);try{const e=Yh({parent:t,name:Xh});return(await(0,go.stat)(e)).isFile()}catch{return!1}}async extractToCache(e){const t=this.getCacheDir(e);await(0,go.mkdir)(t,{recursive:!0});const r=zh.Readable.from(e.tarball);return await(0,Gh.pipeline)(r,(0,Vh.createGunzip)(),(0,Zh.o6)({cwd:t,strip:1})),await this.markCacheComplete(e),t}async listCachedVersions(e){const t=ep(this.cacheRoot,e);try{return(await(0,go.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,go.rm)(t,{recursive:!0,force:!0})}catch{}}async removeAllVersions(e){const t=ep(this.cacheRoot,e);await(0,go.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=>Qh(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,go.writeFile)(Yh({parent:t,name:Xh}),"")}}class rp extends Error{constructor(e,t){super(`Invalid Claude Code plugin identifier "${t}": ${e}`),this.raw=t,this.name="CCPluginIdentifierError"}}function np(e){const t=e.trim();if(!t)throw new rp("Empty identifier",e);const r=/^[a-zA-Z0-9_-]+$/,n=t.indexOf("@");if(n!==t.lastIndexOf("@"))throw new rp("Plugin identifier cannot contain multiple @ symbols",e);if(-1===n){if(!r.test(t))throw new rp("Plugin name must contain only alphanumeric characters, dashes, and underscores",e);if(t.length>100)throw new rp("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 rp("Missing plugin name before @",e);if(!s)throw new rp("Missing source after @",e);if(!r.test(o))throw new rp("Plugin name must contain only alphanumeric characters, dashes, and underscores",e);if(o.length>100)throw new rp("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 rp("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 rp("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 rp("Missing Git URL after 'url:'",e);try{new URL(t)}catch{throw new rp("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 rp("Missing marketplace name",e);if(!r.test(a))throw new rp("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 sp(e){return e.sourceInfo.name}function ip(e){switch(e.source){case"claude-plugin":case"cursor-first-party":case"cursor-third-party":return e.sourceInfo.marketplace;default:return}}function ap(e){switch(e.source){case"cursor-first-party":case"cursor-third-party":return e.sourceInfo.pluginDbId;default:return}}function cp(e){switch(e.source){case"cursor-first-party":case"cursor-third-party":return e.sourceInfo.marketplaceDbId;default:return}}function lp(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function up(e){return!!lp(e)&&(void 0===e.enabledPlugins||lp(e.enabledPlugins))}function dp(e){return JSON.parse(e)}function hp(e){const t=e??process.env.HOME??"";return(0,s.join)(t,".claude")}async function pp(e){const t={enabledPlugins:{}};let r=!1;const n=(0,s.join)(e,".claude","settings.json");try{const e=dp(await(0,go.readFile)(n,"utf-8"));up(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=dp(await(0,go.readFile)(o,"utf-8"));up(e)&&e.enabledPlugins&&(Object.assign(t.enabledPlugins,e.enabledPlugins),r=!0)}catch{}return r?t:null}function fp(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 mp(e){try{return(await(0,go.lstat)(e)).isSymbolicLink()}catch{return!1}}async function gp(e){if(await mp(e))throw new Error(`Refusing to read symlink: ${e}`);return(0,go.readFile)(e,"utf-8")}async function wp(e){if((await(0,go.stat)(e)).size>10485760)throw new Error(`File ${e} exceeds maximum size of 10485760 bytes`)}function yp(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 vp({installPath:e,logo:t}){const r=t?.trim();if(r&&!(0,s.isAbsolute)(r)&&!r.includes("://"))try{const t=await(0,go.realpath)(e),n=fp(t,r),o=await(0,go.realpath)(n);if(fp(t,o),!(await(0,go.stat)(o)).isFile())return;return await wp(o),(0,Lu.pathToFileURL)(o).href}catch{return}}function bp(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 Sp(e){return void 0!==e.version||void 0!==e.homepage||void 0!==e.repository}function kp(e,t){return bp({version:e.version??t?.version,homepage:e.homepage??t?.homepage,repository:e.repository??t?.repository})}async function _p(e,t,r){let n;for(const o of Id){const i=(0,s.join)(e,o);let a;try{if(await mp(i))continue;if(!(await(0,go.stat)(i)).isFile())continue;await wp(i),a=await gp(i)}catch{continue}const c=ih(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 vp({installPath:e,logo:l.logo}),S=bp(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&&!Sp(S))continue;if(!g&&!C){n=n?{...n,fields:kp(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=kp(S,n?.fields);return{manifestFilePath:i,...g&&{manifestOptions:{commands:u,agents:d,skills:h,rules:p,hooks:f,mcpServers:m}},...(C||Sp(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 Cp(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,go.realpath)(o).catch((()=>o));function a(e){const t=(0,s.resolve)(e);try{return fp(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,go.realpath)(t);try{return fp(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,go.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,go.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 wp(i);const l=await(0,go.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,go.stat)(n)).isFile()}catch{return!1}}}}(e),n=new qh(r),o=await n.discoverComponents({manifest:t}),[i,a,c,l]=await Promise.all([Ep(r,o.skills,e),Pp(r,o.agents,e),Ip(r,o.commands,e),xp(r,o.rules,e)]);return{skills:i,agents:a,commands:c,rules:l}}async function Ep(e,t,r){const n=[];for(const o of t)try{const{content:t}=await e.fetchFile(o.path),s=Tp({content:fh(t,r),relativePath:o.path});s&&n.push(s)}catch{}return n}async function xp(e,t,r){const n=[];for(const o of t)try{const{content:t}=await e.fetchFile(o.path),s=Tp({content:fh(t,r),relativePath:o.path});s&&n.push({...s,name:o.name})}catch{}return n}async function Pp(e,t,r){const n=[];for(const o of t)try{const{content:t}=await e.fetchFile(o.path),s=Ap({content:fh(t,r),relativePath:o.path});s&&n.push(s)}catch{}return n}async function Ip(e,t,r){const n=[];for(const o of t)try{const{content:t}=await e.fetchFile(o.path),s=$p({content:fh(t,r),relativePath:o.path});s&&n.push(s)}catch{}return n}function Rp(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 Tp({content:e,relativePath:t}){try{const r=pd(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=Bh(r.data.environments??r.data.metadata?.environments),u=Bh(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:Rp(r.data.globs),alwaysApply:!0===r.data.alwaysApply,content:e,environments:l,disabledEnvironments:u}}catch{return null}}function Ap({content:e,relativePath:t}){try{const n=pd(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 $p({content:e,relativePath:t}){try{const r=pd(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 Mp(e){if(void 0!==e)return{configuredVariables:e.configuredVariables}}async function Dp(e,t,r){const n=r??Mp(t);return async function(e,t={}){const r=t.toSourcePath??(e=>e);let n,o,s;for(const t of Id){const i=await e(t);if(null===i)continue;let a;try{a=JSON.parse(i)}catch{continue}s=_d(a);const c=ih(i);if(c.success){void 0!==c.data.mcpServers&&(n=c.data.mcpServers,o=r(t));break}}return xh(e,n,o,void 0===s?t:{...t,parserOptions:{...t.parserOptions,pluginSchemaId:s}})}(function(e){return async t=>{if(!ch(t))return null;const r=(0,s.join)(e,t);try{return await mp(r)?null:(await(0,go.stat)(r)).isFile()?(await wp(r),await gp(r)):null}catch{return null}}}(e),{fallbackFileNames:kh(),manifestPrecedence:"override",toSourcePath:t=>(0,s.join)(e,t),installPathForExpansion:e,parserOptions:n})}async function Op(e,t,r){const n=await Dp(e,void 0,{log:r});if(n)return n;for(const n of Td){const o=(0,s.join)(e,n);try{if(!(await(0,go.stat)(o)).isFile())continue;const n=await(0,go.readFile)(o,"utf-8"),i=JSON.parse(n);if(!Lp(i)||!Array.isArray(i.plugins))continue;const a=i.plugins.filter(jp),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(!ch(n))continue;const o=(0,s.join)(e,n);try{await wp(o);const t=Ch(await gp(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 Fp=new Set(Object.values(ju));function Np(e){return Fp.has(e)}function Lp(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function jp(e){return!(!Lp(e)||"string"!=typeof e.name)&&(void 0===e.mcpServers||Array.isArray(e.mcpServers)&&e.mcpServers.every((e=>"string"==typeof e)))}function Up(e,t){const r={};for(const[n,o]of Object.entries(e.hooks))Array.isArray(o)&&Np(n)&&(r[n]=o.map((e=>"command"in e&&"string"==typeof e.command?{...e,command:fh(e.command,t)}:"prompt"in e&&"string"==typeof e.prompt?{...e,prompt:fh(e.prompt,t)}:e)));return{...e,hooks:r}}async function Bp(e,t,r,n,o){if("object"==typeof n){const s=Wp(n,t,r);return s&&"config"in s?{config:Up(s.config,e),...void 0!==o&&{sourcePath:o}}:s}let i,a,c;if("string"==typeof n){const t=n.replace(/^\.\//,"");if(!ch(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 mp(i))return;if(!(await(0,go.stat)(i)).isFile())return}catch{return}try{await wp(i),a=await(0,go.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=Wp(c,t,r);return l&&"config"in l?{config:Up(l.config,e),sourcePath:i}:l}function Wp(e,t,r){const n=function(e){if(!Wu(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(Wu(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=Vu(e);return r.isValid&&Vu(e).isValid?{config:e}:{error:{source:"claude-plugin",message:`Plugin ${t} hooks: ${r.errors.join("; ")}`}}}if("claude-code"===n){if(!(Lp(o=e)&&Lp(o.hooks)&&Object.keys(o.hooks).length>0))return;const n=ud(e.hooks,{warn:e=>r.log("warn",`Plugin ${t} hooks: ${e}`),info:e=>r.log("info",`Plugin ${t} hooks: ${e}`)}),s=Vu(n);return s.isValid?{config:n}:{error:{source:"claude-plugin",message:`Plugin ${t} hooks: ${s.errors.join("; ")}`}}}var o}async function Hp(e,t,r,n){const o=n?.log??mh,s=await _p(e,t,o),i={...Mp(r)??(n?.configuredVariables?{configuredVariables:n.configuredVariables}:void 0),log:o},[a,c,l]=await Promise.all([Cp(e,s?.manifestOptions),Dp(e,r,i),Bp(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 qp(e,t,r){const n=r?.log??mh,o=await _p(e,t.raw,n),[s,i,a]=await Promise.all([Cp(e,o?.manifestOptions),Op(e,t,n),Bp(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 zp(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 Hp(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 Gp(e,t,r={}){const n=r.log??mh,o=performance.now(),i=await async function(e){const t=hp(e),r=(0,s.join)(t,"plugins","installed_plugins.json");try{const e=dp(await(0,go.readFile)(r,"utf-8"));return lp(n=e)&&lp(n.plugins)?e:null}catch{return null}var n}(r.userHomeDir);if(!i?.plugins)return n.log("info",`loadAllEnabledPlugins: no installed plugins metadata found (${(performance.now()-o).toFixed(1)}ms)`),[];const a=await async function(e){const t=hp(e),r=(0,s.join)(t,"settings.json");try{const e=dp(await(0,go.readFile)(r,"utf-8"));return up(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 wd(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=wd(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 pp(e)})),{max:8})),u=[],d=r.onError;for(const{pluginId:e,installPath:t}of l)try{const r=performance.now(),o=np(e),s=await qp(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(np(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 Vp(e){const t=e.log??mh,r=performance.now(),{client:n,userId:o,teamId:s,onCursorError:i,pruneOldVersions:a,pluginFilter:c,onPluginsListed:l}=e,u=[],d=e.cacheManager??new tp(e.userHomeDir),h=performance.now();let p;try{p=await n.listEnabledPlugins(o,s)}catch(e){return t.captureException(e,{error_type:"list_enabled_plugins"}),t.increment("marketplace.source_unavailable",1),t.log("error",`marketplace listEnabledPlugins failed after ${(performance.now()-h).toFixed(1)}ms; treating source as unavailable: ${e instanceof Error?e.message:String(e)}`),{plugins:[],failures:[],sourceUnavailable:!0}}t.log("info",`marketplace listEnabledPlugins completed in ${(performance.now()-h).toFixed(1)}ms (${p.plugins.length} plugins)`),l&&await l(p.plugins);const f=[];if(p.listFailures){u.push(...p.listFailures);for(const e of p.listFailures)f.push({identifier:{source:e.marketplaceName&&"cursor-public"!==e.marketplaceName?"cursor-third-party":"cursor-first-party",sourceInfo:{name:e.pluginName,version:"",...void 0!==e.pluginDbId&&{pluginDbId:e.pluginDbId},marketplace:e.marketplaceName}},installPath:"",loadError:e.errorMessage,skills:[],rules:[],agents:[],commands:[],capabilities:[]})}const m=new Map;for(const e of p.plugins)if(!c||c(e))try{const r=e.marketplace?.name;if(!r){const t=new Error(`Plugin ${e.name} has no marketplace metadata — cannot determine cache path`);u.push({pluginName:e.name,pluginId:e.pluginId,marketplaceName:void 0,errorMessage:t.message,errorType:"manifest"}),i&&i(e,t);continue}const o=`${r}/${e.pluginId}`;let s,a=m.get(o);if(a||(a={slug:r,pluginId:e.pluginId,versions:[]},m.set(o,a)),a.versions.push(e.version),await d.isCached({marketplaceSlug:r,pluginId:e.pluginId,version:e.version}))s=d.getCacheDir({marketplaceSlug:r,pluginId:e.pluginId,version:e.version}),t.log("info",`loadFromMarketplaceSource: Found cached plugin: ${e.pluginId} at ${s}`,{marketplaceSlug:r,pluginId:e.pluginId,gitRef:e.version,marketplaceId:e.marketplace?.id});else{const o=d.getCacheDir({marketplaceSlug:r,pluginId:e.pluginId,version:e.version});t.log("info",`loadFromMarketplaceSource: Plugin missing from cache, installing: ${e.pluginId} at ${o}`,{marketplaceSlug:r,pluginId:e.pluginId,gitRef:e.version,marketplaceId:e.marketplace?.id}),await(0,go.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,go.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 zp(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:yp(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 Kp(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 Jp(e){return Kp(e)??`path:${e.installPath}`}function Zp(e,t={}){return{...e,model:t.stripModel?void 0:e.model,tools:t.stripTools?void 0:e.tools}}function Xp(e,t){const r=[];for(const o of e){const e=op(o.identifier),i=`plugin:${e}`,a=sp(o.identifier),c=ip(o.identifier),l=ap(o.identifier),u=cp(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 Qp=r("../proto/dist/generated/agent/v1/agent_skills_pb.js");const Yp=(0,Ls.debuglog)("agent-skills-catalog-cache");function ef(e){return(0,ho.createHash)("sha256").update(JSON.stringify({v:1,...e})).digest("hex")}async function tf(e){try{return(await(0,go.stat)(e)).mtimeMs}catch{return}}function rf(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}const nf=[".kits","cursor-pages"],of={configDir:".cursor",subdir:"skills-cursor",thirdParty:!1,builtin:!0},sf=[{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},of],af=(new Set(sf.map((e=>e.configDir))),new Set(["imagegen","openai-docs","opneai-docs","plugin-creator","skill-creator","skill-installer"]));function cf(e){return e.replace(/\\/g,"/").split("/").filter(Boolean)}function lf(e){const t=cf(e);if(function(e){const t=e.findIndex(((t,r)=>function(e,t){return sf.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&&af.has(o)}function uf(e){return{dirPath:(0,s.join)(e,of.configDir,of.subdir),scope:"builtin",source:"builtin"}}const df="canvas";function hf(e,t){return{dirPath:(0,s.join)(uf(e).dirPath,...nf),scope:"builtin",source:"builtin"}}function pf(e,t){const r=e.replace(/\\/g,"/"),n=t.replace(/\\/g,"/").replace(/\/+$/,"");if(r.startsWith(`${n}/`))return cf(r.slice(n.length+1))}function ff(e,t){const r=pf(e,t);return void 0!==r&&!r.some((e=>e.startsWith(".")))}function mf(e){return sf.filter((t=>!t.builtin&&(e||!t.thirdParty)))}function gf(e,t){return mf(t).map((t=>({dirPath:(0,s.join)(e,t.configDir,t.subdir),scope:"project",source:"workspace"})))}function wf(e,t){return mf(t).map((t=>({dirPath:(0,s.join)(e,t.configDir,t.subdir),scope:"user",source:"user"})))}var yf=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 vf(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}const bf=sf.map((({configDir:e,subdir:t,thirdParty:r})=>({pattern:new RegExp(`[/\\\\]${vf(e)}[/\\\\]${vf(t)}[/\\\\]`,"i"),requiresThirdParty:r}))),Sf=/[/\\]\.cursor[/\\]rules[/\\]/i,kf=[{pattern:/[/\\]\.cursor[/\\]agents[/\\]/i,requiresThirdParty:!1},{pattern:/[/\\]\.claude[/\\]agents[/\\]/i,requiresThirdParty:!0}],_f=new Set(["AGENTS.md","CLAUDE.md","CLAUDE.local.md"]);function Cf(e,t){const r=e.replace(/\\/g,"/"),n=(0,s.basename)(r);if(_f.has(n))return"AGENTS.md"===n||t&&("CLAUDE.md"===n||"CLAUDE.local.md"===n)?"markdown":void 0;if(Sf.test(r)&&n.endsWith(".mdc"))return"rules";if("SKILL.md"===n)for(const{pattern:e,requiresThirdParty:n}of bf)if(e.test(r)){if(n&&!t)continue;return"skills"}if(n.endsWith(".md"))for(const{pattern:e,requiresThirdParty:n}of kf)if(e.test(r)){if(n&&!t)continue;return"agents"}}class Ef{constructor(e,t,r,n){this.root=e,this.gitExecutor=t,this.userHomeDirectory=r,this.getThirdPartyExtensibilityEnabled=n}static getRipwalkCache(){return Ef.ripwalkCache??=new fa,Ef.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||Fs(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 Ea(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:Ta,followSymlinks:!0,source:"nested_extensibility"},u={rules:[],skills:[],markdown:[],agents:[]},d=Ef.getRipwalkCache();try{const e=d.walk(r.ctx,l);try{for await(const t of e.lines){const e=Cf(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{yf(t)}}buildIncludeGlobs(e){const t=["*/**/.cursor/**","*/**/.agents/**","*/**/AGENTS.md"];return e&&t.push("*/**/.claude/**","*/**/.codex/**","*/**/.grok/**","*/**/CLAUDE.md","*/**/CLAUDE.local.md"),t}}const xf=new Set(["node_modules","__pycache__","dist","build"]);async function Pf({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,go.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,go.realpath)(n);if(!l(e))continue;if(a.has(e))continue;a.add(e)}catch{continue}const d=await(0,go.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,go.stat)(r);a=e.isDirectory(),l=e.isFile()}catch{continue}if(a){if((u=e.name).startsWith(".")||xf.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 If={agentStoreSkillsDirs:[],userHomeDirectory:""};function Rf(e){const t=e.replace(/\\/g,"/");return t.endsWith("/")?t.slice(0,-1):t}function Tf(e,t){const r=Rf(t.userHomeDirectory),n=e.replace(/\\/g,"/");if(r.length>0)for(const e of t.agentStoreSkillsDirs){const t=Rf(e);if(t.length>0&&n.startsWith(`${t}/`))return{key:`${r}::skills/${n.slice(t.length+1)}`,inAgentStore:!0}}return{key:Af(e),inAgentStore:!1}}function Af(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 $f(e,t){const r=new Map,n=[];for(const o of e){const{key:e,inAgentStore:s}=Tf(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 Mf=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},Df=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 Of=(0,d.h)("local-exec:cursor-rules");function Ff(e){return"/"===e||"\\"===e}function Nf(e){return e.split(/[\\/]+/).filter((e=>e.length>0)).length}async function Lf(e){return await Pf({rootDir:e,includeFile:e=>"SKILL.md"===e})}async function jf(e){let t;try{t=await $i(e)}catch(t){return{skillFilePath:e,error:Mu(t)}}try{return{skillFilePath:e,content:t,parsed:pd(t)}}catch(t){return{skillFilePath:e,error:Du(t)}}}async function Uf(e){const t=await Vo(e);return{...await jf(e),realSkillFilePath:t}}function Bf(e){return qf(e.data?.environments??e.data?.metadata?.environments)??[]}function Wf(e){return qf(e.data?.["disabled-environments"]??e.data?.metadata?.disabledEnvironments)??[]}function Hf(e){return qf(e.data?.metadata?.scopedTo??e.data?.["metadata.scopedTo"])??[]}function qf(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 zf(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 Gf(e){return jo(e,1536)}function Vf(e){return!0===e.data?.alwaysApply}function Kf(e){return!0===e.data?.["disable-model-invocation"]}function Jf({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---`:fd("",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 ${Nu(s.length)} characters; the limit is 64. Rename the skill's folder.`),Fu.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 ${Nu(i)} characters; the limit is ${Nu(1024)}.`);const a=Math.round(n.length/4);return a>5e3&&o.push(`Body is about ${Nu(a)} tokens; the recommended limit is ${Nu(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(Vf(r))return new Kr.DX({fullPath:e,content:t,frontmatter:n,type:new Kr.f5({type:{case:"global",value:new Kr.i9}}),environments:Bf(r),disabledEnvironments:Wf(r),scopedTo:Hf(r),warnings:o});const s="string"==typeof r.data?.description?Gf(r.data.description):void 0,i=Ou(s,Kf(r));return i?new Kr.DX({fullPath:e,parseError:i,frontmatter:n,scopedTo:Hf(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:Bf(r),disabledEnvironments:Wf(r),scopedTo:Hf(r),warnings:o})}function Zf({skillFilePath:e,content:t,parsed:r}){const n="string"==typeof r.data?.description?Gf(r.data.description):"",o=Rp(r.data?.paths??r.data?.globs),s=Kf(r);return new Qp.N({fullPath:e,content:t,description:n,globs:o??[],parseError:Ou(n,s),environments:Bf(r),disabledEnvironments:Wf(r),scopedTo:Hf(r),disableModelInvocation:s})}function Xf({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 Qp.N({fullPath:e,parseError:t})}({skillFilePath:r,errorMessage:n}))}function Qf(e,t,r,n){if("error"in t)return e.realSkillFilePathsByFullPath.set(t.skillFilePath,t.realSkillFilePath),void Xf({rules:e.rules,agentSkills:e.agentSkills,skillFilePath:t.skillFilePath,errorMessage:t.error});zf(t.parsed,r,n)||(e.realSkillFilePathsByFullPath.set(t.skillFilePath,t.realSkillFilePath),e.rules.push(Jf(t)),Vf(t.parsed)||e.agentSkills.push(Zf(t)))}const Yf=(0,Ls.debuglog)("cursor-rules-service");function em(){return{rules:[],agentSkills:[],realSkillFilePathsByFullPath:new Map}}function tm(e){return t=>(Yf("%s: %O",e,t),em())}function rm(e,t){return ef({kind:"agent-store",surface:e,roots:[...t].sort()})}function nm(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=Rp(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:Gf(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 sm{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=Mf(t,(0,D.VI)(e.withName("MergedCursorRulesService.getAllCursorRules")),!1),n=this.cursorRulesServices.map((e=>e.getAllCursorRules(r.ctx).catch((e=>((0,Ls.debuglog)("Failed to load cursor rules from service:",e),[])))));return $f((await Promise.all(n)).flat(),this.getAgentStoreSkillsContext())}catch(e){t.error=e,t.hasError=!0}finally{Df(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()}),sm.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()}}sm.CHANGE_COALESCE_MS=1e3;class im{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 Ef(r,t,(0,o.homedir)(),i),this.ignoreService=c??new Va(t,void 0,[this.rootDirectory]);const u=performance.now();if(this._rules=this.load(e,l).then((t=>{try{Of.info(e,"LocalCursorRulesService load completed",{durationMs:Math.round(performance.now()-u),ruleCount:t.length})}catch{}return t})).catch((e=>((0,Ls.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=Mf(t,(0,D.VI)(r.withName("LocalCursorRulesService.fileWatcher.subscribe")),!1);if(".cursorignore"===(0,s.basename)(e))return im.getRipwalkCache().clear(),void this.reload(n.ctx);this.reloadAtPath(n.ctx,e)}catch(e){t.error=e,t.hasError=!0}finally{Df(t)}}))}}reload(e){this._rules=this.load(e).catch((e=>((0,Ls.debuglog)("Failed to load cursor rules:",e),[])));for(const e of this.onChangeCallbacks)e()}static getRipwalkCache(){return im.ripwalkCache??=new fa,im.ripwalkCache}reloadAtPath(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Mf(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,Ls.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{Df(r)}}isRuleMarkdownFile(e){return Zr(e)}async readRulesAtPath(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Mf(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 Ea(n.ctx,this.gitExecutor,e)||e,r=await this.loadCursorRulesRule(n.ctx,t);return r?[r]:[]}if(o.endsWith(".mdc"))return await am(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{Df(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=Mf(r,(0,D.VI)(e.withName("LocalCursorRulesService.load")),!1);this.loadTraceId=n.span.spanContext().traceId;const o=(0,s.resolve)(this.rootDirectory),i=await Ea(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,go.stat)(e,{bigint:!0});if(0n!==t.ino)return`ino:${String(t.dev)}:${String(t.ino)}`}catch{}return await Vo(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=Nf(e.dir)-Nf(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)&&(Ff(r.at(-1))||Ff(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{Df(r)}}async loadCursorRulesRule(e,t){const r={stack:[],error:void 0,hasError:!1};try{Mf(r,(0,D.VI)(e.withName("LocalCursorRulesService.loadCursorrules")),!1);try{const e=(0,s.join)(t,".cursorrules");if((await(0,go.stat)(e)).isFile())return{filename:".cursorrules",path:e,frontmatter:{alwaysApply:!0},body:await $i(e)}}catch{}return null}catch(e){r.error=e,r.hasError=!0}finally{Df(r)}}async getAllCursorRules(e){const t={stack:[],error:void 0,hasError:!1};try{return Mf(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{Df(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=Mf(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{Df(r)}}async loadRulesFromMarkdownFile(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{Mf(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,go.stat)(e)).isFile()){const t=Xr({content:await $i(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{Df(n)}}async isCursorIgnored(e){try{const t=await za((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=Mf(r,(0,D.VI)(e.withName("LocalCursorRulesService.parseNestedRuleFiles")),!1),o=(await Promise.all(t.map((async e=>{try{const t=Yr(await $i(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{Df(r)}}async parseNestedMarkdownFiles(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Mf(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{Df(r)}}async loadRulesFromDirectory(e,t){return await async function(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=Mf(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 am(r))}}catch{}return o.span.setAttribute("rules",i.length),i}catch(e){n.error=e,n.hasError=!0}finally{Df(n)}}(e,t,im.getRipwalkCache())}async dirIsDirectory(e,t){const r={stack:[],error:void 0,hasError:!1};try{Mf(r,(0,D.VI)(e.withName("LocalCursorRulesService.dirIsDirectory")),!1);try{return(await(0,go.stat)(t)).isDirectory()}catch{return!1}}catch(e){r.error=e,r.hasError=!0}finally{Df(r)}}}async function am(e){try{const t=Yr(await $i(e));if(t)return[{filename:(0,s.basename)(e,".mdc"),path:e,frontmatter:t.frontmatter,rawFrontmatter:t.rawFrontmatter,body:t.body}]}catch{}return[]}class cm{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=uf(r).dirPath,this.canvasKitSkillRootDir=void 0===h?void 0:hf(r).dirPath,this.workspaceCatalogKey=ef({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 Ef(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{Of.info(e,"AgentSkillsCursorRulesService load completed",{durationMs:Math.round(performance.now()-m),ruleCount:t.rules.length,skillCount:t.agentSkills.length,servedFromCache:g})}catch{}return t})).catch((e=>(w=!0,tm("Failed to load Agent Skills")(e))));if(void 0===this.catalogCache)this._loaded=v;else{const t=this.readCatalog(this.workspaceCatalogKey).then((r=>(y=!0,this._loaded!==t?this._loaded:(w&&this.closeSeedWindow(e),void 0===r?v:(g=!0,r)))));this.seededLoaded=t,this._loaded=t,v.then((r=>{this._loaded===t?w?y&&this.closeSeedWindow(e):(this._loaded=v,g&&this.notifyChanged(),this.persistCatalog(this.workspaceCatalogKey,r),this.closeSeedWindow(e)):this.seededLoaded=void 0}))}this.refreshAgentStoreSkills(),this.setupWatchers(this.foldersToWatch)}closeSeedWindow(e){this.seededLoaded=void 0,this.reloadRequestedDuringSeed&&(this.reloadRequestedDuringSeed=!1,this.reload(e))}async readCatalog(e){if(void 0!==this.catalogCache)try{const t=await this.catalogCache.read(e);return void 0===t?void 0:await async function(e){if(!function(e){if(!rf(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]))&&rf(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 tf(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=>Qp.N.fromJson(e,{ignoreUnknownFields:!0}))).filter((e=>r(e.fullPath))),realSkillFilePathsByFullPath:t}}catch(e){return void Yp("snapshot failed to decode: %O",e)}}(t)}catch(e){return void Yf("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 tf(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=>{Yf("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 gf(r,e))t.add(n.dirPath)}for(const r of wf(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(ff(e,this.canvasKitSkillRootDir))return!1;if(function(e,t){const r=pf(e,t);return void 0!==r&&2===r.length&&r[0]===df&&"SKILL.md"===r[1]}(e,this.builtinSkillRootDir))return!0}return lf(e)}setupWatchers(e){if(!this.fileWatcher)return;const t=["**"];for(const r of e){if(this.watchersByFolder.has(r))continue;const e=this.fileWatcher.subscribe(r,t,(e=>{const t={stack:[],error:void 0,hasError:!1};try{const r=(0,b.q6)(),n=Mf(t,(0,D.VI)(r.withName("AgentSkillsCursorRulesService.fileWatcher.subscribe")),!1);this.reloadAtPath(n.ctx,e)}catch(e){t.error=e,t.hasError=!0}finally{Df(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(tm("Failed to load Agent Skills"));this._loaded=r,t.then((e=>{this._loaded===r&&this.persistCatalog(this.workspaceCatalogKey,e)}),(()=>{})),this.refreshAgentStoreSkills(),this.notifyChanged()}reloadSkillRoots(){try{this.syncWatchers()}finally{this.refreshAgentStoreSkills()}}async agentStoreSkillsSettled(){for(let e=this.agentStoreWalk;void 0!==e;e=this.agentStoreWalk)await e}syncWatchers(){const e=this.computeFoldersToWatch(),t=new Set(this.foldersToWatch),r=new Set(e);this.removeWatchers(this.foldersToWatch.filter((e=>!r.has(e)))),this.setupWatchers(e.filter((e=>!t.has(e)))),this.foldersToWatch=e}isPrunedByExtensibilityScan(e){if(void 0!==this.canvasKitSkillRootDir&&ff(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=Mf(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=>nm(a,e))))return void(this.reloadRequestedDuringSeed=!0);if(this.getAgentStoreSkillRoots().some((e=>nm(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,go.stat)(a)}catch{return r}return await this.loadAll(n.ctx)}let s;try{s=await(0,go.realpath)(a)}catch{return await this.loadAll(n.ctx)}if(s!==o)return await this.loadAll(n.ctx);try{return Qf(r,{...await async function(e){const t=await $i(e);return{skillFilePath:e,content:t,parsed:pd(t)}}(a),realSkillFilePath:s},this.surface,this.getEnabledSkills()),r}catch{return await this.loadAll(n.ctx)}})().catch(tm("Failed to load Agent Skills at path"));this._loaded=l,this.notifyChanged()}catch(e){r.error=e,r.hasError=!0}finally{Df(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(rm(this.surface,e),r))}),(e=>{Yf("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(rm(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=em(),r=(await Promise.all(e.map((e=>Lf(e))))).flat().filter((e=>!lf(e))),n=await Promise.all(r.map((e=>Uf(e)))),o=new Set;for(const e of n)o.has(e.realSkillFilePath)||(o.add(e.realSkillFilePath),Qf(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=Mf(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=>{Yf("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 Lf(e)).filter((e=>!this.isIgnoredSkillPath(e)));return Promise.all(t.map((e=>Uf(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),Xf({rules:o,agentSkills:s,skillFilePath:t.skillFilePath,errorMessage:t.error});else{if(zf(t.parsed,this.surface,this.getEnabledSkills()))continue;i.set(t.skillFilePath,t.realSkillFilePath),o.push(Jf(t)),Vf(t.parsed)||s.push(Zf(t))}const d=(await a).flatMap((e=>e?.skills??[])).filter((e=>!lf(e))),h=await Promise.all(d.map((e=>Vo(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=>Uf(e))));for(const e of f)if("error"in e)i.set(e.skillFilePath,e.realSkillFilePath),Xf({rules:o,agentSkills:s,skillFilePath:e.skillFilePath,errorMessage:e.error});else{if(zf(e.parsed,this.surface,this.getEnabledSkills()))continue;i.set(e.skillFilePath,e.realSkillFilePath),o.push(Jf(e)),Vf(e.parsed)||s.push(Zf(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{Df(r)}}}function lm(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:Gf(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 um{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{Of.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,Ls.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=>(Of.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=Mf(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 Xp(e,(e=>e.skills))}(e),a=function(e){return Xp(e,(e=>e.rules))}(e);for(const e of[...r,...a])o.push(lm(e));for(const t of e){const e=`plugin:${op(t.identifier)}`,r=sp(t.identifier),n=ip(t.identifier),o=ap(t.identifier),a=cp(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===pd(c.content).data?.["disable-model-invocation"]}catch{}i.push(new Qp.N({fullPath:(0,s.join)(t.installPath,c.path),content:c.content,description:Gf(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{Df(r)}}}var dm=r("../proto/dist/generated/agent/v1/subagents_pb.js");const hm=(0,Ls.debuglog)("local-subagents");class pm{async getAllSubagents(){return[]}async reload(){return[]}}function fm(e){return"true"===(e??"").trim().toLowerCase()}function mm(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=fm(o["force-default-model"]),l="true"===(o.readonly??"").trim().toLowerCase()?dm.b$.READONLY:dm.b$.DEFAULT,u=fm(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 gm(e){const t=(0,s.extname)(e).toLowerCase();return".md"===t||".mdc"===t||".markdown"===t}function wm(e){return(0,s.basename)(e,(0,s.extname)(e)).replace(/[\s_]+/g,"-")}async function ym(e,t){return await Pf({rootDir:e,includeFile:gm,containmentRootDir:t})}class vm{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 ym(r,this.allowExternalAgentSymlinks?void 0:this.workspacePath);for(const r of e){const e=(0,s.basename)(r);try{if(!(await(0,go.stat)(r)).isFile())continue}catch(e){hm("Skipping subagent file %s due to stat error: %o",r,e);continue}try{const o=mm(await $i(r));if(!o)continue;t.push(new dm.zz({fullPath:r,name:o.name||wm(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 bm=new Set(["claude-code-tutor"]);class Sm{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)bm.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 km{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=sp(n.identifier),o=ip(n.identifier),i=ap(n.identifier),a=cp(n.identifier);for(const c of n.agents){const l=Zp(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?dm.b$.READONLY:dm.b$.DEFAULT;t.push(new dm.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 _m{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 Cm(e,t){return`${e}:${(0,ho.createHash)("sha256").update(t.toBinary()).digest("hex")}`}function Em(e){return new wo.q({max:e?.max??10,ttl:e?.ttl})}function xm(e,t,r=Em(t)){return{async execute(t,n,o){if(!o?.execId)return e.execute(t,n,o);const s=Cm(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 Pm=r("../proto/dist/generated/agent/v1/computer_use_tool_pb.js");r("node:readline"),Error,r("node:timers/promises");const Im=yl.execFile;function Rm(e,t,r){return new Promise(((n,o)=>{r?.signal?.throwIfAborted();const s={timeout:r?.timeoutMs??3e4,env:r?.env?{...process.env,...r.env}:void 0,signal:r?.signal};(0,vl.D9)(Im,e,t.map(String),{...s,encoding:"utf8"},((e,t)=>{e?o(e):n(t)}))}))}Pm.w3.UNSPECIFIED,Pm.w3.LEFT,Pm.w3.MIDDLE,Pm.w3.RIGHT,Pm.w3.BACK,Pm.w3.FORWARD,Pm.Dh.UNSPECIFIED,Pm.Dh.UP,Pm.Dh.DOWN,Pm.Dh.LEFT,Pm.Dh.RIGHT;const Tm=(0,Ls.promisify)(yl.execFile);function Am(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 $m(e){const{stdout:t}=await(0,vl.D9)(Tm,"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:Am(r.width,r.height),resolutionString:`${r.width}x${r.height}`}}Pm.w3.UNSPECIFIED,Pm.w3.LEFT,Pm.w3.MIDDLE,Pm.w3.RIGHT,Pm.w3.BACK,Pm.w3.FORWARD,Pm.Dh.UNSPECIFIED,Pm.Dh.UP,Pm.Dh.DOWN,Pm.Dh.LEFT,Pm.Dh.RIGHT;const Mm={pattern:"[\\w-]{1,64}",next:e=>e},Dm={pattern:"[0-9a-f-]{36}",next:()=>ho.randomUUID()},Om={pattern:"webp",next:()=>"webp"},Fm={native:[Dm,Om],agent:[Mm,Dm,Om],legacyNative:[Dm,{pattern:"png",next:()=>"png"}]};new RegExp(`^(?:${Object.values(Fm).map((e=>e.map((e=>e.pattern)).join("\\."))).join("|")})$`),new RegExp(`^${Mm.pattern}$`),Pm.Z8.NATIVE_X11,Pm.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 Nm=r("../proto/dist/runtime/compact.js");Nm.HL;var Lm=(0,Nm.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 jm{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 Um={left_ptr:Lm.ARROW,arrow:Lm.ARROW,default:Lm.ARROW,top_left_arrow:Lm.ARROW,hand:Lm.POINTER,hand1:Lm.POINTER,hand2:Lm.POINTER,pointer:Lm.POINTER,pointing_hand:Lm.POINTER,xterm:Lm.TEXT,ibeam:Lm.TEXT,text:Lm.TEXT,watch:Lm.WAIT,wait:Lm.WAIT,progress:Lm.WAIT,left_ptr_watch:Lm.WAIT,crosshair:Lm.CROSSHAIR,cross:Lm.CROSSHAIR,tcross:Lm.CROSSHAIR,move:Lm.MOVE,fleur:Lm.MOVE,size_all:Lm.MOVE,sb_v_double_arrow:Lm.RESIZE_NS,v_double_arrow:Lm.RESIZE_NS,ns_resize:Lm.RESIZE_NS,row_resize:Lm.RESIZE_NS,top_side:Lm.RESIZE_NS,bottom_side:Lm.RESIZE_NS,sb_h_double_arrow:Lm.RESIZE_EW,h_double_arrow:Lm.RESIZE_EW,ew_resize:Lm.RESIZE_EW,col_resize:Lm.RESIZE_EW,left_side:Lm.RESIZE_EW,right_side:Lm.RESIZE_EW,top_left_corner:Lm.RESIZE_NWSE,bottom_right_corner:Lm.RESIZE_NWSE,nwse_resize:Lm.RESIZE_NWSE,size_fdiag:Lm.RESIZE_NWSE,top_right_corner:Lm.RESIZE_NESW,bottom_left_corner:Lm.RESIZE_NESW,nesw_resize:Lm.RESIZE_NESW,size_bdiag:Lm.RESIZE_NESW,not_allowed:Lm.NOT_ALLOWED,no_drop:Lm.NOT_ALLOWED,forbidden:Lm.NOT_ALLOWED,circle:Lm.NOT_ALLOWED,grab:Lm.GRAB,openhand:Lm.GRAB,grabbing:Lm.GRABBING,closedhand:Lm.GRABBING};class Bm{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 jm(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=Lm.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 Rm("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 Rm("xdotool",["getmouselocation","--shell"],{env:this.env})).match(/CURSOR=(\S+)/i);if(e){const t=e[1].toLowerCase();return Um[t]??Lm.ARROW}try{const e=await Rm("xprop",["-root","_XSERVER_CURSOR"],{env:this.env,timeoutMs:500});for(const[t,r]of Object.entries(Um))if(e.toLowerCase().includes(t))return r}catch{}return Lm.ARROW}catch{return Lm.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 Wm=r("node:net");function Hm(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 qm extends Error{constructor(e){super(e),this.name="MacRPCProtocolError"}}const zm=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(),Gm=Be.object({data:Be.string(),mimeType:Be.string().min(1)}).strip(),Vm=Be.object({message:Be.string(),screenshot:Gm.optional(),screenshotBefore:Gm.optional(),structuredContent:Be.unknown().optional(),isError:Be.boolean()}).strip(),Km=Be.object({accessibilityTrusted:Be.boolean(),screenRecordingGranted:Be.boolean()}).strip(),Jm=Be.union([Be.object({id:Be.number().int(),result:Vm,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:Km,result:Be.never().optional(),ok:Be.never().optional(),error:Be.never().optional(),errorCode:Be.never().optional(),sessionId:Be.never().optional()}).strip()]);function Zm(e,t){try{return JSON.parse(e)}catch{throw new qm(`local-cua ${t} is not valid JSON`)}}const Xm={responseMaxBytes:33554432,parseServiceState(e){const t=zm.safeParse(Zm(e,"service state")),r=t.success?t.data.rpcSocketPath??t.data.appControlSocketPath:void 0;if(!t.success||void 0===r)throw new qm("local-cua service state is malformed");return{...t.data,rpcSocketPath:r}},parseResponse({line:e,expectedID:t}){const r=Jm.safeParse(Zm(e.toString("utf8"),"RPC response"));if(!r.success)throw new qm("local-cua RPC response is malformed");if(void 0!==r.data.id&&null!==r.data.id&&r.data.id!==t)throw new qm("local-cua RPC response ID did not match");return r.data}};class Qm extends Error{constructor(e,t){super(e),this.name="MacComputerUseRPCError",this.code=t?.code,this.userFacing=!0===t?.userFacing,this.tool=t?.tool}}function Ym(e){return"object"==typeof e&&null!==e&&"code"in e&&"string"==typeof e.code?e.code:e instanceof Error?Hm(e.message)?e.name:e.message.length>0?`${e.name}: ${e.message}`:e.name:"unknown"}const eg=new Map([["co.anysphere.cursor-computer-use","cursor-computer-use"],["co.anysphere.cursor-computer-use.dev","cursor-computer-use-dev"]]),tg=/^[A-Za-z0-9][A-Za-z0-9._-]*$/;class rg{constructor(e){this.mode=e}static isInstalled(){if((0,yo.existsSync)(rg.serviceExecutablePath()))return!0;let e;try{e=Xm.parseServiceState((0,yo.readFileSync)(rg.serviceStatePath(),"utf8"))}catch{return!1}return void 0===e.pid||rg.isProcessAlive(e.pid)}static async runningHelperPid(){const e=await rg.readServiceState(),t=e?.pid;return void 0!==t&&rg.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!==rg.protocolMajor&&void 0!==e.pid&&!rg.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;rg.throwIfAborted(e.signal);const t=(0,ho.randomUUID)(),r=await this.sendWithRelaunchRetry(e,(()=>({id:rg.requestID,method:"control/start",requestID:t,mode:this.mode})),"control/start");if(void 0!==r.error)throw rg.rpcError(r);if(void 0===r.sessionId)throw new Qm("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 rg.readServiceState();if(void 0===e)return;const r=await rg.sendOnce(rg.socketPathFrom(e),{id:rg.requestID,method:"control/release",requestID:(0,ho.randomUUID)(),mode:this.mode,sessionId:t},rg.defaultCallTimeoutMs);if(void 0!==r.error)throw rg.rpcError(r)}catch(t){rg.logger.warn(e,"local-cua control release failed",{error:Ym(t)})}}}async callTool(e,t,r){rg.throwIfAborted(e.signal);const n=rg.defaultCallTimeoutMs,o=await this.sendWithRelaunchRetry(e,(()=>{const e=Date.now()/1e3,o=this.activeSessionId;return{id:rg.requestID,method:"tools/call",requestID:(0,ho.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 rg.rpcError(o,t);const s=o.result;if(void 0===s)throw new Qm(`local-cua tool ${t} returned no result`,{tool:t});if(s.isError){const e=s.message.trim();throw new Qm(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=rg.defaultCallTimeoutMs,o=await this.ensureSocketPath(e);rg.throwIfAborted(e.signal);try{return await rg.sendOnce(o,t(),n,e.signal)}catch(o){if(!rg.isPreDeliveryConnectionError(o))throw o;rg.logger.warn(e,"local-cua callTool failed; relaunching and retrying",{tool:r,error:rg.spawnErrorCode(o)});const s=await this.ensureSocketPath(e,!0);return rg.throwIfAborted(e.signal),void 0!==this.activeSessionId&&(this.activeSessionId=void 0,await this.startControl(e)),await rg.sendOnce(s,t(),n,e.signal)}}static rpcError(e,t){return new Qm(e.error,{code:e.errorCode,userFacing:!0,tool:t})}async ensureSocketPath(e,t=!1){if(rg.throwIfAborted(e.signal),!t){const e=await rg.readServiceState();if(e&&!rg.isExitedIncompatibleHelper(e))return rg.socketPathFrom(e)}await this.launchAndWait(e);const r=await rg.readServiceState();if(!r)throw new Qm("local-cua sidecar did not publish service.json after launch");return rg.socketPathFrom(r)}static setLaunchGuard(e){rg.launchGuard=e}async launchAndWait(e){const t=rg.serviceAppPath(),r=rg.launchGuard,n=()=>this.launchAppAndWait(e,t);await(void 0===r?n():r(t,n,e.signal))}async launchAppAndWait(e,t){rg.logger.info(e,"launching local-cua sidecar",rg.sidecarLaunchLogFields(t)),"1"===process.env[rg.directLaunchEnv]?await rg.spawnSidecarProcess(e,rg.serviceExecutablePath(),[],{detached:!0}):await rg.spawnSidecarProcess(e,"/usr/bin/open",["-g",t]);const r=Date.now()+rg.launchReadyTimeoutMs;for(;Date.now()<r;){rg.throwIfAborted(e.signal);const t=await rg.readServiceState();if(t&&!rg.isExitedIncompatibleHelper(t)){const r=rg.socketPathFrom(t);try{if("ok"in await rg.sendOnce(r,{id:rg.requestID,method:"ping"},2e3,e.signal))return}catch{}}await(0,Fr.cb)(rg.launchPollIntervalMs)}throw new Qm("local-cua sidecar did not become ready in time")}static isPreDeliveryConnectionError(e){const t=Ym(e);return"ENOENT"===t||"ECONNREFUSED"===t}static serviceStatePath(){return s.join(rg.helperIdentity().appSupportDirectory,"service.json")}static serviceAppPath(){const e=process.env[rg.serviceAppOverrideEnv];return e&&e.length>0?e:s.join(o.homedir(),...rg.sharedInstallRelativePath,`${rg.serviceAppBundleName}.app`)}static helperIdentity(){const e=rg.serviceAppPath(),t=process.env[rg.appSupportOverrideEnv],r=`${e}\0${t??""}`,n=rg.identityCache;if(n?.key===r)return n.identity;const i=function(e){let t;try{t=(0,yo.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&&tg.test(r.trim())?r.trim():void 0};return{executableName:r("CFBundleExecutable"),bundleIdentifier:r("CFBundleIdentifier")}}(e),a=s.join(e,"Contents","MacOS",i.executableName??rg.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:eg.get(i.bundleIdentifier))??rg.appSupportFolder)};return(0,yo.existsSync)(a)&&(rg.identityCache={key:r,identity:c}),c}static sidecarLaunchLogFields(e){const t=`${rg.serviceAppBundleName}.app`;return{appName:s.basename(e)===t?t:"custom",appPathHash:(0,ho.createHash)("sha256").update(e).digest("hex"),usingOverride:Boolean(process.env[rg.serviceAppOverrideEnv])}}static spawnErrorCode(e){return Ym(e)}static socketError(e){const t=Ym(e);return new Qm(`local-cua RPC connection failed: ${t}`,{code:t})}static serviceExecutablePath(){return rg.helperIdentity().executablePath}static spawnSidecarProcess(e,t,r,n){return new Promise(((o,s)=>{const i=(0,yl.spawn)(t,[...r],{detached:!0===n?.detached,stdio:"ignore"}),a=e=>{s(new Qm(`local-cua sidecar launch failed: ${rg.spawnErrorCode(e)}`))};i.once("error",a),i.once("spawn",(()=>{i.removeListener("error",a),i.on("error",(t=>{rg.logger.warn(e,"local-cua sidecar process error after launch",{error:rg.spawnErrorCode(t)})})),i.unref(),o()}))}))}static async readServiceState(){try{const e=await(0,go.readFile)(rg.serviceStatePath(),"utf8");return Xm.parseServiceState(e)}catch(e){if(e instanceof Error&&"code"in e&&"ENOENT"===e.code)return;if(e instanceof qm)return;throw new Qm("local-cua service state could not be read")}}static socketPathFrom(e){if(void 0!==e.protocolMajor&&e.protocolMajor!==rg.protocolMajor)throw new Qm(`The running Cursor Computer Use speaks protocol ${e.protocolMajor}, and this Cursor CLI speaks protocol ${rg.protocolMajor}. Update the Cursor CLI.`,{userFacing:!0});return e.rpcSocketPath}static abortError(e){return e.reason instanceof Error?e.reason:new Qm("local-cua RPC aborted")}static throwIfAborted(e){if(e.aborted)throw rg.abortError(e)}static sendOnce(e,t,r,n){return n?.aborted?Promise.reject(rg.abortError(n)):new Promise(((o,s)=>{let i=!1,a=[],c=0,l=!1;const u=(0,Wm.createConnection)({path:e}),d=e=>{i||(i=!0,clearTimeout(p),n?.removeEventListener("abort",h),u.destroy(),e())},h=()=>{d((()=>s(void 0===n?new Qm("local-cua RPC aborted"):rg.abortError(n))))},p=setTimeout((()=>{d((()=>s(new Qm(`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(rg.socketError(e))))}))})),u.on("data",(e=>{const t=e.indexOf(10),r=c+(t<0?e.length:t);if(r>Xm.responseMaxBytes)return void d((()=>s(new Qm("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=Xm.parseResponse({line:n,expectedID:rg.requestID});d((()=>o(e)))}catch(e){d((()=>s(e)))}})),u.on("error",(e=>{d(l?()=>s(new Qm("local-cua RPC connection failed after request delivery")):()=>s(rg.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 Qm(e))))})))}))}}let ng;function og(){if(void 0===ng){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 ng===e&&(ng=void 0),t}));ng=e}return ng}rg.logger=(0,d.h)("local-cua:rpc"),rg.serviceAppBundleName="Cursor Computer Use",rg.appSupportFolder="cursor-computer-use",rg.productionExecutableName="CUCursorService",rg.sharedInstallRelativePath=[".cursor","computer-use-sidecar"],rg.appSupportOverrideEnv="CUA_APP_SUPPORT_DIR",rg.serviceAppOverrideEnv="CUA_SERVICE_APP",rg.directLaunchEnv="CUA_DIRECT_LAUNCH",rg.protocolMajor=1,rg.defaultCallTimeoutMs=45e3,rg.launchReadyTimeoutMs=8e3,rg.launchPollIntervalMs=200,rg.requestID=1;var sg=r("node:module"),ig=r.t(sg,2);const ag="mac-webp-runtime.cjs";function cg(e){return"function"==typeof e}function lg(e){return"object"==typeof e&&null!==e&&"getFileName"in e&&"function"==typeof e.getFileName}function ug(){const e=(new Error).stack;return Array.isArray(e)?e.filter(lg):[]}let dg,hg;function pg(){return dg??=(()=>{const e=Error.prepareStackTrace;try{Error.prepareStackTrace=(e,t)=>t;const e=ug()[0]?.getFileName();return function(){const e=ig;if("createRequire"in e&&cg(e.createRequire))return e.createRequire;if("default"in e&&"object"==typeof e.default&&null!==e.default&&"createRequire"in e.default&&cg(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}})(),dg}function fg(){const e=globalThis.__MAC_WEBP_IMPORT__;return"function"==typeof e?t=>Promise.resolve(e(t)):(hg??=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 ug()){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,Lu.fileURLToPath)(n):n);r((0,s.join)(t,ag)),r((0,s.join)(t,"..","..","src","computer-use",ag))}var n;"string"==typeof process.argv[1]&&process.argv[1].length>0&&r((0,s.join)((0,s.dirname)(process.argv[1]),ag)),r((0,s.join)(process.cwd(),"src","computer-use",ag)),r((0,s.join)(process.cwd(),"computer-use",ag));try{const e=(0,s.dirname)(pg().resolve("@anysphere/local-exec/package.json"));r((0,s.join)(e,"src","computer-use",ag)),r((0,s.join)(e,"dist","computer-use",ag))}catch{}for(const t of e)try{const e=pg()(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")}(),hg)}function mg(...e){return t=["@jsquash","webp",...e].join("/"),pg().resolve(t);var t}async function gg(...e){var t;return await(t=(0,Lu.pathToFileURL)(mg(...e)).href,fg()(t))}const wg=e=>{let t;return()=>{if(void 0===t){const r=e();r.catch((()=>{t===r&&(t=void 0)})),t=r}return t}},yg=(wg((async()=>{const e=await gg("decode.js");return await e.init({wasmBinary:await yo.promises.readFile(mg("codec","dec","webp_dec.wasm"))}),e})),wg((async()=>{const[e,t,r]=await Promise.all([gg("utils.js"),gg("meta.js"),gg("codec","enc","webp_enc.js")]);return{module:await e.initEmscriptenModule(r.default,void 0,{wasmBinary:await yo.promises.readFile(mg("codec","enc","webp_enc.wasm"))}),defaultOptions:t.defaultOptions}}))),vg="image/png",bg={async normalize(e){if(e.mimeType!==vg)throw new Error(`Mac screenshot must be ${vg}, received ${e.mimeType}`);const t=await og(),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 yg(),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}},Sg={userFacing:function(e){if(e instanceof Qm&&e.userFacing&&e.message.trim().length>0&&!Hm(e.message))return e.message.trim()},isCaptureBlocked:function(e){return e instanceof Qm&&("computer_use_screenshot"===e.tool||"permission_required"===e.code)}},kg=new Set(["keys"]),_g=new Set(["matched","mismatch","unchecked"]),Cg=new Set(["no_text","password","control_keys","too_long","unreadable","moved","chromium","gecko"]),Eg=new Set(["matched"]),xg=new Set(["too_long"]),Pg=new Set(["watched","fell_back","unavailable","over_budget"]);class Ig{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??Sg,this.reportTyping=!0===o}async execute(){const e=this.actions.some((e=>Ig.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:Ig.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:Ig.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:Ig.mouseButtonName(t.value.button),action:"down"}));break;case"mouseUp":this.recordActuation(await this.sidecar.mouseButton(this.ctx,{button:Ig.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:Ig.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===Pm.EB.DOWN||t.value.stroke===Pm.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 Pm.ks({result:{case:"success",value:new Pm.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=Ig.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=Ig.cursorFromResult(e)??Ig.coordinateFromPoint(t)??this.cursor}recordTyping(e){if(!this.reportTyping)return;const t=e.message.trim();""!==t&&this.typingNotes.push(t);const r=Ig.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",_g),a=o("unchecked",Cg),c=void 0!==n.get("unchecked")&&null!==n.get("unchecked"),l=void 0!==i&&Eg.has(i)&&!c||"unchecked"===i&&void 0!==a&&xg.has(a);return new Pm.qA({method:o("method",kg)??"",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",Pg)})}async errorResult(e){let t;if(Ig.logger.error(this.ctx,"local-cua execute failed",void 0,{error:Ym(e)}),!this.errors.isCaptureBlocked(e))try{const e=await this.sidecar.screenshot(this.ctx);t=(await this.normalizeScreenshot(e.screenshot,"error")).data}catch(e){Ig.logger.warn(this.ctx,"local-cua error screenshot capture failed",{error:Ym(e)})}const r=this.errors.userFacing(e);return new Pm.ks({result:{case:"error",value:new Pm.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 Pm.ks({result:{case:"error",value:new Pm.Jb({error:"Screenshot unavailable",actionCount:this.actionCount,durationMs:Date.now()-this.startTime,log:e})}})}abortedResult(){return new Pm.ks({result:{case:"error",value:new Pm.Jb({error:"Computer use aborted",actionCount:this.actionCount,durationMs:Date.now()-this.startTime,log:this.log(),typing:this.typing})}})}static mouseButtonName(e){return Ig.mouseButtonNames[e]??"left"}static scrollDirectionName(e){return Ig.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 bg.normalize(e),failed:!1}}catch(r){const n=Ym(r);return Ig.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 Pm.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 Pm.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()}))}}Ig.logger=(0,d.h)("local-cua:actions"),Ig.mouseButtonNames={[Pm.w3.UNSPECIFIED]:"left",[Pm.w3.LEFT]:"left",[Pm.w3.RIGHT]:"right",[Pm.w3.MIDDLE]:"middle",[Pm.w3.BACK]:"left",[Pm.w3.FORWARD]:"left"},Ig.scrollDirectionNames={[Pm.Dh.UNSPECIFIED]:"down",[Pm.Dh.UP]:"up",[Pm.Dh.DOWN]:"down",[Pm.Dh.LEFT]:"left",[Pm.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 Rg,Tg=r("../proto/dist/generated/agent/v1/delete_exec_pb.js");function Ag({encoding:e,bom:t,lineEnding:r}){return{encoding:e,bom:t,lineEnding:r}}class $g{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,go.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 Oi(e,t,r,n);await(0,go.writeFile)(e,o),await Di(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"}(Rg||(Rg={}));var Mg=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 Dg{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 Tg.Pi({result:{case:"error",value:new Tg.GU({path:n,error:Go})}});const o=(0,zo.o1)(n,this.workspacePath),i=await this.permissionsService.shouldBlockWrite(e,o,"");if(i){const e=await du(i,{onNeedsApproval:async(e,t)=>null,onUserRejected:e=>new Tg.Pi({result:{case:"rejected",value:new Tg.iq({path:o,reason:e||""})}}),onPermissionDenied:(e,t)=>new Tg.Pi({result:{case:"permissionDenied",value:new Tg.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,go.realpath)((0,s.dirname)(e)).catch((()=>{}));if(void 0===r)return e;if(void 0!==t){const n=await(0,go.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:Rg.Delete,details:{path:a},toolCallId:t.toolCallId});if(!c.approved)return new Tg.Pi({result:{case:"rejected",value:new Tg.iq({path:o,reason:c.reason||""})}});let l;try{l=await(0,go.stat)(o)}catch(e){return"ENOENT"===Wa(e)?new Tg.Pi({result:{case:"fileNotFound",value:new Tg.n0({path:o})}}):new Tg.Pi({result:{case:"error",value:new Tg.GU({path:o,error:Ha(e)})}})}if(!l.isFile()){const e=l.isDirectory()?"directory":"other";return new Tg.Pi({result:{case:"notFile",value:new Tg.LX({path:o,actualType:e})}})}const u=l.size;let d,h;if(u<=Jo)try{const e=await Mi(o);d=e.text,h=Ag(e)}catch{}const p=d??"",f=await(0,go.realpath)(o).catch((()=>o)),m=await(0,go.stat)(o).catch((()=>{}));if(m?.dev!==l.dev||m.ino!==l.ino)return new Tg.Pi({result:{case:"error",value:new Tg.GU({path:o,error:"File changed while deleting; nothing was removed"})}});e.signal.throwIfAborted();try{await(0,go.unlink)(o),this.agentFileViews?.recordDelete(o)}catch(e){return"EACCES"===Wa(e)?new Tg.Pi({result:{case:"permissionDenied",value:new Tg.QG({path:o,clientVisibleError:"Permission denied"})}}):"EBUSY"===Wa(e)?new Tg.Pi({result:{case:"fileBusy",value:new Tg.vX({path:o})}}):new Tg.Pi({result:{case:"error",value:new Tg.GU({path:o,error:Ha(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 Tg.Pi({result:{case:"success",value:new Tg.fl({path:o,deletedFile:o,fileSize:BigInt(u),prevContent:p})}})}catch(e){r.error=e,r.hasError=!0}finally{Mg(r)}}}class Og{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===jn));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:jn,serverName:jn,instructions:`User-defined tools for this session (server "${jn}"). 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 Fg extends Og{constructor(e,t){super(e,t),this.observableInner=e}onDidChange(e){return this.observableInner.onDidChange(e)}}var Ng=r("../proto/dist/generated/agent/v1/fetch_exec_pb.js"),Lg=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 jg=/;\s*charset\s*=\s*"?([^";\s]+)/i;class Ug{constructor(e){this.encodingSlices=e?.encodingSlices}async readText(e,t){if(!el(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=jg.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{pl(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 Ng.uN({result:{case:"success",value:new Ng.Uk({url:n,content:r,statusCode:t.status,contentType:o})}})}catch(e){return new Ng.uN({result:{case:"error",value:new Ng.fk({url:n,error:Ha(e)})}})}}catch(e){r.error=e,r.hasError=!0}finally{Lg(r)}}}const Bg=[["safe.bareRepository","explicit"]],Wg=[["core.fsmonitor","false"],["core.hooksPath",o.devNull],["core.attributesFile",o.devNull]],Hg=[["core.quotePath","false"]];function qg(e){const t="allow-hooks"===e?Wg.filter((([e])=>"core.hooksPath"!==e)):Wg;return[...Bg,...t]}const zg=(0,Ls.promisify)(yl.execFile),Gg=new Set(["-c","-C","--git-dir","--work-tree","--namespace","--super-prefix","--config-env","--attr-source"]),Vg=new Set(["diff","show","blame","log","whatchanged"]);function Kg(e){for(let t=0;t<e.length;t++){const r=e[t];if(Gg.has(r))t++;else if(!r.startsWith("-"))return t}return-1}function Jg(e){const t=Kg(e);return-1===t?void 0:e[t]}function Zg(e){const t=Kg(e);if(-1===t||!Vg.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 Xg(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,[...qg(e.repoConfigExecution??"block"),...Hg])}({command:Jg(e),optionsEnv:t})}async function Qg(e,t,r){const{env:n,encoding:o="utf8",...s}=r??{},i=Zg(t),a=await zg(e,i,{...s,encoding:o,env:Xg(i,n)});return{stdout:a.stdout,stderr:a.stderr}}class Yg extends Error{constructor(e,t){super(`git did not run: repository config refused (${e})`),this.name="GitRepoConfigRefusedError",this.reason=e,this.exitCode=t}}const ew=new Map([["status",[!0,!0]],["diff",[!0,!0]],["worktree",[!0,!1]],["read-tree",[!0,!1]],["ls-files",[!0,!1]],["branch",[!1,!1]],["check-attr",[!1,!1]],["check-ignore",[!1,!1]],["config",[!1,!1]],["merge-base",[!1,!1]],["patch-id",[!1,!1]],["remote",[!1,!1]],["rev-parse",[!1,!1]],["show",[!1,!1]],["symbolic-ref",[!1,!1]],["write-tree",[!1,!1]]]),tw=["recurse-submodules","submodule","remerge-diff","diff-merges","alternate-refs"],rw=/^[A-Za-z0-9][A-Za-z0-9_-]*$/,nw=/^filter\.(.*)\.(?:clean|smudge|process)$/s,ow=new Set(["system","global","command"]),sw={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 iw(e){return e.flatMap((([e,t])=>["-c",`${e}=${t}`]))}const aw=iw([...qg("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 cw(e){const t=e?.timeout??0,r=Number.isFinite(t)&&t>0?Math.min(t,2147483647):6e4;return performance.now()+r}function lw(e,t=2147483647){return Math.max(1,Math.ceil(Math.min(t,e-performance.now())))}function uw(){const e=new Map;return{async exec(t,r,n){const o=cw(n);return Qg("git",await dw(e,t,r,o),{cwd:t,env:sw,windowsHide:!0,killSignal:"SIGTERM",timeout:lw(o)})},async run(t,r,n){const o=cw(n);return function(e,t,r,n){return new Promise(((o,s)=>{const i=function(e,t,r){const{env:n,...o}=r??{},s=Zg(t);return(0,yl.spawn)("git",s,{...o,env:Xg(s,n)})}(0,t,{cwd:e,env:sw,windowsHide:!0,stdio:[void 0===n?"ignore":"pipe","pipe","pipe"]}),a=[],c=[];let l=!1;const u=()=>{const e=!l;return l=!0,clearTimeout(d),e},d=setTimeout((()=>{u()&&(i.kill("SIGTERM"),i.stdin?.destroy(),i.stdout?.destroy(),i.stderr?.destroy(),s(Object.assign(new Error("git timed out"),{code:null,killed:!0,signal:"SIGTERM"})))}),lw(r));i.stdout?.on("data",(e=>{a.push(e)})),i.stderr?.on("data",(e=>{c.push(e)}));for(const e of[i.stdout,i.stderr])e?.on("error",(e=>{u()&&(i.kill("SIGTERM"),s(e))}));i.on("error",(e=>{u()&&s(e)})),i.on("close",((e,t)=>{u()&&(null!==e?o({exitCode:e,stdout:Buffer.concat(a).toString("utf8"),stderr:Buffer.concat(c).toString("utf8")}):s(Object.assign(new Error(`git was killed by ${String(t)}`),{code:e,killed:!1,signal:t})))})),void 0!==n&&null!==i.stdin&&(i.stdin.on("error",(()=>{})),i.stdin.end(n))}))}(t,await dw(e,t,r,o),o,n?.input)}}}async function dw(e,t,r,n){const{prefix:o,tail:s,readsConfig:i}=function(e){const t=Zg(e),r=Kg(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=ew.get(s);if(void 0===i)throw new TypeError(`git ${s} is refused: the pins cover only a fixed set of verbs`);const[a,c]=i,l=o.find((e=>function(e,t,r){const n=r.startsWith("--")?r.slice(2).split("=",1)[0]:"",o=[...tw,..."status"===e?["verbose"]:[],..."worktree"===e?["checkout","no-force"]:[],...t?["ignore-submodules","no-ignore-submodules"]:[]];return""!==n&&o.some((e=>e.startsWith(n)))||"status"===e&&/^-[^-]*v/.test(r)}(s,c,e)));if(void 0!==l)throw new TypeError(`git ${s} ${l} is refused: it can start a program the pins miss`);const u=t.slice(r+1),d="worktree"===s?u.find((e=>!e.startsWith("-"))):void 0;if("remove"===d&&!o.includes("--force")&&!o.includes("-f"))throw new TypeError("git worktree remove is refused without --force");if("add"===d&&"--no-checkout"!==u[u.indexOf("add")+1])throw new TypeError("git worktree add is refused unless --no-checkout follows add");return{prefix:[...t.slice(0,r),...aw],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 Qg("git",[...t,"config","--list","--show-scope","--includes","-z"],{cwd:e,env:sw,windowsHide:!0,killSignal:"SIGTERM",timeout:lw(r,1e4),maxBuffer:16777216})).stdout}catch(e){throw function(e){if(!(e instanceof Error))return new Yg("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 Yg("timed-out");const t="code"in e&&"number"==typeof e.code?e.code:void 0;return new Yg("read-failed",t)}(e)}if(performance.now()>=r)throw new Yg("timed-out");return function(e){if(""===e)return[];const t=e.split("\0");if(""!==t.pop()||t.length%2!=0)throw new Yg("read-failed");const r=new Set;for(let e=0;e<t.length;e+=2){if(ow.has(t[e]))continue;const n=t[e+1].split("\n",1)[0],o=nw.exec(n)?.[1];if(void 0!==o){if(!rw.test(o))throw new Yg("unpinnable");r.add(o)}else(n.startsWith("lfs.extension.")||"lfs.storage"===n)&&r.add("lfs")}return[...r].sort().flatMap((e=>iw([[`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 hw(e,t,r){return uw().exec(e,t,r)}var pw=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class fw{async exec(e,t,r,n){return mw(e,t,r,n,hw)}forRequest(){const e=uw();return{exec:(t,r,n,o)=>mw(t,r,n,o,((t,r,n)=>e.exec(t,r,n)))}}}async function mw(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{pw(s)}}var gw=r("../proto/dist/generated/agent/v1/grep_exec_pb.js");class ww{constructor(){this.lineEnd=0,this.nextStart=0}}function yw(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 vw(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 bw=-(2**31),Sw=2**31-1;function kw(e){return Number.isNaN(e)?0:e<bw?bw:e>Sw?Sw:e}function _w(e){if("number"==typeof e&&Number.isFinite(e)&&!(e<0))return kw(Math.trunc(e))}function Cw(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 Ew(e,t){const r=Cw(t),n=(0,s.join)(e,"mcps",r,"tools");let o;try{o=await(0,go.readdir)(n)}catch(e){if("ENOENT"===Wa(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,go.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 xw=(0,d.h)("local-exec:mcp-disk-freshness-on-access"),Pw="/mcps/",Iw=(0,h.Pu)("mcp.discovery_freshness.check",{description:"MCP discovery surface freshness comparison outcome against canonical live tools",labelNames:["surface","outcome"]}),Rw=(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"]}),Tw=(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"]}),Aw=(0,h.v5)("mcp.discovery_freshness.symmetric_difference",{description:"Total symmetric difference between canonical live tools and the observed discovery surface",labelNames:["surface"]}),$w=new Map;function Mw(e){const t=e.replace(/\\/g,"/");return t.endsWith("/mcps")?`${t}/`:t}async function Dw({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 xw.warn(e,"mcp_disk_state_read_failed",{error_type:t instanceof Error?t.name:typeof t})}const a=i.servers.find((e=>Cw(e.serverIdentifier)===n));if(void 0===a)return;let c;try{c=await o(r,a.serverIdentifier)}catch(t){return void xw.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"};Iw.increment(e,1,{...l,outcome:c}),Rw.histogram(e,i.length,l),Tw.histogram(e,a.length,l),Aw.histogram(e,i.length+a.length,l),"mismatch"===c&&xw.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 Ow(e,t,r,n=Ew){if(void 0===r||(void 0===(o=r)||!Mw(o).includes(Pw)))return;var o;const s=function(e){const t=Mw(e),r=t.indexOf(Pw);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=$w.get(i);void 0!==l&&clearTimeout(l);const u=e,d=setTimeout((()=>{$w.delete(i),(async()=>{if(c){const e=await t.getState(u);for(const r of e.servers){const o=Cw(r.serverIdentifier);await Dw({ctx:u,mcpStateAccessor:t,projectDir:s.projectDir,sanitizedServerFolder:o,readDiskCatalog:n,state:e})}}else void 0!==a&&await Dw({ctx:u,mcpStateAccessor:t,projectDir:s.projectDir,sanitizedServerFolder:a,readDiskCatalog:n})})().catch((e=>{xw.warn(u,"mcp_disk_discovery_freshness_schedule_failed",{error_type:e instanceof Error?e.name:typeof e})}))}),2e3);$w.set(i,d)}async function Fw(e){try{return(await(0,go.stat)(e,{bigint:!0})).mtimeNs}catch{return}}function Nw(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 Lw(e,t,r=Fw){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:Nw(n,o,s.sep).map((({item:e})=>e)),statTimedOut:!1}}var jw=r("../proto/dist/generated/agent/v1/read_exec_pb.js");const Uw=Buffer.from([137,80,78,71,13,10,26,10]),Bw=Buffer.from([0,0,0,0,73,69,78,68,174,66,96,130]),Ww=e=>{if(e.length<Uw.length+25+Bw.length||!e.subarray(0,Uw.length).equals(Uw)||13!==e.readUInt32BE(8)||"IHDR"!==e.toString("ascii",12,16)||!(e=>e.subarray(e.length-Bw.length).equals(Bw)||(e=>{let t=Uw.length+25;for(;t+Bw.length<=e.length;){const r=e.readUInt32BE(t);if(r>e.length-t-Bw.length)return!1;if("IEND"===e.toString("ascii",t+4,t+8))return e.subarray(t,t+Bw.length).equals(Bw);t+=Bw.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)}},Hw=e=>1===e||e>=208&&e<=216,qw=e=>192===e||193===e||194===e,zw=e=>e>=195&&e<=207&&196!==e&&200!==e&&204!==e,Gw=e=>0===e||e>=208&&e<=215,Vw=(e,t)=>{let r=e.indexOf(255,t);for(;-1!==r&&r+1<e.length;){const t=e[r+1];if(255!==t){if(!Gw(t))return r;r=e.indexOf(255,r+2)}else r+=1}},Kw=e=>(e=>{const t=Ww(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(Hw(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=Vw(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(Hw(r)){t+=2;continue}if(218===r||217===r||zw(r))return;const n=e.readUInt16BE(t+2);if(n<2)return;if(qw(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),Jw=(e,t)=>({width:Math.max(e?.width??0,t.width),height:Math.max(e?.height??0,t.height)}),Zw=(e,t)=>{for(;t<e.length&&0!==e[t];)t+=1+e[t];return t+1},Xw=e=>{const t=e.toString("latin1",0,6);return e.subarray(0,Uw.length).equals(Uw)?"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},Qw={0:1,2:3,4:2,6:4},Yw=({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}`)}}},ey=({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]]++}},ty=({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)},ry={0:1,2:3,3:1,4:2,6:4},ny=[1,2,4,8,16],oy=[[0,0,8,8],[4,0,8,8],[0,4,4,8],[2,0,4,4],[0,2,2,4],[1,0,2,2],[0,1,1,2]],sy=async e=>{const t=iy(e);if(void 0===t)return;const r=ay(t);let n=0;const o=zh.Readable.from(t.idat).pipe((0,Vh.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`)},iy=e=>{let t;const r=[];let n=8;for(;n+12<=e.length;){const o=e.readUInt32BE(n),s=e.toString("ascii",n+4,n+8),i=e.subarray(n+8,n+8+o);if("IHDR"===s&&void 0===t&&13===i.length){const e=ry[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}},ay=({width:e,height:t,bitsPerPixel:r,interlaced:n})=>{const o=(e,t)=>e<=0||t<=0?0:t*(1+Math.ceil(e*r/8));return n?oy.reduce(((r,[n,s,i,a])=>r+o(Math.ceil((e-n)/i),Math.ceil((t-s)/a))),0):o(e,t)};const cy=()=>{throw new Error("webp codec not registered: registerWebpCodec() must be called by a Node server before decoding/encoding webp")},ly=e=>e.length>=12&&"RIFF"===e.toString("ascii",0,4)&&"WEBP"===e.toString("ascii",8,12),uy=e=>{if(!ly(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)}}},dy=e=>cy().decode(e);async function hy(e){((e,t)=>{if(!Number.isSafeInteger(e)||e<1||e>t)throw new Error("pngByteBudgetBytes must be a positive integer at most MAX_IMAGE_SIZE_BYTES")})(e.budgetBytes,e.maxImageBytes);Kw(e.data);return e.resizeWithoutBudget(e.data)}const py=[{width:1280,height:800},{width:1456,height:840}],fy=1048576,my=e=>{const t=e.buffer;return t instanceof ArrayBuffer?new Uint8Array(t,e.byteOffset,e.byteLength):Uint8Array.from(e)};function gy(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 wy=(e,t,r=1024)=>gy(e,t,r),yy=(e,t,r)=>{e.resize({w:t,h:r})};function vy(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 by=(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:vy(((e,t)=>{switch(t){case"png":return(e=>{let t,r=Uw.length;for(;r+16<=e.length;)"IHDR"===e.toString("ascii",r+4,r+8)&&(t=Jw(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 Jw(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=Zw(e,n+2);else{if(33!==e[n]||255!==e[n+1])break;r=11===e[n+2]?Zw(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))}},Sy=(e,t)=>{if(t)return{width:e.width,height:e.height};const{width:r,height:n}=wy(e.width,e.height,1280);return{width:r,height:n}},ky=async(e,t)=>{let{width:r,height:n}=e,o=await t({width:r,height:n});for(;o.length>fy&&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:my(o),mimeType:"image/webp",reencoded:!0}};const _y=async(e,t)=>{if(void 0!==t?.pngByteBudgetBytes){const{pngByteBudgetBytes:r,...n}=t;return hy({data:e,budgetBytes:r,maxImageBytes:fy,fitImage:gy,resizeWithoutBudget:e=>_y(e,n)})}if(ly(e))return(async(e,t)=>{const r=uy(e);if(!0===t?.preserveWebpDimensions&&void 0!==r)return{data:my(e),mimeType:"image/webp"};const n=void 0!==r&&py.some((e=>e.width===r.width&&e.height===r.height));if(void 0!==r&&(n||!wy(r.width,r.height,1280).needsResize)&&e.length<=fy)return{data:my(e),mimeType:"image/webp"};if("passthrough"===t?.webpWithoutCodec)return{data:my(e),mimeType:"image/webp"};vy(r);const o=void 0;if(void 0!==o)return ky(Sy(r,n),(t=>o({data:e,...t})));const s=await dy(e),i=(await og()).fromBitmap({data:Buffer.from(s.data),width:s.width,height:s.height});return ky(Sy(i.bitmap,n),(async e=>{return i.bitmap.width===e.width&&i.bitmap.height===e.height||yy(i,e.width,e.height),t={data:i.bitmap.data,width:i.bitmap.width,height:i.bitmap.height},cy().encode(t);var t}))})(e,t);const r=Kw(e);if(void 0!==r&&e.length<=fy&&!wy(r.width,r.height).needsResize)return{data:my(e),mimeType:r.mimeType};const n=Xw(e);void 0!==n&&by(e,n);const o=void 0===r?void 0:wy(r.width,r.height),s="image/png"===r?.mimeType&&!0===o?.needsResize?await(async({data:e,width:t,height:r})=>{const n=(e=>{let t;const r=[];let n=8;for(;n+12<=e.length;){const o=e.readUInt32BE(n),s=e.toString("ascii",n+4,n+8),i=e.subarray(n+8,n+8+o);if(i.length!==o)return;if("IHDR"===s){const e=Qw[i[9]];if(void 0!==t||13!==o||8!==i[8]||0!==i[12]||void 0===e)return;t={width:i.readUInt32BE(0),height:i.readUInt32BE(4),channels:e}}else if("IDAT"===s)r.push(i);else{if("tRNS"===s)return;if("IEND"===s)break}n+=o+12}return void 0===t||0===r.length?void 0:{...t,idat:r}})(e);if(void 0===n||t>n.width||r>n.height)return;const o=n.width*n.channels,s=new Uint32Array(n.width);for(let e=0;e<n.width;e++)s[e]=Math.floor(e*t/n.width);const i=new Float64Array(4*t),a=new Uint32Array(t),c=Buffer.alloc(t*r*4);let l=new Uint8Array(o),u=new Uint8Array(o),d=-1,h=0,p=0;const f=zh.Readable.from(n.idat).pipe((0,Vh.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;Yw({filter:d,row:u,previous:l,bytesPerPixel:n.channels}),ey({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||ty({out:c,outY:g,width:t,sums:i,counts:a}),[l,u]=[u,l],d=-1,h=0}if(p===n.height)break}return p===n.height?{data:c,width:t,height:r}:void 0})({data:e,width:o.width,height:o.height}).catch((()=>{})):void 0;void 0===s&&"png"===n&&await sy(e);const i=await og(),a=void 0===s?await i.read(e):i.fromBitmap(s),c=(e=>{switch(e.mime){case"image/png":default:return"image/png";case"image/bmp":return"image/bmp";case"image/tiff":return"image/tiff";case"image/x-ms-bmp":return"image/x-ms-bmp";case"image/gif":return"image/gif";case"image/jpeg":return"image/jpeg"}})(a),l=!0===t?.convertUnsupportedModelFormatsToPng&&"image/png"!==c&&"image/jpeg"!==c?"image/png":c,{width:u,height:d,needsResize:h}=wy(a.width,a.height);if(void 0===s&&!h&&e.length<=fy&&l===c)return{data:my(e),mimeType:c};let p=u,f=d;h&&yy(a,p,f);let m=await a.getBuffer(l);for(;m.length>fy&&p>8&&f>8;)p=Math.max(8,Math.round(.8*p)),f=Math.max(8,Math.round(.8*f)),yy(a,p,f),m=await a.getBuffer(l);return{data:my(m),mimeType:l,reencoded:!0}},Cy=async e=>{const t=Buffer.from(e.buffer,e.byteOffset,e.byteLength),r=Xw(t);let n;if(ly(t))return{kind:"unchecked"};if(void 0===r)return{kind:"unchecked"};{by(t,r);const e=await og();n=async()=>("png"===r&&await sy(t),e.read(t))}try{return await n(),{kind:"decodes"}}catch(e){return{kind:"undecodable",reason:e instanceof Error?e.message:String(e)}}},Ey=BigInt(0),xy=BigInt(8),Py=BigInt(16),Iy=BigInt(65535);function Ry(e){const t=e.trim().toLowerCase();return t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t}function Ty(e){const t=e.split(".");if(4!==t.length)return;let r=Ey;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<<xy|BigInt(t)}return{version:4,value:r}}function Ay(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=Ty(n);if(!o)return;t.push(Number(o.value>>Py&Iy)),t.push(Number(o.value&Iy))}else{if(!/^[0-9a-f]{1,4}$/i.test(n))return;t.push(Number.parseInt(n,16))}}return t}function $y(e){return Ty(e)??function(e){const t=Ry(e);if(0===t.length||t.includes(":::"))return;const r=t.indexOf("::");if(-1===r){const e=Ay(t);if(!e||8!==e.length)return;return{version:6,value:e.reduce(((e,t)=>e<<Py|BigInt(t)),Ey)}}if(-1!==t.indexOf("::",r+1))return;const n=t.slice(0,r),o=t.slice(r+2),s=Ay(n),i=Ay(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<<Py|BigInt(t)),Ey)}}(e)}function My(e,t){const r=Ry(e),n=Ry(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=$y(t.slice(0,r)),o=$y(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 Dy(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=>My(e,t)))}(r.hostname,t)}new Set([1,2]);const Oy="cursor/requiresConfirmation",Fy="https://grok.com/connectors-oauth-exchange-code/",Ny="https://x.com/i/connectors/oauth_callback",Ly="https://chat.x.com/connectors/oauth_callback",jy="https://lite.x.com/i/connectors/oauth_callback",Uy={provider:"google-workspace",clientRegistration:"static",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!0,authorizationParams:{access_type:"offline",prompt:"select_account consent"}},By={provider:"x-money",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0,registeredAppRedirectUris:[Fy,Ny]},Wy="x-cursor-auth";function Hy(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 qy="https://mcp.shop.com",zy={provider:"grok-connectors",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,scopes:["grok-plugins:access","offline_access"]},Gy=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/}]]),Vy=new Map([["gmailmcp.googleapis.com",{...Uy,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",{...Uy,scopes:["https://www.googleapis.com/auth/drive.readonly","https://www.googleapis.com/auth/drive.file"]}],["calendarmcp.googleapis.com",{...Uy,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",{...Uy,scopes:["https://www.googleapis.com/auth/documents"]}],["sheetsmcp.googleapis.com",{...Uy,scopes:["https://www.googleapis.com/auth/spreadsheets"]}],["slidesmcp.googleapis.com",{...Uy,scopes:["https://www.googleapis.com/auth/presentations"]}],["bigquery.googleapis.com",{...Uy,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",By],["mcp.money-staging.x.com",By],["mcp.money.x.com",By],["connectors-gateway.grok.gcp.mouseion.dev",zy],["connectors-gateway.grok.com",zy],["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:qy}}],["api.elections.kalshi.com",{provider:"kalshi",clientRegistration:"dynamic",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!0}],["mcp.squarespace.com",{provider:"squarespace",clientRegistration:"dynamic",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!0}]]),Ky=[".databricks.com",".azuredatabricks.net"];const Jy=/^\/sncapps\/mcp-server\/mcp\/[^/]+$/,Zy={provider:"databricks",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,requiresHostedCallback:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0,scopes:["ai-gateway","offline_access"],pinsScopesOverConfiguredScopes:!0},Xy={provider:"servicenow",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,unauthenticatedEndpointBlocked:!0,backendOnlyTokenExchange:!0,ownMcpJsonClientMayExchange:!0};function Qy(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("."))&&Ky.some((e=>t.endsWith(e)&&t.length>e.length))}(e.hostname)&&"/ai-gateway/mcp-services/system.ai.genie_one_mcp"===e.pathname.replace(/\/+$/,"")}(t)?Zy:function(e){return"https:"===e.protocol&&""===e.port&&""===e.username&&""===e.password&&Jy.test(e.pathname.replace(/\/+$/,""))}(t)?Xy:(r=t.hostname,Vy.get(r.toLowerCase()));var r}function Yy(e){return e.endsWith("/")?e:`${e}/`}async function ev(e,t){if(void 0===t)return;const r=new URL(e),n=new URL(t);if(r.origin!==n.origin||!Yy(r.pathname).startsWith(Yy(n.pathname)))throw new Error(`Protected resource ${t} does not match expected ${r.href} (or origin)`);return n}const tv=/^\/shops\/[A-Za-z0-9-]+\/mcp$/;function rv(e){if(void 0!==e)try{return new URL(e)}catch{return}}async function nv(e,t){if(void 0===t)return;const r=new URL(e),n=rv(t);if(void 0===n||n.origin!==r.origin||n.pathname!==r.pathname&&!tv.test(n.pathname))throw new Error(`Protected resource ${t} does not match expected ${r.href} (or origin)`);return n}function ov(e){const t=rv(e);return void 0===t?void 0:Gy.get(t.hostname.toLowerCase())}const sv=new Set([...Vy].filter((([,e])=>"google-workspace"===e.provider)).map((([e])=>e))),iv="https://www.cursor.com/bot/mcp/oauth/callback",av={portal:"https://www.cursor.com/agents/mcp/oauth/callback",grokBotBounce:iv},cv="tailnet_";new Set([`${cv}waiting_for_approval`,`${cv}tailnet_locked`,`${cv}joining`]);const lv="grokbot://mcp/oauth/callback",uv="http://localhost:8787/callback",dv="gb";function hv(e){const t=new URL(uv);return t.port=String(e),t.toString()}function pv(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 fv(e){const t=e.redirectUrl??uv;if(!0!==e.loopbackIpv4||!pv(t))return t;const r=new URL(t);return r.hostname="127.0.0.1",r.toString()}function mv(e,t=av){const r=new Set,n=void 0!==e&&pv(e);return e&&!n&&r.add(e),r.add(t.portal),e===lv&&r.add(t.grokBotBounce),r.add(uv),e&&n&&r.add(e),Array.from(r)}function gv(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 wv(e){if(void 0===e)return{};const t={};"string"==typeof e.title&&e.title.length>0&&(t.title=jo(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?.[Oy]}(e)&&(t[Oy]=!0),0===Object.keys(t).length?{}:{annotationsJson:JSON.stringify(t)}}new Map([[dv,lv],["gw",Fy],["gd",uv],["xa",Ny],["xc",Ly],["xl",jy],...[18787,28787,31787].map((e=>[`gd${e}`,hv(e)]))]),new Map([[lv,dv],[iv,dv],[Fy,"gw"],[Ny,"xa"],[Ly,"xc"],[jy,"xl"]]),fv({loopbackIpv4:!0});var yv=r("../mcp-core/dist/transport/mcp-url-utils.js");function vv(e){return e.trim().toLowerCase()}const bv="<no-mcp-tool-allowed>";function Sv({mode:e,tools:t}){const r=(t??[]).map(vv).filter((e=>e.length>0)),n=void 0===e?void 0:vv(e);return"all"===n?{mode:"all"}:"reads"===n?{mode:"reads"}:r.length>0?{mode:"custom",tools:r}:{mode:"all"}}function kv(e,t){switch(e.mode){case"all":return!0;case"custom":return function(e,t){const r=vv(e);return 0!==r.length&&r!==bv&&t.some((e=>vv(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 _v(e,t){switch(t.mode){case"all":return[`${e}:*`];case"custom":return t.tools.filter((e=>vv(e)!==bv)).map((t=>`${e}:${t}`));case"reads":return[];default:return t}}const Cv=new Set(["ash","bash","csh","dash","fish","ksh","powershell","pwsh","sh","tcsh","zsh","cmd"]);function Ev(e){return e.trim().split(/\s+/).filter(Boolean)}function xv(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 Ev(t)[0]}(e);if(!t)return!1;const r=t.replace(/^["']|["']$/g,"").replaceAll("\\","/").split("/"),n=(r[r.length-1]??"").replace(/\.exe$/i,"").toLowerCase();return Cv.has(n)}function Pv(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 Iv(e,t){return e.commandName.localeCompare(t.commandName)}function Rv(e){return e.split(" ")[0]??e}function Tv(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=Ev(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(Iv);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=Pv(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&&Pv(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(Rv(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(Rv(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(Rv(e.id))}}if(0===o.length)return{defaultSelectedOptionIds:n,hasClassifierSuggestions:!1};const i=n.filter((e=>!s.has(Rv(e))));return{defaultSelectedOptionIds:[...new Set([...i,...o])],hasClassifierSuggestions:!0}}(e,t).defaultSelectedOptionIds}const Av=["com.todesktop.230313mzl4w4u92","co.anysphere.cursor","com.anysphere.molten-glass"],$v=["cursor","molten glass"];function Mv(e){return Av.some((t=>e===t||e.startsWith(`${t}.`)))}const Dv=[{bundleId:"com.apple.scripteditor2",name:"Script Editor"},{bundleId:"com.apple.automator",name:"Automator"},{bundleId:"com.apple.shortcuts",name:"Shortcuts"}],Ov=[{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"},...Dv,{bundleId:Av[0],name:"Cursor"}];function Fv(e){const t=e.toLowerCase(),r=(0,s.basename)(e,".app").toLowerCase(),n=Ov.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}:Mv(t)?{bundleId:t,name:"Cursor"}:[t,r].some((e=>$v.some((t=>e===t||e.startsWith(`${t} `)))))?{bundleId:Av[0],name:"Cursor"}:void 0}const Nv=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 Lv(e){return Nv.has(e.toLowerCase())}function jv(e){return`app/${e}`}function Uv(e){return"object"==typeof e&&null!==e}function Bv(e){return Hv.includes(e)}function Wv(e){if(!Uv(e))return;const{appArg:t,appSelectorArgs:r,capturesScreen:n}=e;if("boolean"==typeof n){if(void 0!==r){if(void 0!==t||!Uv(r))return;const e={};for(const[t,n]of Object.entries(r)){if(!Bv(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 Hv=["pid","bundleId","path","appName"],qv=/^[+-]?\d+$/;var zv=r("../../node_modules/.pnpm/diff@8.0.3/node_modules/diff/libesm/patch/create.js");const Gv=".cursor/worktrees",Vv=".grok/build-desktop/worktrees",Kv="win32"===process.platform||"darwin"===process.platform,Jv=new Map;function Zv(e,t){if(!(0,zo.BJ)(t,e))return;const r=(Kv?(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 Xv(e,t){const r=Zv(e,t);if(void 0!==r)return r;const n=function(e){if(Jv.has(e))return Jv.get(e);const t=[];let r,n=e;for(;;)try{const e=yo.realpathSync.native(n);r=0===t.length?e:(0,s.join)(e,...t);break}catch(e){const r=Wa(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 Jv.size>=64&&Jv.clear(),Jv.set(e,r),r}(e);var o,i;return void 0!==n&&(o=n,i=e,Kv?o.toLowerCase()!==i.toLowerCase():o!==i)?Zv(n,t):void 0}function Qv(e){const t=e?.trim();return t&&".cursor"!==t?[".cursor",t]:[".cursor"]}function Yv(e,t){const r=(0,o.homedir)();return Qv(t?.dataFolderName).some((t=>void 0!==Xv((0,s.join)(r,t,"projects"),e)))}function eb(e){const t=(0,o.homedir)();return[Gv,Vv].some((r=>void 0!==Xv((0,s.join)(t,...r.split("/")),e)))}function tb(e,t,r){const n=function(e,t){const r=(0,o.homedir)();for(const n of Qv(t?.dataFolderName)){const t=Xv((0,s.join)(r,n,"projects"),e);if(void 0!==t&&t.length>=2)return t[1]}}(e,r);return void 0!==n&&(Kv?t.some((e=>e.toLowerCase()===n.toLowerCase())):t.includes(n))}function rb(e,t,r){const n=Xv(e,t);if(void 0===n)return!1;const o=n[0];return Kv?r.some((e=>e.toLowerCase()===o.toLowerCase())):r.includes(o)}const nb=/[\s"'`=/\\:;()[\]{},&|<>]/,ob="win32"===process.platform||"darwin"===process.platform;async function sb(e,t,r,n){const o=db(await ub((0,s.join)(e,"gitdir")),"");if(void 0===o)return;const i=(0,s.resolve)(e,o);if(".git"!==(0,s.basename)(i)||(0,Ns.$f)(i))return;const a=(0,s.dirname)(i);if(r&&eb(a))return;const c=await hb(i);if(void 0===c)return;const l=(0,s.dirname)(c);if(r&&eb(l))return;if(void 0!==n&&(u=fb(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=ob?e.toLowerCase():e,n=ob?t.toLowerCase():t;let o=0;for(;;){const e=r.indexOf(n,o);if(-1===e)return!1;const t=0===e||nb.test(r[e-1]),s=e+n.length,i=s===r.length||nb.test(r[s]);if(t&&i)return!0;o=e+1}}(d,t)})))))return;var u,d,h;const p=await lb(i,c);return void 0!==p&&fb(p.commonDir,t)?l:void 0}async function ib(e,t){const r=await(0,go.readdir)(e).catch(pb);return void 0===r?[]:r.sort().slice(0,t)}function ab(e,t){return t.some((t=>(0,zo.BJ)(t,e)))}async function cb(e){for(let t=e;;t=(0,s.dirname)(t)){if((0,Ns.$f)(t))return;const e=(0,s.join)(t,".git"),r=await(0,go.lstat)(e).catch(pb);if(r?.isFile())return(await lb(e))?.commonDir;if(r?.isDirectory())return e;if(void 0!==r||(0,s.dirname)(t)===t)return}}async function lb(e,t){const r=db(await ub(e),"gitdir: ");if(void 0===r)return;const n=await hb((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=db(await ub((0,s.join)(n,"commondir")),"");if(void 0===i)return;const a=await hb((0,s.resolve)(n,i));if(void 0===a||!fb(a,o))return;const c=db(await ub((0,s.join)(n,"gitdir")),"");if(void 0===c)return;const[l,u]=await Promise.all([hb((0,s.resolve)(n,c)),t??hb(e)]);return void 0!==l&&void 0!==u&&fb(l,u)?{commonDir:o,realDotGit:u}:void 0}async function ub(e){const t=await(0,go.lstat)(e).catch(pb);if(void 0!==t&&t.isFile()&&!(t.size>4096))return(0,go.readFile)(e,"utf8").catch(pb)}function db(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 hb(e){if(!(0,Ns.$f)(e))return(0,go.realpath)(e).catch(pb)}function pb(e){const t=Wa(e);if(void 0===t||t.startsWith("ERR_"))throw e}function fb(e,t){return ob?e.toLowerCase()===t.toLowerCase():e===t}function mb(e,t,r){return{resolvedPath:e,originalPath:t,resolution:r}}function gb(e){const t=Wa(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:Ha(e)}}}async function wb(e,t){const r=(0,zo.o1)(e,t);try{return mb(await(0,go.realpath)(r),r,{status:"resolved"})}catch(e){if("ENOENT"!==Wa(e))return mb(r,r,gb(e));try{if((await(0,go.lstat)(r)).isSymbolicLink()){let e=null;try{e=await(0,go.readlink)(r)}catch{}return mb(r,r,{status:"danglingSymlink",symlinkTarget:e})}try{return mb(await(0,go.realpath)(r),r,{status:"resolved"})}catch(e){if("ENOENT"!==Wa(e))return mb(r,r,gb(e))}return mb(r,r,{status:"unknownError",errno:"ENOENT",message:"realpath returned ENOENT but lstat found a non-symlink entry"})}catch(e){return"ENOENT"===Wa(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,go.realpath)(t);return mb((0,s.join)(n,...r),e,{status:"newFile"})}catch(t){if("ENOENT"!==Wa(t))return mb(e,e,gb(t))}r.unshift((0,s.basename)(t)),t=(0,s.dirname)(t)}return mb(e,e,{status:"newFile"})}(r):mb(r,r,gb(e))}}}function yb(e){return"resolved"===e.status||"newFile"===e.status}function vb(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 bb({realAbsolutePath:e,setting:t,resolvedWorkspaceRoots:r,resolvedAllowFolders:n,resolvedAllowGlobs:o}){return!("workspace"!==t.boundary||Sb(e,r)||Sb(e,n)||_b(e,t.allowPaths)||_b(e,o))}function Sb(e,t){return t.some((t=>(0,zo.BJ)(e,t)))}function kb(e){return e.flatMap((e=>{const t=(0,zo.jl)(e.trim());return!t.includes("*")&&(0,s.isAbsolute)(t)?[(0,s.resolve)(t)]:[]}))}function _b(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))&&cs(r(t),n)}))}const Cb={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 Eb(e){const t=[];let r=!0,n=!1,o=e;for(;;){const e=Cb[s.posix.basename(o.name)];if(void 0===e)return{command:o,wrapperForms:t,allowlistable:r,readsArguments:n};const i=xb(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||!Ab(a))return{command:o,wrapperForms:t,allowlistable:!1,readsArguments:n};(o.name.includes("/")||o.args.slice(0,i).some((t=>Pb(t,e)||Ib(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 xb(e,t){let r=0;for(;r<e.length;){const n=e[r];if(Pb(n,t))break;if(void 0===n||!Ab(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=Rb(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(Tb))return"unreadable";for(r=n;r<e.length&&Pb(e[r],t);)r++;return r<e.length?r:"none"}function Pb(e,t){return!0===t.assignments&&/^[A-Za-z_][A-Za-z0-9_]*=/.test(e?.value??"")}function Ib(e,t){return(t.directoryOptions??[]).some((t=>t.startsWith("--")?e===t||e.startsWith(`${t}=`):/^-[^-]/.test(e)&&e.includes(t.slice(1))))}function Rb(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 Tb(e){return"raw_string"===e.type||!/[$`]/.test(e.value)&&("string"===e.type||!/[*?[]|\{[^}]*(,|\.\.)/.test(e.value))}function Ab(e){return("word"===e.type||"number"===e.type)&&!/[$`]/.test(e.value)}const $b=/(?<![\w-])(?:rm|rmdir|rd|del|erase|ri|remove-item)(?![\w-])/i,Mb=/\s(?:-[dfiv]*r[dfiv]*|--recursive|-recurse|-recurs|-recur|-recu|-rec|-re)(?![\w-])/i;function Db(e,t,r){const n=t.exec(e);return null!==n&&r.test(e.slice(n.index+n[0].length))}var Ob=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},Fb=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 Nb=(0,d.h)("permissions-service"),Lb=(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"]}),jb=(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"]}),Ub=/[\p{Cc}\p{Bidi_Control}\p{Cs}]/gu,Bb=/^[\p{M}\p{Cf}\p{Default_Ignorable_Code_Point}\s]+/u,Wb=/[^\p{M}\p{Cf}\p{Default_Ignorable_Code_Point}\s\u2800]/u;function Hb(e,t){for(const r of[e?.title,t?.title]){if("string"!=typeof r)continue;const e=jo(r,1024).replace(Ub," ").replace(/\s+/g," ").replace(Bb,"").trim(),t=jo(e,256).trimEnd();if(Wb.test(t))return t}}function qb(e,t){return{toolTitle:Hb(e,t),destructiveHint:"boolean"==typeof t?.destructiveHint?t.destructiveHint:void 0}}function zb(e){return Promise.all(e.map((async e=>{const t=await wb(e);return yb(t.resolution)?t.resolvedPath:(0,zo.o1)(e)})))}function Gb(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 Vb(e){return[...new Set(e)]}function Kb(){return{fdTargets:new Map([[0,"original-stdin"],[1,"original-stdout"],[2,"original-stderr"]])}}function Jb({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 Zb(e){return">"===e||">>"===e||">|"===e||"&>"===e||"&>>"===e}function Xb(e){return"<"!==e.operator&&"<&"!==e.operator}function Qb(e){if(void 0===e||e.trim()!==e)return;const t=Number(e);return Number.isInteger(t)&&t>=0?t:void 0}function Yb(e){return"<<"===e.operator&&"heredoc_redirect"===e.targetNodeType&&1===e.destinationFds.length&&0===Number(e.destinationFds[0])&&void 0!==e.targetText}function eS(e,t){return!(/^=|[~*?[{(#^`]/.test(e)||"\\"!==t.sep&&e.includes("\\"))}function tS(e){return"word"===e.type||"number"===e.type?eS(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 rS({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(tS);return t?[...r,void 0]:r}async function nS({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(!yb(a.resolution))return;const c=[];for(const e of r){const t=await o(e);yb(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,Po.OK)(e,r).catch((()=>!0)))return!0;return!1}({targetPath:a.resolvedPath,rootPaths:c,pathModule:s})?void 0:c.some((e=>Jb({basePath:e,targetPath:a.resolvedPath,pathModule:s})))?"workspace-file":n&&!(0,Po.dA)(a.originalPath)&&gS(a.resolvedPath,i)?"tmp-file":void 0}async function oS({parsingResult:e,workingDirectory:t,rootDirectories:r,allowTmpRedirects:n}){for(const s of e.executableCommands.map(Eb).flatMap(rS))if("/dev/null"!==s&&(void 0===s||!await nS({targetText:s,workingDirectory:t,rootDirectories:r,allowTmpRedirects:n,resolvePathForPermissions:wb,pathModule:i,tempPathOptions:{platform:process.platform,env:process.env,pathModule:i,homeDirectory:(0,o.homedir)()}})))return!1;return!0}function sS(e){return Vb(e.map((e=>e.trim())).filter(Boolean))}function iS(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 aS(e,t){const r=t.trim();return!!r&&e.some((e=>e===r||e.startsWith(`${r} `)))}function cS(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 lS(e,t={}){return{type:e,...t}}function uS(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 dS(...e){return e.filter((e=>void 0!==e)).join(" • ")}function hS(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 pS(e,t){if("workspace"===e&&void 0!==t)return t}const fS={workspace:0,system:1};function mS(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 gS(e,{platform:t,env:r,pathModule:n,homeDirectory:o}){if((0,Po.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||!Jb({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 wS(e,t){if("insecure_none"===t.type)return!0;if("insecure_none"===e.type)return!1;const r=(0,Po.$b)(e.networkPolicy),n=(0,Po.$b)(t.networkPolicy);if(r&&!n)return!1;const o=(0,Po._B)(e.networkPolicy),s=(0,Po._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!(fS[i]>fS[a])}function yS(e){return{wrapperForms:e.flatMap((e=>e.wrapperForms)),allowlistable:e.every((e=>e.allowlistable)),readsArguments:e.some((e=>e.readsArguments))}}function vS(e){return[...e.wrapperForms,e.command.fullText.trim()].filter(Boolean)}class bS{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&&wS(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||!wS(this.requestedPolicy,e)||(this.state="allowlisted")}deny(){this.state="denied"}isRunnable(){return"preapproved"===this.state||"allowlisted"===this.state}}function SS(e){return e?.type??"undefined"}const kS=["skills","skills-cursor","rules","plugins"],_S=["assets","agent-notes","agent-tools","swarm-agents"];async function CS(e,t,r){return e.shouldBlockFileRead?.(t,r)??e.shouldBlockRead(t,r)}function ES(e){const t=e.lastIndexOf("::mcpScope:");return-1===t?e:e.slice(0,t)}function xS({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 PS=/^\s*Read\s*\((.*)\)\s*$/,IS=/^\s*Write\s*\((.*)\)\s*$/;class RS{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&&bb({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:hS(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 zb([...kb(e),...(0,Po.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 zb(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,po.r_)(e)))),...kS.map((e=>(0,s.join)(t,e)))],n=this.rootDirectories.flatMap((e=>(0,Po.W1)(e)??[]));return zb([...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 za(n);if(null===o)return{type:"unsafeResolution",message:Gb("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&&!eb(o)&&!Yv(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(Sb(e,n))return!1;const[o,s]=await Promise.all([this.resolvedReadAllowFolders(r.allowPaths),this.resolvedReadAllowGlobs(r.allowPaths)]);return!!bb({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 wb(this.projectDir);return!!yb(r.resolution)&&rb(r.resolvedPath,e,t)}async isFreelyWritableOutsideWorkspace(e,t){return function(e){return gS(e,{platform:process.platform,env:process.env,pathModule:i,homeDirectory:(0,o.homedir)()})}(e)||tb(e,_S,{dataFolderName:t})||await this.isProjectDirInternalPath(e,_S)}async shouldBlockWrite(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{Ob(n,(0,D.VI)(e.withName("InteractivePermissionsService.shouldBlockWrite")),!1).ctx;const i=await wb(t);if(!yb(i.resolution))return{type:"unsafeResolution",message:vb(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,Po.dA)(i.originalPath)||(0,Po.dA)(a))return{type:"permissionsConfig"};const d=await this.getPermissions();if(!eb(c)&&!Yv(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 $i(a),e=!1}catch{e=!0}if(e)t=r;else{const e=e=>e.endsWith("\n")?e:`${e}\n`,{hunks:o}=(0,zv.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 wb(e);if(yb(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,Ns.$f)(o))return;const e=(0,s.join)(o,".git"),i=await(0,go.lstat)(e).catch(pb);if(i?.isFile()){const s=await lb(e);if(void 0!==s){const{commonDir:e}=s;if(ab(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=>cb(e)))),n)).some((t=>void 0!==t&&fb(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,Po.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{Fb(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 za(t.workingDirectory);if(null===o){if(!0!==t.skipUnsafeWorkingDirectoryBlock)return{kind:"block",reason:{type:"unsafeResolution",message:Gb("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(Nb.info(e,"Shell permissions: evaluating shell command",{toolCallId:r.toolCallId,approvalMode:a,userConfiguredPolicyType:SS(l),requestedPolicyType:SS(n),effectiveRequestedPolicyType:SS(n??l),smartAllowlistEnabled:!0===i.smartAllowlistEnabled,hasSmartModeApprovalReason:void 0!==r.smartModeApprovalReason,hasSmartModeApprovalRequestId:void 0!==r.smartModeApprovalRequestId,hookForcesPrompt:Co(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 Nb.info(e,"Shell permissions: prompting for empty allowlist",{toolCallId:r.toolCallId,approvalMode:a,userConfiguredPolicyType:SS(l),requestedPolicyType:SS(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(Eb),b=w?w.map(cS):v.map((e=>e.command)),S=void 0!==w?w.map(iS):b.map((e=>[e.fullText.trim()].filter(Boolean))),k=void 0!==g?g.commands.map(iS):v.map(vS);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,Po.$b)(l.networkPolicy)&&"insecure_none"!==n.type&&!(0,Po._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,Po.XX)(e.readBoundary,t.readBoundary),n="workspace"===r?(0,Po.wG)(pS(e.readBoundary,e.additionalReadPaths),pS(t.readBoundary,t.additionalReadPaths)):void 0;return{...e,readBoundary:r,additionalReadPaths:n}}({requestedPolicy:n,userConfiguredPolicy:l}),p&&Nb.info(e,"Smart allowlist: classifier result received",{classificationFailed:p.classificationFailed,suggestedSandboxMode:p.suggestedSandboxMode,commandCount:p.commands.length,suggestedAllowlistEntryCount:p.commands.filter((e=>e.suggestedAllowlistEntry)).length});const C=[],E=[];let x=[],P=[],I=[];const R=sS(i.smartAllowlistDenylist??[]);if(R.length>0){P=[];const t=k.map((e=>e[0]??""));for(let e=0;e<k.length;e++){const r=k[e];if(r&&0!==r.length&&R.some((e=>aS(r,e)))){const r=t[e];r&&P.push(r)}}P.length>0&&(Nb.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)));Nb.info(e,"Smart allowlist: checking commands against lists",{commandCount:t.length,allowlistCount:r.length,commandBlocklistCount:R.length});const n=S.map((e=>r.some((t=>e.some((e=>this.matchesShell(t,e))))))),o=n.every(Boolean),s=[];for(let e=0;e<p.commands.length;e++){if(n[e])continue;const t=p.commands[e];t&&s.push(t)}if(x=sS(s.flatMap((e=>function(e){const t=e.name.trim();if(!t)return[];if(xv(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),sS(o)}(e)))),I=s.map((e=>e.suggestedAllowlistEntry)).filter((e=>"string"==typeof e)).filter((e=>x.includes(e))),x.length>0){const e=Tv(x,I),t=e.length>0?e.join(", "):x.join(", ");E.push(`Not in allowlist: ${t}`)}_=o&&0===P.length,_&&Nb.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=yS(v),$=b.map(((e,t)=>new bS(e,n,T,S[t],y?A:v[t])));if((0===b.length||h&&!y)&&!c){Nb.info(e,"Shell permissions: prompting after parser miss",{toolCallId:r.toolCallId,approvalMode:a,requestedPolicyType:SS(n),userConfiguredPolicyType:SS(l),isSmartAllowlistActive:y,parsingFailed:h,parserCommandCount:b.length,hasSmartModeApprovalReason:void 0!==f,hasSmartModeApprovalRequestId:void 0!==m});const o={type:Rg.Shell,toolCallId:r.toolCallId,details:{command:t,workingDirectory:r.workingDirectory,timeout:r.timeout,reason:dS(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 Nb.info(e,"Shell permissions: blocked by readonly mode"),{kind:"block",reason:{type:"permissionsConfig",isReadonly:!0}};const j=Co(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&&$b.test(r)||Db(r,$b,Mb)||Db(r,/(?<![\w-])(?:rmdir|rd|del|erase)(?![\w-])/i,/\/s(?![\w-])/i)||Db(r,/(?<![\w-])find(?![\w-])/i,/\s-delete\b/i))return!0;e||=Db(r,/(?<![\w-])(?:get-childitem|gci|ls|dir)(?![\w-])/i,Mb)}}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&&Nb.info(e,"Shell permissions: all commands allowed by sandbox policy");const t=await this.applyServerAndAdminPolicies(W);return Nb.info(e,"Shell permissions: auto-approved shell command",{toolCallId:r.toolCallId,approvalMode:a,requestedPolicyType:SS(n),userConfiguredPolicyType:SS(l),autoApprovalPolicyType:SS(W),mergedPolicyType:SS(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=Tv(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(", ");Nb.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=dS(...G,await this.adminNetworkLimitReason(Z)),Q=[];if(z){const e=void 0!==f?$.filter((e=>"allowlisted"!==e.state)):L.unapprovedCommands;Q.push(...this.generateAllowlistPatterns(e))}const Y=y&&E.length>0,ee=Y?x:Q,te=Y&&I.length>0?I:void 0,re="insecure_none"!==n.type&&"insecure_none"!==l.type,ne="insecure_none"!==n.type,oe=[void 0!==f?"smart_mode_approval":void 0,j?"hook_forces_prompt":void 0,B?"unsandboxed_recursive_delete":void 0,C.length>0?"command_blocklist":void 0,y&&E.length>0?"smart_allowlist_miss":void 0,L.unapprovedCommands.length>0?"unapproved_commands":void 0,L.hasSecurityDenies?"security_denies":void 0,K?"team_allowlist_miss":void 0].filter((e=>void 0!==e));Nb.info(e,"Shell permissions: requesting shell approval",{toolCallId:r.toolCallId,approvalMode:a,requestedPolicyType:SS(n),userConfiguredPolicyType:SS(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:Rg.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(Eb),d=l?c.commands.map(cS):u.map((e=>e.command));if(0===d.length)return!1;const h=l?c.commands.map(iS):d.map((e=>[e.fullText.trim()].filter(Boolean))),p=void 0!==c?c.commands.map(iS):u.map(vS),f={type:"insecure_none"},m=yS(u),g=d.map(((e,t)=>new bS(e,f,void 0,h[t],l?m:u[t])));if(await this.hasHardDeny(n,g))return!1;const w=sS(o.smartAllowlistDenylist??[]);if(w.length>0)for(const e of p)if(e&&0!==e.length&&w.some((t=>aS(e,t))))return!1;if(await this.teamSettingsService.getDeleteFileProtection()&&g.some((e=>"rm"===e.command.name)))return!1;const y=await this.teamSettingsService.getAutoRunControls();if(void 0!==y&&g.some((e=>this.isInTeamBlocklist(y,e))))return!1;for(const e of g)if(!await this.cmdIsAllowedByAllowlist(e,{redirectsAllowlistSafe:i,autoRunControls:y,applyTeamAllowlist:s}))return!1;return!0}async applyServerAndAdminPolicies(e){if("insecure_none"===e.type)return e;const t=this.rootDirectories.at(0)??(0,o.homedir)(),{userSandboxDataFolderName:r,teamAdminPolicy:n}=await this.getPermissions(),i=void 0!==r&&r.length>0?(0,s.join)((0,o.homedir)(),r,"sandbox.json"):this.perUserSandboxConfigPath,a=await this.foldPerUserFilePolicy(e,i),c=a.skipStatsigDefaults?a:await this.applyStatsigDefaults(a),l=await this.loadPerRepoFilePolicy(c.type,t),u=await this.resolveTeamAdminLayer(n);if("unavailable"===u){const{policy:e}=await(0,Po.resolveSandboxPolicyForWorkspace)(t,{perUser:c,perRepo:l});return function(e){return"insecure_none"===e.type?e:{...e,networkPolicy:(0,Po.Po)(),readBoundary:"workspace",additionalReadPaths:[]}}(e)}const d=void 0===u?void 0:lS(c.type,u),h=(0,Po._B)(e.networkPolicy)&&!uS(d?.networkPolicy),{policy:p}=await(0,Po.resolveSandboxPolicyForWorkspace)(t,{perUser:c,perRepo:l,teamAdmin:d});return h?{...p,networkPolicy:(0,Po.T6)()}:p}async resolveLinkedWorktreeSandboxGrants(e,t){if("workspace_readwrite"!==e.type||"workspace"===e.readBoundary)return;const{perms:r,setting:n}=await this.readControlSetting();if("workspace"===n.boundary||"unavailable"===r.teamAdminPolicy)return;const i=r.userSandboxDataFolderName;if(void 0===e.readBoundary){const t=this.rootDirectories.at(0)??(0,o.homedir)(),n=void 0!==i&&i.length>0?(0,s.join)((0,o.homedir)(),i,"sandbox.json"):this.perUserSandboxConfigPath,a="readBoundary"in r.userConfiguredPolicy&&void 0!==r.userConfiguredPolicy.readBoundary?{...e,readBoundary:r.userConfiguredPolicy.readBoundary}:e,[c,l]=await Promise.all([this.foldPerUserFilePolicy(a,n),this.loadPerRepoFilePolicy(e.type,t)]);if("workspace"===(l?.readBoundary??c.readBoundary))return}const a=[];for(const e of this.rootDirectories){if((0,Ns.$f)(e))continue;const t=await wb(e);yb(t.resolution)&&!eb(t.resolvedPath)&&a.push(t.resolvedPath)}if(0===a.length)return;let c;if(!(0,Ns.$f)(t.workingDirectory)){const e=await wb(t.workingDirectory);yb(e.resolution)&&(c=e.resolvedPath)}return async function(e,t={}){if(0===e.length)return;const r=await Promise.all(e.map((e=>cb(e)))),n=[];for(const o of r)void 0===o||n.some((e=>fb(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 ib((0,s.join)(r,"worktrees"),256),c=await(0,Fr.PH)(n,(e=>sb((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=>fb(e,r)))||e.some((e=>(0,zo.BJ)(r,e)))||ab(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,Po.tv)(t,(0,o.homedir)());if(!r||"insecure_none"===r.type)return e;let n=(0,Po.fZ)(r.networkPolicy,e.networkPolicy);n&&void 0!==e.networkPolicy?.default&&(n={...n,default:e.networkPolicy.default});const s=(0,Po.s9)(r.additionalReadonlyPaths,e.additionalReadonlyPaths),i={...e,networkPolicy:n,additionalReadonlyPaths:s.length>0?s:void 0,readBoundary:r.readBoundary??e.readBoundary,additionalReadPaths:void 0!==r.additionalReadPaths?r.additionalReadPaths:e.additionalReadPaths};if("workspace_readwrite"===e.type&&"workspace_readwrite"===r.type){const t=(0,Po.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,Po._B)(e.networkPolicy))return e;const r={default:"deny",allow:Vb(t.allowlist)};return{...e,networkPolicy:(0,Po.fZ)(e.networkPolicy,r)}}async loadPerRepoFilePolicy(e,t){const r=await(0,Po.tv)((0,s.join)(t,".cursor","sandbox.json"),t);if(r&&"insecure_none"!==r.type)return r.type!==e?lS(e,{networkPolicy:r.networkPolicy,additionalReadonlyPaths:r.additionalReadonlyPaths,..."additionalReadwritePaths"in r?{additionalReadwritePaths:r.additionalReadwritePaths}:{},disableTmpWrite:r.disableTmpWrite,networkPolicyStrict:r.networkPolicyStrict,readBoundary:r.readBoundary,additionalReadPaths:r.additionalReadPaths}):r}async resolveTeamAdminLayer(e){return void 0!==e?"unavailable"===e?"unavailable":"workspace"===(t=e).readBoundary?t:void 0===t.networkPolicy?{}:{networkPolicy:t.networkPolicy}:async function(e){const{teamSettings:t}=e,r=e.adminNetworkControlsEnabled?(i=await t.getNetworkAccessControls()).available?0!==i.allowlist.length||0!==i.denylist.length?{...i.allowlist.length>0?{default:"deny",allow:Vb(i.allowlist)}:{},...i.denylist.length>0?{deny:Vb(i.denylist)}:{}}:void 0:(0,Po.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,Po._B)(e.networkPolicy))return;const{teamAdminPolicy:t}=await this.getPermissions(),r=await this.resolveTeamAdminLayer(t);return function(e){if(uS(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,Po.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=wb,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=Kb();for(const e of l){if(Yb(e))continue;const o=u?Kb():d,{operator:i,targetText:l}=e,p=e.destinationFds;if(">&"===i){const e=Qb(l),t=void 0===e?void 0:o.fdTargets.get(e);if("original-stdout"!==(h=t)&&"original-stderr"!==h&&"dev-null"!==h&&"workspace-file"!==h&&"tmp-file"!==h){for(const e of p)o.fdTargets.set(e,"unsafe");return!1}for(const e of p)o.fdTargets.set(e,t);continue}if("<&"===i){const e=Qb(l),t=void 0===e?void 0:o.fdTargets.get(e);if("dev-null"!==t){for(const e of p)o.fdTargets.set(e,"unsafe");return!1}for(const e of p)o.fdTargets.set(e,t);continue}if("/dev/null"===l){for(const e of p)o.fdTargets.set(e,"dev-null");continue}if(!Zb(i)||void 0===l||"word"===e.targetNodeType&&!eS(l,a)){for(const e of p)o.fdTargets.set(e,"unsafe");return!1}const f=await nS({targetText:l,workingDirectory:t,rootDirectories:r,allowTmpRedirects:n,resolvePathForPermissions:s,pathModule:a,tempPathOptions:c});if(!f){for(const e of p)o.fdTargets.set(e,"unsafe");return!1}for(const e of p)o.fdTargets.set(e,f)}var h;return!0}({parsingResult:e,workingDirectory:t,rootDirectories:this.rootDirectories,allowTmpRedirects:r}),l=await oS({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(Xb))}({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:Rg.Shell,toolCallId:t.toolCallId,details:{command:e,workingDirectory:t.workingDirectory,timeout:t.timeout,reason:dS(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 oS({parsingResult:t,workingDirectory:e.workingDirectory,rootDirectories:this.rootDirectories,allowTmpRedirects:!0})?[]:this.generateAllowlistPatterns(t.executableCommands.map(Eb))}async getAdminCommandDenylistBlock(e,t){const r=(await this.teamSettingsService.getAdminCommandDenylist()).rules;if(0===r.length)return;const n=ps({matchForms:t.parsingResult?ls({command:t.command,parsingResult:t.parsingResult}):[t.command],blockedCommands:r});return void 0!==n?(Nb.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!==mS(e)}isPathEntry(e,t){return new RegExp(`^\\s*${e}\\s*\\(`).test(t)}matchesShell(e,t){const r=mS(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&&!xv(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?PS:IS}(e));if(r)return(r[1]??"").trim()}compileReadDenyMatcher(e){try{const t=this.pathEntryRawPattern("Read",e);if(void 0===t)return()=>!1;const r=function(e){const{trimmedPattern:t,regexSource:r}=as(e);let n;try{n=new RegExp(r)}catch{return e=>t===e}return e=>{try{return n.test(e)}catch{return t===e}}}((0,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 cs(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{Ob(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:gv(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=xS({server:ES(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,...qb(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,...qb(r,l),providerIdentifier:a,args:c,canAllowlist:_,allowlistEntry:b,computerUseApp:S}}}catch(e){o.error=e,o.hasError=!0}finally{Fb(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 jb.increment(e,1,{reason:"outside_limit"}),"Your team's admin limits this MCP tool";case"settings_unavailable":return jb.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 jb.increment(e,1,{reason:"unknown_server"}),"Your team's MCP rules could not be checked for this MCP server, so this MCP tool can't run right now";default:return n}}async judgeMcpAdminToolLimit(e,t){if("unresolved"===e)return"unknown_server";const r=await(this.teamSettingsService.getMcpAdminToolLimit?.(e.client));if(void 0!==r)switch(r.kind){case"none":return;case"settings_unavailable":return"settings_unavailable";case"unknown_server":return"unknown_server";case"limit":return kv(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(ES(e.serverIdentifier||e.providerIdentifier),t);if(!1===n)return{kind:"notComputerUse"};const o=await async function(e,t){const r=Wv(e.meta?.["cursor/computerUseScope"])??Wv(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])=>Bv(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&&qv.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?Fv(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&&qv.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:Fv(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 Mv(t)?"Computer Use doesn't control Cursor itself, including its approval cards. Ask the user to do it instead.":Dv.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.":Ov.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=Lv(o.app.bundleId)?void 0:xS({server:r.serverId,tool:jv(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=ES(e);return!0===this.computerUse?.providerIdentifiers.has(t)}async isComputerUseDisabledByAdminFor(e){const t=this.computerUseAdminPolicy;return t?.providerIdentifiers.has(ES(e))?await t.isDisabledByAdmin():!!this.isComputerUseServer(e)&&!0===await(this.teamSettingsService.isComputerUseDisabledByAdmin?.())}allowComputerUseAppForSession({bundleId:e}){const t=void 0===this.computerUse||Lv(e)?void 0:xS({server:this.computerUse.serverId,tool:jv(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??gv(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=ES(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}){Lb.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&&My(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&&kv(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 TS=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 AS=65536,$S=1048576,MS=(0,d.h)("LocalReadExecutor"),DS=async(e,t,r,n)=>{const o=setTimeout((()=>{MS.warn(e,`[watchdog, LocalReadExecutor] ${t} still not completed after ${r}ms`)}),r);try{return await n()}finally{clearTimeout(o)}};function OS(e){return BigInt(Math.min(e,4294967295))}async function FS(e,t){if(0===t)return(0,go.readFile)(e);if(t>2147483647)throw new RangeError(`File size (${t}) is greater than 2 GiB`);const r=await(0,go.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 NS(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 LS(e){return e>=32&&e<=126||9===e||10===e||13===e}function jS(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&&LS(t)&&r++,0===t&&LS(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 US=Buffer.from("\n---\n");function BS(e,t){const r=e.length;if(r<2*US.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(US,r-US.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+US.length,r-4).toString("utf-8"))?o:r}const WS=[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 HS(e){return new jw.sV({result:{case:"invalidFile",value:new jw.cW({path:e,reason:"File content is binary data, not text"})}})}function qS(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=zS(s,e),c=zS(i,e);return{applied:!0,start:a,end:Math.max(a,c)}}function zS(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 GS(e){return-1===e.indexOf("\r\n")?e:e.replaceAll("\r\n","\n")}function VS(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 KS(e,t,r){const n=VS((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 JS(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=GS(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=jo(c,o)),{text:c,truncated:l}}function ZS(e,t,r,n){if(t>=r)return{text:"",truncated:!1};const o=Math.min(r,t+2*n+1);let s=GS(e.slice(t,o));const i=s.length>n||o<r;return s.length>n&&(s=jo(s,n)),s.length<e.length&&(s=pk(s)),{text:s,truncated:i}}function XS(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+jo(t,n),truncated:!0}:{text:e.text+t,truncated:e.truncated}}function QS(e,t){if(e.truncated)return e;const r=XS(e,t);return{text:r.text,truncated:r.truncated}}function YS(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=XS(n,"\n")),n=XS(n,o.text),o.truncated&&(n={text:n.text,truncated:!0})})),n}function ek(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 tk(e){return void 0===e.maxChars||void 0!==e.offset||void 0!==e.limit?js:Math.min(js,e.maxChars+2)}function rk(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 nk extends Error{constructor(){super("Invalid UTF-8 while streaming read"),this.name="InvalidUtf8Error"}}function ok(e){for(let t=1;t<=Math.min(3,e.length);t++){const r=e[e.length-t]??0;if(128!=(192&r))return sk(r)>t?t:0}return 0}function sk(e){return e>=240?4:e>=224?3:e>=192?2:1}class ik{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 nk}validate(e){let t=e;if(this.carry.length>0){const r=sk(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 nk;t=e.subarray(r)}const r=ok(t);if(!(0,n.isUtf8)(t.subarray(0,t.length-r)))throw new nk;this.carry=Buffer.from(t.subarray(t.length-r))}}function ak(e,t){const r=function({file:e,stats:t,format:r},n){return ek(n??zi(e,t)??r.encoding)}(e,t),n=function(e){const t=ek(e);return"utf8bom"===t?"utf8":t}(r);return"utf8"===n?{kind:"strictUtf8",cacheEncoding:"utf8"}:Us.encodingExists(n)?{kind:"iconv",decoderEncoding:n,cacheEncoding:r}:{kind:"strictUtf8",cacheEncoding:"utf8"}}function ck(e){const t=NS(e),r=BS(e,t);return"utf-8"!==jS(e.subarray(t,r))?"other_encoding":function(e){if((0,n.isUtf8)(e))return"utf8_valid";const t=rl(e);return t>0&&(0,n.isUtf8)(e.subarray(0,e.length-t))?"utf8_cut":"utf8_invalid"}(e)}async function lk(e,t){const r=t>0?Math.min(t,$S):$S,o=await FS(e,r);return o.length===t&&(0,n.isUtf8)(o)||ti(new Ls.TextDecoder("utf-8",{fatal:!1}).decode(o,{stream:o.length===$S&&o.length!==t}))?{kind:"lossyUtf8",cacheEncoding:"utf8"}:{kind:"iconv",decoderEncoding:"latin1",cacheEncoding:"latin1"}}async function uk(e){const t=await(0,go.stat)(e),r=await Fi(e);if(r.isBinaryFile)return;const n=ak({file:e,stats:t,format:r},void 0);if("iconv"===n.kind)return n.decoderEncoding;const o=await lk(e,t.size);return"iconv"===o.kind?o.decoderEncoding:void 0}async function dk(e,{file:t,stats:r},n,o,s){const i=r.size,a=void 0!==n.offset||void 0!==n.limit,c=(n.offset??1)<0,l=n.offset??1,u=Math.max(0,l-1),d=void 0===n.limit?void 0:u+n.limit,h=c?Math.abs(l):0,p=a?1/0:n.maxChars??1/0,f=a&&!c?n.maxChars??1/0:1/0;let m=[],g=0,w=!1,y=0,v=!1,b=!(c||a&&u<=0),S=!1;const k=[];let _,C=0,E=!1,x=0,P=!1,I=[],R=0,T=0,A=0,$=!1,M={text:"",truncated:!1},D=!1,O=!1,F=0,N=0,L=0,j=!1,U=!1;const B=e=>{let t=e;return!j&&t.length>0&&(j=!0,65279===t.charCodeAt(0)&&(U=!0,t=t.slice(1))),t},W=(e,t)=>t&&13===e.text.charCodeAt(e.text.length-1),H=()=>P||E&&C>=js,q=()=>v||w&&g>=js,z=(e,t)=>{if(H())return;const r=k.length>0?1:0;let n=js-C;if(r>0){if(n<=0)return void(E=!0);n--}const o=e.text.length>n?{line:{text:jo(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=js-g;if(r>0){if(n<=0)return void(w=!0);n--}const o=e.text.length>n?{line:{text:jo(e.text,n),truncated:!0},hasNewline:t}:{line:e,hasNewline:t};m.push(o),g+=r+(o.line.truncated?n:o.line.text.length),(e.truncated||o.line.truncated)&&(w=!0),W(o.line,t)&&y++,g-y>p&&(v=!0,_=F)},V=(e,t)=>{e&&(t?N++:L++),F++},K=()=>{const e=I[R];void 0!==e&&(A-=e.line.text.length+1),I[R]=void 0,R=(R+1)%I.length,T--},J=(e,t,r)=>{const n=F;if(0===n&&(S=0===e.text.length),!c&&a&&b&&n>=u&&(b=!1,m=[]),b&&G(e,t),c){if(h>0)for(T===h&&K(),(e=>{if(T===I.length){const e=new Array(Math.min(h,Math.max(16,2*I.length)));for(let t=0;t<T;t++)e[t]=I[(R+t)%I.length];I=e,R=0}I[(R+T)%I.length]=e,T++})({line:e,hasNewline:t}),A+=e.text.length+1;T>1&&A>js;)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-ok(e));return Q=new ik(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 Ls.TextDecoder("utf-8",{fatal:"strictUtf8"===r.kind,ignoreBOM:!0}),i=(0,yo.createReadStream)(t,{highWaterMark:AS,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 nk;throw e}return}const i=(0,yo.createReadStream)(t,{highWaterMark:AS,signal:e.signal,...s}).pipe(Us.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=QS(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=QS(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&&Gi(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)+AS,ae=e=>e.text.length>ie?{text:jo(e.text,ie),truncated:!0}:e,ce=()=>YS({text:"",truncated:w||se},m,re);if(!a){const e=ae(ce());return{content:e.text,totalLines:F,truncated:e.truncated,rangeApplied:!1}}if(F<=1&&S)return{content:"",totalLines:F,truncated:!1,rangeApplied:!1};if(c){const e=n.limit??h,t=[];for(let e=0;e<T;e++){const r=I[(R+e)%I.length];void 0!==r&&t.push(r)}let r={text:"",truncated:$};return r=YS(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(YS({text:"",truncated:E||se},k,re));return{content:le.text,totalLines:F,truncated:le.truncated,rangeApplied:!0}}class hk{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 jw.sV({result:{case:"error",value:new jw.F_({path:o,error:Go})}});const i=(0,zo.o1)(o,this.workspacePath),a=await DS(e,"permissionsService.shouldBlockFileRead",3e3,(()=>CS(this.permissionsService,i)));if(a){const r=await DS(e,"resolveFileReadBlock",3e3,(()=>async function(e,t){return await du(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:Rg.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 jw.sV({result:{case:"rejected",value:new jw.f4({path:i,reason:r.reason??""})}});if("denied"===r.kind)return new jw.sV({result:{case:"permissionDenied",value:new jw.lW({path:i})}})}void 0!==this.mcpStateAccessor&&Ow(e,this.mcpStateAccessor,i);try{const r=await DS(e,"stat",3e3,(()=>(0,go.stat)(i)));if(r.isDirectory())return new jw.sV({result:{case:"invalidFile",value:new jw.cW({path:i,reason:"Path is a directory, not a file"})}});if(!r.isFile())return new jw.sV({result:{case:"invalidFile",value:new jw.cW({path:i,reason:"Path is neither a file nor a directory"})}});const o=function(e){return null!==function(e){const t=Kh(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=Kh(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 DS(e,"getFormatForFile",3e3,(()=>Fi(i))),l=c.isImageFile,u=function(e){return".pdf"===(0,s.extname)(e).toLowerCase()}(i),d=Ti(i);if(l){const t=await DS(e,"prepareImageForModel",3e3,(async()=>(async e=>{let t;try{t=await _y(e)}catch(t){const r=await Cy(e);if("undecodable"===r.kind)return r;throw t}if(!0===t.reencoded)return{kind:"image",image:t};const r=await Cy(t.data);return"undecodable"===r.kind?r:{kind:"image",image:t}})(await(0,go.readFile)(i))));return"undecodable"===t.kind?new jw.sV({result:{case:"invalidFile",value:new jw.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 jw.sV({result:{case:"success",value:new jw.mE({path:i,output:{case:"data",value:t.image.data},totalLines:0,fileSize:OS(r.size),truncated:!1})}})}if(u){const t=await DS(e,"readPdfBinary",3e3,(()=>(0,go.readFile)(i)));return new jw.sV({result:{case:"success",value:new jw.mE({path:i,output:{case:"data",value:t},totalLines:0,fileSize:OS(r.size),truncated:!1})}})}if(c.isBinaryFile&&d){if(void 0!==t.maxVideoBytes&&r.size>t.maxVideoBytes)return new jw.sV({result:{case:"success",value:new jw.mE({path:i,totalLines:0,fileSize:OS(r.size),truncated:!0})}});const n=await DS(e,"readBinaryFile",3e3,(()=>(0,go.readFile)(i)));return new jw.sV({result:{case:"success",value:new jw.mE({path:i,output:{case:"data",value:n},totalLines:0,fileSize:OS(r.size),truncated:!1})}})}if(c.isBinaryFile)return HS(i);{const n=this.useStreamingRead,o=!n||await DS(e,"useStreamingRead",3e3,(()=>n()));if(o||r.size>js){const n=await DS(e,"readTextStreaming",7e3,(()=>async function(e,t,r,n){const o=ak(t,r.encodingHint);try{return{...await dk(e,t,r,o,n),decoder:o.kind}}catch(o){if(o instanceof nk){const o=await lk(t.file,t.stats.size);return{...await dk(e,t,r,o,n),decoder:o.kind}}throw o}}(e,{file:i,stats:r,format:c},t,o))),s=rk(n.content,n.truncated,t);return el(this.encodingSlices,e)&&this.recordStreamedRead(e,i,r.size,n,s),new jw.sV({result:{case:"success",value:new jw.mE({path:i,output:{case:"content",value:s},totalLines:n.totalLines,fileSize:OS(r.size),truncated:n.truncated,rangeApplied:n.rangeApplied})}})}const s=await DS(e,"readText",3e3,(()=>$i(i,t.encodingHint))),a=await DS(e,"countLines",3e3,(()=>Ws(s))),l=function(e,t,r){const n=qS(t,""===e,r);return n.applied?n.start>=n.end?{content:"",rangeApplied:!0}:{content:KS(e,n.start,n.end),rangeApplied:!0}:{content:e,rangeApplied:!1}}(s,a,t);let u=l.content,d=!1;const h=tk(t);return u.length>h&&(u=rk(u.substring(0,h),!0,t),d=!0),u.length<s.length&&(u=pk(u)),pl(this.encodingSlices,e,{layer:"exec_read"},u),new jw.sV({result:{case:"success",value:new jw.mE({path:i,output:{case:"content",value:u},totalLines:a,fileSize:OS(r.size),truncated:d,rangeApplied:l.rangeApplied})}})}}catch(e){const t=Wa(e);return"ENOENT"===t?new jw.sV({result:{case:"fileNotFound",value:new jw.Ko({path:i})}}):"EACCES"===t||"EPERM"===t?new jw.sV({result:{case:"permissionDenied",value:new jw.lW({path:i})}}):new jw.sV({result:{case:"error",value:new jw.F_({path:i,error:e instanceof Error?e.message:"Unknown error occurred"})}})}}catch(e){r.error=e,r.hasError=!0}finally{TS(r)}var n}async recordStreamedRead(e,t,r,o,s){try{const i=function(e){try{const t=new ll;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 FS(e,t),!(0,n.isAscii)(r)&&(0,n.isUtf8)(r)?"utf8_as_other":"other_encoding"}catch{return"other_encoding"}var r}(t,r)),fl(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 DS(e,"readTerminalFile",3e3,(()=>FS(t,r.size)));if(o&&(i=s,WS.some((e=>function(e,t){return e.length>=t.length&&e.subarray(0,t.length).equals(t)}(i,e)))))return HS(t);var i;const a=function(e,t,r=8388608){if(0===e.length)return{content:"",totalLines:1,rangeApplied:!1,truncated:!1};const n=NS(e),o=BS(e,n);if("utf-8"!==jS(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=qS(o,n,t);if(!s.applied){const t=ZS(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=VS((t=>e.indexOf("\n",t)),e.length,(t=>e.charCodeAt(t-1)),s.start,s.end,!0),a=ZS(e,i.from,i.to,r);return{content:a.text,totalLines:o,rangeApplied:!0,truncated:a.truncated}}(function(e){const t=NS(e),r=t>0?e.subarray(0,t).toString("utf-8"):"",n=BS(e,t),o=n<e.length?e.subarray(n).toString("utf-8"):"",s=e.subarray(t,n),i=jS(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=qS(s,o,r);if(!i.applied){if(o)return{content:"",totalLines:s,rangeApplied:!1,truncated:!1};const r=JS(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=VS((t=>e.indexOf(10,t)),e.length,(t=>e[t-1]??0),i.start,i.end,!0),c=JS(e,a.from,a.to,t,n);return{content:c.text,totalLines:s,rangeApplied:!0,truncated:c.truncated}}(e,s,t,r)}(s,n,tk(n)),c=rk(a.content,a.truncated,n);return el(this.encodingSlices,e)&&(o||this.terminalReads.firstRead(n.toolCallId,t))&&pl(this.encodingSlices,e,{layer:o?"exec_read":"exec_terminal_context",evidence:ck(s),partial:a.rangeApplied||a.truncated},c),new jw.sV({result:{case:"success",value:new jw.mE({path:t,output:{case:"content",value:c},totalLines:a.totalLines,fileSize:OS(r.size),truncated:a.truncated,rangeApplied:a.rangeApplied})}})}}function pk(e){return Buffer.from(e,"utf16le").toString("utf16le")}var fk=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},mk=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 gk(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 wk(e){return`Path '${e}' is neither a file nor a directory`}async function yk(e){const t=await(0,go.stat)(e).catch((()=>{}));return void 0!==t&&!t.isFile()&&!t.isDirectory()}function vk(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 bk extends Error{}function Sk(e){const t=new AbortController,r=setTimeout((()=>t.abort()),e);return{signal:t.signal,clear:()=>clearTimeout(r)}}function kk(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 _k(e){switch(e){case"content":return new gw.vD({result:{case:"content",value:new gw.Zp({ripgrepTruncated:!0})}});case"files_with_matches":return new gw.vD({result:{case:"files",value:new gw.T7({ripgrepTruncated:!0})}});case"count":return new gw.vD({result:{case:"count",value:new gw.xA({ripgrepTruncated:!0})}});default:throw new Error(`Unknown output mode: ${String(e)}`)}}function Ck(e){return"success"===e.result.case&&Object.values(e.result.value.workspaceResults).some((e=>!0===e.result.value?.clientTruncated))}function Ek(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 xk(e){return/^(utf-?16|ucs-?2)/i.test(e)}const Pk=(0,d.h)("local-exec/grep"),Ik=(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"]}),Rk=(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"]}),Tk=(0,h.v5)("local_exec.grep.rg.spawn_ms",{description:"Time to start the ripgrep process for one Grep or Glob search",labelNames:["sandboxed"]}),Ak=(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 $k(e){return e instanceof Error&&e.message.includes("ENOENT")&&e.message.includes("spawn")}function Mk(e){try{return(0,yo.existsSync)(e)}catch{return"check_failed"}}function Dk(e){if("object"==typeof e&&null!==e&&"errno"in e){const t=e.errno;if("number"==typeof t)return t}}function Ok(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 Fk(e,t,r,n){return{...Lk(e),...n,cwd:t,cwdExists:Mk(t),errorMessage:Ha(r),errorCode:Wa(r),errno:Dk(r),syscall:Ok(r,"syscall"),errorPath:Ok(r,"path")}}function Nk(e){return new Error(`Path does not exist: ${e}`)}function Lk(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,yo.existsSync)(e)}catch(e){t.rgPathExists=!1,t.rgPathExistsError=e instanceof Error?e.message:String(e)}try{const r=(0,yo.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,yo.existsSync)(r),t.parentDirExists&&(t.parentDirContents=(0,yo.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,yo.existsSync)(n),t.grandparentDirExists&&(t.grandparentDirContents=(0,yo.readdirSync)(n).slice(0,50))}catch(e){t.grandparentDirError=e instanceof Error?e.message:String(e)}if(t.rgPathExists)try{const r=(0,yo.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,yo.existsSync)(n)}catch{t.asarExists="check_failed"}const i=r.concat(o);try{if(t.asarUnpackedDirExists=(0,yo.existsSync)(i),t.asarUnpackedDirExists){const r=(0,s.dirname)((0,s.dirname)(e));t.ripgrepPkgDirExists=(0,yo.existsSync)(r)}}catch{t.asarUnpackedDirExists="check_failed"}}}return t}class jk{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 ia(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,go.stat)(e)).isFile())return;const{encoding:t}=await Fi(e);return xk(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 za(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 Lw(t,(e=>(0,zo.o1)(n(e),r)));return s.statTimedOut&&(Pk.info(e,"newest_first.stat_timeout_fallback",{toolCallId:o.toolCallId,execId:o.execId,outputMode:o.outputMode,fileCount:t.length}),Rk.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,jk.CLIENT_LIMIT_LINES)}async runFilesMode(e,t,r,n,o,s,i){const a={stack:[],error:void 0,hasError:!1};try{const d=fk(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?jk.HARD_MAX_OUTPUT_LINES:jk.CLIENT_LIMIT_LINES,u=jk.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 ww;let s=0,i=0,a=0;for(;yw(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&&yw(c,a,o);)l.push(c.slice(a,o.lineEnd)),a=o.nextStart;return{files:l,totalFiles:kw(s),clientTruncated:s>t,ripgrepTruncated:s>=r}}(c,l,u)),m=f.totalFiles>jk.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 gw.T7({files:w,totalFiles:kw(f.totalFiles-y),clientTruncated:m,ripgrepTruncated:f.ripgrepTruncated||p.timedOut||p.stdoutByteCapped});return{result:new gw.vD({result:{case:"files",value:v}}),timedOut:p.timedOut}}catch(e){a.error=e,a.hasError=!0}finally{mk(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=fk(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?jk.HARD_MAX_OUTPUT_LINES:jk.CLIENT_LIMIT_LINES,u=jk.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 ww;let i=0;for(;yw(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:kw(a),totalMatches:kw(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 gw.xA({counts:g.map((e=>new gw.sS({file:e.file,count:kw(e.count)}))),totalFiles:kw(f.totalFiles-y),totalMatches:kw(f.totalMatches-v),clientTruncated:f.totalFiles>jk.CLIENT_LIMIT_LINES,ripgrepTruncated:f.ripgrepTruncated||p.timedOut||p.stdoutByteCapped});return{result:new gw.vD({result:{case:"count",value:b}}),timedOut:p.timedOut}}catch(e){a.error=e,a.hasError=!0}finally{mk(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=fk(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=jk.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 fk(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 ww;let a=0,c=0,l=0,u=0;for(;yw(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:kw(l),totalMatchedLines:kw(a),totalFiles:kw(s.size),clientTruncated:c>=t,ripgrepTruncated:l>=r}}(e,t,r)}catch(e){o.error=e,o.hasError=!0}finally{mk(o)}}(p,jk.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 gw.Zp({matches:C.map((e=>new gw.uI({file:e.file,matches:e.matches.map((e=>new gw.dx({lineNumber:e.lineNumber,content:e.content,isContextLine:e.isContextLine})))}))),totalLines:kw(m-k),totalMatchedLines:kw(g-_),clientTruncated:w,ripgrepTruncated:y||h.timedOut||h.stdoutByteCapped});return{result:new gw.vD({result:{case:"content",value:E}}),timedOut:h.timedOut}}catch(e){a.error=e,a.hasError=!0}finally{mk(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=fk(s,(0,D.VI)(e.withName("LocalGrepExecutor.decodeLinesAsRead")),!1),c=function(e,t){const r=[],o=new ww;let s=0,i=0,a=e.indexOf("�");for(;-1!==a&&yw(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=vw(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()+jk.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)(uk((0,zo.o1)(l[h],r)),e,"encoding detection timed out")}catch(e){if(e instanceof Fr.MU)break;continue}void 0===t||xk(t)||u.set(l[h],t)}return h<l.length&&Pk.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),Us.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{mk(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 Pk.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){Pk.info(e,"ripgrep.deadline_reached",{toolCallId:t.toolCallId,execId:t.execId,outputMode:t.outputMode,...r}),Ik.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(jk.INDEXED_GREP_CONTEXT_TIMEOUT_MS),i={phase:"provider"},a=performance.now();try{return await(0,Fr.wj)(this.grepProvider.executeIndexedGrep(o,t,r,i),jk.INDEXED_GREP_TIMEOUT_MS,`Indexed grep timed out after ${jk.INDEXED_GREP_TIMEOUT_MS/1e3}s`)}catch(t){if(t instanceof Fr.MU)return s(t),void Pk.debug(e,"indexed_grep.timeout_fallback",{...n,totalMs:Math.round(performance.now()-a),...i});throw t}finally{s()}}static ripgrepTimeoutError(){return new bk(`Timed out after ${jk.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??jk.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(jk.ripgrepTimeoutError());let f;const m="insecure_none"===s.type?"false":"true",g=performance.now();let w=g;try{const e=s;f=(0,Po.spawnInSandbox)((0,Po.Ko)(),r,{cwd:t},e),w=performance.now(),0}catch(r){if(p(),$k(r)){const n=(0,Po.Ko)();if(Pk.error(e,"rg_diagnostics.spawn_throw",void 0,Fk(n,t,r,i)),!1===Mk(t))return u(Nk(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=Ek(y,!0,this.stdoutDecodes.get(i));""===e.stdout?u(jk.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(),$k(r)){const n=(0,Po.Ko)();if(Pk.error(e,"rg_diagnostics.spawn_enoent",void 0,Fk(n,t,r,i)),!1===Mk(t))return void u(Nk(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=Ek(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}),Tk.histogram(e,w-g,{sandboxed:m}),C||_||o.aborted||e.signal.aborted||0!==t&&1!==t||Ak.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 za(t[0]);return null===r?{error:gk(e)}:await this.ignoreService.isCursorIgnored(r)?{error:`Path '${e}' is filtered out by .cursorignore`}:await yk(t[0])?{error:wk(e)}:{resolvedTarget:r}}async execute(e,t,r){if(!el(this.encodingSlices,e))return this.search(e,t,r,void 0);const n=new ml,o=await this.search(e,t,r,n);return"success"===o.result.case&&pl(this.encodingSlices,e,{layer:"exec_grep",evidence:n.evidence(),partial:Ck(o)},o),o}async search(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{const a=fk(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=ts(t.sandboxPolicy),p=this.grepProvider.getWorktreeGuardInfo?.(c);if((0,zo.fl)({targetPath:t.path,workspacePaths:c,mainWorktreePath:p?.mainWorktreePath}))return new gw.Ud({result:{case:"error",value:new gw.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 gw.Ud({result:{case:"error",value:new gw.ts({error:r.error})}});void 0!==this.mcpStateAccessor&&Ow(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 za(s);if(null!==i)if(await this.ignoreService.isCursorIgnored(i))r=!0;else{if(await yk(s))return new gw.Ud({result:{case:"error",value:new gw.ts({error:wk(m.path)})}});t.push(n),void 0!==this.mcpStateAccessor&&Ow(e,this.mcpStateAccessor,i)}}if(0===t.length){const e=r?`Path '${m.path}' is filtered out by .cursorignore`:gk(m.path);return new gw.Ud({result:{case:"error",value:new gw.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?Sk(jk.MAIN_TIMEOUT_MS):void 0;let n=0,o=!1;try{for(const s of g){if(!0===t?.signal.aborted){r[s]=_k(u),n++,o=!0;continue}if(!1===Mk(s))return new gw.Ud({result:{case:"error",value:new gw.ts({error:`Path does not exist: ${s}`})}});const i=t??Sk(jk.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 bk))throw t;if(r[s]=_k(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(kk));if(this.reportDeadlineReached(a.ctx,d,{streaming:e,folderCount:g.length,stoppedFolderCount:n,outcome:t?"failed":"partial"}),t)throw jk.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=>vk(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 gw.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 gw.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 gw.vD({result:{case:"count",value:s}});break}default:n[t]=o}}return n}(r,g),i=new gw._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 gw.Ud({result:{case:"success",value:i}})}catch(e){if(m.path){const e=(0,zo.o1)(m.path,this.singleWorkspacePath);try{await(0,go.stat)(e)}catch(t){return new gw.Ud({result:{case:"error",value:new gw.ts({error:`Path does not exist: ${e}`})}})}}return new gw.Ud({result:{case:"error",value:new gw.ts({error:e instanceof Error?e.message:String(e)})}})}}catch(e){o.error=e,o.hasError=!0}finally{mk(o)}var i}}jk.MAIN_TIMEOUT_MS=25e3,jk.INDEXED_GREP_TIMEOUT_MS=25e3,jk.INDEXED_GREP_CONTEXT_TIMEOUT_MS=jk.INDEXED_GREP_TIMEOUT_MS+100,jk.HARD_MAX_OUTPUT_LINES=1e4,jk.CLIENT_LIMIT_LINES=2e3,jk.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 Uk=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()}),Uk.extend({memory:Be.object({anon_bytes:Be.number()}).nullish().catch(null)});const Bk=Be.number().int().nonnegative(),Wk=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(Wk)}),Be.object({type:Be.literal("summary"),files_searched:Bk,more:Be.boolean(),stop_reason:Be.string().nullable(),skipped:Be.object({over_size:Bk,size_unknown:Bk,budget_exhausted:Bk,fetch_failed:Bk,unreadable:Bk})}),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 Hk=r("../proto/dist/generated/agent/v1/ls_exec_pb.js"),qk=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},zk=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 Gk{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{qk(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,go.stat)(n)}catch(e){return"ENOENT"===Wa(e)?function(e){const t=Kh(e,"terminals");return null!==t&&0===t.remainingPath.length}(n)?new Hk.fv({result:{case:"error",value:new Hk.uj({path:n,error:"No active terminals."})}}):new Hk.fv({result:{case:"error",value:new Hk.uj({path:n,error:`Path does not exist: ${n}`})}}):new Hk.fv({result:{case:"error",value:new Hk.uj({path:n,error:Ha(e)})}})}if(!r.isDirectory())return new Hk.fv({result:{case:"error",value:new Hk.uj({path:n,error:`Path is not a directory: ${n}`})}});const o=ts(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 Hk.fv({result:{case:"timeout",value:new Hk.ze({directoryTreeRoot:a})}}):new Hk.fv({result:{case:"success",value:new Hk.PC({directoryTreeRoot:a})}})}catch(e){return new Hk.fv({result:{case:"error",value:new Hk.uj({path:n,error:e instanceof Error?e.message:"Unknown error occurred"})}})}}catch(e){r.error=e,r.hasError=!0}finally{zk(r)}}async getDirectoryTree(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{return qk(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{zk(o)}}async buildTreeFromRipgrepStream(e,t,r,n,o){const i={stack:[],error:void 0,hasError:!1};try{qk(i,(0,D.VI)(e.withName("LocalLsExecutor.buildTreeFromRipgrepStream")),!1);const a=(0,s.resolve)(t),c=new Hk.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}=la(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 za(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{zk(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 Hk.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]=kw(e.fullSubtreeExtensionCounts[i]+1),e.numFiles??=0,e.numFiles=kw(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 Hk.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 Vk extends Error{constructor(e,t){super(`Tool ${e} not found, available tools: ${t.join(", ")}`),this.toolName=e,this.availableTools=t,this.name="McpToolNotFoundError"}}function Kk(e){if(e instanceof Vk)return!0;if(!(e instanceof Error)||"McpToolNotFoundError"!==e.name)return!1;const t=e;return"string"==typeof t.toolName&&Array.isArray(t.availableTools)}function Jk(e){return!0===e.url?.startsWith("mcp-provider://")}function Zk(e){const t=e?.trim();return void 0===t||0===t.length?void 0:t}function Xk(e){const t=e?.trim();return void 0===t||0===t.length?void 0:t}function Qk(e,t){return(t??[]).some((t=>{const r=Zk(t.command),n=Xk(t.serverUrl);if(void 0===r&&void 0===n)return!1;const o=void 0===r||void 0!==e.command&&(0,yv.mD)(r,e.command),s=void 0===n||void 0!==e.url&&(0,yv.eA)(n,e.url);return o&&s}))}function Yk(e,t){if(Jk(e))return!1;const r=t?.rules??[];return r.length>0&&Qk(e,r)}var e_=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 t_ extends Error{constructor(e){super(`MCP server "${e}" is disabled`),this.name="McpServerDisabledError"}}class r_ extends Error{constructor(e){super(`MCP server "${e}" has not been approved`),this.serverName=e,this.name="McpServerNotApprovedError"}}class n_ extends Error{constructor(e,t){super(`MCP server "${e}" is overridden by ${t}`),this.serverName=e,this.overridingConfigPath=t,this.name="McpServerOverriddenError"}}class o_{constructor(e){this.disabledService=e}async load(e,t,r,n,o){if(await this.disabledService.isServerDisabled(t))throw new t_(t);return await o(e,r)}}class s_{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 r_(t);return await o(e,r)}catch(e){s.error=e,s.hasError=!0}finally{e_(s)}}}class i_{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,ho.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,go.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,go.mkdir)(s.dirname(this.approvalsPath),{recursive:!0}),await(0,go.writeFile)(this.approvalsPath,JSON.stringify(e,null,2))}async saveApprovals(e){await this.saveApprovalsToFile(e),this.approvalsPromise=Promise.resolve(e)}}var a_=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},c_=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 l_{async load(e,t,r,n,o){const s=o(e,r);return new d_(e,t,s,r)}}function u_(e){let t;return e.then((e=>{t=e})).catch((()=>{})),t}class d_{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=a_(t,(0,D.VI)(e.withName("CachedMcpClient.getTools")),!1);r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("cacheTraceId",this.clientPromiseTraceId??"undefined");const n=u_(this.toolsPromise);return void 0!==n?n:await this.toolsPromise}catch(e){t.error=e,t.hasError=!0}finally{c_(t)}}async callTool(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{const i=a_(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{c_(s)}}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{const r=a_(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{c_(t)}}async getClient(e){const t={stack:[],error:void 0,hasError:!1};try{const r=a_(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{c_(t)}}async listResources(e){const t={stack:[],error:void 0,hasError:!1};try{const r=a_(t,(0,D.VI)(e.withName("CachedMcpClient.listResources")),!1);r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("cacheTraceId",this.clientPromiseTraceId??"undefined");const n=u_(this.resourcesPromise);return void 0!==n?{resources:n}:{resources:await this.resourcesPromise}}catch(e){t.error=e,t.hasError=!0}finally{c_(t)}}async readResource(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=a_(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{c_(r)}}async listPrompts(e){const t={stack:[],error:void 0,hasError:!1};try{const r=a_(t,(0,D.VI)(e.withName("CachedMcpClient.listPrompts")),!1);r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("cacheTraceId",this.clientPromiseTraceId??"undefined");const n=u_(this.promptsPromise);return void 0!==n?n:await this.promptsPromise}catch(e){t.error=e,t.hasError=!0}finally{c_(t)}}async getPrompt(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=a_(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{c_(n)}}async getState(e){const t={stack:[],error:void 0,hasError:!1};try{const r=a_(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{c_(t)}}async close(){try{const e=await this.clientPromise;await(e?.close?.())}catch{}}}function h_(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function p_(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 f_(e){return e?` (${p_(e,"")})`:""}function m_(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=m_(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=m_(n);if(void 0===e)return;r[t]=e}return r}function g_(e){const t=m_(e);if(null!=t&&"object"==typeof t&&!Array.isArray(t))return t}const w_=new TextDecoder("utf-8",{fatal:!0});function y_(e){return"string"==typeof e?e.split(";")[0]?.trim().toLowerCase()??"":""}function v_(e,t){const r=Buffer.from(t,"base64"),n=function(e){try{const t=w_.decode(e);return t.includes("\0")?void 0:t}catch{return}}(r)??(function(e){const t=y_(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: ${p_(e.uri,"unknown")} (${o}, ${r.byteLength} bytes). The file is not text, so its contents are not included.]`,binary:!0}}const b_=new Set(["image/png","image/jpeg","image/jpg","image/gif","image/webp"]);function S_(e){return"string"==typeof e.text&&e.text.length>0?e.text:void 0}function k_(e){if(!h_(e))return;const t=e.resource;return h_(t)&&void 0===S_(t)&&"string"==typeof t.blob&&b_.has(y_(t.mimeType))?t.blob:void 0}function __(e){const t=e,r=t.resource;if(h_(r)){const e=S_(r);return void 0!==e?e:"string"==typeof r.blob?v_(r,r.blob).text:`Resource: ${p_(r.uri,"unknown")}${f_(r.name)}`}return t.uri?`Resource: ${p_(t.uri,"unknown")}${f_(t.name)}`:`Unsupported content type "${e.type}": ${JSON.stringify(e)}`}function C_(e){const t=g_(e);if(void 0!==t&&0!==Object.keys(t).length)try{return Buffer.byteLength(JSON.stringify(t))<=262144?t:void 0}catch{return}}var E_=r("zod/v4-mini");const x_=E_.object({CLIENT_ID:E_.string(),CLIENT_SECRET:E_.optional(E_.string()),scopes:E_.optional(E_.array(E_.string()))}),P_=E_.strictObject({caBundle:E_.string().check(E_.trim(),E_.minLength(1),E_.maxLength(131072))}),I_=E_.object({type:E_.optional(E_.literal("stdio")),command:E_.string(),args:E_.optional(E_.array(E_.string())),env:E_.optional(E_.record(E_.string(),E_.string())),envFile:E_.optional(E_.string()),cwd:E_.optional(E_.string()),enabledTools:E_.optional(E_.array(E_.string())),startupTimeoutSec:E_.catch(E_.optional(E_.number().check(E_.positive())),void 0)}),R_=E_.object({type:E_.optional(E_.enum(["http","sse"])),url:E_.string(),headers:E_.optional(E_.record(E_.string(),E_.string())),auth:E_.optional(x_),tls:E_.optional(P_),placement:E_.optional(E_.enum(["server","client"])),enabledTools:E_.optional(E_.array(E_.string()))}),T_=E_.union([I_,R_]),A_=E_.object({mcpServers:E_.record(E_.string(),T_)});Error;const $_=/\$\{(?:env:([A-Za-z_][A-Za-z0-9_]*)|([^:}]+)(?::-([^}]*))?)\}/g;function M_(e,t){if("string"==typeof e)return function(e,t){return e.replace($_,((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=>M_(e,t)));if(null!==e&&"object"==typeof e){const r={};for(const[n,o]of Object.entries(e))r[n]=M_(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 D_(e){const t=Object.entries(e);return{jsonKeyOf:new Map(t.map((([e,t])=>[t,e]))),tomlKeyOf:new Map(t)}}const O_=D_({CLIENT_ID:"client_id",CLIENT_SECRET:"client_secret",scopes:"scopes"}),F_=D_({caBundle:"ca_bundle"}),N_=D_({type:"type",command:"command",args:"args",env:"env",envFile:"env_file",cwd:"cwd",enabledTools:"enabled_tools",startupTimeoutSec:"startup_timeout_sec"}),L_=D_({type:"type",url:"url",headers:"http_headers",auth:"auth",tls:"tls",placement:"placement",enabledTools:"enabled_tools"}),j_=(new Map([["auth",{keys:O_,unknownKeyIsError:!1}],["tls",{keys:F_,unknownKeyIsError:!0}]]),"enabled");new Set([...N_.jsonKeyOf.keys(),...L_.jsonKeyOf.keys(),j_]);Symbol("disabled");const U_=(0,d.h)("McpConfig");async function B_(e,t=e=>process.env[e]){try{const r=await(0,go.readFile)(e,"utf8"),n=M_((0,lh.qg)(r),t);return A_.parse(n)}catch{return{mcpServers:{}}}}async function W_(e,t=e=>process.env[e]){const r={config:{mcpServers:{}},diagnostics:[]};return r}async function H_(e,t=e=>process.env[e]){const{config:r,diagnostics:n}=await W_(0,t);return n.length>0&&U_.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 q_=["enterprise","project","user","env"];function z_(e){return"project"===e||"env"===e}const G_=["0.0.0.0/0","::/0"];function V_(e){const t=(e??[]).filter((e=>e.trim().length>0)),r=t.flatMap((e=>{const t=(0,yv.bi)(e);return void 0===t?[]:[t]}));return{hasInvalidEntries:r.length!==t.length,entries:r}}function K_(e){const t=!0===e.enabled,r=V_(e.mcpNetworkDenylist),n="deny_all"===e.mcpNetworkMode||r.entries.includes("*")||r.hasInvalidEntries,o=t?function(e){if("allow_all"===e.mcpNetworkMode)return[...G_];const t=V_(e.mcpNetworkAllowlist);if("allowlist"===e.mcpNetworkMode)return t.entries.includes("*")?[...G_]:t.entries;if(!function(e){return(e.mcpNetworkAllowlist??[]).some((e=>e.trim().length>0))}(e))return[...G_];const r=(0,yv.b6)(e);return r.includes("*")?[...G_]:r}(e):[],s=t?n?["*"]:r.entries:[];return JSON.stringify({enabled:t,mode:e.mcpNetworkMode,allow:n?[]:o,deny:s})}class J_ 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 Z_=new Set(["invalid_auth","not_authed","account_inactive","token_revoked","token_expired"]);class X_ extends Error{constructor(){super("Your organization admin only allows Slack workspaces your company manages. Connect your company Slack workspace instead."),this.name="SlackWorkspaceNotManagedError"}}class Q_ 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 Y_(e){return URL.canParse(e)&&"mcp.slack.com"===new URL(e).hostname.toLowerCase()}function eC(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&&Z_.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(!Y_(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 Q_;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 Q_;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 X_;return e(i,a)}}function tC(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)&&uC(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=oC(e,n),s=cC(o,t,r);return Object.is(s,o)?[]:[[n,s]]})),a=Object.getOwnPropertyDescriptor(e,"cause"),c=void 0===a?void 0:oC(e,"cause"),l=cC(c,t,r),u=e instanceof AggregateError?oC(e,"errors"):void 0,d=function(e,t,r){if(!Array.isArray(e))return e;const n=e.map((e=>cC(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])=>nC(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(iC(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[sC];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=pC(e);return void 0!==g&&pC(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 rC(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 nC(e,t,r){const n=Object.getOwnPropertyDescriptor(e,t);return!0===n?.writable&&Reflect.defineProperty(e,t,{...n,value:r})}function oC(e,t){try{const r=Object.getOwnPropertyDescriptor(e,t);return void 0===r?.get?r?.value:r.get.call(e)}catch{return}}const sC=Symbol.for("nodejs.util.inspect.custom");function iC(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 aC(e,t,r,n){if("string"==typeof e)return t(e);if("object"!=typeof e||null===e)return e;if(e instanceof Error)return tC(e,t,n);if(Array.isArray(e)){if(r>=4)return;return e.slice(0,64).map((e=>aC(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:aC(a,t,r,n),writable:!0,enumerable:!0,configurable:!0})}catch{}return o}(e,t,r+1,n)}function cC(e,t,r){if(e instanceof Error)return tC(e,t,r);try{return uC(e,t)?aC(e,t,1,r):e}catch{return}}const lC=4096;function uC(e,t){const r=new Set,n=[e];for(let o=0;n.length>0;o++){if(o>=lC||n.length>lC)return dC(e,t);const s=n.pop();if("string"==typeof s){if(t(s)!==s)return!0}else if((hC(s)||s instanceof Error)&&!r.has(s)){r.add(s),s instanceof Error&&(n.push(oC(s,"message"),oC(s,"stack"),oC(s,"cause")),s instanceof AggregateError&&n.push(oC(s,"errors")));for(const e of Object.keys(s))n.push(oC(s,e))}}return!1}function dC(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,oC(n,e)]))),message:oC(n,"message"),stack:oC(n,"stack"),cause:oC(n,"cause"),...n instanceof AggregateError?{errors:oC(n,"errors")}:{}}):t);var n}))}catch{return!0}return void 0!==n&&t(n)!==n}function hC(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 pC(e){try{return"string"==typeof e.name?e.name:void 0}catch{return}}const fC=/spt_[A-Za-z0-9_]{6,}/g,mC=/[A-Z0-9]/;function gC(e){return function(e){return e.replace(fC,(e=>function(e){return e.slice(4).split("_").some((e=>e.length>=8&&mC.test(e)))}(e)?"[redacted Link shared payment token]":e))}(e)}var wC=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 yC=new Set([429,502,503,504]);function vC(e){return"object"==typeof e&&null!==e}function bC(e){const t=vC(e)?e.code:void 0,r=(e instanceof Error||vC(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&&yC.has(o)&&!yC.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 SC=8192;function kC(e){return void 0===e?"unknown":"url"in e&&e.url.length>0?void 0!==Hy(e.url)?"rest_mcp":"streamable_http":"command"in e?"stdio":"unknown"}new Set(["ENOENT","EACCES","ENOTDIR","EPERM"]);const _C=/\$\{[^}]*\}/;function CC(e){if(void 0!==function(e){if(void 0===e)return;const t=e.trim();return 0!==t.length&&_C.test(t)?t:void 0}(e))return;const t=e?.trim();return t&&t.length>0?t:void 0}const EC=new Map;async function xC(e,t=fetch){if(void 0===Hy(e))return;const r=new URL(e),n=`${r.origin}/.well-known/oauth-protected-resource${r.pathname.replace(/\/+$/,"")}`,o=EC.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 EC.set(n,{metadata:s,expiresAtMs:Date.now()+3e5}),s}(0,gs.J)((function(){EC.clear()}));const PC={info:()=>{},warn:()=>{},error:()=>{},debug:()=>{}};function IC(e){return PC}const RC=/^[\x21\x23-\x5B\x5D-\x7E]+$/,TC=["invalid_request","invalid_token","insufficient_scope"];function AC(e){return TC.some((t=>t===e))}function $C(e){const t=new Set;for(const r of e)r.length<=200&&RC.test(r)&&t.add(r);return[...t]}const MC=/[!#$%&'*+.^_`|~0-9A-Za-z-]+/y,DC=/"((?:[^"\\]|\\.)*)"?/y,OC=/[^\s,]*/y;function FC(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(MC);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(DC)?.[1]??"").replace(/\\(.)/g,"$1"):o(OC)?.[0]??"";if((void 0===r||"bearer"===r)&&s[0].toLowerCase()===t)return i}}const NC={stepUpScopes:[],signInMissing:[]};function LC(e){return Array.isArray(e)?e.filter((e=>"string"==typeof e&&e.length>0)):void 0}function jC(e){if("object"!=typeof e||null===e||Array.isArray(e))return NC;const t=LC("grantedScopes"in e?e.grantedScopes:void 0),r=LC("requestedScopes"in e?e.requestedScopes:void 0);return{...void 0!==t?{grantedScopes:t}:{},stepUpScopes:LC("stepUpScopes"in e?e.stepUpScopes:void 0)??[],signInMissing:LC("signInMissing"in e?e.signInMissing:void 0)??[],...void 0!==r?{requestedScopes:r}:{}}}function UC(e){return(e??"").split(/\s+/).filter((e=>e.length>0))}function BC(e,t){return e.filter((e=>!t.has(e)))}function WC(e){const t=ov(e.serverUrl),r=e.connectorName??t?.displayName??e.accountKey,n=IC(e.accountKey);let o;const s=async()=>jC(await e.readRecord()),i=async t=>{if(void 0!==t.grantedScopes)return t.grantedScopes;const r=UC(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=FC(t,"error")?.toLowerCase(),n=FC(t,"resource_metadata");return{error:void 0===r||""===r?"none":AC(r)?r:"other",scopes:$C((FC(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 sv.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 $C(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:UC(t.searchParams.get("scope"))})}}},async recordTokens(t,{isRefresh:r}){const n=await e.readRecord();if(void 0===n)return;const o=jC(n),s=UC(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=BC(o.requestedScopes,c);await e.writeRecord({grantedScopes:i,stepUpScopes:BC(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}=jC(e);return t.length>0?{stepUpScopes:t,signInMissing:[]}:void 0}(await e.readRecord()):void 0)}}}function HC(e){const t=ov(e.serverUrl);for(const r of e.scopes){const e=t?.stepUpScopes[r]?.action;if(void 0!==e)return e}return e.toolTitle}function qC(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:HC(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 zC extends Error{constructor(e,t,r){super(qC({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 qC({kind:this.decision.kind,serverUrl:this.serverUrl,connectorName:this.connectorName,scopes:this.decision.scopes,toolTitle:e??this.decision.toolName})}}function GC(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 VC(e){return e instanceof Error&&/does not support dynamic client registration/i.test(e.message)}Error,Error;const KC=new Set(["UnauthorizedError","InvalidGrantError","InvalidTokenError","InvalidClientError","UnauthorizedClientError"]),JC=new Set(["invalid_grant","invalid_token","invalid_client","unauthorized_client"]),ZC=[/\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 XC=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/types.js");const QC="2026-07-28",YC=-32022,eE="io.modelcontextprotocol/protocolVersion",tE="io.modelcontextprotocol/clientCapabilities",rE="io.modelcontextprotocol/clientInfo",nE="io.modelcontextprotocol/serverInfo",oE={name:"cursor",version:"1.0.0"},sE=new Map;function iE(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function aE(e){const t=new URL(String(e));return t.hash="",t.href}function cE(e,t){const r=sE.get(e);return!(void 0===r||r<=t()&&(sE.delete(e),1))}function lE(e,t){try{return aE(e)===t}catch{return!1}}function uE(e){return(e.headers.get("content-type")??"").toLowerCase().includes("application/json")}const dE=new Set(["events/subscribe","events/unsubscribe","events/poll","events/stream"]);function hE(e,t,r,n,o=t.message){const s=new Headers(e?.headers);if(s.set("mcp-protocol-version",QC),s.set("mcp-method",r),s.delete("mcp-session-id"),!t.isRequest&&o===t.message)return{...e,headers:s};const i=iE(o.params)?o.params:{},a=iE(i._meta)?i._meta:{},c=function(e,t){const r="tools/call"===e||"prompts/get"===e||dE.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,[eE]:QC,[tE]:n.capabilities,[rE]:n.clientInfo}}});return{...e,headers:s,body:l}}function pE(e){return new Response(JSON.stringify({jsonrpc:"2.0",...e}),{status:200,headers:{"content-type":"application/json"}})}function fE(e,t){const r=aE(t.serverUrl),n=t.now??Date.now;let o={capabilities:{},clientInfo:{...oE}},s=!1;const i=()=>s||cE(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,hE(a,t,"server/discover",o,c)),d=await async function(e,t,r){if(!e.ok||!uE(e))return e;let n;try{n=await e.clone().json()}catch{return e}if(!iE(n)||!iE(n.result))return e;const o=n.result,s=o.supportedVersions;if(!Array.isArray(s)||!s.includes(QC))return pE({id:t,error:{code:YC,message:"Unsupported protocol version",data:{requested:QC,supported:s??[]}}});const i=iE(o._meta)?o._meta:{},a=iE(i[nE])?i[nE]:{name:new URL(r).hostname,version:"unknown"};return pE({id:t,result:{protocolVersion:XC.aE,capabilities:iE(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){sE.set(e,t()+6e5)}(r,n)),d}return e(i,hE(a,t,c,o))};return async(t,c)=>{const l=function(e,t,r){if("POST"!==(t?.method??"GET").toUpperCase()||"string"!=typeof t?.body||!lE(e,r))return;let n;try{n=JSON.parse(t.body)}catch{return}if(!iE(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()&&lE(e,r)}(t,c,r)&&i()?new Response(null,{status:405}):e(t,c);if(l.isRequest&&"initialize"===l.method){const e=iE(l.message.params)?l.message.params:{};o={capabilities:iE(e.capabilities)?e.capabilities:{},clientInfo:iE(e.clientInfo)?e.clientInfo:o.clientInfo}}const u=l.isRequest&&"initialize"===l.method;if(u?cE(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||!uE(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(!iE(r)||!iE(r.error))return!1;const n=r.error;if(n.code!==YC||!iE(n.data))return!1;const o=n.data.supported;return Array.isArray(o)&&o.includes(QC)}(d)){const e=await a(l,t,c);return s?e:d}return d}}function mE(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()===Wy));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()!==Wy))),cursorAuthHeaderValue:n[1],cursorAuthOrigin:o}}function gE(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(Wy,i),r(n,{...o,headers:a,redirect:"manual"})}}class wE{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 yE=r("crypto");function vE(e){const t={};for(const[r,n]of Object.entries(e))void 0!==n&&(t[r]=n);return t}function bE(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 SE(e,t){return bE(e,t)}function kE(e){if(e)return(0,yE.createHash)("sha256").update(e).digest("hex").slice(0,12)}function _E(e){if(e&&0!==e.length)return kE(JSON.stringify([...e].sort()))}function CE(e){return{clientIdHash:kE(e?.client_id),hasClientSecret:(e?.client_secret??"").length>0,redirectUrisHash:_E(e?.redirect_uris),redirectUriCount:e?.redirect_uris?.length??0}}function EE(e){return"object"==typeof e&&null!==e}function xE(e,t){let r=e;for(const e of t){if(!EE(r)||!(e in r))return;r=r[e]}return r}function PE(e,t){for(const r of t){const t=xE(e,r.split("."));if("string"==typeof t)return t}}function IE(e){if(!e||"object"!=typeof e)return;const t=e.errorCode;return"string"==typeof t?t:void 0}function RE(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 TE=e=>e;function AE(e,t){if(e instanceof Error){const r=e.message;return r&&r!==e.name?LE(t(r)):void 0}if("string"==typeof e||"number"==typeof e||"boolean"==typeof e){const r=String(e);return r?LE(t(r)):void 0}}function $E(e){if(e&&"object"==typeof e)return EE(e)?e.cause:void 0}function ME(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(LE(t(String(o)))):EE(o)&&"string"==typeof o.message&&n.push(LE(t(o.message)));break}{const e=AE(o,t);n.push(e?`${o.name}: ${e}`:o.name),o=$E(o)}}return n.length>1?n.join(" > "):void 0}const DE="[REDACTED]",OE=/(^|_|-)(token|secret|password|assertion|authorization|verifier|challenge|code)(_|-|$)/i;function FE(e){return e.replace(/(authorization[^:=\r\n]{0,32}[:=]\s*["']?)(?:[A-Za-z][\w.~+/-]*[ \t]+)?[^"',\s&}]+/gi,`$1${DE}`).replace(/((?:access_token|refresh_token|id_token|client_secret|code|password|assertion|token|secret)[^:=\r\n]{0,32}[:=]\s*["']?)([^"',\s&}]+)/gi,`$1${DE}`).replace(/(\bBearer\s+)([A-Za-z0-9\-._~+/]+=*)/gi,`$1${DE}`)}function NE(e,t=256){return e.length>t?`${e.slice(0,Math.max(0,t-3))}...`:e}function LE(e,t){return NE(FE(e),t?.maxLength)}function jE(e,t=TE){if("string"==typeof e)return NE(FE(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")||OE.test(t)}(e)?DE:"string"==typeof r?FE(t(r)):r));if(!r)return;return NE(r)}catch{return}}function UE(e,t=TE){const r=$E(e),n=e instanceof Error?e.name:null!=e?typeof e:void 0,o=r instanceof Error?r.name:void 0,s=AE(r,t),i=AE(e,t)??s,a=PE(e,["code","cause.code"]),c=IE(e)??IE(r)??PE(e,["errorCode","error","cause.errorCode","cause.error","body.error","response.body.error"]),l=void 0===c?void 0:LE(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=xE(e,t.split("."));if("number"==typeof r&&Number.isFinite(r))return r}}(e)??RE(i)??RE(s),d=jE(xE(e,["response","body"])??xE(e,["body"])??xE(e,["data"])??xE(e,["cause","body"])??xE(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 vE({errorName:n,errorMessage:i,errorType:null!=e?typeof e:void 0,httpStatus:u,oauthErrorCode:l,errorResponseSummary:d,networkClassification:h,causeName:o,causeMessage:s,causeChain:ME(e,t),sdkErrorKind:p})}const BE={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 WE(e){const t=e.message??BE[e.event],r={event:e.event,cursorMcp:{oauth:vE({...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 HE=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]))),qE=4096;function zE(e){return"object"==typeof e&&null!==e&&"url"in e&&"string"==typeof e.url}function GE(e){return"string"==typeof e?e:e instanceof URL?e.toString():e.url}function VE(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function KE(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(VE(e)){const t={};for(const[r,n]of Object.entries(e)){if("string"!=typeof n)return;t[r]=n}return t}}function JE(e){const t=[];return e.forEach(((e,r)=>{t.push(r)})),t.sort()}function ZE(e){if(null===e)return null;const t=Number.parseInt(e,10);return Number.isNaN(t)?null:t}function XE(e,t){if(null==e)return{kind:"none",bytes:0,contentLength:ZE(t.get("content-length"))};if("string"==typeof e){const r=(new TextEncoder).encode(e).length;return{kind:"text",bytes:r,contentLength:ZE(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:ZE(t.get("content-length"))??n}}return e instanceof Blob?{kind:"blob",bytes:e.size,contentLength:ZE(t.get("content-length"))??e.size}:e instanceof ArrayBuffer||ArrayBuffer.isView(e)?{kind:"binary",bytes:e.byteLength,contentLength:ZE(t.get("content-length"))??e.byteLength}:"object"==typeof e&&null!==e&&("getReader"in e||Symbol.asyncIterator in e)?{kind:"stream",bytes:null,contentLength:ZE(t.get("content-length"))}:{kind:"unknown",bytes:null,contentLength:ZE(t.get("content-length"))}}function QE(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 YE(e){const{input:t,init:r}=e,n=bE(GE(t)),o=function(e,t){const r=new Headers(KE(zE(e)?e.headers:void 0));return new Headers(KE(t?.headers)).forEach(((e,t)=>{r.set(t,e)})),r}(t,r),s=JE(o),i=o.get("content-type"),a=kE(o.get("mcp-session-id")??void 0),c=function(e){if(!e)return null;const t=e.trim().split(/\s+/,1)[0]??"";return HE.get(t.toLowerCase())??"unrecognized"}(o.get("authorization"));return{method:(r?.method??(zE(t)?t.method:void 0)??"GET").toUpperCase(),url:n,headers:{names:s,count:s.length},contentType:i,body:XE(r?.body,o),sessionIdHash:a??null,authorizationScheme:c}}function ex(e,t){const r=JE(e.headers),n=ZE(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:kE(e.headers.get("mcp-session-id")??void 0)??null,wwwAuthenticateHash:kE(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:tx(e.headers,"retry-after"),slackRateLimitType:tx(e.headers,"x-slack-ratelimit-type")}}function tx(e,t){return e.get(t)?.slice(0,64)??null}function rx(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 nx(e,t){const r=YE({input:e,init:t});if(void 0!==QE(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 ox=e=>e;async function sx(e,t,r){try{const n=r(await e.clone().text());return n.length>t?n.slice(0,t):n}catch{return}}async function ix(e){if(!nx(e.input,e.init))return;const t=await sx(e.response,qE,e.redact);if(void 0!==t)try{return jE(JSON.parse(t))}catch{return LE(t,{maxLength:qE})}}async function ax(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 sx(t,qE,r);if(void 0===o)return;return function(e){if("/mcp"!==(t=bE(GE(e.input)).path)&&!0!==t?.endsWith("/mcp"))return LE(e.rawText,{maxLength:qE});var t;try{const t=JSON.parse(e.rawText);return VE(t)?function(e){const t=e.error;if("string"==typeof t)return JSON.stringify({error:t});if("object"!=typeof t||null===t)return;if(!VE(t))return;const r=t,n="number"==typeof r.code||"string"==typeof r.code?r.code:void 0,o="string"==typeof r.message?LE(r.message,{maxLength:qE}):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 ix({input:e.input,response:e.response,init:e.init,redact:e.redact}):void 0}}function cx(e,t,r){try{e()}catch{t.warn?.("MCP HTTP exchange logging failed",{event:"mcp_http_exchange_logging_failure",phase:r})}}function lx(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=>lx(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,lx(n,t,r+1)])))}function ux(e,t){const r=e=>{const r=lx(e,t,0);return VE(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 dx(e){const{fetch:t,logSuccessfulExchanges:r=!0,redactLogText:n}=e,o=void 0===n?e.logger:ux(e.logger,n);return async(s,i)=>{const a=Date.now(),c="function"==typeof e.metadata?e.metadata(s):e.metadata;try{const e=await t(s,i),{responseErrorSummary:l,oauthTokenErrorBodySummary:u}=e.ok?{}:await ax({input:s,init:i,response:e,redact:n??ox});return!r&&e.ok||cx((()=>{!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=YE({input:t,init:r}),l=QE(c.contentType,r?.body);return{event:"mcp_http_exchange",outcome:n.ok?"success":"http_error",durationMs:o,cursorMcp:{transport:{...s,request:c,response:ex(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")&&!nx(e.input,e.init)}({response:r,request:n.cursorMcp.transport.request,input:e.input,init:e.init})?t.debug?.("MCP HTTP exchange completed",n):t.warn?.("MCP HTTP exchange completed",n)}({logger:o,input:s,init:i,response:e,durationMs:Date.now()-a,metadata:c,responseErrorSummary:l,oauthTokenErrorBodySummary:u})}),o,"success"),e}catch(e){const t=function(e){if(!EE(e))return;const t=EE(e.cause)?e.cause:void 0,r=[e.response,t?.response];for(const e of r)if("object"==typeof(n=e)&&null!==n&&"status"in n&&"number"==typeof n.status&&"headers"in n&&"object"==typeof n.headers&&null!==n.headers&&"get"in n.headers&&"function"==typeof n.headers.get)return e;var n}(e),{responseErrorSummary:r,oauthTokenErrorBodySummary:l}=t?await ax({input:s,init:i,response:t,redact:n??ox}):{};throw cx((()=>{!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=UE(n,e.redactLogText),u=YE({input:t,init:r}),d=QE(u.contentType,r?.body);return{event:"mcp_http_exchange",outcome:"error",durationMs:o,cursorMcp:{transport:{...s,request:u,response:void 0!==i?ex(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:rx(l)}}}}(e))}({logger:o,input:s,init:i,error:e,durationMs:Date.now()-a,metadata:c,responseFromError:t,responseErrorSummary:r,oauthTokenErrorBodySummary:l,redactLogText:n})}),o,"failure"),e}}}function hx(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 px(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 fx(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 mx=["PYTHONIOENCODING","PYTHONUTF8","PYTHONLEGACYWINDOWSSTDIO"],gx=[".exe",".cmd",".bat"],wx=/^pythonw?(?:\d+(?:\.\d+)*t?)?$/,yx=new Set(["py","pyw"]),vx=new Set(["--cache-dir","--color","--allow-insecure-host","--directory","--project","--config-file"]),bx=new Set;function Sx(e){return mx.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 kx(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 _x(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 gx)if(t.endsWith(e))return t.slice(0,-e.length);return t}(e);if(wx.test(r)||yx.has(r)||"uvx"===r)return!0;if("uv"===r){const e=kx(t,vx);return"run"===e?.value||"tool"===e?.value&&"run"===kx(e.rest,vx)?.value}return"pipx"===r&&"run"===kx(t,bx)?.value}(n,o)?Sx(i)||Sx(r)?i:{...i,PYTHONIOENCODING:"utf-8:surrogateescape"}:i}async function Cx(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 Ex=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js"),xx=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/sse.js"),Px=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.js"),Ix=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js");var Rx=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js");function Tx(e){return`${typeof e}:${String(e)}`}function Ax(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(Tx(e.id),r)}else if("notifications/cancelled"===e.method){const n=e.params?.requestId;if("string"!=typeof n&&"number"!=typeof n)return;const o=Tx(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=Tx(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 $x(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,ho.createHash)("sha256").update(JSON.stringify([e.url,t,e.accessToken??null])).digest("hex")}class Mx{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,XC.vo)(e)&&(0,XC.eK)(e)){const t={jsonrpc:"2.0",id:e.id,result:this.initializeResult};queueMicrotask((()=>this.onmessage?.(t)))}else(0,XC.wU)(e)||await this.inner.send(e,t)}}const Dx=Be.object({tools:Be.array(Be.unknown()),nextCursor:Be.unknown().optional()}),Ox={typeFilled:0,toolDropped:0,outputStripped:0};function Fx(e){if(Wx(e))return"string"==typeof e.name?e.name:void 0}function Nx(e){return Lx(e.issues.filter((e=>"outputSchema"===e.path[0])))}function Lx(e){return e.map((e=>`${e.path.map(String).join(".")}: ${e.message}`))}function jx(e){if(!Wx(e))return e;const t={...e};return delete t.outputSchema,t}function Ux(e){return Wx(e)&&!("type"in e)}function Bx(e,t){return{...e,inputSchema:{type:"object",...t}}}function Wx(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var Hx=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/ajv-provider.js");const qx=new class{constructor({maxSchemasPerCompiler:e=2048,createCompiler:t=()=>new Hx.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,ho.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 zx{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>=SC}append(e){const t=SC-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}=Ho(e,Math.trunc(t));return r>=e.length?e:e.slice(0,r)}(e,t);this.captured+=r,this.capturedBytes=r.length<e.length?SC:this.capturedBytes+function(e){return Ho(e,1/0).written}(r)}}const Gx=new WeakMap;var Vx=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},Kx=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 Jx=(0,d.h)("McpSdkClient"),Zx=(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 Xx(e,t,r){try{Zx.increment(e,1,function(e){const t=e.httpStatus??(void 0!==e.error?function(e){if(!e||"object"!=typeof e)return;const t=bC(e);if(void 0!==t)return t;const r=vC(e)?e.cause:void 0;return r&&"object"==typeof r?bC(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:kC(t),...r}))}catch{}}const Qx=(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 Yx(e){return void 0===e?"unknown":"url"in e?"http":"stdio"}const eP=["authorization_code","refresh_token"],tP=["code"];class rP{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=rv(e);return void 0!==r&&function(e){return"https:"===e.protocol&&e.hostname===new URL(qy).hostname}(r)?async()=>{}:void 0!==r&&function(e){return"https:"===e.protocol&&"setup.shopify.com"===e.hostname&&""===e.port&&"/mcp"===e.pathname}(r)?nv:ev}(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,ho.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=Qy(e);return!0!==n?.pinsScopesOverConfiguredScopes?void 0!==t&&t.length>0||void 0===r?t:ov(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=Qy(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 nP(e){const{serverName:t,config:n,tokenStorage:o}=e,s=await xC(n.url,e.fetchImpl),i=fv({loopbackIpv4:s?.loopbackIpv4,redirectUrl:e.authRedirectUrl}),a=function(e,t){const r=CC(e?.CLIENT_ID);if(void 0!==r)return{client_id:r,...e?.CLIENT_SECRET?{client_secret:e.CLIENT_SECRET}:{},redirect_uris:mv(t),grant_types:[...eP],response_types:[...tP],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 rP({identifier:t,redirectUrl:i,serverUrl:n.url,restMcpProviderMetadata:s,gtmMcpMatch:e.gtmMcpMatch??{gtmApiOrigin:void 0},clientMetadata:{redirect_uris:mv(i),token_endpoint_auth_method:"none",grant_types:[...eP],response_types:[...tP],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:WC({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 oP=new Set;let sP=!1;function iP(){for(const e of oP)try{process.kill(e,"SIGKILL")}catch{}}function aP(e){return VC(e)?new Ex.D_:e}function cP(e,t){return fE(e??globalThis.fetch.bind(globalThis),{serverUrl:t})}function lP(e,t,r){const n=mE(e,t),o=r??(globalThis.fetch?globalThis.fetch.bind(globalThis):void 0),s=void 0!==n.cursorAuthHeaderValue&&void 0!==n.cursorAuthOrigin&&void 0!==o?gE((()=>n.cursorAuthHeaderValue),n.cursorAuthOrigin,o):o;return{transportHeaders:n.headers,baseFetch:s}}class uP{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 wE,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}})();WE({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 Rx.K({name:"Cursor",version:"1.0.0"},{capabilities:t,jsonSchemaValidator:qx})}setupElicitationHandler(){this.client.setRequestHandler(XC.$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??uv;const f=await nP({serverName:e,config:t,tokenStorage:r,authRedirectUrl:o,fetchImpl:s,gtmMcpMatch:c,isScopePinGateEnabled:l,scopeChallengeStepUp:u}),m=f.tokens(),g=mE(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?gE((()=>g.cursorAuthHeaderValue),g.cursorAuthOrigin,v):v,S=e=>void 0===b||void 0===i?b:dx({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,Ex.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:GC(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){IC(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 zC(n,o.serverUrl,o.scopeStepUp.connectorName)});var o},C=uP.createClient(h),E=e=>e instanceof Ex.D_||function(e){if(null===e||"object"!=typeof e)return!1;const t=e.name;if("string"==typeof t&&KC.has(t))return!0;const r=e.errorCode;return!("string"!=typeof r||!JC.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&&ZC.some((e=>e.test(n)))}(e)}(e)||VC(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,Ex.j2)(f,{serverUrl:p.toString(),authorizationCode:t,...void 0!==r?{resourceMetadataUrl:r}:{},...void 0!==b?{fetchFn:b}:{}}),a&&WE({logger:a,event:"mcp_oauth_callback_completion",metadata:{identifier:e,...SE(p.toString()),...hx(f.tokens(),{expiresInIsFresh:!0})}})},P=r=>{const n=f.lastRedirectUrl?.toString?.()??"",o=new uP(e,C,{oauthLifecycleLogger:a,redactLogText:i?.redactLogText,initialState:{kind:"requires_authentication",url:n,callback:async e=>{try{await x(e),o.updateState({kind:"ready"})}catch(e){const t=e instanceof Error?e.message:"Authentication failed";throw new Error(`Authentication callback failed: ${t}`)}}},authProvider:f,authCodeExchange:x,sessionId:r,config:t});return o},I=async r=>{const n=new xx.A(p,{authProvider:y,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...w??{}}},fetch:_(S("sse"))});try{return await C.connect(n),new uP(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&&WE({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),...SE(p.toString()),...UE(t,i?.redactLogText)}}),P();if(void 0!==r&&px(t)&&t instanceof xx._)throw function(e,t){let r=e;for(let e=0;e<8&&r instanceof Error&&r.cause instanceof Error;e++)r=r.cause;return r instanceof Error&&void 0===r.cause&&Reflect.defineProperty(r,"cause",{value:t,writable:!0,configurable:!0,enumerable:!1}),e}(r,t);throw t}};if("sse"===t.type)return I();const R=new Ix.j(p,{authProvider:y,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...w??{}}},fetch:_(cP(S("streamableHttp"),p))});try{await C.connect(R);const r=function(e,t=Date.now){return cE(aE(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:$x({url:t.url,headers:n,accessToken:f.tokens()?.access_token})}}(C,R);return new uP(e,C,{initialState:{kind:"ready"},authProvider:f,authCodeExchange:x,sessionId:R.sessionId,protocolVersion:R.protocolVersion,...void 0===r?{}:{sessionlessInitialize:r},config:t,oauthLifecycleLogger:a,redactLogText:i?.redactLogText})}catch(t){if(E(t))return a&&WE({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),...SE(p.toString()),...UE(t,i?.redactLogText)}}),P(R.sessionId);if(px(t))return I(t);throw t}}static async fromStreamableHttpWithoutOAuth(e,t,r){const n=uP.createClient(),o=new Ix.j(new URL(t.url),{requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...t.headers}},fetch:r});return await n.connect(o),new uP(e,n,{initialState:{kind:"ready"},sessionId:o.sessionId,protocolVersion:o.protocolVersion,config:t})}static async fromCachedSession(e,t,r,n,o,s=uv,i,a,c,l,u){const d=new URL(t.url),h=await nP({serverName:e,config:t,tokenStorage:n,authRedirectUrl:s,fetchImpl:i,gtmMcpMatch:l,isScopePinGateEnabled:u}),{transportHeaders:p,baseFetch:f}=lP(t.url,o,i),m=new Ix.j(d,{authProvider:h,sessionId:r.sessionId,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...p??{}}},fetch:void 0!==f&&void 0!==a?dx({fetch:f,logger:a.logger,metadata:{...a.metadata,transportType:"streamableHttp"},redactLogText:a.redactLogText}):f});m.setProtocolVersion(r.protocolVersion);const g=uP.createClient();return await g.connect(m),new uP(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=uv,i,a,c,l){const u=await nP({serverName:e,config:t,tokenStorage:n,authRedirectUrl:s,fetchImpl:i,gtmMcpMatch:a,isScopePinGateEnabled:c});if($x({url:t.url,headers:o,accessToken:u.tokens()?.access_token})!==r.credentialFingerprint)return;const{transportHeaders:d,baseFetch:h}=lP(t.url,o,i),p=new Ix.j(new URL(t.url),{authProvider:u,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...d??{}}},fetch:h}),f=uP.createClient();return await f.connect(new Mx(p,r.result)),new uP(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 Ix.j&&await e.resumeStream("")}static async fromCommand(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{Vx(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,vl.D9)(yl.spawn,e,t,r)),u=r.args??[],d=new Px.oQ({command:r.command,args:u,env:fx(_x({command:r.command,args:u,env:n})),cwd:r.cwd,stderr:"pipe",...l&&{spawn:l}}),h=function(e){const t=new zx;let r=null===e;return null!==e&&(e.on("data",(e=>{t.full||t.push(e)})),e.once("end",(()=>{t.end(),r=!0}))),{read:()=>LE(t.text.replace(/\s+/g," ").trim(),{maxLength:SC}),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=uP.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,oP.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,oP.add(i),sP||(sP=!0,process.on("exit",iP)));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}`,Gx.set(r,t),r}(e,h.read())}finally{w=!1,void 0!==b&&clearTimeout(b)}return new uP(t,p,{initialState:{kind:"ready"},config:r,stdioServer:void 0!==m,serverSignals:Ax(d)})}catch(e){s.error=e,s.hasError=!0}finally{Kx(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 Ix.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 Ix.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=Vx(t,(0,D.VI)(e.withName("McpSdkClient.getTools")),!1);if(r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("mcp.transport",Yx(this.config)),"requires_authentication"===this.stateValue.kind)return r.span.setAttribute("mcp.tools.requires_authentication",!0),[];if("error"===this.stateValue.kind)return[];const n=++this._toolListGeneration;let o=0,s=0;try{const e=await this.tools.get((async()=>{const e=await Cx({fetchPage:async e=>{o++;const t=await async function(e,t,r){try{const r=await e.listTools({cursor:t});return{tools:r.tools,nextCursor:r.nextCursor,...Ox}}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}},Dx),o=[];let s=0,i=0,a=0;for(const e of n.tools){let t=e;if(Wx(e)){const r=e.inputSchema;Ux(r)&&(t=Bx(e,r),s++)}let n=XC.Dn.safeParse(t);if(!n.success&&(c=n.error).issues.some((e=>"outputSchema"===e.path[0]))){const o=XC.Dn.safeParse(jx(t));o.success&&(a++,r(Fx(e),Nx(n.error),"output_stripped"),n=o)}n.success?o.push(n.data):(i++,r(Fx(e),Lx(n.error.issues),"dropped"))}var c;return{tools:o,nextCursor:"string"==typeof n.nextCursor?n.nextCursor:void 0,typeFilled:s,toolDropped:i,outputStripped:a}}(this.client,e,((e,t,n)=>{(function(e,t,r){const n=JSON.stringify([e,t,r]);if(hP.has(n))return hP.delete(n),hP.add(n),!1;if(hP.add(n),hP.size>256){const e=hP.keys().next().value;void 0!==e&&hP.delete(e)}return!0})(n,this.serverName,e??"")&&Jx.warn(r.ctx,"output_stripped"===n?"Removed an MCP tool output schema the client rejected":"Left out an MCP tool whose definition is invalid",{serverName:this.serverName,..."string"==typeof e?{toolName:e}:{},issues:t})}));return s+=t.typeFilled,pP(r.ctx,"type_filled",t.typeFilled),pP(r.ctx,"tool_dropped",t.toolDropped),pP(r.ctx,"output_stripped",t.outputStripped),t},itemsOf:e=>e.tools,nextCursorOf:e=>e.nextCursor});return e.map((e=>({...e,inputSchema:m_(e.inputSchema),outputSchema:void 0===e.outputSchema?void 0:m_(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=aP(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 Ex.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",{...UE(t,this._redactLogText)}),this._stateEnteredAtMs=Date.now()}throw t}}catch(e){t.error=e,t.hasError=!0}finally{Kx(t)}}toolListAttemptIsCurrent(e){return e>this._toolListSuccessGeneration&&e>this._toolListStateGeneration}noteToolListSuccess(){this._toolListError=void 0,this._toolListSuccessGeneration=this._toolListGeneration}discardToolListError(){this._toolListError=void 0,this._toolListStateGeneration=this._toolListGeneration}noteToolListFailure(e,t,r){const n=XC.O4.MethodNotFound;if(t instanceof XC.Nh&&t.code===n&&void 0===this.client.getServerCapabilities()?.tools)return void this.noteToolListSuccess();if(t instanceof Ex.D_||!this.toolListAttemptIsCurrent(r))return;const o=function(e){if(e instanceof XC.Nh)return{descriptor:`McpError ${e.code}`,errorClass:"McpError",jsonRpcCode:e.code};if(e instanceof Ix.b||e instanceof xx._){const t=e instanceof Ix.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&&Jx.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=Vx(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",Yx(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=Vx(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{Kx(e)}}if("requires_authentication"===this.stateValue.kind)throw new Ex.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=Vx(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),Xx(e,this.config,{isError:!0===c.isError}),{content:c.content,isError:!0===c.isError,structuredContent:(i=c.structuredContent,g_(i)),_meta:C_(c._meta)}}catch(e){n.error=e,n.hasError=!0}finally{Kx(n)}}catch(t){const r=aP(t);r instanceof zC?(Xx(e,this.config,{error:r,httpStatus:r.decision.status}),function(e,t){try{Qx.increment(e,1,{decision:t.decision.kind,dropped:String(t.decision.dropped.length>0)})}catch{}}(e,r)):Xx(e,this.config,{error:r});const n=r instanceof zC&&"offer"===r.decision.kind&&void 0!==this._authProvider?.lastRedirectUrl&&this._authProvider.lastRedirectUrl!==u;if((r instanceof Ex.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",{...UE(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{Kx(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},XC.TF,n):this.client.callTool(e,void 0,n)}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{if(Vx(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{Kx(t)}}async listResources(e){const t={stack:[],error:void 0,hasError:!1};try{if(Vx(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 Cx({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{Kx(t)}}async readResource(e,t){const r={stack:[],error:void 0,hasError:!1};try{return Vx(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{Kx(r)}}async listPrompts(e){const t={stack:[],error:void 0,hasError:!1};try{return Vx(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 Cx({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{Kx(t)}}async getPrompt(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{return Vx(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{Kx(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 dP=(0,h.Pu)("mcp_tool.schema",{description:"One MCP tool definition a tools/list repair touched",labelNames:["outcome"]}),hP=new Set;function pP(e,t,r){if(0!==r)try{dP.increment(e,r,{outcome:t})}catch{}}class fP 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 mP{constructor(e){this.tools=e}async execute(e,t,r,n){const o=this.tools[e];if(!o)throw new Vk(e,Object.keys(this.tools));return o.execute(t,r,n)}getTools(){return Object.entries(this.tools).map((([e,t])=>({...t.definition,name:e})))}}class gP{async getClients(e){return{}}async getClient(e,t){}async getInstructions(e){return[]}async getToolSet(e){return new mP({})}async getTools(e){return[]}async getToolsForServers(e,t){return[]}}class wP{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=Vx(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{Kx(t)}}async getToolSet(e){const t={stack:[],error:void 0,hasError:!1};try{const r=Vx(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{Kx(t)}}async getTools(e){const t={stack:[],error:void 0,hasError:!1};try{const r=Vx(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{Kx(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 yP{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=Vx(t,(0,D.VI)(e.withName("McpManager.getToolSet")),!1),n=Vx(t,vP(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},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 mP(a)}catch(e){t.error=e,t.hasError=!0}finally{Kx(t)}}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{const r=Vx(t,(0,D.VI)(e.withName("McpManager.getInstructions")),!1),n=Vx(t,vP(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{Kx(t)}}}function vP(e){if(void 0===e)return{concurrency:4,within:(e,t,r)=>r(),[Symbol.dispose]:()=>{}};let t;const r=new Promise((r=>{t=setTimeout((()=>r(void 0)),Math.max(0,e-performance.now()))}));return{concurrency:Number.POSITIVE_INFINITY,within:async(e,t,n)=>{const o=await Promise.race([e.getState(t).catch((()=>{})),r]);return"ready"===o?.kind?n():Promise.race([n(),r])},[Symbol.dispose]:()=>clearTimeout(t)}}function bP(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 SP{constructor(e){this.options=e,WE({logger:e.logger,event:"mcp_oauth_provider_initialized",metadata:this.baseMetadata})}get baseMetadata(){return{identifier:this.options.identifier,...this.options.serverUrl?{serverUrl:SE(this.options.serverUrl)}:{}}}async loadTokens(){const e=await this.options.inner.loadTokens();return WE({logger:this.options.logger,event:"mcp_oauth_tokens_loaded",level:"debug",metadata:{...this.baseMetadata,...hx(e)}}),e}async saveTokens(e){await this.options.inner.saveTokens(e),WE({logger:this.options.logger,event:"mcp_oauth_tokens_saved",metadata:{...this.baseMetadata,...hx(e,{expiresInIsFresh:!0})}})}async prepareForRefresh(){WE({logger:this.options.logger,event:"mcp_oauth_refresh_prepare",metadata:this.baseMetadata}),await(this.options.inner.prepareForRefresh?.())}async releaseRefreshLeaseOnError(e){WE({logger:this.options.logger,event:"mcp_oauth_refresh_error_release",level:"warn",error:e,metadata:{...this.baseMetadata,...UE(e,this.options.redactLogText)}}),await(this.options.inner.releaseRefreshLeaseOnError?.(e))}async loadClientInformation(){const e=await this.options.inner.loadClientInformation();return WE({logger:this.options.logger,event:"mcp_oauth_client_info_loaded",level:"debug",metadata:{...this.baseMetadata,...CE(e)}}),e}async saveClientInformation(e){await this.options.inner.saveClientInformation(e),WE({logger:this.options.logger,event:"mcp_oauth_client_info_saved",metadata:{...this.baseMetadata,...CE(e)}})}async invalidateCredentials(e){void 0!==this.options.inner.invalidateCredentials&&(WE({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 kP{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 _P{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 CP=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},EP=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 xP=(0,d.h)("DefinitionMcpLoader"),PP=(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 IP(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 RP(e){return"getManagedSlackWorkspaceLists"in e&&"function"==typeof e.getManagedSlackWorkspaceLists}function TP(e){return"getMcpNetworkControlsConfig"in e&&"function"==typeof e.getMcpNetworkControlsConfig}function AP(e){return e?.length??0}function $P(e){if(void 0!==e)return(0,ho.createHash)("sha256").update(K_(e)).digest("hex")}function MP(e){if(void 0===e)return;let t;return r=>(void 0===t&&(t=e(),queueMicrotask((()=>{t=void 0}))),t?gC(r):r)}async function DP(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=CP(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),xP.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=CP(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(TP);return await async function(e,t,n,o,s={}){const i=n.cwd?IP({filePath:n.cwd}):void 0;let a,c;if(n.args&&n.args.length>0)a=IP({filePath:n.command,baseDir:i}),c=n.args.map((e=>IP({filePath:e,baseDir:i})));else{const e=(0,wC.A)(n.command);a=IP({filePath:e[0],baseDir:i}),c=e.slice(1).map((e=>IP({filePath:e,baseDir:i})))}const l=n.env??{},{startupTimeoutSec:u}=n,d=await(o?.getMcpNetworkControlsConfig?.({command:[n.command,...n.args??[]].join(" ")})),h=(0,yv.$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);xP.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=${AP(e.networkControlsConfig?.mcpNetworkAllowlist)}, mcpNetworkDenylistCount=${AP(e.networkControlsConfig?.mcpNetworkDenylist)}, localAgentNetworkAllowlistCount=${AP(e.networkControlsConfig?.localAgentNetworkAllowlist)}, sandboxPolicyHash=${$P(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:AP(e.networkControlsConfig?.mcpNetworkAllowlist),mcpNetworkDenylistCount:AP(e.networkControlsConfig?.mcpNetworkDenylist),localAgentNetworkAllowlistCount:AP(e.networkControlsConfig?.localAgentNetworkAllowlist),sandboxPolicyHash:$P(e.sandboxNetworkControlsConfig)}}({serverName:t,networkControlsConfig:d,sandboxNetworkControlsConfig:h}));try{return await uP.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 J_(t,e);throw e}}return!0===d?.enabled&&"no_sandbox"===d.mcpNetworkMode&&(!0===d.win32UserExtensionUnsandbox?xP.info(e,`Starting local MCP server "${t}" without MCP sandboxing`,{event:"mcp_stdio_win32_user_extension_unsandbox",serverName:t}):xP.info(e,`Starting local MCP server "${t}" without MCP sandboxing`)),uP.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=bP(e,xP),u=function(e,t,r){return{logger:{debug:(t,r)=>xP.debug(e,t,r),info:(t,r)=>xP.info(e,t,r),warn:(t,r)=>xP.warn(e,t,r),error:(t,r,n)=>xP.error(e,t,r,n)},metadata:{identifier:t,source:"mcp-agent-exec"},redactLogText:MP(r)}}(e,t,a),d=void 0!==s&&Y_(r.url)?eC(globalThis.fetch.bind(globalThis),{managedSlackWorkspaceLists:()=>s.getManagedSlackWorkspaceLists()}):void 0;return uP.fromStreamableHttp(t,r,n,r.headers,o,d,u,l,void 0,void 0,i,!1,c)}(h,t,n,o,e,d.find(RP),a,c.isLinkSharedPaymentTokenLogRedactionEnabled,l)}throw new Error(`Invalid server: ${JSON.stringify(n)}`)}catch(e){s.error=e,s.hasError=!0}finally{EP(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=Gx.get(e);void 0!==r&&Gx.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=tC(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<lC;e++){const e=n.pop();if(!(e instanceof Error||hC(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=oC(e,r),s=rC(o,t);s!==o&&nC(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=Gx.get(e);void 0!==r&&Gx.set(t,r)}(e,r),r}(e,MP(c.isLinkSharedPaymentTokenLogRedactionEnabled))}}catch(e){u.error=e,u.hasError=!0}finally{EP(u)}}class OP{constructor(e,t=B_){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 FP{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{CP(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=MP(n)??(e=>e),s=function(e){if("object"==typeof e&&null!==e)return Gx.get(e)}(r);xP.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 yP(o,this.options.elicitationFactory)}catch(e){r.error=e,r.hasError=!0}finally{EP(r)}}clearClient(e){this.clientCache.delete(e)}clearAllMcpCaches(){this.clientCache.clear()}async evictClientsOnSandboxPolicyChange(e,t){const r=this.middlewares.find(TP);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,K_(t)]}))))}catch{return}const o=this.sandboxPolicyFingerprint;this.sandboxPolicyFingerprint=n,void 0!==o&&o!==n&&(xP.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{CP(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{EP(n)}}async loadDefinitionClient(e,t,r){const n=t.authStorageKey??t.identifier,o=new kP(this.tokenStorage,n),s=bP(e,xP),i=new SP({inner:o,logger:s,redactLogText:MP(this.options.isLinkSharedPaymentTokenLogRedactionEnabled),identifier:n,serverUrl:"url"in t.serverConfig?t.serverConfig.url:void 0}),a=r?new _P(i):i;return DP(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){xP.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 t_||e instanceof r_||e instanceof n_||e instanceof NP}(r)}}class NP 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 LP=[1e3,3e3];class jP{constructor(e){this.blockingService=e,this.countedPolicyBlocks=new Set}async getMcpNetworkControlsConfig(e){return await(this.blockingService.getMcpNetworkControlsConfig?.(e))??{}}async getManagedSlackWorkspaceLists(){return await(this.blockingService.getManagedSlackWorkspaceLists?.())??[]}async load(e,t,r,n,o){const s={command:"command"in r?[r.command,...r.args??[]].join(" "):void 0,url:"url"in r?r.url:void 0},i=await(this.blockingService.getMcpServerBlockInfo?.(s))??{blocked:await this.blockingService.isServerBlocked(s)};if(i.blocked){const r=i.reason??"teamPolicy";throw"teamPolicy"!==r||this.countedPolicyBlocks.has(t)||(this.countedPolicyBlocks.add(t),PP.increment(e,1,{surface:"desktop",stage:"tool_call",reason:"server_not_allowed"})),new NP(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 X_)throw new NP(t,"teamPolicy",e.message);const r=e instanceof Q_?LP[n]:void 0;if(void 0===r)throw e;await(0,Fr.cb)(r)}}}class UP extends FP{constructor(e,t,r=[],n={}){super(new OP(e),t,r,n),this.configPath=e}static init(e,t,r=[]){return new UP(t,e,r)}}function BP(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 WP=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth.js");function HP(e){const t=WP.VE.safeParse(e);return t.success?t.data:void 0}function qP(e){const t=WP.H5.safeParse(e);return t.success?t.data:void 0}class zP{constructor(e){this.mcpAuthPath=e;const t=zP.mcpAuthPromises.get(e);if(t)this.mcpAuthPromise=t;else{const t=this.loadMcpAuth();this.mcpAuthPromise=t,zP.mcpAuthPromises.set(e,t),t.catch((()=>{zP.mcpAuthPromises.get(e)===t&&zP.mcpAuthPromises.delete(e)}))}zP.saveLocks.has(e)||zP.saveLocks.set(e,Promise.resolve())}async loadMcpAuth(){try{const e=await(0,go.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=HP(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?HP(n.tokens):void 0,clientInfo:"clientInfo"in n?qP(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=zP.saveLocks.get(this.mcpAuthPath)??Promise.resolve();let r;zP.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,go.mkdir)(s.dirname(this.mcpAuthPath),{recursive:!0}),await(0,go.writeFile)(this.mcpAuthPath,JSON.stringify(e,null,2))}}zP.mcpAuthPromises=new Map,zP.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 GP=(0,b.cF)(Symbol("execHookWorkspaceRoots"),void 0);var VP=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},KP=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const JP=(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"]}),ZP=(0,h.Pu)("mcp.filesystem.sync_check",{description:"MCP filesystem sync check executed",labelNames:["synced","mcp_source","configured_servers","mcp_version"]}),XP=(0,h.wt)("mcp.filesystem.sync_check.expected_servers",{description:"Number of expected MCP servers at last sync check",labelNames:["mcp_source","mcp_version"]}),QP=(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"]}),YP=(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"]}),eI=(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"]}),tI=(0,d.h)("McpFileSystemWriter"),rI="mcpFsStructuredLogOptIn";function nI(e,t){return t?.includeStructuredLogs?{...e??{},[rI]:!0}:e}const oI={debug(e,t,r,n){tI.debug(e,t,nI(r,n))},info(e,t,r,n){tI.info(e,t,nI(r,n))},warn(e,t,r,n){tI.warn(e,t,nI(r,n))},error(e,t,r,n,o){tI.error(e,t,r,nI(n,o))}},sI="mcps",iI="tools",aI="~staging",cI="~prev",lI=[25,50,100,200],uI=new Set(["EPERM","EBUSY","EACCES"]),dI=new Map;function hI(e){return e.slice(0,e.indexOf("~"))}function pI(e,t){return`${e}~${Date.now()}-${process.pid}-${(0,ho.randomBytes)(4).toString("hex")}${t}`}const fI=/~(\d+)-\d+-[0-9a-f]+~(?:staging|prev)$/;async function mI(e,t){const r=fI.exec(t),n=r?Number(r[1]):0;try{const{mtimeMs:r}=await(0,go.stat)((0,s.join)(e,t));return Date.now()-Math.max(n,r)>6e4}catch{return!1}}const gI="mcp_auth",wI="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.",yI="# >>> CURSOR MANAGED BLOCK >>>",vI="# <<< CURSOR MANAGED BLOCK <<<",bI=["# 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 SI(e,t,r=15e3){let n;return Promise.race([e.catch((()=>t)),new Promise((e=>{n=setTimeout((()=>e(t)),r)}))]).finally((()=>clearTimeout(n)))}function kI(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_")}function _I(e){if(void 0===e)return;const t=e.trim();return t.length>0?t:void 0}function CI(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 EI(e){if(Array.isArray(e))return e.map((e=>EI(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,EI(t)]));return Object.fromEntries(t)}return e}function xI(e){return JSON.stringify(EI(e))}function PI(e){const t=e.map((e=>({value:e,key:xI(e)})));return t.sort(((e,t)=>e.key<t.key?-1:e.key>t.key?1:0)),t.map((e=>e.value))}function II(e){const t=PI(e.tools.map((e=>({name:e.toolName,description:e.description,inputSchema:e.inputSchema,outputSchema:e.outputSchema})))),r=PI(e.resources.map((e=>({uri:e.uri,name:e.name,description:e.description,mimeType:e.mimeType})))),n=PI(e.prompts.map((e=>({name:e.name,description:e.description,arguments:e.arguments}))));return xI({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 RI{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=>{oI.info(this.ctx,"Lease change event received",{serverIdentifiers:e?.serverIdentifiers,reason:e?.reason}),this.onLeaseChanged(this.ctx,e)})),oI.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=`${yI}\n${bI}\n${vI}\n`;let n;await(0,go.mkdir)(e,{recursive:!0});try{n=await(0,go.readFile)(t,"utf-8")}catch(e){if("ENOENT"!==Wa(e))throw e}if(void 0===n)return void await(0,go.writeFile)(t,r);const o=n.indexOf(yI),i=n.indexOf(vI,o+30);if(-1===o||-1===i)await(0,go.writeFile)(t,r);else{const e=`${n.slice(0,o)}${r}${n.slice(i+30).replace(/^\n/,"")}`;e!==n&&await(0,go.writeFile)(t,e)}})((0,s.join)((0,o.homedir)(),".cursor")).catch((e=>{oI.warn(this.ctx,"Failed to ensure ~/.cursor/.gitignore",e)}))}async cleanupStaleStagingDirs(e){const t=this.getLogContext(e),r=(0,s.join)(this.projectDir,sI);try{const e=await(0,go.readdir)(r);await Promise.allSettled(e.filter((e=>e.endsWith(aI))).map((async e=>{await mI(r,e)&&await(0,go.rm)((0,s.join)(r,e),{recursive:!0,force:!0})})))}catch(e){"ENOENT"!==Wa(e)&&oI.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:Gn(r)?{serverIdentifiers:void 0,reason:t?.reason??r?.reason}:void 0===t?r:Gn(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){oI.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 _I(this.mcpAuthCopyOverrides?.authToolDescription)??wI}shouldExposeVirtualMcpAuthToolForStatus(e,t){return this.exposeVirtualMcpAuthTool&&Bn(e)&&(this.alwaysExposeVirtualMcpAuthTool||"needsAuth"===t)}getErrorStatusMessage(){return _I(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=_I(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:gI},t.replace(/\{serverIdentifier\}/g,r.serverIdentifier).replace(/\{authToolName\}/g,r.authToolName);var t,r}getNeedsAuthStatusMessageForWrite(e){return this.exposeVirtualMcpAuthTool&&Bn(e)?this.getNeedsAuthStatusMessage(e):_I(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){oI.warn(r,`getToolsForServers() threw, falling back to filtered getTools(): ${Ha(n)}`);const o=await this.mcpLease.getTools(e).catch((e=>(oI.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 SI(r.getState(e),{kind:"error"}).then((r=>("error"!==r.kind||"message"in r||oI.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?SI(r.listResources(e),{resources:[]}):Promise.resolve({resources:[]}),s?SI(r.listPrompts(e),[]):Promise.resolve([]),s&&n?.fetchInstructions?SI(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:CI(o)}}buildServerDataMap(e,t,r){const n=new Map;for(const e of t){const t=Cw(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,sI,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=Cw(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,sI,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===gI))||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:gI,name:gI,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)?oI.warn(e,`Skipping server "${o.serverIdentifier}" — sanitizedId "${o.sanitizedId}" collides with another server`):(n.add(o.sanitizedId),r.push(o)):oI.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===gI))){const t=e.tools.find((e=>e.toolName===gI));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??[])];oI.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=>(oI.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 oI.warn(r,`getClient("${t}") threw during scoped refresh, preserving cached data: ${Ha(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=>{oI.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):oI.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)),oI.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=Cw(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{VP(r,(0,D.VI)(e.withName("McpFileSystemWriter.fetchAndWrite")),!1);const n=this.getLogContext(e);try{if(void 0!==this.cachedServerData&&void 0!==t&&!Gn(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=>(oI.warn(n,`getTools() threw, defaulting to []: ${e}`),[]))),this.mcpLease.getInstructions(e).catch((()=>[])),this.mcpLease.getClients(e).catch((e=>(oI.warn(n,`getClients() threw, defaulting to {}: ${e}`),{})))]),i=Object.keys(s);oI.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){oI.error(n,"Error fetching/writing MCP state",e)}}catch(e){r.error=e,r.hasError=!0}finally{KP(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,iI,`${kI(t.toolName)}.json`)})))})));this.onDidWrite(t)}catch{}}async writeServerData(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{VP(n,(0,D.VI)(e.withName("McpFileSystemWriter.writeServerData")),!1);const o=this.getLogContext(e),i=(0,s.join)(this.projectDir,sI);await(0,go.mkdir)(i,{recursive:!0});const a=new Map;for(const e of t)try{a.set(e.serverIdentifier,II(e))}catch(t){oI.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&&oI.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,go.stat)((0,s.join)(i,e.sanitizedId))}catch{oI.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??Cw(e);r.has(n)?(oI.info(o,`Server "${e}" (sanitized="${n}") still in lease but excluded from write, preserving directory`),a.set(e,this.cachedFingerprints.get(e))):(oI.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,go.readdir)(i),t=new Set(e.filter((e=>!e.endsWith(aI)&&!e.endsWith(cI))));for(const r of e){const e=r.endsWith(aI),n=r.endsWith(cI);if((e||n)&&await mI(i,r))if(e)await(0,go.rm)((0,s.join)(i,r),{recursive:!0,force:!0});else{const e=hI(r);if(t.has(e))await(0,go.rm)((0,s.join)(i,r),{recursive:!0,force:!0});else try{await(0,go.rename)((0,s.join)(i,r),(0,s.join)(i,e)),t.add(e)}catch{await(0,go.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){oI.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})));oI.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,ho.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),oI.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,go.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];oI.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{KP(n)}}async writeServerAtomic(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{VP(n,(0,D.VI)(e.withName("McpFileSystemWriter.writeServerAtomic")),!1);const o=(0,s.join)(r,t.sanitizedId),i=dI.get(o),a=(async()=>{await(i?.catch((()=>{}))),await this.swapServerDirectory(e,t,r)})();dI.set(o,a);try{await a}finally{dI.get(o)===a&&dI.delete(o)}}catch(e){n.error=e,n.hasError=!0}finally{KP(n)}}async swapServerDirectory(e,t,r){const n=pI(t.sanitizedId,aI),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,go.rm)(o,{recursive:!0,force:!0}).catch((()=>{})),e}const a=(0,s.join)(r,pI(t.sanitizedId,cI));let c=!1;try{try{await this.renameWithRetry(i,a),c=!0}catch(e){if("ENOENT"!==Wa(e))throw e}await this.renameWithRetry(o,i)}catch(r){if(oI.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,go.stat)(i).then((()=>!0),(()=>!1))&&await(0,go.rm)(a,{recursive:!0,force:!0}).catch((()=>{}))}throw await(0,go.rm)(o,{recursive:!0,force:!0}).catch((()=>{})),r}await(0,go.rm)(a,{recursive:!0,force:!0}).catch((()=>{}))}async renameWithRetry(e,t){for(let r=0;;r++)try{return void await(0,go.rename)(e,t)}catch(e){const t=Wa(e);if(r>=lI.length||void 0===t||!uI.has(t))throw e;await(0,Fr.cb)(lI[r])}}async writeServerDirectory(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{VP(n,(0,D.VI)(e.withName("McpFileSystemWriter.writeServerDirectory")),!1);const o=(0,s.join)(r.basePath,r.dirName??t.sanitizedId);if(await(0,go.mkdir)(o,{recursive:!0}),t.tools.length>0){const e=(0,s.join)(o,iI);await(0,go.mkdir)(e,{recursive:!0});for(const r of t.tools){const t=kI(r.toolName),n=(0,s.join)(e,`${t}.json`),o=qn(r);await(0,go.writeFile)(n,JSON.stringify(o,null,2))}}if(t.resources.length>0){const e=(0,s.join)(o,"resources");await(0,go.mkdir)(e,{recursive:!0});for(const r of t.resources){const t=kI(r.name||r.uri.replace(/[^a-zA-Z0-9_-]/g,"_")),n=(0,s.join)(e,`${t}.json`),o={uri:r.uri,name:r.name,description:r.description,mimeType:r.mimeType};await(0,go.writeFile)(n,JSON.stringify(o,null,2))}}if(t.prompts.length>0){const e=(0,s.join)(o,"prompts");await(0,go.mkdir)(e,{recursive:!0});for(const r of t.prompts){const t=kI(r.name),n=(0,s.join)(e,`${t}.json`),o={name:r.name,description:r.description,arguments:r.arguments};await(0,go.writeFile)(n,JSON.stringify(o,null,2))}}if(t.instructions&&t.instructions.trim().length>0){const e=(0,s.join)(o,"INSTRUCTIONS.md");await(0,go.writeFile)(e,t.instructions.trim())}if("error"===t.status||"needsAuth"===t.status){const e=(0,s.join)(o,"STATUS.md"),r="error"===t.status?this.getErrorStatusMessage():this.getNeedsAuthStatusMessageForWrite(t.serverIdentifier);await(0,go.writeFile)(e,r)}const i=(0,s.join)(o,"SERVER_METADATA.json"),a={serverIdentifier:t.serverIdentifier,serverName:t.serverName};await(0,go.writeFile)(i,JSON.stringify(a,null,2))}catch(e){n.error=e,n.hasError=!0}finally{KP(n)}}async getMcpFileSystemOptions(e,t){const r={stack:[],error:void 0,hasError:!1};try{if(this.disposed)return;VP(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&&oI.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=kI(t.toolName),n=(0,s.join)(e.folderPath,iI,`${r}.json`);return new gn.E$({toolName:t.toolName,definitionPath:n,...wv(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{KP(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&&oI.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){oI.error(r,"Error waiting for pending write to complete",e)}finally{clearTimeout(e)}return n&&oI.warn(r,`getMcpFileSystemOptions timed out after ${t}ms waiting for write; returning stale cache`),n}try{await this.writePromise}catch(e){oI.error(r,"Error waiting for pending write to complete",e)}return!1}async buildOptionsFromSnapshots(e){const t={stack:[],error:void 0,hasError:!1};try{VP(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,sI),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=Cw(e.serverIdentifier),r=(0,s.join)(i,t),n=e.tools.map((e=>{const t=kI(e.name);return new gn.E$({toolName:e.name,definitionPath:(0,s.join)(r,iI,`${t}.json`),...wv(e.annotations)})}));if(this.shouldExposeVirtualMcpAuthToolForStatus(e.serverIdentifier,e.status)&&!e.tools.some((e=>e.name===gI))){const e=kI(gI);n.push(new gn.E$({toolName:gI,definitionPath:(0,s.join)(r,iI,`${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 oI.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{KP(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<RI.DIVERGENCE_CHECK_COOLDOWN_MS||(this.lastDivergenceCheckMs=o,this._checkDescriptorsVsFilesystemAsync(e,t,r).catch((e=>{oI.warn(n,"Divergence check failed",e)})))}async _checkDescriptorsVsFilesystemAsync(e,t,r){const n=this.getLogContext(e),o=(0,s.join)(this.projectDir,sI),i=new Set,a=new Map;for(const e of t){const t=Cw(e.serverIdentifier);i.add(t),a.set(t,e.tools.length)}let c=[];try{c=await(0,go.readdir)(o),c=c.filter((e=>!e.endsWith(aI)&&!e.endsWith(cI)))}catch(e){if("ENOENT"!==Wa(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++,JP.increment(e,1,this.getMetricTags({divergence_type:"server_missing",mcp_source:r,configured_servers:f})),oI.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++,JP.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,iI);let h=0;try{h=(await(0,go.readdir)(d)).filter((e=>e.endsWith(".json"))).length}catch{}h!==c&&(u=!1,p++,JP.increment(e,1,this.getMetricTags({divergence_type:"tool_count_mismatch",mcp_source:r,configured_servers:f})),oI.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}))}ZP.increment(e,1,this.getMetricTags({synced:String(u),mcp_source:r,configured_servers:f})),XP.gauge(e,i.size,this.getMetricTags({mcp_source:r})),QP.gauge(e,l.size,this.getMetricTags({mcp_source:r})),YP.gauge(e,d,this.getMetricTags({mcp_source:r})),eI.gauge(e,p,this.getMetricTags({mcp_source:r})),oI.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||oI.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())}}RI.DIVERGENCE_CHECK_COOLDOWN_MS=1e4;var TI=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},AI=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 $I(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 MI=(0,d.h)("local-exec:mcp");function DI(e,t){const r=s.relative(e,t);return""===r||!s.isAbsolute(r)&&".."!==r&&!r.startsWith(`..${s.sep}`)}function OI(e){return e instanceof Error&&"code"in e&&"string"==typeof e.code?e.code:void 0}function FI(e){return new Qa._Z({content:{case:"image",value:new Qa.do({data:e.data,mimeType:e.mimeType})}})}function NI(e){return new Qa._Z({content:{case:"text",value:new Qa.zN({text:e})}})}async function LI(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 du(n,{onNeedsApproval:async(e,n)=>{if("mcp"!==n.type)return new Qa.iz({result:{case:"error",value:new Qa.Nh({error:"Invalid approval details type for MCP execution"})}});const o=await r.pendingDecisionProvider.requestApproval({type:Rg.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 Qa.iz({result:{case:"approved",value:new Qa.Ke}}):null:new Qa.iz({result:{case:"rejected",value:new Qa.xo({reason:`User rejected MCP: ${t.name}${o.reason?` - ${o.reason}`:""}`})}})},onUserRejected:e=>new Qa.iz({result:{case:"error",value:new Qa.Nh({error:`User rejected MCP: ${t.name}${e?` - ${e}`:""}`})}}),onPermissionDenied:(e,r)=>{const n=`MCP tool execution blocked: ${t.name} - ${e}`;return new Qa.iz({result:{case:"permissionDenied",value:new Qa.HQ({error:n,isReadonly:r?.isReadonly??!1})}})}});return o??void 0}class jI{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}}(Vn(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=TI(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 Qa.iz({result:{case:"error",value:new Qa.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 LI(o,t,{permissionsService:this.permissionsService,pendingDecisionProvider:this.pendingDecisionProvider,toolDef:l,...void 0===d?{}:{client:d},...void 0===h?{}:{resolvedTool:void 0===p?"unresolved":{client:p,annotations:h.annotations}}});if(void 0!==f)return f;const m=await this.toolSet.getToolSet(o),g=void 0===h&&!0===await(this.permissionsService.enforcesMcpAdminToolLimits?.());let w;try{if(g)throw new Vk(t.name,a.map((e=>e.name)));w=await m.execute(l?.name??t.name,Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t.toJson()]))),t.toolCallId,this.elicitationFactory)}catch(e){let r=e;if(Kk(r)&&t.providerIdentifier.length>0&&!a.some((e=>e.clientKey===t.providerIdentifier||e.providerIdentifier===t.providerIdentifier))&&(r=new fP(t.providerIdentifier,c)),r instanceof fP){const e=await this.describeDisconnectedServer(o,[i,t.providerIdentifier]);return void 0!==e?new Qa.iz({result:{case:"error",value:new Qa.Nh({error:e})}}):new Qa.iz({result:{case:"serverNotFound",value:new Qa.JL({name:r.serverName,availableServers:r.availableServers})}})}if(Kk(r))return new Qa.iz({result:{case:"toolNotFound",value:new Qa.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(NI(e.text));else if("resource"===r){const r=k_(e),n=void 0===r?void 0:Buffer.from(r,"base64"),s=void 0===n?void 0:await _y(n).then(FI,(e=>{MI.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??NI(__(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 _y(s)}catch(e){MI.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(NI(`[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(FI(i))}else if("image"!==r){const t=__(e);y.push(NI(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 Qa._Z({content:{case:"text",value:new Qa.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,Ya),n=s.join(r,`${(0,ho.randomUUID)()}.txt`);await(0,go.mkdir)(s.dirname(n),{recursive:!0});const o=jo(e,ec),i=Ws(o),a=Buffer.byteLength(o,"utf8");return await(0,go.writeFile)(n,o,"utf8"),new tc.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 Qa.QW({content:v,isError:w.isError,structuredContent:b,resultMeta:void 0===w._meta?void 0:ve.Struct.fromJson(w._meta)});return new Qa.iz({result:{case:"success",value:S}})}catch(e){r.error=e,r.hasError=!0}finally{AI(r)}var n}}class UI{constructor(e,t){this.mcpLease=e,this.ensureMcpServersLoaded=t}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=TI(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 Qa.kP({result:{case:"error",value:new Qa.w2({error:`Server "${t.server}" not found`})}});const o=await this.listResourcesFromClient(n,r,t.server,!0);return new Qa.kP({result:{case:"success",value:new Qa.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 Qa.kP({result:{case:"success",value:new Qa.T2({resources:s})}})}catch(e){const t=e instanceof Error?e.message:String(e);return new Qa.kP({result:{case:"error",value:new Qa.w2({error:`Failed to list MCP resources: ${t}`})}})}}catch(e){r.error=e,r.hasError=!0}finally{AI(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 Qa.X2({uri:e.uri,name:e.name,description:e.description,mimeType:e.mimeType,server:r,annotations:$I(e.annotations)}))):[]}}class BI{constructor(e,t=".",r,n=[],o,s){this.mcpLease=e,this.projectDir=t,this.permissionsService=r,this.pendingDecisionProvider=o,this.ensureMcpServersLoaded=s,this.workspacePaths=n.filter((e=>e.length>0))}resolveProjectDir(e){const t=e.get(GP),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=TI(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 Qa.ZD({result:{case:"error",value:new Qa.Jx({uri:t.uri,error:"Auto-review approval provider is not configured"})}});const e=await this.pendingDecisionProvider.requestApproval({type:Rg.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 Qa.ZD({result:{case:"rejected",value:new Qa.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 Qa.ZD({result:{case:"error",value:new Qa.Jx({uri:t.uri,error:`Server "${t.server}" not found`})}});try{if("ready"!==(await a.getState(n)).kind)return new Qa.ZD({result:{case:"error",value:new Qa.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 Qa.ZD({result:{case:"notFound",value:new Qa.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,go.realpath)(r),o=s.resolve(r,t.replace(/^\/+/,""));if(!DI(r,o))throw new Error("downloadPath must stay within the workspace");let i=s.dirname(o);for(;;)try{if(!DI(n,await(0,go.realpath)(i)))throw new Error("downloadPath must stay within the workspace");break}catch(e){if("ENOENT"!==OI(e))throw e;const t=s.dirname(i);if(t===i)throw e;i=t}if(await(0,go.mkdir)(s.dirname(o),{recursive:!0}),!DI(n,await(0,go.realpath)(s.dirname(o))))throw new Error("downloadPath must stay within the workspace");try{if((await(0,go.lstat)(o)).isSymbolicLink())throw new Error("downloadPath must stay within the workspace")}catch(e){if("ENOENT"!==OI(e))throw e}return o}(this.resolveProjectDir(n),t.downloadPath);if(r.text)await(0,go.writeFile)(e,r.text,"utf8");else if(r.blob){const t=Buffer.from(r.blob,"base64");await(0,go.writeFile)(e,t)}return new Qa.ZD({result:{case:"success",value:new Qa.KZ({uri:t.uri,name:r.name,description:r.description,mimeType:r.mimeType,downloadPath:e})}})}if(r.text)return new Qa.ZD({result:{case:"success",value:new Qa.KZ({uri:t.uri,name:r.name,description:r.description,mimeType:r.mimeType,annotations:$I(r.annotations),metaJson:Hn(r._meta),content:{case:"text",value:r.text}})}});if(r.blob){const e=Buffer.from(r.blob,"base64");return new Qa.ZD({result:{case:"success",value:new Qa.KZ({uri:t.uri,name:r.name,description:r.description,mimeType:r.mimeType,annotations:$I(r.annotations),metaJson:Hn(r._meta),content:{case:"blob",value:e}})}})}return new Qa.ZD({result:{case:"error",value:new Qa.Jx({uri:t.uri,error:"Failed to read resource"})}})}catch(e){const r=e instanceof Error?e.message:String(e);return MI.warn(n,"LocalReadMcpResourceExecutor.execute failed",{server:t.server,hasDownloadPath:Boolean(t.downloadPath),errorName:e instanceof Error?e.name:typeof e,errorMessage:r}),new Qa.ZD({result:{case:"error",value:new Qa.Jx({uri:t.uri,error:`Failed to read MCP resource: ${r}`})}})}}catch(e){r.error=e,r.hasError=!0}finally{AI(r)}}}var WI=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 HI=1e4,qI=5e3,zI={PAGER:"cat",MANPAGER:"cat",LESS:"-R",PIP_PROGRESS_BAR:"off",TQDM_DISABLE:"1"};class GI{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<qI&&(this.outputHead=jo(this.outputHead+e,qI)),this.outputTail=Uo(this.outputTail+e,qI),t<HI){const r=Math.min(e.length,HI-t);this.fullOutput+=e.slice(0,r)}this.totalChars>HI&&(this.fullOutput="")}getOutput(){return this.totalChars<=HI?this.fullOutput:void 0}getTruncation(){if(!(this.totalChars<=HI))return{outputHead:this.outputHead,outputTail:this.outputTail,elidedChars:this.totalChars-this.outputHead.length-this.outputTail.length}}}class VI{constructor(){this.kept="",this.full=!1}append(e){if(this.full)return;const t=Ko-this.kept.length;this.full=e.length>=t,this.kept+=jo(e,t)}get text(){return this.kept}}function KI(e,t){return null!==e?e:null===t?-1:-o.constants.signals[t]}class JI{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:rs(n)})}async runProcess({ctx:e,args:t,workingDirectory:r,sandboxPolicy:n,timeoutMs:o}){const s=performance.now(),i=this.defaultCwd,a=(await(0,Po.resolveSandboxPolicyForWorkspace)(i,n?{perRepo:n}:void 0)).policy,c="insecure_none"!==a.type?{...a,sandboxWorkspaceRoot:i}:a;return await new Promise((n=>{const i=new GI,a=new VI,l=new VI;let u,d,h=!1,p=!1,f="",m=()=>{};const g=(0,Po.Qw)((0,Po.ue)((0,Po.Xw)({...process.env,...zI,CURSOR_AGENT:"1"}))),w={cwd:r,env:g,stdio:["pipe","pipe","pipe"],detached:"win32"!==process.platform,windowsVerbatimArguments:"win32"===process.platform},y="win32"===process.platform?{executable:process.env.ComSpec??"cmd.exe",args:(v=t.command,["/d","/s","/c",`"${v}"`])}:{executable:"/bin/sh",args:["-c",t.command]};var v;const b="insecure_none"===c.type?(0,vl.D9)(yl.spawn,y.executable,y.args,w):(0,Po.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:_w(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:KI(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?ts(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,Es()&&(a=As(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{WI(r)}}}const ZI=G("shell-executor",(e=>new H(e,Q("shellArgs"),Y("shellResult"))),((e,t)=>{t.register(new A(e,te("shellArgs"),ee("shellResult")))})),XI=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 QI(e){return`${e} changed on disk after this tool call read it. Nothing was written. Read the file again and retry.`}function YI(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 eR=G("write-executor",(e=>new H(e,Q("writeArgs"),Y("writeResult"))),((e,t)=>{t.register(new A(e,te("writeArgs"),ee("writeResult")))})),tR=G("delete-executor",(e=>new H(e,Q("deleteArgs"),Y("deleteResult"))),((e,t)=>{t.register(new A(e,te("deleteArgs"),ee("deleteResult")))})),rR=G("fetch-executor",(e=>new H(e,Q("fetchArgs"),Y("fetchResult"))),((e,t)=>{t.register(new A(e,te("fetchArgs"),ee("fetchResult")))})),nR=G("git-diff-executor",(e=>new H(e,Q("gitDiffRequest"),Y("gitDiffResponse"))),((e,t)=>{t.register(new A(e,te("gitDiffRequest"),ee("gitDiffResponse")))})),oR=G("grep-executor",(e=>new H(e,Q("grepArgs"),Y("grepResult"))),((e,t)=>{t.register(new A(e,te("grepArgs"),ee("grepResult")))})),sR="[REDACTED]",iR=new TextEncoder;async function aR(e){const t=iR.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 cR{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 aR(t.output.value),o=t.clone();return o.output={case:void 0},o.outputBlobId=void 0,o.sha256=r,o.sizeBytes=BigInt(n),new jw.sV({result:{case:"success",value:o}})}(await this.inner.execute(e,n,r))}}const lR=G("read-executor",(e=>new H(e,Q("readArgs"),Y("readResult"))),((e,t)=>{t.register(new A(e,te("readArgs"),ee("readResult")))})),uR=G("redacted-read-executor",(e=>new H(e,Q("redactedReadArgs"),Y("redactedReadResult"))),((e,t)=>{t.register(new A(e,te("redactedReadArgs"),ee("redactedReadResult")))})),dR=G("ls-executor",(e=>new H(e,Q("lsArgs"),Y("lsResult"))),((e,t)=>{t.register(new A(e,te("lsArgs"),ee("lsResult")))})),hR=G("diagnostics-executor",(e=>new H(e,Q("diagnosticsArgs"),Y("diagnosticsResult"))),((e,t)=>{t.register(new A(e,te("diagnosticsArgs"),ee("diagnosticsResult")))})),pR=G("canvas-diagnostics-executor",(e=>new H(e,Q("canvasDiagnosticsArgs"),Y("canvasDiagnosticsResult"))),((e,t)=>{t.register(new A(e,te("canvasDiagnosticsArgs"),ee("canvasDiagnosticsResult")))})),fR="$file:";const mR=(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"]}),gR=(0,h.v5)("mcp.symbolic_args.bytes",{description:"Total bytes substituted into one MCP tool call by $file:/abs/path arguments",labelNames:["route"]}),wR=(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"]}),yR=(0,h.v5)("mcp.symbolic_args.paths",{description:"Number of distinct $file:/abs/path arguments expanded in one MCP tool call",labelNames:["route"]});function vR(e,t,r){return{kind:e,message:`Could not resolve the symbolic argument "${fR}${t}": ${r} A string argument of the form "${fR}/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 bR={redacted:e=>`${e} contains a saved secret, and a saved secret is never sent through a "${fR}/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 "${sR}", 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 SR(e,t){return{kind:e,message:`Could not resolve the symbolic argument "${fR}${t}": ${bR[e](t)}`}}class kR extends Error{constructor(e){super(e.message),this.failure=e}}let _R;async function CR(e,t,r,n,o,{maxFileBytes:s=8388608,maxTotalBytes:i=16777216,refuseSavedSecrets:a=!1}){if(t.length>4)throw new kR(vR("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 kR(vR("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 jw.a2({path:r,toolCallId:n,...o.digestOnly?{digestOnly:!0}:{}}));if("success"!==s.result.case)throw new kR(function(e,t,r){switch(e.result.case){case"fileNotFound":return vR("not_found",t,"the file does not exist.");case"permissionDenied":return vR("permission_denied",t,"reading it was not permitted.");case"rejected":return vR("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 vR("not_text",t,"the file cannot be read as text.");case"error":return r?{kind:"read_error",message:`Could not resolve the symbolic argument "${fR}${t}": ${e.result.value.error}`}:vR("read_error",t,e.result.value.error);default:return vR("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 kR(vR("not_text",r,"the file is not a text file."));if(n){if(wR.increment(e,1,{source:void 0!==o?"vm_digest":"outdated_executor"}),void 0===o)throw new kR(vR("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 aR(a??""),u={content:a,bytes:l,sha256:c};if(t.truncated||l>n)throw new kR(vR("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 kR(SR("redacted",r));if(void 0===e.redacted&&await async function(e){return void 0!==e.content?e.content.includes(sR):(await(_R??=Promise.all([sR,`${sR}\n`,`${sR}\r\n`].map((async e=>(await aR(e)).sha256))).then((e=>new Set(e))),_R)).has(e.sha256)}(t))throw new kR(SR("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 kR(vR("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 ER(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=>(mR.increment(e,1,{route:r,outcome:t.kind}),{kind:"failed",failure:t,result:new Qa.iz({result:{case:"error",value:new Qa.Nh({error:t.message})}})});let c;try{c=await CR(e,i,n,t.toolCallId,!1,o)}catch(e){return a(function(e,t){return e instanceof kR?e.failure:vR("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(vR("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(fR))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,mR.increment(e,1,{route:r,outcome:"expanded"}),gR.record(e,l,{route:r}),yR.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 xR=/\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 PR(e,t,r,n){return xR.test(t)?(mR.increment(e,1,{route:n,outcome:"server_rejected_body"}),`${t}\n\nThe request carried ${r.bytes} bytes of file contents substituted from ${r.paths} "${fR}/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 IR(e){return e.files.map((e=>`"${fR}${e.path}" was replaced with the contents of ${e.path} (${e.bytes} bytes) before the call.`)).join("\n")}class RR{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 ER(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=PR(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 Qa._Z({content:{case:"text",value:new Qa.zN({text:IR(r)})}})):"error"===n.result.case&&(n.result.value.error=PR(e,n.result.value.error,r,"local")),n}(e,o,n.expansion)}}const TR=G("background-shell-executor",(e=>new H(e,Q("backgroundShellSpawnArgs"),Y("backgroundShellSpawnResult"))),((e,t)=>{t.register(new A(e,te("backgroundShellSpawnArgs"),ee("backgroundShellSpawnResult")))})),AR=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")))})),$R=G("agent-store-conflict-executor",(e=>new H(e,Q("agentStoreConflictArgs"),Y("agentStoreConflictResult"))),((e,t)=>{t.register(new A(e,te("agentStoreConflictArgs"),ee("agentStoreConflictResult")))})),MR=G("shell-allowlist-precheck-executor",(e=>new H(e,Q("shellAllowlistPrecheckArgs"),Y("shellAllowlistPrecheckResult"))),((e,t)=>{t.register(new A(e,te("shellAllowlistPrecheckArgs"),ee("shellAllowlistPrecheckResult")))})),DR=G("mcp-allowlist-precheck-executor",(e=>new H(e,Q("mcpAllowlistPrecheckArgs"),Y("mcpAllowlistPrecheckResult"))),((e,t)=>{t.register(new A(e,te("mcpAllowlistPrecheckArgs"),ee("mcpAllowlistPrecheckResult")))})),OR=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")))})),FR=G("force-background-shell-executor",(e=>new H(e,Q("forceBackgroundShellArgs"),Y("forceBackgroundShellResult"))),((e,t)=>{t.register(new A(e,te("forceBackgroundShellArgs"),ee("forceBackgroundShellResult")))})),NR=G("computer-use-executor",(e=>new H(e,Q("computerUseArgs"),Y("computerUseResult"))),((e,t)=>{t.register(new A(e,te("computerUseArgs"),ee("computerUseResult")))})),LR=G("record-screen-executor",(e=>new H(e,Q("recordScreenArgs"),Y("recordScreenResult"))),((e,t)=>{t.register(new A(e,te("recordScreenArgs"),ee("recordScreenResult")))}));var jR=r("../proto/dist/generated/agent/v1/agent_store_conflict_exec_pb.js");function UR(e){if(void 0!==e)return{journalEpoch:e.journalEpoch,seq:Number(e.seq),lastEventId:e.lastEventId}}class BR{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:UR(t.cursor),advance:!1!==t.advance});return new jR.Ev({result:{case:"success",value:new jR.iS({events:e.events.map((e=>new jR.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 jR.LK({journalEpoch:r.journalEpoch,seq:BigInt(r.seq),lastEventId:r.lastEventId})),gap:e.gap})}})}catch(e){return new jR.Ev({result:{case:"error",value:new jR.h6({error:e instanceof Error?e.message:String(e)})}})}var r}}class WR{constructor(e){this.shellStdinWriter=e}async execute(e,t){const r=t.shellId;try{await this.shellStdinWriter(r,t.chars)}catch(e){return new xo.nt({result:{case:"error",value:new xo.Gv({error:`Failed to write to shell ${r} stdin: ${e instanceof Error?e.message:"Unknown error"}`})}})}return new xo.nt({result:{case:"success",value:new xo.tR({shellId:r,terminalFileLengthBeforeInputWritten:0})}})}}var HR=r("../proto/dist/generated/agent/v1/canvas_diagnostics_exec_pb.js"),qR=r("../proto/dist/generated/agent/v1/diagnostics_exec_pb.js");class zR{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"),GR(VR(t.path,"diagnostics unavailable"),await o)):(r(e.some((e=>1===e.severity))?"failed":"passed"),GR(new HR.GL({result:{case:"success",value:new HR.uX({path:t.path,diagnostics:e.map(KR)})}}),await o))}catch(e){return r("unavailable"),GR(VR(t.path,e instanceof Error?e.message:String(e)),await o)}}}function GR(e,t){return void 0===t||(e.saveState=t.saveState,e.canvasId=t.canvasId,e.title=t.title,e.saveDetail=t.saveDetail),e}function VR(e,t){return new HR.GL({result:{case:"error",value:new HR.HW({path:e,error:t})}})}function KR(e){return new qR.oQ({severity:JR(e.severity),range:new tc.Q6({start:new tc.yX({line:e.range.start.line+1,column:e.range.start.character+1}),end:new tc.yX({line:e.range.end.line+1,column:e.range.end.character+1})}),message:e.message,source:"ts",code:e.code??""})}function JR(e){switch(e){case 1:return qR.h_.ERROR;case 2:return qR.h_.WARNING;case 3:return qR.h_.INFORMATION;case 4:return qR.h_.HINT;default:return qR.h_.UNSPECIFIED}}class ZR{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 ZR(e)}static fromUrl(e){if(!e.startsWith("file://"))throw new Error(`Expected file:// URL, got: ${e}`);return new ZR(e)}static fromString(e){return new ZR(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 XR=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class QR{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,go.stat)(r);if(!e.isFile()&&!e.isDirectory())return new qR.Ek({result:{case:"fileNotFound",value:new qR.Mu({path:t.path})}})}catch(e){if("ENOENT"===Wa(e))return new qR.Ek({result:{case:"fileNotFound",value:new qR.Mu({path:t.path})}});if("EACCES"===Wa(e))return new qR.Ek({result:{case:"permissionDenied",value:new qR.RP({path:t.path})}});throw e}const n=(0,zo.o1)(r,this.workspacePath),o=new ZR(n);await this.diagnosticsProvider.open(e,o);const s=(await this.diagnosticsProvider.getDiagnostics(e,o)).map((e=>this.convertDiagnostic(e)));return new qR.Ek({result:{case:"success",value:new qR.a1({path:t.path,diagnostics:s,totalDiagnostics:s.length})}})}catch(r){return e.canceled?new qR.Ek({result:{case:"error",value:new qR.Ho({path:t.path,error:"Request timed out after 10 seconds"})}}):new qR.Ek({result:{case:"error",value:new qR.Ho({path:t.path,error:r instanceof Error?r.message:String(r)})}})}finally{n()}}catch(e){r.error=e,r.hasError=!0}finally{XR(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 qR.oQ({severity:this.convertSeverity(e.severity),range:e.range?new tc.Q6({start:new tc.yX({line:e.range.start.line,column:e.range.start.character}),end:new tc.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 qR.h_.ERROR;case 2:return qR.h_.WARNING;case 3:return qR.h_.INFORMATION;case 4:return qR.h_.HINT;default:return qR.h_.UNSPECIFIED}}}async function YR(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 uw().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 eT(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 eT(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 eT{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 tT=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]=oT(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=iT(e)}],[/^\+\+\+\s/,e=>{u(),n.to=iT(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},rT=/(a|i|w|c|o|1|2)\/.*(?=["']? ["']?(b|i|w|c|o|1|2)\/)|(b|i|w|c|o|1|2)\/.*$/g,nT=/^(a|b|i|w|c|o|1|2)\//,oT=e=>{const t=e?.match(rT);return t?.map((e=>e.replace(nT,"").replace(/("|')$/,"")))},sT=/^\\?['"]|\\?['"]$/g,iT=e=>{let t=aT(e,"-+").trim();return t=lT(t),t.replace(sT,"").replace(nT,"")},aT=(e,t)=>{if(e=dT(e),!t&&String.prototype.trimLeft)return e.trimLeft();const r=uT(t);return e.replace(new RegExp(`^${r}+`),"")},cT=/\t.*|\d{4}-\d\d-\d\d\s\d\d:\d\d:\d\d(.\d+)?\s(\+|-)\d\d\d\d/,lT=e=>{const t=cT.exec(e);return t&&(e=e.substring(0,t.index).trim()),e},uT=e=>null==e?"\\s":e instanceof RegExp?e.source:`[${dT(e).replace(/([.*+?^=!:${}()|[\]/\\])/g,"\\$1")}]`,dT=e=>`${e??""}`,hT=(0,d.h)("local-mercurial-diff"),pT=5242880,fT="0000000000000000000000000000000000000000";let mT,gT;async function wT(e,t,r={}){const n=await async function(){if(void 0===mT&&(mT=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 go.stat(t)).isFile())continue;return"win32"!==process.platform&&await go.access(t,yo.constants.X_OK),t}catch{}}}(process.env.PATH??"")??null),null===mT){const e=new Error("hg executable not found");throw e.code="ENOENT",e}return mT}();return await new Promise(((o,s)=>{const i=(0,yl.spawn)(n,t,{cwd:e,env:{...process.env,HGPLAIN:"+strictflags",HGRCPATH:"",HGRCSKIPREPO:"1"},shell:!1}),a=new Yi.StringDecoder("utf8");let c="";i.stdout.on("data",(e=>{c+=a.write(e)})),i.stderr.on("data",(()=>{})),i.on("error",(e=>{!0===r.allowFailure?o(""):s(e)})),i.on("close",(e=>{if(0===e||!0===r.allowFailure)o(c+a.end());else{const r=t.find((e=>!e.startsWith("-")))??"hg";s(new Error(`MercurialDiffFailed: hg ${r} exited ${e??"unknown"}`))}}))}))}async function yT(e){const t=await async function(e){let t=s.resolve(e);for(;;){try{if((await go.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!==gT)return gT;const e=await go.mkdtemp(s.join((0,o.tmpdir)(),"hg-probe-"));try{const t=await wT(e,["help","environment"]);gT=/\bHGRCSKIPREPO\b/.test(t)?"skips-repo-config":"reads-repo-config"}catch(e){gT=function(e){return"object"==typeof e&&null!==e&&"code"in e&&"ENOENT"===e.code}(e)?"absent":"reads-repo-config"}finally{await go.rm(e,{recursive:!0,force:!0})}return gT}());if("not-mercurial"===r)return;if("unsafe"===r)throw new Error("MercurialClientUnsafe: hg would read repository config");let n;try{n=(await wT(e,["root"])).trim()}catch{return}if(0!==n.length)try{return(await go.stat(s.join(n,".hg"))).isDirectory()?n:void 0}catch{return}}function vT(e,t){return"win32"===process.platform?s.win32.normalize(e).toLowerCase()===s.win32.normalize(t).toLowerCase():s.resolve(e)===s.resolve(t)}function bT(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 ST(e){const t=s.resolve(e);try{return await go.realpath(t)}catch{return t}}function kT(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 _T(e){if(e.includes("\0")||/[\r\n]/.test(e))throw new Error("MercurialDiffFailed: base ref contains a newline")}async function CT({repositoryRoot:e,rev:t,filePath:r}){const n=await async function({repositoryRoot:e,rev:t,filePath:r}){let n;try{n=await wT(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>pT?"":wT(e,["cat","-r",t,"--",r])}async function ET(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 wT(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){_T(t),r.push("log");const n=(await wT(e,["log","-r",`ancestor(., (${t}))`,"-T","{node}"])).trim();if(0===n.length||n===fT)throw new Error("MercurialDiffFailed: base ref did not resolve");return n}r.push("log");const n=(await wT(e,["log","-r","max(::. and public())","-T","{node}"],{allowFailure:!0})).trim();if(n.length>0&&n!==fT)return n;const o=(await wT(e,["log","-r","ancestor(., default)","-T","{node}"],{allowFailure:!0})).trim();if(o.length>0&&o!==fT)return o;const s=(await wT(e,["log","-r",".","-T","{node}"],{allowFailure:!0})).trim();return s.length>0?s:fT}({cwd:t,baseRef:r.baseRef,commands:o});else if(_T(r.baseRef),o.push("log"),a=(await wT(t,["log","-r",r.baseRef,"-T","{node}"])).trim(),0===a.length)throw new Error("MercurialDiffFailed: base ref did not resolve");r.ref.length>0&&(_T(r.ref),o.push("log"),c=(await wT(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 wT(t,l),d=function(e){const t=e.replace(/\r\n/g,"\n");return new Ue.o$({diffs:tT(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 wT(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 go.stat(r);if(n.size>pT){const t=await async function(e){const t=(0,ho.createHash)("sha256"),r=await go.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 go.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=kT(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 CT({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 go.stat(e);t.afterFileContents=r.size>pT?"":await go.readFile(e,"utf8")}catch{t.afterFileContents=""}else try{t.afterFileContents=await CT({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=kT(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,ho.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 wT(t,["log","-r",".","-T","{node}"],{allowFailure:!0})).trim();m=e.length>0?e:fT,g=(await wT(t,["status","-0"])).length>0}hT.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 hT.info(e,"Local diff outcome",{sourceControl:"mercurial",outcome:"too_large"}),new Error(`GetDiffResponseTooLarge: ${t} bytes exceeds the ${y} byte limit`)}return hT.info(e,"Local diff outcome",{sourceControl:"mercurial",outcome:"ok",fileCount:d.diffs.length,patchIdPrefixed:!0===f?.startsWith("hg:")}),w}const xT=(0,d.h)("local-git-diff");function PT({exitCode:e,stderr:t}){return new Error(`Git command failed with code ${e}: ${t}`)}async function IT(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 PT(n);return!0===r.shouldNotTrimOutput?n.stdout:n.stdout.trim()}function RT(e){const t=tT(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 TT(e){const t=[];for(const n of e){const e={body:`+${(r=n.contents).replaceAll("\n","\n+")}`,numLines:Ws(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 AT=["main","master","develop"];async function $T(e,t){const r=s.join(e,t),n=await go.lstat(r);if(n.isSymbolicLink())return{contents:await go.readlink(r),path:t,isSymlink:!0};if(!n.isFile())throw new Error("Not a regular file or symlink");return{contents:await go.readFile(r,"utf8"),path:t,isSymlink:!1}}async function MT(e,t,r){const n=uw(),o=(e,r)=>n.run(t,e,r),i=await async function(e,t){let r;try{const e=(await IT(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 ST(t);let n=await ST(e);if(vT(n,r))return;let o=!1;for(;bT(n,r)&&!vT(n,r);){try{if((await go.stat(s.join(n,".hg"))).isDirectory()){o=!0;break}}catch{}const e=s.dirname(n);if(e===n)break;n=e}return o?yT(e):void 0}({cwd:e,gitRoot:r});return void 0!==t?"mercurial":"git"}return void 0===await yT(e)?"none":"mercurial"}(t,o);if(xT.info(e,"Local diff source control",{sourceControl:i}),"none"===i)throw xT.info(e,"Local diff outcome",{sourceControl:i,outcome:"no_version_control"}),new Error("NoVersionControl: no git or mercurial repository");if("mercurial"===i)return ET(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 IT(e,["symbolic-ref","--short","refs/remotes/origin/HEAD"]);if(t)return t.trim()}catch{}for(const t of AT){const r=`origin/${t}`;try{return await IT(e,["rev-parse","--verify",r]),r}catch{}}try{const t=(await IT(e,["branch","-r"])).split("\n").map((e=>e.trim())).find((e=>e.startsWith("origin/")));if(t)return t}catch{}try{const t=await IT(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 IT(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=RT(h);else{const t=PT(d);if(r.computePatchId||!await async function(e){return(await IT(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 IT(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})),xT.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 IT(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 $T(e,t)}catch{return}})))).filter((e=>void 0!==e))}(t,o,r.maxUntrackedFiles);for(const e of f){const t=e.isSymlink?`${TT([e])}\n\`:await IT(o,["diff","--no-color","--no-index","--","/dev/null",e.path],{ignoreErrors:!0,shouldNotTrimOutput:!0});p.diffs.push(...RT(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 IT(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 IT(o,["show","--end-of-options",`${n}:${s.to}`],{shouldNotTrimOutput:!0})}catch{s.afterFileContents=""}else try{s.afterFileContents=(await $T(t,s.to)).contents}catch{try{s.afterFileContents=await IT(o,["show","--end-of-options",`${n}:${s.to}`],{shouldNotTrimOutput:!0})}catch{s.afterFileContents=""}}else s.afterFileContents=""}catch(t){xT.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 YR({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 IT(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){xT.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,TT(f))):void 0,v=!0===r.returnHeadSha?(await IT(o,["rev-parse","HEAD"])).trim():void 0,b=!0===r.returnHeadSha?(await IT(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 DT{async execute(e,t){return MT(e,t.cwd,t)}}var OT=r("../proto/dist/generated/agent/v1/mcp_allowlist_precheck_exec_pb.js");class FT{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 OT.M({allowlisted:r})}}var NT=r("../proto/dist/generated/agent/v1/record_screen_exec_pb.js"),LT=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 jT(e){return null!==e.exitCode||null!==e.signalCode||e.killed}function UT(e,t){return"object"==typeof e&&null!==e&&"code"in e&&e.code===t}function BT(e){return e instanceof Error?e.message:String(e)}function WT(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: ${BT(r)}`),o.length>0?`${e} (${o.join("; ")})`:e}const HT=(0,Ls.promisify)(yl.execFile);class qT{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(!jT(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),qT.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 go.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 go.mkdir(this.stagingDir,{recursive:!0}),await go.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:NT.y.UNSPECIFIED}:t.includes("/")||t.includes("\\")?{success:!1,reason:NT.y.SLASHES_NOT_ALLOWED}:(t=t.replace(/[^a-zA-Z0-9 ._-]/g,"_"),t=t.trim(),0===t.length?{success:!1,reason:NT.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 go.rename(e,t)}catch(e){if(!UT(e,"EXDEV"))throw e}try{await go.copyFile(e,t)}catch(e){throw await go.rm(t,{force:!0}).catch((()=>{})),e}try{await go.unlink(e)}catch(e){throw await go.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 go.open(e,"wx");return await t.close(),e}catch(e){if(!UT(e,"EEXIST"))throw e;o=`${r}-${i}${n}`,i++}}}async resolveArtifactVideoPath(e){const{saveAsFilename:t,stagingSessionDir:r}=e;let n,o;if(t){const e=this.validateAndNormalizeSaveAsFilename(t);e.success?o=e.filename:(n=e.reason,o=`${s.basename(r)}.mp4`)}else o=`${s.basename(r)}.mp4`;return{finalVideoPath:await this.getUniqueArtifactVideoPath(o),requestedFilePathRejectedReason:n}}async getVideoDurationMs(e){const{stdout:t}=await(0,vl.D9)(HT,"ffprobe",["-v","error","-show_entries","format=duration","-of","default=noprint_wrappers=1:nokey=1",e],{encoding:"utf8"}),r=parseFloat(t.trim());if(!Number.isFinite(r)||r<0)throw new Error(`Invalid video duration from ffprobe: ${t.trim()}`);return Math.floor(1e3*r)}async getVideoDimensions(e){const{stdout:t}=await(0,vl.D9)(HT,"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:qT.PROXY_TARGET_FPS,includeBrandTag:!0}),await go.access(n,go.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,vl.D9)(HT,"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 ${qT.PROXY_TARGET_FPS}fps`)}catch(e){console.warn(`[record-screen] Failed to read video framerate: ${e instanceof Error?e.message:String(e)}, defaulting to ${qT.PROXY_TARGET_FPS}fps`)}return qT.PROXY_TARGET_FPS}async startFfmpegRecording(e,t){const r=s.join(t,"recording");await go.mkdir(r,{recursive:!0});const n=s.join(r,"recording_render_proxy_1080p.mp4");let o;try{o=(await $m(this.display)).display.refreshRate}catch(e){console.warn(`[record-screen] Failed to detect refresh rate: ${e instanceof Error?e.message:String(e)}, using default ${qT.DEFAULT_REFRESH_RATE}Hz`),o=qT.DEFAULT_REFRESH_RATE}const i=["-video_size",e,"-framerate",String(o),"-draw_mouse","0","-f","x11grab","-i",this.display,"-vf",`scale=${qT.PROXY_TARGET_WIDTH}:-2:flags=lanczos,fps=${qT.PROXY_TARGET_FPS}`,"-c:v","libx264","-preset",qT.PROXY_PRESET,"-crf",String(qT.PROXY_CRF),"-pix_fmt","yuv420p","-profile:v","high","-x264-params","keyint=1:min-keyint=1:scenecut=0:bframes=0","-movflags","+faststart","-tune","fastdecode","-y",n],a=(0,vl.D9)(yl.spawn,"ffmpeg",i,{stdio:["ignore","pipe","pipe"],detached:!0}),c=new Promise(((e,t)=>{let r="",n=!1;a.stderr?.on("data",(t=>{r+=t.toString(),!n&&r.includes("frame=")&&(n=!0,e(Date.now()))}));const o=setTimeout((()=>{n||t(new Error("ffmpeg did not start encoding within 5 seconds"))}),5e3);a.once("exit",((e,r)=>{clearTimeout(o),n||t(new Error(`ffmpeg exited before starting: code=${e} signal=${r}`))})),a.once("error",(e=>{clearTimeout(o),n||t(new Error(`ffmpeg failed to start: ${e.message}`))}))}));return await new Promise(((e,t)=>{const r=setTimeout(e,300);a.once("error",(e=>{clearTimeout(r),t(new Error(`Failed to start ffmpeg: ${e.message}`))})),a.once("exit",((e,n)=>{clearTimeout(r),t(null!==e&&0!==e?new Error(`ffmpeg exited with code ${e}`):null!==n?new Error(`ffmpeg killed by signal ${n}`):new Error("ffmpeg exited unexpectedly during startup"))}))})),{process:a,videoStartedPromise:c}}async runFfmpegCommand(e,t){return await new Promise(((r,n)=>{const o=(0,vl.D9)(yl.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 go.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(jT(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),UT(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{!jT(r.childProcess)&&r.childProcess.pid&&await this.stopFfmpegRecording(r)}catch(e){a=e,console.warn(`[record-screen] Failed to stop ffmpeg: ${BT(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 go.access(d,go.constants.R_OK)}catch(e){await this.cleanupRecording(r),this.clearActiveRecordingIfCurrent(r);const t=UT(e,"ENOENT")?`Recording proxy not found at ${d}`:`Recording proxy at ${d} could not be validated: ${BT(e)}`;return new NT.Tj({result:{case:"failure",value:new NT.yH({error:WT(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=BT(e),o=t.includes(d)?t:`Recording proxy at ${d} could not be validated: ${t}`;return new NT.Tj({result:{case:"failure",value:new NT.yH({error:WT(o,r,a,n)})}})}const m={profileVersion:qT.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:qT.PROXY_TARGET_FPS,codec:"h264",profile:qT.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 go.copyFile(d,g);else{const t=await this.renderPolished(e,l);await this.movePolishedVideo(t,g)}}catch(e){throw await go.rm(g,{force:!0}).catch((()=>{})),e}try{await go.rm(l,{force:!0,recursive:!0})}catch(e){console.warn(`[record-screen] Failed to remove staging session ${l}: ${BT(e)}`)}return this.clearActiveRecordingIfCurrent(r),new NT.Tj({result:{case:"saveSuccess",value:new NT.ol({path:g,recordingDurationMs:ve.protoInt64.parse(h.toString()),requestedFilePathRejectedReason:w})}})}catch(e){return await this.cleanupRecording(r),this.invokeStoppedCallbackIfCurrent(r),new NT.Tj({result:{case:"failure",value:new NT.yH({error:BT(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 NT.Tj({result:{case:"failure",value:new NT.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===NT.$u.UNSPECIFIED)return new NT.Tj({result:{case:"failure",value:new NT.yH({error:"Mode must be one of START_RECORDING, SAVE_RECORDING, DISCARD_RECORDING"})}});switch(t.mode){case NT.$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 go.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 go.mkdir(o,{recursive:!0});const{resolutionString:s,resolution:i}=await $m(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 Bm({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 NT.Tj({result:{case:"startSuccess",value:new NT.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 go.rm(o,{force:!0,recursive:!0}).catch((()=>{})),this.activeRecording=null,new NT.Tj({result:{case:"failure",value:new NT.yH({error:e instanceof Error?e.message:String(e)})}})}}case NT.$u.SAVE_RECORDING:{if(!this.activeRecording)return 1===this.inFlightSaves.length?await this.inFlightSaves[0].promise:new NT.Tj({result:{case:"failure",value:new NT.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 NT.$u.DISCARD_RECORDING:{if(!this.activeRecording)return new NT.Tj({result:{case:"failure",value:new NT.yH({error:"No active recording to discard"})}});const e=this.activeRecording;if(this.findInFlightSave(e))return new NT.Tj({result:{case:"failure",value:new NT.yH({error:"Save in progress for this recording; wait for it or start a new recording"})}});try{return await e.inputEventLogger.stop(),this.invokeStoppedCallbackOnce(),!jT(e.childProcess)&&e.childProcess.pid&&await this.stopFfmpegRecording(e),await go.rm(e.sessionDir,{force:!0,recursive:!0}),this.activeRecording=null,new NT.Tj({result:{case:"discardSuccess",value:new NT.N8}})}catch(t){await this.cleanupRecording(e),this.invokeStoppedCallbackOnce();const r=e.sessionDir;let n=!1;try{await go.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 NT.Tj({result:{case:"failure",value:new NT.yH({error:`Failed to discard recording: ${o}${s}`})}})}}default:{const e=t.mode;return new NT.Tj({result:{case:"failure",value:new NT.yH({error:`Unhandled recording mode: ${String(e)}`})}})}}}catch(e){r.error=e,r.hasError=!0}finally{LT(r)}}}async function zT(e){const t=await(0,go.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 zT(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 GT(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(...GT(t,e,s))}))}return n}async function VT(e){if(!await(0,go.access)(e,go.constants.R_OK).then((()=>!0),(()=>!1)))return"(No notes directory yet - will be created when you write your first note)";const t=await zT(e);return 0===t.length?"(Notes directory is empty)":t.flatMap(((e,r)=>GT(e,"",r===t.length-1))).join("\n")}async function KT(e,t){return VT(s.join(e,"agent-notes",t))}async function JT(e){return VT(s.join(e,"agent-notes","shared"))}qT.IN_FLIGHT_SAVE_DISPOSE_TIMEOUT_MS=3e4,qT.PROXY_TARGET_WIDTH=1920,qT.PROXY_TARGET_FPS=60,qT.PROXY_CRF=17,qT.PROXY_PRESET="veryfast",qT.PROXY_PROFILE_VERSION="render-proxy-h264-all-i-v1",qT.DEFAULT_REFRESH_RATE=60;var ZT=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},XT=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 QT=3e3,YT=(0,d.h)("local-exec:request-context"),eA=Symbol("sectionLoadTimedOut");function tA(e,t){if(void 0===t)return e;let r;const n=new Promise((e=>{r=setTimeout((()=>e(eA)),t)}));return e.catch((()=>{})),Promise.race([e,n]).finally((()=>{clearTimeout(r)}))}class rA{async read(e,t){const r=this.inFlight??this.begin(e),n=this.last;if(void 0===n)return r;const o=await tA(r,t).catch((()=>eA));return o===eA?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 nA(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{ZT(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{XT(o)}}async function oA(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 sA(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(nA(e,t,r,n)),o(oA(e,t,r,n))]);return{status:s,branchName:i}}async function iA(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,Po.G6)(f),_=v?.(),C=(()=>{try{return(new Intl.DateTimeFormat).resolvedOptions().timeZone??void 0}catch{return}})(),E=n,x=n?`${n}/terminals`:void 0,P=n&&!1!==i?`${n}/agent-notes/shared`:void 0,I=n&&s&&!1!==i?`${n}/agent-notes/${s}`:void 0,R=n?`${n}/agent-transcripts`:void 0,T=!!d&&d(),A=h?.(),$=c?.();let M;if(p)try{M=await p()}catch{M=void 0}return new Or.GE({osVersion:S,workspacePaths:t,shell:k,sandboxEnabled:T,projectFolder:E,terminalsFolder:x,agentSharedNotesFolder:P,agentConversationNotesFolder:I,agentTranscriptsFolder:R,timeZone:C,...!1!==a&&{processWorkingDirectory:process.cwd()},artifactsFolder:m,...void 0!==$&&{smartModeClassifierAutoModeEnabled:$},...void 0!==l&&{devForceNextSmartModeClassifierBlockToken:l},...void 0!==_&&{devMockPromptTime: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 aA={type:"object",properties:{},additionalProperties:!1};function cA(e,t){return{tools:(!0===t?.internalBrowserProvidersOnly?e.servers.filter((e=>Wn.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 lA(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,...wv(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!Bn(e.serverIdentifier)||!0!==t?.alwaysExposeVirtualMcpAuthTool&&"needsAuth"!==e.status||o.some((e=>e.toolName===gI))||o.push(new gn.E$({toolName:gI,...r?{}:{description:wI,...!0===t?.inputSchemaJson?{inputSchemaJson:JSON.stringify(aA)}:{inputSchema:ve.Value.fromJson(aA)}}})),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 uA(e){const t=e?.trim();return t||void 0}function dA(e,t){const r=function(e){return uA(e.serverIdentifier)}(e);if(r)return r;const n=uA(e.serverName);return n?t.get(n)??n:void 0}class hA{constructor(e){this.mcpLease=e}async getState(e){const[t,r]=await Promise.all([this.mcpLease.getTools(e).catch((t=>(YT.warn(e,"Error fetching MCP tools",{error:t}),[]))),this.mcpLease.getInstructions(e).catch((t=>(YT.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=>dA(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=>dA(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=>(YT.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:Vn(n),errorMessage:"error"===n.kind&&void 0!==n.message?n.message:void 0}]})));return new Map(n)}(e,this.mcpLease))}}function pA(e){return new Qa._W({result:{case:"success",value:new Qa.pv({servers:e.servers.map((e=>new Qa.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:Hn(e._meta),...wv(e.annotations)}))),instructions:e.instructions,status:e.status,errorMessage:e.errorMessage})))})}})}class fA{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!==Qa.ew.FORCE_IF_MISSING&&t.refreshPolicy!==Qa.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 pA({...r,servers:n})}return pA(r)}}class mA{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 rA,this.reusedAgentSkills=new rA,this.reusedAdminCommandDenylist=new rA,this.cachedWorkspaces=new Map,this.inFlightWorkspaceWarms=new Map;const{projectDir:l,getSmartModeClassifierAutoModeEnabled:u,getAdminCommandDenylist:d,devForceNextSmartModeClassifierBlockToken:h,isWorkingDirHomeDir:p,agentNotesEnabled:f,reportProcessWorkingDirectory:m,createFileWatcher:g,getSandboxEnabled:w,getSandboxSupported:y,getNetworkAllowlistInfo:v,userTerminalHint:b,getMcpFileSystemOptions:S,mcpMetaToolEnabled:k,mcpMetaToolSlimDescriptors:_,mcpInputSchemaJson:C,alwaysExposeVirtualMcpAuthTool:E,getArtifactsFolder:x,secretRedactionEnabled:P,attributionConfigProvider:I,isAttributionDisabledByAdmin:R,getAgentSkills:T,additionalRules:A,getComputerUseSupported:$,getComputerUseDesktop:M,getMockPromptTime:D}=c;this.projectDir=l,this.isWorkingDirHomeDir=p,this.agentNotesEnabled=f??!0,this.reportProcessWorkingDirectory=m??!0,this.getSandboxEnabled=w,this.getSandboxSupported=y,this.getNetworkAllowlistInfo=v,this.getSmartModeClassifierAutoModeEnabled=u,this.getAdminCommandDenylist=d,this.devForceNextSmartModeClassifierBlockToken=h,this.getMockPromptTime=D,this.userTerminalHint=b,this.getMcpFileSystemOptions=S,this.mcpMetaToolEnabled=k??!1,this.mcpMetaToolSlimDescriptors=_??!1,this.mcpInputSchemaJson=C??!1,this.alwaysExposeVirtualMcpAuthTool=E??!1,this.getArtifactsFolder=x,this.secretRedactionEnabled=P,this.attributionConfigProvider=I,this.isAttributionDisabledByAdmin=R,this.getAgentSkills=T,this.additionalRules=A??[],this.getComputerUseSupported=$,this.getComputerUseDesktop=M,this.reduceContextHotPath=c.reduceContextHotPath??!1,this.sectionLoadTimeoutMs=c.sectionLoadTimeoutMs,this.reportSectionCompleteness=c.reportSectionCompleteness??!1,this.freshSectionWaitMs=c.freshSectionWaitMs,this.onRequestContext=c.onRequestContext,!0!==c.deferWarmup&&this.warm(),void 0!==g&&(this.fileWatcher=g(),this.fileWatcher.onDidChange((e=>{this.onWorkspacePathChanged(e)})),this.fileWatcher.onDidCreate((e=>{this.onWorkspacePathChanged(e)})),this.fileWatcher.onDidDelete((e=>{this.onWorkspacePathChanged(e)})))}warm(){this.warmWorkspaceCaches(),void 0===this.globalCache&&this.rebuildGlobalCache()}onWorkspacePathChanged(e){this.rebuildAllCaches()}getWorkspaceCache(e){return this.cachedWorkspaces.get(e)}warmWorkspaceCaches(){const e=(0,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=ZT(r,(0,D.VI)(e.withName("LocalRequestContextExecutor.warmWorkspaceCache")),!1),o=await Ea(n.ctx,this.gitExecutor,t),s=o?await xa(n.ctx,this.gitExecutor,o):void 0,i={repoPath:o??void 0,remoteUrl:void 0!==s?Pa(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((()=>sA((0,b.q6)(),this.gitExecutor,e,QT)))}}catch(e){r.error=e,r.hasError=!0}finally{XT(r)}}gitInfoSection(e){let t=this.reusedGitInfo.get(e);return void 0===t&&(t=new rA,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=ZT(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{XT(e)}}async computeGlobalCache(e){const t={stack:[],error:void 0,hasError:!1};try{const r=ZT(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&&YT.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{XT(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=ZT(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:_a(r.remoteUrl)});if(void 0===r.repoPath)return;const c=r.repoPath,{status:l,branchName:u}=void 0===this.freshSectionWaitMs?await sA(n.ctx,t.gitExecutor,c,QT):await this.gitInfoSection(c).read((()=>sA((0,b.q6)(),t.gitExecutor,c,QT)),this.freshSectionWaitMs);return void 0===l&&(i=!1),new Or.DS({path:r.repoPath,status:l,branchName:u,remoteUrl:r.remoteUrl,isOriginBacked:_a(r.remoteUrl)})})))).filter((e=>void 0!==e)),gitRepoInfoComplete:s,gitStatusInfoComplete:s&&i}}catch(e){r.error=e,r.hasError=!0}finally{XT(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=ZT(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=ZT(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{XT(e)}},a=performance.now(),c={},l=(e,t)=>{const r=performance.now();return t.finally((()=>{c[e]=Math.round(performance.now()-r)}))},u=e=>tA(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",u(p(this.reusedMcpState,(()=>d((()=>this.inFlightMcpState),(e=>{this.inFlightMcpState=e}),(()=>this.mcpStateAccessor.getState(f))))))),l("env",iA(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?KT(s,t.notesSessionId):Promise.resolve(void 0)),l("sharedNotes",this.agentNotesEnabled&&s?JT(s):Promise.resolve(void 0)),l("mcpFileSystemOptions",this.getMcpFileSystemOptions?this.getMcpFileSystemOptions(o.ctx,{timeoutMs:3e3}):Promise.resolve(void 0)),l("attribution",this.isAttributionDisabledByAdmin?this.isAttributionDisabledByAdmin().catch((()=>!0)):Promise.resolve(!1)),l("agentSkills",u(p(this.reusedAgentSkills,(()=>d((()=>this.inFlightAgentSkills),(e=>{this.inFlightAgentSkills=e}),(()=>this.getAgentSkills?this.getAgentSkills(f):Promise.resolve([]))))))),l("adminCommandDenylist",u(p(this.reusedAdminCommandDenylist,(()=>d((()=>this.inFlightAdminCommandDenylist),(e=>{this.inFlightAdminCommandDenylist=e}),(()=>this.getAdminCommandDenylist?this.getAdminCommandDenylist():Promise.resolve(void 0)))))))]),I=m===eA,R=g===eA,T=x===eA,A=P===eA,$=I?this.lastGoodGlobalCache??{rules:[...this.additionalRules],cloudRule:null,codebaseReference:void 0,customSubagents:[]}:m,M=R?{servers:[]}:g,O=T?[]:x,F=A?void 0:P;(I||R||T||A)&&YT.warn(o.ctx,"computeCachedRequestContext: section load timed out",{timeoutMs:this.sectionLoadTimeoutMs,rulesAndSubagents:I,mcpState:R,agentSkills:T,adminCommandDenylist:A});const N=performance.now()-a;for(const[e,t]of Object.entries(c))o.span.setAttribute(`requestContext.timing.${e}Ms`,t);o.span.setAttribute("requestContext.timing.totalMs",Math.round(N)),N>1e3&&YT.warn(o.ctx,"computeCachedRequestContext: slow parallel data collection",{durationMs:Math.round(N),...c});const L=this.mcpMetaToolEnabled?lA(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}]:[],...cA(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=!I,W.customSubagentsInfoComplete=!I,W.agentSkillsInfoComplete=!T,W.mcpInfoComplete=!R,W.mcpFileSystemInfoComplete=this.mcpMetaToolEnabled||void 0!==C,W.envInfoComplete=!0,W.gitStatusInfoComplete=S),W}catch(e){n.error=e,n.hasError=!0}finally{XT(n)}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{this.onRequestContext?.();const n=ZT(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(Ha(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{XT(r)}}}function gA(e){return 0!==e.timeout?e.timeout:e.isBackground||e.timeoutBehavior===fe._d.BACKGROUND||void 0!==e.hardTimeout&&e.hardTimeout>0?0:3e4}var wA=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 yA{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:rs(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:rs(e.sandboxPolicy)})}async executeWithPolicy(e,t,r,n,o){const s=Date.now(),i=new AbortController,a=e.signal?AbortSignal.any([e.signal,i.signal]):i.signal,c=setTimeout((()=>{i.abort()}),n);try{let n,l,u,d="",h="",p=null;const f=o?{perRepo:o}:void 0;for await(const o of this.coreExecutor.execute(e,{command:t.command,workingDirectory:r,signal:a,toolCallId:t.toolCallId,conversationId:t.conversationId,requestId:t.requestId,secretScopeId:t.secretScopeId,sandboxPolicy:f,fileOutputThresholdBytes:t.fileOutputThresholdBytes,pipeStdin:!1}))"stdout"===o.type?d+=o.data:"stderr"===o.type?h+=o.data:"exit"===o.type&&(p=null!=o.code?0|o.code:null,l=o.outputLocation,n=o.aborted?a.aborted?i.signal.aborted&&a.reason===i.signal.reason?fe.Lv.TIMEOUT:fe.Lv.USER_ABORT:fe.Lv.UNSPECIFIED:void 0,u=_w(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:rs(o)}):e.signal.aborted?new fe.W4({result:{case:"rejected",value:new fe.pZ({command:t.command,workingDirectory:r,reason:"Command aborted"})},sandboxPolicy:rs(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:rs(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?ts(t.requestedSandboxPolicy):void 0,i=t.workingDirectory||await this.coreExecutor.getCwd(t.conversationId),a=gA(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(Eo(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:pu(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:_o(t)},s);if("block"===e.kind)return new fe.W4({result:pu(o,c,e.reason)});l=e.policy}return l=await Xa(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{wA(r)}}}var vA=r("../proto/dist/generated/agent/v1/shell_allowlist_precheck_exec_pb.js");class bA{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 vA.e({allowlisted:n})}}class SA{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 kA=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=(0,d.h)("local-exec:shell-stream");class CA{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 EA(){let e=()=>{};return{promise:new Promise((t=>{e=t})),resolve:e}}class xA{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:EA()},""!==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?ts(t.requestedSandboxPolicy):void 0;const i=t.workingDirectory||await this.coreExecutor.getCwd(t.conversationId),a=gA(t),c=(0,zo.o1)(i),l=Date.now(),u=performance.now(),d=new fe.HO(Do(o).structured),h=ms({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:Eo(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(_A.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}),Eo(t)){const r=p.policy??s;_A.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:_o(t),onApprovalRequested:()=>{r.registered.resolve(void 0),r.registered=EA()}},s);if(r.awaitingApproval=!1,"block"===n.kind){if(_A.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,_A.info(e,"Shell stream: approval gate allowed command",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,effectivePolicyType:s.type})}s=await Xa(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:rs(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?{perRepo:s}:void 0,b=this.coreExecutor.execute(e,{command:o,workingDirectory:i,signal:w,toolCallId:t.toolCallId,conversationId:t.conversationId,requestId:t.requestId,secretScopeId:t.secretScopeId,sandboxPolicy:v,fileOutputThresholdBytes:t.fileOutputThresholdBytes,pipeStdin:m,showElapsedTime:y});let S;f||(S=setTimeout((()=>g.abort()),a));const k=f?new CA(b[Symbol.asyncIterator](),a):null;let _,C,E,x="",P=!1,I=!1;const R=t.toolCallId&&k?{requestBackground:()=>{if(k.requestBackground())return E=E??this.backgroundShellManager.generateShellId(),new fe.W4({result:{case:"success",value:new fe.QR({shellId:E,pid:C,command:o,workingDirectory:c,msToWait:_w(performance.now()-u),backgroundReason:fe.Jg.USER_REQUEST,interleavedOutput:x})}})}}:void 0;t.toolCallId&&R&&this.activeForegroundExecutions.set(t.toolCallId,R),this.settle(t.toolCallId,r,R);const T=()=>{t.toolCallId&&this.activeForegroundExecutions.get(t.toolCallId)===R&&this.activeForegroundExecutions.delete(t.toolCallId)},A=()=>{k&&!k.backgroundRequested&&(g.abort(),k.abort())};let $;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;I=!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:_w(r.localExecutionTimeMs)})}})}}catch(r){if(!(r instanceof Po.SandboxUnsupportedError))throw r;const n=s?.type??"unknown";return _A.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||I||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{kA(n)}}}const PA={kind:"absent"};class IA{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 wo.q({max:1e3,ttl:6e4,ttlResolution:0,perf:e})}begin(e){this.entries.purgeStale();const t=++this.nextGeneration;return this.claims.set(OA(e),t),t}record(e,t,r){if(!this.claim(e,r))return;const n=OA(e);this.entries.set(n,{recorded:t,generation:r}),this.commitGeneration(n,r)}forget(e,t){if(!this.claim(e,t))return;const r=OA(e);this.entries.delete(r),this.commitGeneration(r,t)}end(e,t){this.claim(e,t)}take(e){const t=OA(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=OA(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=OA(e);return this.claims.get(r)===t&&(this.claims.delete(r),!0)}}class RA{constructor(){this.views=new wo.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>js)return void this.views.delete(e);const r=(0,ho.createHash)("sha256").update(t).digest("hex");this.views.set(e,{kind:"fingerprint",byteLength:t.length,sha256:r})}recordDelete(e){this.views.set(e,PA)}}async function TA(e,t){if(void 0===e)return!1;try{if("absent"===e.kind)return await DA(t);const r=await MA(t);return void 0===r||r.byteLength!==e.byteLength||r.sha256!==e.sha256}catch{return!1}}async function AA(e,t){if("fingerprint"!==e?.kind)return!1;try{return!await DA(t)}catch{return!1}}class $A{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 CS(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 MA(t)}catch{return}}(i,o.resolvedPath);return this.commit(o,s,i,a,n),i}try{a=await MA(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=PA: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 MA(e){try{const t=await(0,go.stat)(e);if(!t.isFile()||t.size>js)return}catch(e){return FA(e)}let t;try{t=await(0,go.open)(e,function(){const e=yo.constants;return e.O_RDONLY|(e.O_NONBLOCK??0)}());const r=await t.stat();if(!r.isFile()||r.size>js)return;const n=(0,ho.createHash)("sha256");let o=0;const s=Buffer.alloc(65536);for(;o<=js;){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>js)return;return{byteLength:o,sha256:n.digest("hex")}}catch(e){return FA(e)}finally{await(t?.close())}}async function DA(e){try{return await(0,go.stat)(e),!0}catch(e){if(NA(e))return!1;throw e}}function OA({toolCallId:e,resolvedPath:t}){return`${e}\0${t}`}function FA(e){if(!NA(e))throw e}function NA(e){const t=Wa(e);return"ENOENT"===t||"ENOTDIR"===t}var LA=r("../proto/dist/generated/agent/v1/web_fetch_allowlist_precheck_exec_pb.js");class jA{constructor(e){this.permissionsService=e}async execute(e,t){const r=await this.permissionsService.isWebFetchFullyAllowlisted(e,{url:t.url});return new LA.M({allowlisted:r})}}var UA=r("node:constants");const BA=[".md",".markdown",".mdown",".mkd",".mkdn",".mdx"],WA=/(?:^|\/)\.cursor\/projects\/[^/]+\/canvases\/[^/]+\.canvas\.tsx$/i;function HA(e){const t=e.trim().toLowerCase();return BA.some((e=>t.endsWith(e)))}function qA(e){return WA.test(e.trim().replace(/\\/g,"/"))}const zA="win32"===process.platform;process.platform;var GA=r("../proto/dist/generated/agent/v1/write_exec_pb.js");class VA extends Error{constructor(e,t){super(t),this.name="SymlinkRefusedError",this.path=e}}function KA(e,{nonBlocking:t}){const r=yo.constants;let n=e;return"number"==typeof r.O_NOFOLLOW&&(n|=r.O_NOFOLLOW),t&&"number"==typeof r.O_NONBLOCK&&(n|=r.O_NONBLOCK),"number"==typeof r.O_CLOEXEC&&(n|=r.O_CLOEXEC),n}async function JA(e,t,r){const{fd:n}=await async function(e,t,r){let n;try{n=await async function(e,t){try{return await(0,go.open)(e,KA(t,{nonBlocking:!0}),438)}catch(r){const n=Wa(r);if(("EAGAIN"===n||"EWOULDBLOCK"===n)&&await async function(e){try{return(await(0,go.lstat)(e)).isFile()}catch{return!1}}(e))return await(0,go.open)(e,KA(t,{nonBlocking:!1}),438);throw r}}(e,t)}catch(t){if(function(e){const t=Wa(e);return"ELOOP"===t||"EMLINK"===t||"EPERM"===t&&"number"==typeof yo.constants.O_NOFOLLOW}(t))throw new VA(e,`Refusing to ${r} through a symlink at ${e}`);throw t}try{let t;try{t=(0,yo.realpathSync)(e)}catch{throw new VA(e,`Cannot verify canonical path before ${r}: ${e}`)}if(t!==e)throw new VA(e,`Refusing ${r}: ${e} now resolves through a symlinked parent to ${t}`);const o=await n.stat();if(!o.isFile())throw new VA(e,`Refusing to ${r} non-regular file at ${e}`);return{fd:n,stats:o}}catch(e){throw await n.close(),e}}(e,yo.constants.O_WRONLY|yo.constants.O_CREAT,"write");try{await n.truncate(0);const e=function(e){return Buffer.isBuffer(e)?e:Buffer.from(e)}(t);let o=0;for(;o<e.length;){const{bytesWritten:t}=await n.write(e,o,e.length-o,o);if(0===t)break;o+=t}r?.flush&&await n.sync()}finally{await n.close()}}var ZA=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 XA=(0,d.h)("LocalWriteExecutor"),QA=(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"]}),YA=async(e,t,r,n)=>{const o=setTimeout((()=>{XA.warn(e,`[watchdog, LocalWriteExecutor] ${t} still not completed after ${r}ms`)}),r);try{return await n()}finally{clearTimeout(o)}};function e$(e){return new Error(`Could not create ${e}: directory creation exceeded the path depth and was stopped.`)}async function t$(e){try{return(await(0,go.stat)(e)).isDirectory()?"directory":"present"}catch(e){if("ENOENT"===Wa(e))return"missing";throw e}}async function r$(e,t){const r=[];let n=e;for(let o=0;o<=t;o+=1){const t=await t$(n);if("directory"===t)return r.reverse(),r;if("present"===t)return await(0,go.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 e$(e)}class n${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,Lu.fileURLToPath)(e),!1}catch{return!0}}(t.path))return new GA.v3({result:{case:"error",value:new GA.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 i$(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=tb(r,d)||void 0!==this.projectDir&&!this.workspacePaths.some((e=>{return t=e,n=r,zA&&(t=t.toLowerCase(),n=n.toLowerCase()),t===n||(t.charAt(t.length-1)!==s.sep&&(t+=s.sep),n.startsWith(t));var t,n}))&&rb(this.projectDir,r,d);if((0,zo.fl)({targetPath:r,workspacePaths:this.workspacePaths,mainWorktreePath:this.worktreeMainPath}))return new GA.v3({result:{case:"error",value:new GA.QM({path:r,error:zo.PS})}});let p,f,m,g,w=!1;try{const e=await(0,go.stat)(r);if(g=511&e.mode,e.size<=Jo){const e=await YA(c,"readText before write",3e3,(()=>Mi(r,t.encodingHint)));p=e.text,f=e.encoding,m=Ag(e)}else w=!0}catch(e){w="ENOENT"!==Wa(e)}const y=await wb(r),v=y.resolvedPath,b=async()=>{return await TA(n,v)?QI(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 TA(o,v)?void 0:YI(r));var e,t};if(t.planMode&&!await YA(c,"isPlanModeAllowedWriteTarget",3e3,(()=>async function(e,t){switch(t.resolution.status){case"resolved":case"newFile":return HA(t.resolvedPath)||qA(t.resolvedPath)||await async function(e,t){if(!qA(e))return!1;const r=await wb((0,s.dirname)(e));return t===(0,s.join)(r.resolvedPath,(0,s.basename)(e))}(e,t.resolvedPath);case"danglingSymlink":{const e=await async function(e){let t=e;for(let e=0;e<40;e++){let e;try{e=await(0,go.readlink)(t)}catch(e){const r=Wa(e);return"ENOENT"===r||"EINVAL"===r?t:void 0}t=(0,s.resolve)((0,s.dirname)(t),e)}}(t.resolvedPath);return void 0!==e&&HA(e)}case"permissionDenied":case"symlinkLoop":case"unknownError":return!1;default:return t.resolution,!1}}(r,y))))return new GA.v3({result:{case:"rejected",value:new GA.en({path:r,reason:"Cannot edit non markdown files in plan mode"})}});const S=(".cursorignore"===(r.split(s.sep).pop()?.toLowerCase()??"")?{type:"permissionsConfig"}:void 0)??await YA(c,"permissionsService.shouldBlockWrite",3e3,(()=>this.permissionsService.shouldBlockWrite(c,v,l)));if(S){const e=await YA(c,"handleBlockReason",3e3,(()=>du(S,{onNeedsApproval:async(e,n)=>{const o="fileEdit"!==n?.type||n.isNewFile,s="fileEdit"===n?.type?n.diffString:l,i="fileEdit"===n?.type?n.blockReason:void 0,a=await b();if(void 0!==a)return o$(r,a);const c=await this.pendingDecisionProvider.requestApproval({type:Rg.Write,details:{path:r,reason:e,isNewFile:o,diffString:s,before:p,after:l,blockReason:i},toolCallId:t.toolCallId});return c.approved?null:new GA.v3({result:{case:"rejected",value:new GA.en({path:r,reason:c.reason||""})}})},onUserRejected:e=>new GA.v3({result:{case:"rejected",value:new GA.en({path:r,reason:e||""})}}),onPermissionDenied:(e,t)=>new GA.v3({result:{case:"permissionDenied",value:new GA.U7({path:r,error:e,isReadonly:t?.isReadonly??!1})}})})));if(null!==e)return e}const k=await YA(c,"anotherSpellingRefusal",3e3,(()=>async function(e){const t=(0,s.basename)(e);let r;try{if(!(await(0,go.stat)(e)).isFile())return;const n=await(0,go.readdir)((0,s.dirname)(e));if(n.includes(t))return;const o=t.normalize("NFC");if(n.some((e=>e.normalize("NFC")===o)))return;const i=t.toLowerCase(),a=n.filter((e=>e.toLowerCase()===i)),c=o.toLowerCase();r=a.length>0?a:n.filter((e=>e.normalize("NFC").toLowerCase()===c))}catch{return}const n=1===r.length?r[0]:void 0;return void 0===n?`${t} names an existing file that this folder lists under another name, so writing it would replace that file. Nothing was written. List the folder and write the file by its listed name to change it; for a new file, choose a different name.`:`${t} names the existing file ${n}: this volume does not tell names apart by case, so writing it would replace ${n}. Nothing was written. To change that file, write ${n}; for a new file, choose a name no file in this folder has in any case.`}(r)));if(void 0!==k)return new GA.v3({result:{case:"error",value:new GA.QM({path:r,error:k})}});const _=(0,s.dirname)(v);if(await AA(n,_))return o$(r,QI(r));if(await AA(o,_))return o$(r,YI(r));let C,E,x,P;try{C=await YA(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 r$(e,t),a=0;for(;a<i.length;){const c=i[a];if(n+=1,n>r)throw e$(e);try{await(0,go.mkdir)(c,{recursive:!1})}catch(r){const n=Wa(r);if("EEXIST"===n){if("directory"!==await t$(c))throw r;a+=1;continue}if("ENOENT"===n){const n=(0,s.dirname)(c);if(n===c||"missing"!==await t$(n))throw r;i=await r$(e,t),a=0,o=0;continue}throw r}o+=1,a+=1}return o}(_)))}catch(e){const t=Wa(e);return"EACCES"===t||"EPERM"===t?new GA.v3({result:{case:"permissionDenied",value:new GA.U7({path:r,directory:_,operation:"create_directory",error:"Permission denied"})}}):new GA.v3({result:{case:"error",value:new GA.QM({path:r,error:Ha(e)})}})}if(void 0!==u)E=u,x=0;else{const e=await YA(c,"getBufferForWrite",3e3,(()=>Oi(r,l,this.workspacePath,t.encodingHint)));E=e.buffer,x=e.lines,P=e.format.encoding}const I=()=>YA(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 JA(v,E,{flush:!0}),this.agentFileViews?.recordWrite(r,E),void 0!==P&&await Di(r,{buffer:E,encoding:P});try{t=await(0,go.open)((0,s.dirname)(v),UA.O_RDONLY),await t.sync()}catch{}finally{await(t?.close())}}));let R,T=!1;const A=async()=>{try{await I()}catch(e){throw R=e,T=!0,e}};try{void 0===this.writeFileMutationGuard?await I():await this.writeFileMutationGuard.runExclusive(v,A)}catch(e){if(void 0!==this.writeFileMutationGuard&&(!T||e!==R))return new GA.v3({result:{case:"error",value:new GA.QM({path:r,error:e instanceof Error?e.message:String(e)})}});if(e instanceof VA)return new GA.v3({result:{case:"permissionDenied",value:new GA.U7({path:r,directory:"",operation:"create_file",error:e.message})}});const t=Wa(e);return"EACCES"===t||"EPERM"===t?new GA.v3({result:{case:"permissionDenied",value:new GA.U7({path:r,directory:"",operation:"create_file",error:"Permission denied"})}}):"ENOSPC"===Wa(e)?new GA.v3({result:{case:"noSpace",value:new GA.bM({path:r})}}):"EDQUOT"===t?new GA.v3({result:{case:"error",value:new GA.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 GA.v3({result:{case:"error",value:new GA.QM({path:r,error:Ha(e)})}})}if(this.fileChangeTracker&&void 0===u&&!h&&!w){const e={...t.toolCallId?{toolCallId:t.toolCallId}:{},...v===r?{}:{writtenPath:v},...void 0===g?{}:{beforeMode:g},...C>0?{createdDirectories:C}:{}};await this.fileChangeTracker.trackChange(r,p,l,e,m)}if(this.onWriteForAiTracking&&void 0===u&&!h){const e=t.toolCallId?{toolCallId:t.toolCallId}:{};try{await this.onWriteForAiTracking({path:r,beforeContent:p,afterContent:l,metadata:e})}catch(e){XA.warn(c,"onWriteForAiTracking failed (write succeeded)",{path:r,error:e instanceof Error?e.message:String(e)})}}const $=E.byteLength;let M;if(void 0!==u||w||h||this.recordEncodingChecks(c,r,p,f,l),t.returnFileContentAfterWrite)try{M=await YA(c,"readText after write",3e3,(()=>$i(r,t.encodingHint)))}catch{}return new GA.v3({result:{case:"success",value:new GA.j6({path:r,linesCreated:x,fileSize:$,...void 0!==M&&{fileContentAfterWrite:M}})}})}catch(e){a.error=e,a.hasError=!0}finally{ZA(a)}}recordEncodingChecks(e,t,r,n,o){try{const i={path:t,encoding:n,pages:(s=Tl.pages(),"failed"===s?"none":s)};for(const t of function(e,t,r){return[xc(e,t,r),Pc(e,t,r)]}(r,n,o))QA.increment(e,1,Mc(t,i))}catch(t){for(const t of vc)QA.increment(e,1,{detector:t,outcome:"error",file:"unclassified"});XA.warn(e,"encoding check failed (write succeeded)",{error:t instanceof Error?t.message:String(t)})}var s}}function o$(e,t){return new GA.v3({result:{case:"error",value:new GA.QM({path:e,error:t})}})}class s$ extends Error{constructor(e){super("stale write refusal"),this.result=e,this.name="StaleWriteRefusal"}}function i$(e){if("error"!==e.result.case)return!1;const{error:t,path:r}=e.result.value;return t===QI(r)||t===YI(r)}const a$=(0,d.h)("local-exec:provider"),c$=new Set,l$=new Au.AsyncLocalStorage;class u$ extends Z{getMcpExecutionPolicyDeps(){return{permissionsService:this.permissionsService,pendingDecisionProvider:this.pendingDecisionStore}}static dropOwnedRequestContextCaches(){for(const e of c$)e.ownedRequestContextExecutor?.invalidateGlobalCache()}static rebuildRequestContextCachesFor(e){for(const t of c$)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,yo.readFileSync)(t,"utf-8"),n=JSON.parse(r),o=(0,Po.$6)(n);return(0,Po.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,Po.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 cu(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 uu(c,this.askpassConfig)),this.shellManager&&(c=new lu(c,this.shellManager));const l=e.overrideShellExecutor??(!0===e.suppressDefaultShellExecutor?void 0:new yA(this.permissionsService,c,this.ignoreService,this.pendingDecisionStore));void 0!==l&&this.register(ZI,xm(l)),this.register(XI,xm(new JI(this.permissionsService,this.ignoreService,a??t??this.projectDir)));const u=new IA,d=new RA,h=e.overrideWriteExecutor??new n$(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(eR,function(e){const t=(r={execute:(t,r,n)=>e.execute(t,r,n).then((e=>{if(i$(e))throw new s$(e);return e}))},xm(r));var r;return{async execute(e,r,n){try{return await t.execute(e,r,n)}catch(e){if(e instanceof s$)return e.result;throw e}}}}(h));const p=e.overrideDeleteExecutor??new Dg(this.pendingDecisionStore,this.fileChangeTracker,this.permissionsService,a,e.onDeleteForAiTracking,d);this.register(tR,xm(p)),this.register(rR,xm(new Ug({encodingSlices:e.encodingSlices}))),this.register(nR,new DT);const f=this.mcpStateAccessor??new hA(this.mcpLease),m=e.overrideGrepExecutor??new jk(this.ignoreService,this.grepProvider,this.workspacePaths,{mcpStateAccessor:f,permissionsService:this.permissionsService,useStreamingGrep:e.useStreamingGrep,encodingSlices:e.encodingSlices});this.register(oR,xm(m));const g=e.overrideReadExecutor??new $A(new hk(this.permissionsService,a,{mcpStateAccessor:f,useStreamingRead:e.useStreamingRead,pendingDecisionProvider:this.pendingDecisionStore,encodingSlices:e.encodingSlices}),u,this.permissionsService,a,d),w=new cR(g);this.register(lR,w),e.registerRedactedReadExecutor&&this.register(uR,w);const y=e.overrideLsExecutor??new Gk(this.permissionsService,this.ignoreService,a);this.register(dR,xm(y)),this.register(hR,xm(new QR(a,this.diagnosticsProvider))),e.getCanvasDiagnostics&&this.register(pR,xm(new zR(e.getCanvasDiagnostics,e.beginCanvasSave))),this.register(Kn,xm(new RR(gl(new jI(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(lR))))),this.register(Jn,xm(new UI(this.mcpLease,e.ensureMcpServersLoaded))),this.register(Zn,xm(gl(new BI(this.mcpLease,a||this.projectDir,this.permissionsService,this.workspacePaths,this.pendingDecisionStore,e.ensureMcpServersLoaded),e.encodingSlices,"exec_mcp",(e=>"success"===e.result.case)))),this.register(Xn,xm(new fA(f,e.ensureMcpServersLoaded,{filterToRequestedServers:this.mcpMetaToolEnabled&&this.mcpMetaToolSlimDescriptors})));const v=this.sharedRequestContextExecutor??this.createOwnedRequestContextExecutor(f,t,e),b=xm({execute:(e,t,r)=>{const n=l$.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 l$.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=cA(c,{internalBrowserProvidersOnly:this.mcpMetaToolEnabled&&this.mcpMetaToolSlimDescriptors,inputSchemaJson:this.mcpInputSchemaJson});if(a.tools=l.tools,a.mcpInstructions=l.mcpInstructions,a.mcpMetaToolOptions=this.mcpMetaToolEnabled?lA(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=[],a$.warn(t,"Failed to get mounted agent stores; continuing without prompt inventory")}return i}}),this.backgroundShellExecutor=new Tu(this.permissionsService,c,this.ignoreService,this.projectDir,this.backgroundShellFactory,this.backgroundWorkRegistry,this.wakeupOwnerConversationId,e.backgroundShellManager),this.shellRedeliveryCaches=e.shellRedeliveryCaches??{backgroundShell:Em(),shellStream:Em(),writeStdin:Em()},this.register(TR,xm(this.backgroundShellExecutor,void 0,this.shellRedeliveryCaches.backgroundShell)),this.shellStreamExecutor=new xA(this.permissionsService,c,this.ignoreService,this.backgroundShellExecutor.getManager()),this.register(re,function(e,t,r=Em(t)){return{async*execute(t,n,o){if(!o?.execId)return void(yield*e.execute(t,n,o));const s=Cm(o.execId,n),i=r.get(s);if(i)return void(yield*i.fork());const a=e.execute(t,n,o),c=new _m(a);r.set(s,c),yield*c.fork()}}}(this.shellStreamExecutor,void 0,this.shellRedeliveryCaches.shellStream)),void 0!==e.agentStoreConflictDrainer&&this.register($R,new BR(e.agentStoreConflictDrainer)),this.register(MR,new bA(this.permissionsService)),this.register(DR,new FT(this.permissionsService)),this.register(OR,new jA(this.permissionsService));const S=new SA(this.shellStreamExecutor);this.register(FR,xm(S));const k=!1===e.enableWriteBackgroundShellStdin?new WR((async()=>{throw new Error(e.writeBackgroundShellStdinDisabledReason??"write_shell_stdin is disabled for this session")})):new WR(((e,t)=>this.backgroundShellExecutor.writeStdin(e,t)));if(this.register(AR,xm(k,void 0,this.shellRedeliveryCaches.writeStdin)),e.computerUseExecutor&&(this.computerUseExecutor=e.computerUseExecutor,this.register(NR,xm(this.computerUseExecutor))),this.enableRecordScreen){if(!this.recordScreenArtifactsDir||!this.recordScreenDisplay)throw new Error("recordScreenArtifactsDir and recordScreenDisplay are required when enableRecordScreen is true");this.recordScreenExecutor=new qT({artifactsDir:this.recordScreenArtifactsDir,display:this.recordScreenDisplay,disablePolishedRendering:this.disableRecordScreenRendering,polishedRenderer:e.polishedRecordingRenderer}),this.register(LR,xm(this.recordScreenExecutor))}}createOwnedRequestContextExecutor(e,t,r){const n=new mA(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,deferWarmup:!0===r.deferRequestContextWarmup});return!0===r.deferRequestContextWarmup&&(this.requestContextExecutorAwaitingWarmup=n),this.rebuildRequestContextOnRulesChange&&(this.ownedRequestContextExecutor=n,c$.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&&(c$.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 d$(e){return e.replace(/\\/g,"/")}function h$(e,t){for(const r of t){const t=d$(r);if(e===t||e.startsWith(`${t}/`))return!0}return!1}var p$;function f$(e,t,r){if(function(e){return Boolean(e.plugin?.trim()||e.pluginId?.trim()||e.marketplaceId?.trim())}(e))return p$.Plugin;const n=d$(e.fullPath);return h$(n,r.builtinDirs)?p$.Builtin:Tf(e.fullPath,t).inAgentStore?p$.UserStore:h$(n,r.userDirs)?p$.UserHome:(h$(n,r.workspaceDirs),p$.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"}(p$||(p$={}));var m$=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 g$=(0,Ls.debuglog)("merged-agent-skills"),w$=(0,d.h)("merged-agent-skills");class y${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=>(g$("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 w$.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=$f(c,l??If);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(v$));var t})),void 0!==l?function(e,t){if(e.length<=1)return e;const r=function(e){const t=[uf(e.userHomeDirectory).dirPath],r=wf(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 gf(t,!0))n.push(e.dirPath)}return{builtinDirs:t,userDirs:r,workspaceDirs:n}}(t),n=e.map(((e,n)=>({skill:e,index:n,tier:f$(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{m$(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()}),y$.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()}}y$.CHANGE_COALESCE_MS=1500;const v$=`/${of.configDir}/${of.subdir}/`;function b$(e,t){if((e.disabledEnvironments??[]).includes(t))return!1;const r=e.environments??[];return 0===r.length||r.includes(t)}const S$=(0,d.h)("skill-sync-manifest"),k$=".sync-manifest.json",_$=new Set(["EPERM","EBUSY"]),C$=[20,50,100],E$=new Map;async function x$(e,t){try{const r=await(0,go.readFile)((0,s.join)(e,k$),"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:(S$.warn(t,"Manifest failed schema validation, resetting",{skillDir:e}),{version:1,skills:{}})}catch(r){return r instanceof Error&&"ENOENT"===Wa(r)||S$.debug(t,"Failed to read sync manifest, resetting",{skillDir:e,error:String(r)}),{version:1,skills:{}}}}function P$(e,t,r){e.skills[t]={lastSyncedAt:r}}function I$(e,t){delete e.skills[t]}var R$=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const T$=(0,d.h)("builtin-skills-sync");function A$(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function $$(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 M$(e){const t=pd(e.content),r=A$(t.data)?t.data:{};return fd(`${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={...A$(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 D$(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 O$(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,go.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,go.mkdtemp)((0,s.join)(e,`.${t.id}-staging-`)),o=`${n}-backup`;let i=!1;try{await(0,go.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,go.mkdir)((0,s.dirname)(t),{recursive:!0}),await(0,go.writeFile)(t,r,"utf-8")}try{await(0,go.rename)(r,o),i=!0}catch(e){if(!(e instanceof Error)||"ENOENT"!==Wa(e))throw e}try{await(0,go.rename)(n,r)}catch(e){throw i&&(await(0,go.rename)(o,r),i=!1),e}i&&(await(0,go.rm)(o,{recursive:!0,force:!0}),i=!1)}finally{await(0,go.rm)(n,{recursive:!0,force:!0})}}(t,r),!0}try{if(await(0,go.readFile)(o,"utf-8")===i)return!1}catch(t){t instanceof Error&&"ENOENT"===Wa(t)||T$.warn(e,"Unexpected error reading skill file",{skillId:r.id,error:String(t)})}return await(0,go.mkdir)(n,{recursive:!0}),await(0,go.writeFile)(o,i,"utf-8"),!0}async function O$(e,t=""){const r=t?(0,s.join)(e,...t.split("/")):e;let n;try{n=await(0,go.readdir)(r,{withFileTypes:!0})}catch(e){if(e instanceof Error&&"ENOENT"===Wa(e))return[];throw e}const o=[];for(const r of n){const n=t?`${t}/${r.name}`:r.name;r.isDirectory()?o.push(...await O$(e,n)):r.isFile()&&r.name.endsWith(".md")&&"SKILL.md"!==n&&o.push(n)}return o}async function F$(e,t){try{return(await(0,go.readdir)(t,{withFileTypes:!0})).filter((e=>e.isDirectory()&&!e.name.startsWith("."))).map((e=>e.name))}catch(r){return r instanceof Error&&"ENOENT"===Wa(r)||T$.warn(e,"Failed to list skills directory, skipping cleanup",{skillDir:t,error:String(r)}),[]}}async function N$(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??uf(c).dirPath;await(0,go.mkdir)(l,{recursive:!0});const[u,d]=await Promise.all([x$(l,i),F$(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([L$((0,s.join)(r,"SKILL.md")),"canvas"===e?L$((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}})));T$.info(e,"managed_skills.startup_inventory",{skills_on_disk:o,manifest_present:Object.keys(n.skills).length>0})}catch(t){T$.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):T$.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 L$((0,s.join)(f,df)),g=new Set([...p.keys(),...d,...m?[df]:[]]),w=e=>void 0!==f&&e===df?f:l,y=e=>void 0!==f&&e===df?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&&b$(t,"local"),d=void 0!==t&&!c,h=void 0!==r||y(e),f=w(e);if(t&&!1!==t.enabled&&c)$$(t),f!==l&&await(0,go.mkdir)(f,{recursive:!0}),await D$(i,f,{id:e,fileContent:M$(t),resources:t.resources??{}})?v++:b++,P$(u,e,a);else if(!1===t?.enabled||d||o){const n=!1===t?.enabled?"enabled_false":d?"environment_ineligible":"grace_expired";await(0,go.rm)((0,s.join)(f,e),{recursive:!0,force:!0}),I$(u,e),h&&(S.push(e),T$.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||P$(u,e,a)}catch(t){T$.warn(i,"Failed to apply skill, will retry next sync",{skillId:e,error:String(t)})}try{await function(e,t){const r=(E$.get(e)??Promise.resolve()).then((()=>async function(e,t){const r=(0,s.join)(e,`${k$}.${process.pid}.${(0,ho.randomBytes)(6).toString("hex")}.tmp`);await(0,go.mkdir)(e,{recursive:!0});try{await(0,go.writeFile)(r,JSON.stringify(t,null,2),"utf-8"),await async function(e,t){for(let r=0;;r++)try{return void await(0,go.rename)(e,t)}catch(e){const t=Wa(e),n=C$[r];if(void 0===n||void 0===t||!_$.has(t))throw e;await(0,Fr.cb)(n)}}(r,(0,s.join)(e,k$))}catch(e){throw await(0,go.rm)(r,{force:!0}).catch((()=>{})),e}}(e,t))),n=r.catch((()=>{}));return E$.set(e,n),n.then((()=>{E$.get(e)===n&&E$.delete(e)})),r}(l,u)}catch(e){!function(e){if(e instanceof Error&&"ENOENT"===Wa(e))return!0;const t=String(e);return t.includes("ENOENT")||t.includes("no such file or directory")}(e)?T$.warn(i,"Failed to persist sync manifest",{skillDir:l,error:String(e)}):T$.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{R$(r)}var n}async function L$(e){try{return await(0,go.stat)(e),!0}catch(e){const t=Wa(e);if("ENOENT"===t||"ENOTDIR"===t)return!1;throw e}}const j$=(0,d.h)("managed-skills-sync");function U$(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 B$(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 W${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(...U$(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=B$(n.url);r.has(e)||(r.add(e),t.push(n))}return t}(t)}}var H$=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function q$(e,t){return void 0===e?[]:(Array.isArray(e)?e:[e]).map((e=>({...e,userHomeDir:t})))}class z${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??mh,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: ${Ha(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: ${Ha(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(Jp));return this.plugins.filter((e=>"extension"!==e.identifier.source&&void 0===e.loadError&&e.installPath.length>0&&!t.has(Jp(e))))}async reloadPlugin(e){this.loadPromise&&await this.loadPromise;const t=q$(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 Vp({...l,log:l.log??this.pluginLogger,pluginFilter:r})}catch(t){this.pluginLogger.log("error",`reloadPlugin: source load failed for ${e.name}: ${Ha(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,go.realpath)(r);if(!(await(0,go.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,go.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 Hp(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}: ${Ha(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=q$(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??mh,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(Gp(e,0,{userHomeDir:t.userHomeDir,onError:t.onError,log:r})),c&&a.length>0&&(d=Promise.allSettled(a.map((e=>Vp({...e,userHomeDir:e.userHomeDir??t.userHomeDir,log:e.log??r}))))),i&&l.push(async function(e={}){const t=e.log??mh,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,go.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,go.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,go.realpath)(n)}catch(e){t.log("warn",`loadUserLocalPlugin ${r.name} rejected: failed to resolve symlink (${e instanceof Error?e.message:String(e)})`);continue}try{fp(a,e)}catch{t.log("warn",`loadUserLocalPlugin ${r.name} rejected: symlink target ${e} is outside ${o}`);continue}}if(!(await(0,go.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 Hp(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,go.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=Kp(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=>Kp(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: ${Ha(e)}`),{plugins:[],failures:[],sourceUnavailable:!0}}}catch(t){e.error=t,e.hasError=!0}finally{H$(e)}}}var G$=r("../proto/dist/generated/aiserver/v1/dashboard_pb.js");const V$=BigInt(0),K$=BigInt(8),J$=BigInt(16),Z$=BigInt(65535);function X$(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 Q$(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 Y$(e){const t=e.split(".");if(4!==t.length)return;let r=V$;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<<K$|BigInt(t)}return{version:4,value:r}}function eM(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=Y$(n);if(!o)return;t.push(Number(o.value>>J$&Z$)),t.push(Number(o.value&Z$))}else{if(!/^[0-9a-f]{1,4}$/i.test(n))return;t.push(Number.parseInt(n,16))}}return t}function tM(e){return Y$(e)??function(e){const t=Q$(e);if(0===t.length||t.includes(":::"))return;const r=t.indexOf("::");if(-1===r){const e=eM(t);if(!e||8!==e.length)return;return{version:6,value:e.reduce(((e,t)=>e<<J$|BigInt(t)),V$)}}if(-1!==t.indexOf("::",r+1))return;const n=eM(t.slice(0,r)),o=eM(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<<J$|BigInt(t)),V$)}}(e)}function rM(e,t){const r=Q$(e),n=Q$(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=tM(t.slice(0,r)),o=tM(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 nM(e,t){if(!e.includes("*"))return e===t;const r=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${r}$`).test(t)}function oM(e,t){if(nM(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=Q$(r.hostname);return!!rM(Q$(n.hostname),o)&&nM(`${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=Q$(t.slice(0,r));if(e.length>0)return`${e}/${t.slice(r+1).trim()}`}const n=X$(t);if(n)return Q$(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=Q$(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=X$(e);if(t)return Q$(t.hostname);const r=Q$(e);return r.length>0?r:void 0}(t);return!(!r||!n)&&rM(n,r)}async function sM(e){try{return await e.current()}catch{return}}function iM(e){try{const t=new URL(e);return`${t.protocol}//${t.host}${t.pathname}`}catch{return}}function aM({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||Dy(t.url,n)?{blocked:!1}:{blocked:!0,reason:"teamNetworkAllowlist",message:"Not on the team network allowlist"}}function cM(e){const t=e?.trim();return t&&t.length>0?t:void 0}function lM(e,t,r){if(!0===r?.useCorePolicy)return!function(e,t){if(void 0===t)return!0;if(!0===t.disableAll)return!1;if(Jk(e))return!0;if(Yk(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=Zk(t.command),n=Xk(t.serverUrl);if(void 0===r&&void 0===n)return!1;const o=void 0===r||void 0!==e.command&&(0,yv.mD)(r,e.command),s=void 0===n||void 0!==e.url&&(0,yv.vc)(n,e.url);return o&&s}))}(e,t)}(e,r)||!0===t.allowUserOverrideMcpServers&&!Qk(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=cM(e.command),n=cM(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&&oM(n,t.url);return o&&s}(t,e)))}class uM{constructor(e,t={}){this.dashboardClient=e,this.options=t}getTeamAdminSettings(){return this.dashboardClient.getTeamAdminSettingsOrEmptyIfNotInTeam(new G$.Byz(!0===this.options.supportsHostMcpBridgeExemption?{supportsHostMcpBridgeExemption:!0}:{}))}getTeamRepos(){return this.dashboardClient.getTeamReposOrEmptyIfNotInTeam(new G$.aYW({}))}}function dM(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 hM{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 pM{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 hM((()=>this.fetchSettings())),this.droppedReplies=new WeakSet,this.hostMcpBridgeClients=new WeakSet,this.mcpServerByClient=new WeakMap,this.teamRepos=new hM((()=>this.teamAdminSettingsProvider.getTeamRepos())),this.defaultAllowlist=new hM((()=>this.fetchDefaultAllowlist())),this.getTeamAdminSettings(),this.prefetchTeamRepos()}async prefetchTeamRepos(){try{await this.teamRepos.get()}catch{}}invalidateCache(){this.settingsGeneration+=1,this.settings.invalidate(),!0!==this.options.preserveTeamReposOnInvalidate&&this.teamRepos.invalidate(),this.defaultAllowlist.invalidate()}invalidateTeamRepos(){this.teamRepos.invalidate()}async fetchSettings(){const{fetchIdentity:e}=this.options;if(void 0!==e)return this.fetchSettingsFor(e);const t=this.settingsGeneration;try{const e=await this.teamAdminSettingsProvider.getTeamAdminSettings();return this.lastFetchSucceeded=!0,t>=this.lastFetchedGeneration&&(this.lastFetchedSettings=e,this.lastFetchedGeneration=t),e}catch(e){throw this.lastFetchSucceeded=!1,e}}async fetchSettingsFor(e){const t=await sM(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 sM(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 sM(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 sM(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(Yk(e,r?.offMcpServerRules))return{blocked:!0,reason:"teamPolicy",message:"Blocked by team policy"};if(n){if(lM(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,yv.ME)(e.url,n);if(!o.allowed)return{blocked:!0,reason:"teamNetworkAllowlist",message:o.message};const s=aM({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?aM({failOpenWhenEmpty:!0,server:t,settings:r}):{blocked:!1}}({isMcpAccessNetworkAllowlistEnabled:await this.isMcpAccessNetworkAllowlistEnabled(),server:e,settings:t});if(r.blocked)return r}return{blocked:!1}}async getManagedSlackWorkspaceLists(){const e=await this.getTeamAdminSettings()??this.lastFetchedSettings;return void 0===e?[]:function(e){return e.memberSlackManagedWorkspacesUnreadable?"unconfirmed":e.memberSlackManagedWorkspaces.map((e=>e.slackTeamIds)).filter((e=>e.length>0))}(e)}async getMcpNetworkControlsConfig(e){const t=await this.getTeamAdminSettings(),r=t?.allowedMcpConfiguration;if(await this.isMcpSettingsOverhaulEnabled()&&(void 0===e||!this.isHostMcpBridge(t,e))){const n="win32"===process.platform&&await this.isWin32UserExtensionStdioUnsandboxEnabled();return(0,yv._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=iM(t.url);return void 0!==n&&r.some((e=>iM(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,yv.rM)(e,t)));if(void 0!==r)return Sv({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?"":vv(e.name);if(0===t.length)return[];const r=Sv({mode:e.toolAllowlistMode,tools:e.toolAllowlist});return[{name:t,policy:r,flattened:_v(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===G$.h0i.WORKSPACE?"workspace":"system");var n;return{sandboxingDisabled:t?.sandboxing===G$.faf.DISABLED,networkingDisabled:t?.sandboxNetworking===G$._mX.ALWAYS_DISABLED,gitDisabled:t?.sandboxGit===G$.i24.ALWAYS_DISABLED,readBoundary:r,readAllowlistPaths:dM(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 fM=new fw,mM={async resolveWorkspaceState(e){const t=e.workingDirectory??e.projectRoot??e.workspaceRoots?.[0],r=e.projectRoot??(void 0!==t?await Ea((0,b.q6)(),fM,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?mo(r):void 0),workspaceRoots:n,createdAt:new Date}}},gM=(0,d.h)("ControlledConversationActionManager");class wM{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){gM.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 yM=r("../cursor-sdk-local-runtime/dist/utils/logger.js"),vM=r("../agent-kv/dist/agent-store.js");const bM="x-blob-encryption-key";function SM(e,t){const r={...t};return void 0!==r[bM]||(0,vM.TU)(e)&&(r[bM]=e),r}const kM=new Map;function _M(e){if("userMessageAction"===e.action.case)return e.action.value.userMessage?.text}function CM(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 EM(e){return new c.QFf({action:{case:"userMessageAction",value:new c.Vtf({userMessage:new c.RGk({text:e})})}})}function xM(e){return e instanceof DOMException&&"AbortError"===e.name||e instanceof Error&&("AbortError"===e.name||"The operation was aborted"===e.message)}function PM(e){e?.catch((e=>{yM.Jz.warn("[agent-session-runner] fire-and-forget hook failed:",e)}))}const IM=new Set(["mcp.slack.com","setup.shopify.com"]);async function RM(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?Hy(e):void 0}({serverUrl:i,restMcpHost:a}));var i,a;if(!IM.has(o)&&!s)return t;let c=await r.resolve(e);if(!c&&s){const t=(await xC(e,n))?.clientId;void 0!==t&&(c={CLIENT_ID:t})}return c?t?void 0===CC(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 TM{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 RM(e.serverConfig,this.resolver);return t===e.serverConfig?e:{...e,serverConfig:t}})))}clearCache(){this.inner.clearCache?.()}}class AM{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 $M{constructor(e,t){this.storage=e,this.prefix=t}async isServerApproved(e,t,r){return this.storage.isServerApproved(this.prefix+e,t,r)}}class MM{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 n_(t,n.configPath??"another config")}return await o(e,r)}}class DM{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 yP(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 OM{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 OP(e,"enterprise"===r||"env"===r?H_:void 0)}))),y=[];for(const{prefix:e,scope:o,fileSource:s}of w){const l=i?"":e,d=new AM(t,l),p=new $M(n,l),f=w.flatMap((e=>{return t=e.scope,r=o,q_.indexOf(t)<q_.indexOf(r)&&("enterprise"===t||"env"===r)?[e.fileSource]:[];var t,r})),m=[new l_,...z_(o)?[new s_(p)]:[],new jP(r),...c?[new o_(c)]:[],...f.length>0?[new MM(f)]:[]],g=new FP(u?new TM(s,u):s,d,m,{authRedirectUrlGenerator:a,isLinkSharedPaymentTokenLogRedactionEnabled:h});y.push({prefix:l,loader:g})}this.loader=new DM(y)}static init(e,t,r,n=!1,o,i={}){const a=new zP(s.join(r,"mcp-auth.json"));(async function(e){await(0,go.rm)(s.join(e,"mcp-cache.json"),{force:!0})})(r).catch((()=>{}));const c=n?{isServerApproved:()=>Promise.resolve(!0)}:new i_(s.join(r,"mcp-approvals.json"),t);return new OM(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 FM="cursor-plugins/local";function NM(e){var t;if(e)for(const r of e)if("object"==typeof(t=r)&&null!==t&&t.kind===FM)return r}class LM extends wP{constructor(e){super(e),this.runtimeManager=e,this.disposed=!1}async dispose(){this.disposed||(this.disposed=!0,await this.runtimeManager.closeAllClients())}}class jM{constructor(e){this.storagePath=e}async isServerDisabled(e){try{const t=await(0,go.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,go.mkdir)((0,s.dirname)(this.storagePath),{recursive:!0}),await(0,go.writeFile)(this.storagePath,JSON.stringify(e,null,2))}}class UM{constructor(e,t){this.pluginMcpService=e,this.importThirdPartyPlugins=t}async getDefinitions(){let e;try{e=await this.pluginMcpService.getPluginMcpServers()}catch(e){return yM.Jz.warn("[cursor-config-mcp] Failed to enumerate plugin MCP servers:",e),[]}const t=[];for(const r of e){if(!this.importThirdPartyPlugins&&zM(r))continue;const e=BP(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}}):yM.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 BM{constructor(e){this.servers=e}async getDefinitions(){return Object.entries(this.servers).map((([e,t])=>({identifier:e,authStorageKey:`inline:${e}`,serverConfig:qM(e,t),source:"inline",metadata:{source:"cursor-sdk"}})))}}function WM(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 gP;const d=new jM((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 OM.init(t,r,n,i,a,{isLinkSharedPaymentTokenLogRedactionEnabled:u});if(!c&&!l)return;const d=new zP((0,s.join)(n,"mcp-auth.json")),h=i?{isServerApproved:()=>Promise.resolve(!0)}:new i_((0,s.join)(n,"mcp-approvals.json"),r),p=[new l_,new s_(h),new jP(t),new o_(a)],f=[];return c&&f.push({prefix:"",loader:new UP((0,s.join)(r,".cursor","mcp.json"),d,p,{isLinkSharedPaymentTokenLogRedactionEnabled:u})}),l&&f.push({prefix:"",loader:new UP((0,s.join)((0,o.homedir)(),".cursor","mcp.json"),d,p,{isLinkSharedPaymentTokenLogRedactionEnabled:u})}),HM(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 zP((0,s.join)(u,"mcp-auth.json")),r=[new l_,new jP(t)];p.push({prefix:"",loader:new FP(new BM(f),e,r,i)})}const m=NM(a.services.pluginBootstrapOutputs);if(m&&(e.includePluginMcp??1)){const e=new i_((0,s.join)(u,"mcp-approvals.json"),l),o=new zP((0,s.join)(u,"mcp-auth.json")),a=[new l_];r||a.push(new s_(e)),a.push(new jP(t),new o_(d));const c=new W$(m.pluginsService),h=new FP(new UM(c,n),o,a,i);p.push({prefix:"",loader:h})}if(h&&p.push({prefix:"",loader:h}),0===p.length)return new gP;const g=HM(p),w=await g.load(e.initializationCtx??(0,b.q6)(),e.cache);return new LM(w)}}}function HM(e){return 1===e.length?e[0].loader:new DM(e)}function qM(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 zM(e){return"claude-plugin"===e.pluginSource}const GM=["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass"];function VM(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 KM(e){return e.slice(Math.max(e.lastIndexOf("\\"),e.lastIndexOf("/"))+1)}const JM=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 ZM(e){const t=VM(e),r=KM(t);return!JM.has(r.toLowerCase())&&(!!/\.(exe|bat|cmd|com)$/i.test(r)||t===r&&/^[A-Za-z0-9_]+$/.test(r))}function XM(e){if(ZM(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=VM(e),r=KM(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=VM(e);if(0===t.length||ZM(e))return!1;const r=KM(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 QM=[".ps1",".exe",".bat",".cmd"];function YM(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 eD(e){return e?.enableClaudeNestedHookSpecificOutputCompatibility??!1}function tD(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function rD(e){if(!tD(e))return;const t=e.hookSpecificOutput;return tD(t)?t:void 0}function nD(e,t){if(!e)return!1;const r=e.hookEventName;return void 0===r||""===r||r===t}function oD(e,t,r){if(!tD(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(!eD(t))return n;const o=rD(e),s=nD(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 sD=e=>{const t=[];return Bu(e)?Hu(!0):(t.push("Expected an object"),Hu(!1,t))},iD=e=>{const t=[],r=sD(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"),Hu(0===t.length,t)};function aD(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 cD=new Set([ju.sessionStart,ju.beforeSubmitPrompt,ju.preToolUse,ju.postToolUse,ju.postToolUseFailure]);function lD(e){return"prompt"===e.type}function uD(e){return"command"===e.type||void 0===e.type}const dD={[ju.beforeShellExecution]:iD,[ju.beforeMCPExecution]:iD,[ju.afterShellExecution]:e=>{const t=sD(e);return t.isValid,t},[ju.afterMCPExecution]:e=>{const t=sD(e);return t.isValid,t},[ju.beforeReadFile]:e=>{const t=[],r=sD(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"),Hu(0===t.length,t)},[ju.afterFileEdit]:e=>{const t=sD(e);return t.isValid,t},[ju.beforeTabFileRead]:e=>{const t=[],r=sD(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"),Hu(0===t.length,t)},[ju.afterTabFileEdit]:e=>sD(e),[ju.beforeSubmitPrompt]:e=>{const t=sD(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||Uu(e.additional_context)||r.push("additional_context must be a string if provided"),Hu(0===r.length,r)},[ju.stop]:e=>{const t=sD(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"),Hu(0===r.length,r)},[ju.afterAgentResponse]:e=>{const t=sD(e);return t.isValid,t},[ju.afterAgentThought]:e=>{const t=sD(e);return t.isValid,t},[ju.sessionStart]:e=>{const t=sD(e);if(!t.isValid)return t;const r=[];if(void 0!==e.env)if(Bu(e.env))for(const[t,n]of Object.entries(e.env))Uu(t)||r.push(`env key "${t}" must be a string`),Uu(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||Uu(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||Uu(e.user_message)||r.push("user_message must be a string if provided"),Hu(0===r.length,r)},[ju.sessionEnd]:e=>{const t=sD(e);return t.isValid?Hu(!0,[]):t},[ju.preCompact]:e=>{const t=sD(e);if(!t.isValid)return t;if(null==e||0===Object.keys(e).length)return Hu(!0,[]);const r=[];if(!Wu(e))return r.push("PreCompact response must be an object"),Hu(!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"),Hu(0===r.length,r)},[ju.subagentStart]:e=>{const t=sD(e);if(!t.isValid)return t;if(!Wu(e))return Hu(!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||Uu(n.user_message)||r.push("user_message must be a string if provided"),Hu(0===r.length,r)},[ju.subagentStop]:e=>{const t=sD(e);if(!t.isValid)return t;const r=[];return Wu(e)&&void 0!==e.followup_message&&"string"!=typeof e.followup_message&&r.push("followup_message must be a string if provided"),Hu(0===r.length,r)},[ju.preToolUse]:e=>{const t=[],r=sD(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"),qu(e.additional_context,"additional_context",t),Hu(0===t.length,t)},[ju.postToolUse]:e=>{const t=[],r=sD(e);return r.isValid?(qu(e.additional_context,"additional_context",t),Hu(0===t.length,t)):r},[ju.postToolUseFailure]:e=>{const t=sD(e);if(!t.isValid)return t;const r=[];return qu(e.additional_context,"additional_context",r),Hu(0===r.length,r)},[ju.workspaceOpen]:e=>{const t=sD(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")),Hu(0===r.length,r)}},hD=(e,t,r)=>{const n=function(e,t,r){let n;return n=e===ju.preToolUse?function(e,t){if(!tD(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(!eD(t))return r;const n=rD(e);if(!nD(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),tD(n.updatedInput)&&(o.updated_input=n.updatedInput,s=!0),s?o:r}(t,r):e===ju.stop?oD(t,r,"Stop"):e===ju.subagentStop?oD(t,r,"SubagentStop"):t,function(e,t,r,n){if(!cD.has(e)||!tD(r)||void 0!==r.additional_context)return r;const o=tD(t)?function(e){return"string"==typeof e.additionalContext?e.additionalContext:void 0}(t)??function(e,t,r){if(!eD(r))return;const n=Ju[e];if(void 0===n)return;const o=rD(t);return nD(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,dD[e])(n);return o.isValid?{success:!0,data:n}:{success:!1,errors:o.errors}},pD=[ju.beforeShellExecution,ju.beforeMCPExecution,ju.beforeReadFile,ju.beforeTabFileRead,ju.subagentStart,ju.preToolUse],fD=[ju.workspaceOpen];function mD(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 gD(e,t){return{..."object"==typeof e&&null!==e?e:{},...t}}function wD(e){return pD.includes(e)}function yD({step:e,command:t,failClosed:r,kind:n}){const o=wD(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:bD(e,s),cause:r?"script_fail_closed":"permission_hook_invalid_output",reason:s,shouldNotifyUser:o&&!r}}function vD(e,t){return t}function bD(e,t){return wD(e)?vD(0,{permission:"deny",user_message:t}):e===ju.beforeSubmitPrompt||e===ju.sessionStart?vD(0,{continue:!1,user_message:t}):e===ju.stop?vD(0,{}):void 0}function SD(e){try{return{value:JSON.parse(e)}}catch{return}}function kD(e){if("object"!=typeof e||null===e)return!1;const t=e.event;return"backgrounded"===t?.case}function _D(e){if("object"!=typeof e||null===e)return;const t=e.path;return"string"==typeof t&&t.length>0?t:void 0}class CD{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>CD.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===eR.symbol||e===tR.symbol?{kind:"path"}:e===ZI.symbol||e===re.symbol||e===TR.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=_D(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&&kD(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===eR.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=_D(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 ED(e){return new RegExp(`<${e}(?:\\s[^>]*)?>[\\s\\S]*?</${e}>`,"gi")}CD.CARRIERS_BY_EXEC_ID_MAX=32,Error,yl.execFileSync,new Map,yo.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 xD=["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(ED);function PD(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(ID,"\n\n"):r).trim()}(e,xD)}["system_reminder","system-reminder"].map(ED);const ID=/\n{3,}/g;function RD(e){const t=(0,po.sh)(e.conversationId);if("subagent"===e.kind&&e.parentConversationId){const r=(0,po.sh)(e.parentConversationId);return`${po.O2}/${r}/subagents/${t}.${e.ext}`}return`${po.O2}/${t}/${t}.${e.ext}`}function TD(e){const t=(0,po.sh)(e.conversationId);return`${po.O2}/${t}.${e.ext}`}function AD(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(RD({conversationId:e.conversationId,ext:n,kind:e.kind,parentConversationId:e.parentConversationId})),"subagent"===e.kind&&e.parentConversationId&&o(RD({conversationId:e.conversationId,ext:n,kind:"primary"})),r&&o(TD({conversationId:e.conversationId,ext:n}));return n}var $D;!function(e){e.INTERNAL="INTERNAL",e.EXTERNAL="EXTERNAL",e.NO_PREAMBLE="NO_PREAMBLE"}($D||($D={}));var MD=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},DD=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 OD(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 FD(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 ND(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 LD=new TextEncoder,jD=new TextDecoder,UD=new class{serialize(e){const t=JSON.stringify(e,FD);return LD.encode(t)}deserialize(e){const t=jD.decode(e);return t.includes('"__type":"Uint8Array"')?JSON.parse(t,ND):JSON.parse(t)}};function BD(e){const t=e.providerOptions;return!0===t?.cursor?.isSummary}function WD(e){return"system"!==e.role&&!BD(e)}function HD(e,t){return"user"===e.role&&"user"===t.role}async function qD(e,t,r){const n=await t.getBlob(e,r);return n?c.Anz.fromBinary(n).summarizedMessages:[]}async function zD(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=UD.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 GD(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 zD(e,t,o,n);r&&n.messages.push(r)}return n}async function VD(e,t,r,n,o){const s=[];let i=0;const a=()=>{const o=zD(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 KD(e,t){switch(e.type){case"text":return t?JD(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 JD(e){return PD(e)}const ZD=/<think>[\s\S]*?<\/think>/gi,XD=/<thinking>[\s\S]*?<\/thinking>/gi,QD=/\n{3,}/g;function YD(e){let t=e;return t.includes("<")&&(t=t.replace(ZD,"").replace(XD,"")),(t.includes("\n\n\n")?t.replace(QD,"\n\n"):t).trim()}function eO(e,t,r){if(void 0===e)return"";if("string"==typeof e){const n=t?JD(e):e;return r?YD(n):n}return e.map((e=>{if(r&&"text"===e.type){const r=YD(t?JD(e.text):e.text);return KD({...e,text:r},!1)}return KD(e,t)})).filter(Boolean).join("\n")}function tO(e,t){const r={role:e.role},n=e.content;if("string"==typeof n){const o=t?JD(n):n,s="assistant"===e.role?YD(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?JD(r.text):r.text,s="assistant"===e.role?YD(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 rO(e){return e.endsWith("\n")?e:`${e}\n`}function nO(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 oO(e){if("system"===e.role||BD(e))return;const t=tO(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 sO{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=RD({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=MD(o,(0,D.VI)(e.withName("writeFromState")),!1);try{const{overviewFactory:e}=n,o=nO(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=MD(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 qD(i,t,e);return s+=r.length,await GD(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=MD(n,(0,D.VI)(e.withName("hydratePromptMessages")),!1),w=await GD(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(WD);return a.push(...y),a}catch(e){n.error=e,n.hasError=!0}finally{DD(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=eO(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=tO(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:OD(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&&HD(t[0],t[1])&&(t=t.slice(1));const r=[];for(const e of t){const t=oO(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"),rO(n))}return!0}catch(e){return console.error("[TranscriptStore] Failed to write transcript:",e),!1}}catch(e){o.error=e,o.hasError=!0}finally{DD(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 qD(e,t,s)}catch{continue}await VD(e,t,r,o,{skipFailedReads:!0,visit:n})}return await VD(e,t,r.rootPromptMessagesJson,o,{skipFailedReads:!1,visit:async e=>{WD(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&&(HD(u,e)||await l(oO(u)),u=void 0),await l(oO(e))):u=e)}));u&&await l(oO(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=nO(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=MD(s,(0,D.VI)(e.withName("writeFromStateIncremental")),!1);if(i===n&&c)try{return await l(this.resolveFilePath(r,"jsonl"),rO(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 GD(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=oO(e);t&&s.push(t)}if(s.push(...a.jsonlLines),s.length>0){const e=rO(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{DD(s)}}}function iO(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 aO(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 cO(e){return`Tool blocked because this hook is configured to fail closed (block when it fails). ${e}`}function lO(e){return Object.values(ju).some((t=>t===e))}function uO(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 dO(e){return lD(e)?`prompt:${e.prompt}`:`command:${e.command}`}function hO(e){return(e.repoHooks??[]).flatMap((e=>[e.projectHooks,e.claudeProjectHooks,e.claudeProjectLocalHooks]))}class pO{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(dO(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=dO(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(!Wu(e))return!1;if(!("hooks"in e))return!1;const r=e.hooks;if(!Wu(r))return!1;const n=r;for(const[e,r]of Object.entries(n))if(e in Ku&&Array.isArray(r)){const n=!0===t.allowMatcherlessStop&&"Stop"===e;for(const e of r)if(Wu(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=ud(r,this.logger),o=Vu(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=Vu(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,...hO(e)];for(const e of r)if(e?.hooks)for(const r of Object.keys(e.hooks))lO(r)&&t.add(r);for(const r of e.pluginHooks??[])for(const e of Object.keys(r.config.hooks))lO(e)&&t.add(e);return t}}const fO="Read",mO="Write",gO="Delete",wO="List",yO="Grep",vO="Shell",bO="ReadLints";function SO(e,t){if("object"==typeof e&&null!==e)return Object.getOwnPropertyDescriptor(e,t)?.value}const kO=new Set([fO,mO,gO,wO,yO,bO]);function _O(e){const t=SO(e,"tool_name"),r=[SO(e,"file_path"),"string"==typeof t&&kO.has(t)?SO(SO(e,"tool_input"),"file_path"):void 0];for(const e of r)if("string"==typeof e&&e.length>0)return e}const CO=(0,d.h)("cli-hooks-executor");function EO(e){try{return(0,yo.statSync)(e).isFile()}catch{return!1}}const xO="\nJSON Parse Error: Error: Failed to parse hook stdout as JSON";function PO(e,t){for(const[r,n]of Object.entries(e))if(r===t)return n}function IO(e,t){const r=PO(e,t);if("string"==typeof r||null===r)return r}class RO{constructor(e,t,r,n,o,s,i,a){this.workspacePath=t,this.globalContext=r,this.shellExecutor=n,this.promptHookClient=o,this.onHookExecution=i,this.options=a,this.sessionEnvById=new Map,this.sessionUserEmailById=new Map,this.activeSessionIdsByConversationId=new Map,this.transcriptParentConversationIdById=new Map,this.configReadyPromises=[],this.config=e,s&&this.addConfigReadyPromise(s)}addConfigReadyPromise(e){this.configReadyPromises.push(e.catch((()=>{})))}reportCommandFailure(e,t){if(void 0!==e)try{e(t)}catch{}}finishHookRun(e,t,r,n){const o=e.transportMode??("prompt"===e.hookType?"prompt":this.getCommandHookPayloadTransportMode());try{this.onHookExecution?.({...e,transportMode:o})}catch{}const s=this.options?.onHookRun;if(void 0===s)return;const i=n.exitCode??e.exitCode,a="spawn_error"===(c=e.errorClass)?"shell_exec_transport_error":"prompt_error"===c?"prompt_execution_error":void 0;var c;try{s({step:e.hookStep,script:t,source:e.hookSource,...void 0===e.pluginId?{}:{pluginId:e.pluginId},request:r,response:n.response??null,durationMs:e.latencyMs,...void 0===i?{}:{exitCode:i},stderr:n.stderr,transportMode:o,configuredTimeoutSec:t.timeout??60,timedOut:!0===e.timedOut,...void 0===a?{}:{failureType:a}})}catch{}}getCommandHookPayloadTransportMode(){return"stdin"===this.options?.commandHookPayloadTransport?"win32"===process.platform?"windows_temp_file":"stdin":"argv_heredoc"}shouldUseCommandHookDirectStdinTransport(){return"stdin"===this.getCommandHookPayloadTransportMode()}async writeCommandHookStdinPayload(e,t){if(!e)throw new Error("Hook stdin transport was requested, but the executor did not provide stdin");try{e.end(Buffer.from(t,"utf8"))}catch(e){const t=e instanceof Error&&"code"in e?e.code:void 0;if("EPIPE"===t||"ERR_STREAM_DESTROYED"===t||"ERR_STREAM_PREMATURE_CLOSE"===t)return;throw e}try{await(0,Gh.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,po.Rv)((0,o.homedir)(),this.workspacePath),r=this.transcriptParentConversationIdById.get(e),n=AD(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,go.access)(e),e}catch{}return null}catch{return null}}async getSubagentTranscriptPathIfExists(e){const{subagentId:t,parentConversationId:r}=e;try{const e=(0,po.Rv)((0,o.homedir)(),this.workspacePath),n=AD({conversationId:t,kind:"subagent",parentConversationId:r}).map((t=>(0,s.join)(e,t)));for(const e of n)try{return await(0,go.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,...hO(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?aO(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?aO(n,t):n).some((e=>uD(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=PO(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 fD.includes(e)}(e),o=t,i=n?null:o.conversation_id?await this.getTranscriptPathIfExists(o.conversation_id):null;let a;if(e===ju.subagentStop){const e=IO(t,"subagent_id"),r=IO(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===ju.subagentStop&&{agent_transcript_path:a??null}},u=function(e,t){switch(e){case"beforeShellExecution":case"afterShellExecution":return iO(t,"command");case"beforeMCPExecution":case"afterMCPExecution":{const e=iO(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 iO(t,"subagent_type");case"preToolUse":case"postToolUse":case"postToolUseFailure":return iO(t,"tool_name");default:return}}(e,l),d=[],h=(e,t,n)=>{if(!e)return;const o=aO(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)lD(e)?this.promptHookClient&&d.push({type:"prompt",script:e,source:t}):uD(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:_O(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===ju.stop||e===ju.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 aO(n,u))uD(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=cO(`Hook execution failed: ${n}`),r=bD(e,t);if(r)return{success:!0,data:r,source:i,index:o}}return CO.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;if(1===t.length)return t[0];const r=pD.includes(e),n=e===ju.sessionStart,o=e===ju.workspaceOpen,s=cD.has(e),i={};for(const e of t){const t=e;for(const[e,l]of Object.entries(t))if(void 0!==l)if(o&&"pluginPaths"===e&&Array.isArray(l)){const t=i[e],r=Array.isArray(t)?t:[],n=new Set(r),o=[...r];for(const e of l)"string"!=typeof e||n.has(e)||(n.add(e),o.push(e));i[e]=o}else"permission"===e&&r?i[e]=(c=l,"deny"===(a=i[e])||"deny"===c?"deny":"ask"===a||"ask"===c?"ask":"allow"===a||"allow"===c?"allow":void 0):"user_message"!==e&&"agent_message"!==e?s&&"additional_context"===e&&"string"==typeof l?i[e]=mD(i[e],l):"continue"!==e||"boolean"!=typeof l?i[e]=n&&"env"===e&&"object"==typeof l&&null!==l?gD(i[e],l):l:void 0===i[e]?i[e]=l:i[e]=i[e]&&l:i[e]=mD(i[e],l)}var a,c;return i}(e,c)}async executeCommandHook(e,t,r,n,o,s,i,a,c,l,u){if(this.shouldSkipHookDueToLoopLimit(e,t,o))return{success:!1,source:s,index:i};const d=Date.now(),h=a(),p=h.payloadSizeBytes,f=(e,r)=>this.finishHookRun(e,t,o,r);let m;try{m=await this.executeCommandScript({script:t,cwd:r,request:o,jsonPayload:h.json,env:n,...void 0!==l&&{pluginInstallPath:l}})}catch(r){const n=r instanceof Error?r.message:String(r),o=n.toLowerCase().includes("timed out");this.reportCommandFailure(u,{command:t.command,source:s,exitCode:null,stderr:"",errorMessage:n});const a=Date.now()-d,l=o?"timeout":"spawn_error";if(!0===t.failClosed){const u=bD(e,cO(`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=bD(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=bD(e,cO(`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=bD(e,cO(`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=SD(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=SD(t.slice(e));if(void 0!==r)return r.value}}(g);if(void 0===w){const r=yD({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+xO}),{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+xO}),{success:!1,source:s,index:i})}const y=hD(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=yD({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 wD(e)?vD(0,{permission:"allow"}):e===ju.beforeSubmitPrompt||e===ju.sessionStart?vD(0,{continue:!0}):e===ju.stop?vD(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=bD(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=bD(e,cO(`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=QM.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:EO}):t.command;let w;if(m)w=e?YM(g):g;else if("windows_temp_file"===f){d=await(0,go.mkdtemp)((0,s.join)((0,o.tmpdir)(),"cursor-hooks-"));const e=(0,s.join)(d,"payload.json");await(0,go.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 | ${YM(t)} }`+XM(t)}(e,g)}else w=e?`@'\n${c.replace(/'/g,"''")}\n'@ | & ${g}`+XM(g):`${t.command} <<'CURSOR_HOOK_EOF'\n${c}\nCURSOR_HOOK_EOF`;const y=IO(n,"conversation_id")??void 0,v=IO(n,"session_id")??void 0,S=IO(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 Yi.StringDecoder("utf8"),I=new Yi.StringDecoder("utf8");let R,T="",A="",$=null,M=!1;for await(const e of this.shellExecutor.execute(x,w,{workingDirectory:r,signal:h.signal,sandboxPolicy:{perUser:{type:"insecure_none"}},env:E,pipeStdin:m}))switch(e.type){case"stdin_ready":m&&(await this.writeCommandHookStdinPayload(e.stdin,c),M=!0);break;case"stdout":T+=P.write(e.data);break;case"stderr":A+=I.write(e.data);break;case"exit":$=e.code,R=e.aborted}if(T+=P.end(),A+=I.end(),m&&!M)throw new Error("Hook stdin transport was requested, but the executor did not signal stdin readiness");clearTimeout(p);const D=Date.now()-u;if(R??h.signal.aborted)throw new Error(`Hook script timed out after ${l}ms`);return{stdout:T,stderr:A,exitCode:$,duration:D}}catch(e){if(clearTimeout(p),Date.now(),h.signal.aborted)throw new Error(`Hook script timed out after ${l}ms`);throw e}finally{if(d)try{await(0,go.rm)(d,{recursive:!0,force:!0})}catch{}}}}class TO{constructor(e){this.config=e,this.configuredSteps=pO.getConfiguredSteps(e)}getConfig(){return this.config}hasHookForStep(e){return this.configuredSteps.has(e)}getConfiguredSteps(){return new Set(this.configuredSteps)}}var AO=r("node:perf_hooks");const $O=(0,b.cF)(Symbol.for("@anysphere/agent-exec/toolCallHooks"),{kind:"none"});function MO(e){return"inExecute"!==e.get($O).kind}function DO(e,t){const r=e.get($O);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 OO=(0,b.cF)(Symbol.for("@anysphere/agent-exec/hookStepTime"),void 0),FO=new Au.AsyncLocalStorage;function NO(e,t){return FO.run(e,t)}function LO(e,t){void 0!==e&&t.length>0&&e.push(...t)}class jO 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 UO=r("../proto/dist/generated/agent/v1/hook_additional_context_pb.js");function BO({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 jO({hookEventName:e,actualLength:r.length,maxLength:1e4});return[new UO.C({hookEventName:e,content:r})]}Object.fromEntries(Array.from(cD).map((e=>{if(!function(e){return e===ju.sessionStart||e===ju.beforeSubmitPrompt||e===ju.preToolUse||e===ju.postToolUse||e===ju.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 WO="Agent note: Do not suggest workarounds to the blocked tool.";function HO(e){return e.includes(WO)?e:`${e}\n\n${WO}`}class qO extends Error{constructor(e){super(`Hook denied: ${e}`),this.failureType="permission_denied",this.name="HookDeniedError",this.reason=e}}class zO extends Error{constructor(e,t){super(`Hook failed (fail-closed): ${e}`),this.failureType="error",this.name="FailClosedError",this.reason=e,this.cause=t}}const GO="To view or modify configured hooks, go to Cursor Settings > Hooks.";function VO(e,t){return HO(`${t?`${e} was blocked by a hook: ${t}`:`${e} was blocked by a hook.`}\n\n${GO}`)}function KO(e){return function(e){return e instanceof qO}(e)||function(e){return e instanceof zO}(e)}const JO=(0,d.h)("generic-hooks");function ZO(e,t,r,n){try{return BO({hookEventName:r,additionalContext:n})}catch(n){if(n instanceof jO)return JO.warn(e,`${r} additional_context exceeded max size; dropping carrier`,{toolName:t,hookEventName:r,actualLength:n.actualLength,maxLength:n.maxLength}),[];throw n}}const XO=e=>Math.round(1e3*e)/1e3;function QO(e,t,r,n,o,s){const i=n(e),a=o.getToolCallId?.(t)??(0,ho.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 NO(e.signal,(()=>t.executeHookForStep(ju.postToolUseFailure,{...a,tool_name:r,tool_input:o,error_message:l,failure_type:u,duration:n,tool_use_id:c,is_interrupt:d,...s})));LO(i,ZO(e,r,ju.postToolUseFailure,h?.additional_context))}catch(t){JO.warn(e,"postToolUseFailure hook error",{toolName:r,error:t instanceof Error?t.message:String(t)})}},fireSuccessAsync:async(n,l)=>{try{const u=await NO(e.signal,(()=>t.executeHookForStep(ju.postToolUse,{...a,tool_name:r,tool_input:o,tool_output:l,duration:n,tool_use_id:c,...s})));LO(i,ZO(e,r,ju.postToolUse,u?.additional_context))}catch(t){JO.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 YO(e,t,r,n,o,s,i,a){const{baseHookRequest:c,toolUseId:l,extraHookFields:u}=n;try{const a=await NO(e.signal,(()=>r.executeHookForStep(ju.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=HO(r);try{LO(n.hookContextCollector,BO({hookEventName:ju.preToolUse,additionalContext:a.additional_context}))}catch(t){if(!(t instanceof jO))throw t;JO.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))),LO(n.hookContextCollector,BO({hookEventName:ju.preToolUse,additionalContext:a?.additional_context}))}catch(n){const a=r.hasFailClosedHooksForStep?.(ju.preToolUse,s.toolName)??!1,c=n instanceof jO;if(a){const e=cO(`${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}}JO.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(KO(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 eF(e){return e.toolCallId}function tF(e,t,r,n){return{async execute(o,s,i){const a=nF(o,t),{hookContext:c,helpers:l}=QO(o,s,a,r,n,i);let u;try{u=await YO(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=AO.performance.now();try{const t=await e.execute(o,s,i),r=XO(AO.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(KO(e))return await l.fireFailureAsync(r,e.reason,e.failureType),n.runCleanup?.(c.toolUseId),n.createRejectedResult(s,e.reason);JO.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=XO(AO.performance.now()-d);throw await l.fireFailureAsync(t,e instanceof Error?e.message:String(e),"error"),n.runCleanup?.(c.toolUseId),e}}}}function*rF(e,t){const r=t.hookContextCollector;e.createHookContextEvent&&void 0!==r&&0!==r.length&&(yield e.createHookContextEvent(r))}function nF(e,t){const r=MO(e),n=e.get(OO);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===ju.preToolUse||e===ju.postToolUse||e===ju.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 oF(e){if("object"!=typeof e||null===e||!("code"in e))return!1;const t=e.code;return"ENOENT"===t||"ENOTDIR"===t}class sF{async readFile(e){try{return await go.readFile(e,"utf-8")}catch(e){if("ENOENT"===e?.code)return;throw e}}async exists(e){try{return await go.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,go.lstat)(e)).isSymbolicLink())return!0}catch(e){if(oF(e))return!0;throw e}return!1}(e,t)}}var iF=r("../proto/dist/generated/agent/v1/hooks_pb.js");const aF=G("hook-executor",(e=>new H(e,Q("executeHookArgs"),Y("executeHookResult"))),((e,t)=>{t.register(new A(e,te("executeHookArgs"),ee("executeHookResult")))})),cF=new Set(Object.values(ju));function lF(e){switch(e){case"completed":case"aborted":case"error":return e;default:return"error"}}function uF(e){switch(e){case"error":case"timeout":case"permission_denied":return e;default:return"error"}}function dF(e){const t=e?.toJson();return"object"!=typeof t||null===t||Array.isArray(t)?{}:t}class hF{constructor(e){this.hookExecutor=e}hasFailClosedHooksForStep(e,t){return!!function(e){return cF.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??"",...aD(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(ju.preCompact,t);return new p.S1({response:new p.w5({response:{case:"preCompact",value:new iF.$_({userMessage:n?.user_message})}})})}case"subagentStart":{const e=r.request.value,t={conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...aD(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(ju.subagentStart,t);return new p.S1({response:new p.w5({response:{case:"subagentStart",value:new iF.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??"",...aD(e),subagent_id:e.subagentId,subagent_type:e.subagentType,status:lF(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(ju.subagentStop,t);return new p.S1({response:new p.w5({response:{case:"subagentStop",value:new iF.AH({followupMessage:n?.followup_message,additionalContext:n?.additional_context})}})})}case"beforeSubmitPrompt":{const e=r.request.value,t=await this.hookExecutor.executeHookForStep(ju.beforeSubmitPrompt,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...aD(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 iF.u1({continue:t?.continue,userMessage:t?.user_message,additionalContext:t?.additional_context})}})})}case"afterAgentResponse":{const e=r.request.value;return await this.hookExecutor.executeHookForStep(ju.afterAgentResponse,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...aD(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 iF.FW}})})}case"afterAgentThought":{const e=r.request.value;return await this.hookExecutor.executeHookForStep(ju.afterAgentThought,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...aD(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 iF.H}})})}case"stop":{const e=r.request.value,t=await this.hookExecutor.executeHookForStep(ju.stop,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...aD(e),status:lF(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 iF.rT({followupMessage:t?.followup_message})}})})}case"preToolUse":{if(!MO(e))return this.skipToolUseStep();const t=r.request.value,n=dF(t.toolInput),o={conversation_id:t.conversationId??"",generation_id:t.generationId??"",model:t.model??"",...aD(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(ju.preToolUse,o);return new p.S1({response:new p.w5({response:{case:"preToolUse",value:new iF.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(!MO(e))return this.skipToolUseStep();const t=r.request.value,n=dF(t.toolInput),o={conversation_id:t.conversationId??"",generation_id:t.generationId??"",model:t.model??"",...aD(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(ju.postToolUse,o);return new p.S1({response:new p.w5({response:{case:"postToolUse",value:new iF.uB({additionalContext:s?.additional_context})}})})}case"postToolUseFailure":{if(!MO(e))return this.skipToolUseStep();const t=r.request.value,n=dF(t.toolInput),o={conversation_id:t.conversationId??"",generation_id:t.generationId??"",model:t.model??"",...aD(t),...t.parentToolCallId?{parent_tool_call_id:t.parentToolCallId}:{},tool_name:t.toolName,tool_input:n,error_message:t.errorMessage,failure_type:uF(t.failureType),duration:Number(t.durationMs),tool_use_id:t.toolUseId,is_interrupt:t.isInterrupt},s=await this.hookExecutor.executeHookForStep(ju.postToolUseFailure,o);return new p.S1({response:new p.w5({response:{case:"postToolUseFailure",value:new iF.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 pF{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 fF(e){return!!e&&e.type!==Zo.vc.INSECURE_NONE&&e.type!==Zo.vc.UNSPECIFIED}async function mF({hookExecutor:e,baseHookRequest:t,toolUseId:r,command:n,cwd:o,sandbox:s}){const i=await e.executeHookForStep(ju.beforeShellExecution,{...t,command:n,cwd:o,sandbox:s,tool_use_id:r});if("deny"===i?.permission){const e=VO("Command execution",i.user_message);throw new qO(e)}if("ask"===i?.permission)return a=i.user_message,new fe.In({kind:fe.b.FORCE_PROMPT,reason:a});var a}const gF={toolName:vO,getToolCallId:eF,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 xo.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=fF(r.sandboxPolicy);DO(t,ju.beforeShellExecution)&&ko(r,await mF({hookExecutor:o,baseHookRequest:n,toolUseId:s,command:r.command,cwd:i,sandbox:a}))}};class wF{constructor(e,t,r){this.wrappedExecutor=tF(e,t,r,gF)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const yF={toolName:"WriteShellStdin",createToolInput:e=>({shell_id:e.shellId,chars_length:e.chars.length}),createRejectedResult:(e,t)=>new xo.nt({result:{case:"error",value:new xo.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 vF{constructor(e,t,r){this.wrappedExecutor=tF(e,t,r,yF)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const bF={toolName:"ComputerUse",getToolCallId:eF,createToolInput:e=>({actions_count:e.actions.length}),createRejectedResult:(e,t)=>new Pm.ks({result:{case:"error",value:new Pm.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 SF{constructor(e,t,r){this.wrappedExecutor=tF(e,t,r,bF)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const kF={toolName:gO,getToolCallId:eF,createToolInput:e=>({file_path:e.path}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new Tg.Pi({result:{case:"rejected",value:new Tg.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 _F{constructor(e,t,r){this.wrappedExecutor=tF(e,t,r,kF)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const CF={toolName:bO,getToolCallId:eF,createToolInput:e=>({file_path:e.path}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new qR.Ek({result:{case:"rejected",value:new qR.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 EF{constructor(e,t,r){this.wrappedExecutor=tF(e,t,r,CF)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const xF={toolName:"Fetch",getToolCallId:eF,createToolInput:e=>({url:e.url}),applyUpdatedInput:(e,t)=>{"string"==typeof t.url&&(e.url=t.url)},createRejectedResult:(e,t)=>new Ng.uN({result:{case:"error",value:new Ng.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 PF{constructor(e,t,r){this.wrappedExecutor=tF(e,t,r,xF)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const IF={toolName:yO,getToolCallId:eF,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 gw.Ud({result:{case:"error",value:new gw.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 RF{constructor(e,t,r){this.wrappedExecutor=tF(e,t,r,IF)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const TF={toolName:wO,getToolCallId:eF,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 Hk.fv({result:{case:"rejected",value:new Hk.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 AF{constructor(e,t,r){this.wrappedExecutor=tF(e,t,r,TF)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const $F=(0,d.h)("hooks-exec:mcp");function MF(e){return!!(null===e||"string"==typeof e||"boolean"==typeof e||"number"==typeof e&&Number.isFinite(e))||(Array.isArray(e)?e.every(MF):"object"==typeof e&&Object.values(e).every((e=>void 0!==e&&MF(e))))}function DF(e,t,r,n){try{return BO({hookEventName:r,additionalContext:n})}catch(n){if(n instanceof jO)return $F.warn(e,`${r} additional_context exceeded max size; dropping carrier`,{toolName:t,hookEventName:r,actualLength:n.actualLength,maxLength:n.maxLength}),[];throw n}}class OF{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(ju.preToolUse)||!0===this.hooksConfigLease?.hasHookForStep(ju.beforeMCPExecution)))return new Qa.iz({result:{case:"error",value:new Qa.Nh({error:`"${fR}" 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=nF(e,this.hookExecutor),o=this.baseHookRequestExtractor(e),s=(0,ho.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(ju.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{LO(i,BO({hookEventName:ju.preToolUse,additionalContext:r.additional_context}))}catch(t){if(!(t instanceof jO))throw t;$F.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 Qa.iz({result:{case:"permissionDenied",value:new Qa.HQ({error:VO("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(!MF(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){$F.warn(e,"Failed to merge updated_input for MCP",{error:t instanceof Error?t.message:String(t)})}LO(i,BO({hookEventName:ju.preToolUse,additionalContext:r?.additional_context}))}catch(t){const r=n.hasFailClosedHooksForStep?.(ju.preToolUse,c)??!1,l=t instanceof jO;if(r){const r=cO(`${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 Qa.iz({result:{case:"permissionDenied",value:new Qa.HQ({error:VO("MCP tool execution",r),isReadonly:!1})}})}$F.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=DO(e,ju.beforeMCPExecution)?await n.executeHookForStep(ju.beforeMCPExecution,f):void 0;if("deny"===m?.permission){const t=VO("MCP tool execution",m.user_message);return await this.firePostToolUseFailureAsync(e,n,o,c,a,t,"permission_denied",0,s,!1,i),new Qa.iz({result:{case:"permissionDenied",value:new Qa.HQ({error:t,isReadonly:!1})}})}const g=AO.performance.now();try{const l=await this.innerExecutor.execute(e,t,r),u=XO(AO.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){$F.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(ju.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 Qa._Z({content:{case:"text",value:new Qa.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 Qa._Z({content:{case:"text",value:new Qa.zN({text:String(e.text)})}})):t.push(new Qa._Z({content:{case:"text",value:new Qa.zN({text:JSON.stringify(e)})}}))}else t.push(new Qa._Z({content:{case:"text",value:new Qa.zN({text:JSON.stringify(e)})}}));const r="object"==typeof e&&null!==e&&"isError"in e&&Boolean(e.isError);return new Qa.iz({result:{case:"success",value:new Qa.QW({content:t,isError:r})}})}catch(t){return $F.warn(e,"Failed to process updated_mcp_tool_output",{error:t instanceof Error?t.message:String(t)}),l}return l}catch(t){const r=XO(AO.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(ju.postToolUse,{...r,tool_name:n,tool_input:o,tool_output:s,duration:i,tool_use_id:a});return LO(c,DF(e,n,ju.postToolUse,l?.additional_context)),l}catch(t){return void $F.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(ju.postToolUseFailure,{...r,tool_name:n,tool_input:o,error_message:s,failure_type:i,duration:a,tool_use_id:c,is_interrupt:l});LO(u,DF(e,n,ju.postToolUseFailure,d?.additional_context))}catch(t){$F.warn(e,"postToolUseFailure hook error in MCP executor",{error:t instanceof Error?t.message:String(t)})}}}const FF={toolName:"ListMcpResources",createToolInput:e=>({server:e.server}),applyUpdatedInput:(e,t)=>{"string"==typeof t.server&&(e.server=t.server)},createRejectedResult:(e,t)=>new Qa.kP({result:{case:"error",value:new Qa.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 NF{constructor(e,t,r){this.wrappedExecutor=tF(e,t,r,FF)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const LF={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 Qa.ZD({result:{case:"error",value:new Qa.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 jF{constructor(e,t,r){this.wrappedExecutor=tF(e,t,r,LF)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const UF={toolName:fO,getToolCallId:eF,createToolInput:e=>({file_path:e.path}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new jw.sV({result:{case:"rejected",value:new jw.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?.(ju.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${GO}`}(t,e instanceof Error?e.message:String(e));throw new zO(r,e)}}((()=>o.executeHookForStep(ju.beforeReadFile,{...n,content:i,file_path:t.path,attachments:[],tool_use_id:s})),"File read");if("deny"===a?.permission){const e=VO("File read",a.user_message);throw new qO(e)}}};class BF{constructor(e,t,r){this.wrappedExecutor=new cR(tF(e,t,r,UF))}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const WF={toolName:"RecordScreen",getToolCallId:eF,createToolInput:e=>({mode:e.mode,save_as_filename:e.saveAsFilename}),createRejectedResult:(e,t)=>new NT.Tj({result:{case:"failure",value:new NT.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 HF{constructor(e,t,r){this.wrappedExecutor=tF(e,t,r,WF)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}function qF(e){return"success"===e.result.case||"failure"===e.result.case?e.result.value.stdout+e.result.value.stderr:""}const zF={toolName:vO,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:qF(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||"";DO(t,ju.beforeShellExecution)&&ko(r,await mF({hookExecutor:o,baseHookRequest:n,toolUseId:s,command:r.command,cwd:i,sandbox:fF(r.requestedSandboxPolicy)}))},runPostExecutionHooks:async e=>{const{args:t,result:r,baseHookRequest:n,hookExecutor:o,executionDurationMs:s,toolUseId:i}=e,a=qF(r);await o.executeHookForStep(ju.afterShellExecution,{...n,command:t.command,output:a,duration:s,sandbox:fF(t.requestedSandboxPolicy),tool_use_id:i})}};class GF{constructor(e,t,r){this.wrappedExecutor=tF(e,t,r,zF)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}class VF{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 KF={toolName:vO,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 VF,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=fF(r.requestedSandboxPolicy);DO(t,ju.beforeShellExecution)&&ko(r,await mF({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=fF(t.requestedSandboxPolicy);await n.executeHookForStep(ju.afterShellExecution,{...r,command:t.command,output:o.getOutput(),duration:s,sandbox:a,tool_use_id:i})}};class JF{constructor(e,t,r){this.wrappedExecutor=function(e,t,r,n){return{async*execute(o,s,i){const a=nF(o,t),{hookContext:c,helpers:l}=QO(o,s,a,r,n,i),u=n.runPreExecutionHooks?async e=>{await n.runPreExecutionHooks(e)}:void 0,d=await YO(o,s,a,c,l,n,((e,t)=>n.createRejectedEvent(e,t)),u);if("rejected"===d.type){yield d.result;for(const e of rF(n,c))yield e;return}const h=AO.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=XO(AO.performance.now()-h),r=e instanceof Error?e.message:String(e);await l.fireFailureAsync(t,r,"error");for(const e of rF(n,c))yield e;throw e}const f=XO(AO.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){JO.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 rF(n,c))yield e}}}(e,t,r,KF)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}class ZF{constructor(e,t,r){const n=new Map;this.wrappedExecutor=tF(e,t,r,function(e){return{toolName:mO,getToolCallId:eF,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 GA.v3({result:{case:"error",value:new GA.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?.(ju.afterFileEdit))return;let s,i=!1;try{(await(0,go.stat)(r.path)).size>262144?i=!0:s=await $i(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?.(ju.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,zv.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(ju.afterFileEdit,d);if(r.returnFileContentAfterWrite&&void 0!==h){const e=n.result.value.path;try{const t=await $i(e),r=Ws(t),o=Buffer.byteLength(t,"utf8");return new GA.v3({result:{case:"success",value:new GA.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 XF(e,t,r){return t===e.symbol}function QF(e,t,r){return XF(ZI,e)?new GF(t,r.hookExecutor,r.baseHookRequestExtractor):XF(re,e)?new JF(t,r.hookExecutor,r.baseHookRequestExtractor):XF(eR,e)?new ZF(t,r.hookExecutor,r.baseHookRequestExtractor):XF(Kn,e)?new OF(t,r.hookExecutor,r.baseHookRequestExtractor,r.mcpLease,r.hooksConfigLease):XF(lR,e)||XF(uR,e)?new BF(t,r.hookExecutor,r.baseHookRequestExtractor):XF(dR,e)?new AF(t,r.hookExecutor,r.baseHookRequestExtractor):XF(oR,e)?new RF(t,r.hookExecutor,r.baseHookRequestExtractor):XF(rR,e)?new PF(t,r.hookExecutor,r.baseHookRequestExtractor):XF(tR,e)?new _F(t,r.hookExecutor,r.baseHookRequestExtractor):XF(hR,e)?new EF(t,r.hookExecutor,r.baseHookRequestExtractor):XF(Jn,e)?new NF(t,r.hookExecutor,r.baseHookRequestExtractor):XF(Zn,e)?new jF(t,r.hookExecutor,r.baseHookRequestExtractor):XF(TR,e)?new wF(t,r.hookExecutor,r.baseHookRequestExtractor):XF(AR,e)?new vF(t,r.hookExecutor,r.baseHookRequestExtractor):XF(NR,e)?new SF(t,r.hookExecutor,r.baseHookRequestExtractor):XF(LR,e)?new HF(t,r.hookExecutor,r.baseHookRequestExtractor):XF(Mr,e)&&(r.hooksAdditionalContextPromise||r.hooksConfigLease)?new pF(t,r.hooksAdditionalContextPromise??Promise.resolve(void 0),r.teamHooksReadyPromise,r.hooksConfigLease):void 0}class YF{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===aF.symbol)return new hF(t)}(e,this.hookExecutor);return void 0!==t?t:function(e,t,r){const n=QF(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=QF(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=aF;yield[e,new hF(this.hookExecutor)]}}const eN={cursor_version:process.env.AGENT_CLI_STATIC_VERSION??"1.0.0",user_email:null};function tN(e=process.cwd()){let t=e;return{getCwd:async()=>t,clone:e=>tN(e??t),async*execute(e,r,n={}){const o=n.workingDirectory??t;t=o;const s=function(e){return"win32"===process.platform?{executable:(0,Po.oG)(),args:[...GM,"-Command",e]}:{executable:process.env.SHELL||"/bin/sh",args:["-lc",e]}}(r),i=(0,yl.spawn)(s.executable,[...s.args],{cwd:o,env:{...process.env,...n.env??{}},signal:n.signal,stdio:[!0===n.pipeStdin?"pipe":"ignore","pipe","pipe"]}),a=[];let c,l,u=!1;const d=()=>{c?.(),c=void 0},h=e=>{a.push(e),d()};for(i.on("spawn",(()=>{!0===n.pipeStdin&&h({type:"stdin_ready",stdin:i.stdin??void 0})})),i.stdout?.setEncoding("utf8"),i.stdout?.on("data",(e=>{h({type:"stdout",data:String(e)})})),i.stderr?.setEncoding("utf8"),i.stderr?.on("data",(e=>{h({type:"stderr",data:String(e)})})),i.on("error",(e=>{l=e,u=!0,d()})),i.on("close",(e=>{h({type:"exit",code:e}),u=!0}));!u||a.length>0;)0!==a.length?yield a.shift():await new Promise((e=>{c=e}));if(void 0!==l)throw l}}}function rN(e,t,...r){for(const n of r){const r=t(e[n]);if(void 0!==r)return r}}function nN(e){return"string"==typeof e&&e.length>0?e:void 0}function oN(e){return"object"==typeof e&&null!==e&&"string"==typeof e.id&&"string"==typeof e.value}function sN(e){if(Array.isArray(e)&&e.every(oN))return e.map((e=>({id:e.id,value:e.value})))}class iN{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 aN(e,t={}){const r=await new pO(new sF,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?uO():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 TO(r),i=function(e){return e.projectRoot??e.workingDirectory??e.workspaceRoots[0]??process.cwd()}(e),a=function(e){return Object.freeze({...eN,...e.globalContext??{}})}(t);return{projectDir:e.projectRoot,workspacePath:i,hooksConfig:r,hooksConfigLease:n,globalContext:a,createSessionRuntime(){const e=new RO(r,i,a,(t.createTerminalExecutor??tN)(),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 cN(e={}){return{createHooksRuntime:t=>aN(t.workspaceState,e)}}var lN=r("../proto/dist/generated/aiserver/v1/dashboard_connect.js");async function uN(e){(function(e){return"object"==typeof e&&null!==e&&"dispose"in e&&"function"==typeof e.dispose})(e)&&await e.dispose()}function dN(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 fw,l=(0,o.homedir)(),u=uf(l).dirPath;let d,h=!0;return{async prepareLocalExtensibility(){h=i&&await async function(e){if(!e)return!1;const t=(0,be.createClient)(lN.I,e);return"synced"===(await async function(e,t){try{const r=await t.getManagedSkills()??[],n=await N$(e,{managedSkills:[...r]});return{status:"synced",managedSkillsCount:r.length,syncResult:n}}catch(t){return j$.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 G$.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:yN(),getAgentSkills:async e=>[]};const p=(0,b.q6)(),f=e.loadNestedRules??!0,m=n?i.map((e=>new im(p,c,e,f,t,void 0))):[],g=function(e,t){const r=hN(t);return{getAllCursorRules:async t=>pN(await e.getAllCursorRules(t),r),reload(t){e.reload(t)},onDidChangeRules:t=>e.onDidChangeRules(t),dispose(){e.dispose()}}}(0===m.length?yN():1===m.length?m[0]:new sm(m,(()=>If)),{allowedRoots:n?i:[],excludedRoots:[]}),w=function(e,t){const r=hN(t);return{getAllCursorRules:async t=>pN(await e.getAllCursorRules(t),r),getAllAgentSkills:async t=>pN(await e.getAllAgentSkills(t),r),reload(t){e.reload(t)},onDidChangeRules:t=>e.onDidChangeRules(t),onDidChangeSkills:t=>e.onDidChangeSkills(t),dispose(){e.dispose()}}}(new cm(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 vm(e,t))):[],v=0===y.length?new pm:1===y.length?y[0]:new Sm(y),S=NM(o.services.pluginBootstrapOutputs),k=S&&a?new um(p,(()=>({importThirdPartyPlugins:r})),void 0,S.pluginsService):void 0,_=S&&a?new km((()=>({importThirdPartyPlugins:r})),S.pluginsService):void 0,C=new sm([g,w,...k?[k]:[]],(()=>If)),E=new y$([w,...k?[k]:[]],(()=>[]),(()=>({workspacePaths:n?i:[],userHomeDirectory:l,agentStoreSkillsDirs:[]}))),x=new Sm([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 uN(e)}catch(e){t??=e}if(void 0!==t)throw t}(e)}}}function hN(e){const t=Promise.all(e.allowedRoots.map(gN)),r=Promise.all(e.excludedRoots.map(gN));return async e=>{const[n,o,s]=await Promise.all([wN(e.fullPath),t,r]);return void 0!==n&&!s.some((e=>fN(n,e)))&&o.some((e=>fN(n,e)))}}async function pN(e,t){const r=await Promise.all(e.map(t));return e.filter(((e,t)=>r[t]))}function fN(e,t){if(e===t)return!0;const r=`${t}/`;return e.startsWith(r)}function mN(e){return e.replace(/\\/g,"/").replace(/\/+$/,"")}async function gN(e){try{return mN(await(0,go.realpath)(e))}catch{return mN(e)}}async function wN(e){try{return mN(await(0,go.realpath)(e))}catch{return}}function yN(){return{getAllCursorRules:async()=>[],reload(){},onDidChangeRules:()=>()=>{},dispose(){}}}function vN(e,t){const r=e.releaseTag??t;if(e.releaseRepo&&e.releaseAsset&&r)return{kind:"release",releaseRepo:e.releaseRepo,releaseAsset:e.releaseAsset,releaseTag:r}}function bN(){const e=["-c","credential.interactive=false","-c","core.fsmonitor=false"];return"win32"===process.platform&&e.push("-c","core.longpaths=true"),e}function SN(e){return"function"==typeof e?e():e}async function kN(e,t){const r=function(e){const t={...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:void 0,VSCODE_GIT_ASKPASS_NODE:void 0,VSCODE_GIT_ASKPASS_MAIN:void 0,VSCODE_GIT_ASKPASS_EXTRA_ARGS:void 0,GCM_INTERACTIVE:"Never"};if(t.GIT_CONFIG_NOSYSTEM=void 0,!0===e?.sshBatchMode){const e=process.env.GIT_SSH_COMMAND?.trim()||"ssh";t.GIT_SSH_COMMAND=`${e} -oBatchMode=yes`}if(void 0!==e?.extraGitConfig){const r=Object.entries(e.extraGitConfig).flatMap((([e,t])=>Array.isArray(t)?t.map((t=>[e,t])):[[e,t]]));t.GIT_CONFIG_COUNT=String(r.length);for(const[e,[n,o]]of r.entries())t[`GIT_CONFIG_KEY_${e}`]=n,t[`GIT_CONFIG_VALUE_${e}`]=o}return{cwd:e?.cwd,env:t}}({cwd:t?.cwd,sshBatchMode:t?.sshBatchMode,extraGitConfig:t?.extraGitConfig});return Qg("git",[...bN(),...e],{...r,...void 0!==t?.timeoutMs&&{timeout:t.timeoutMs,killSignal:"SIGTERM"}})}const _N=/^[0-9a-f]{7,40}$/i,CN=/^[0-9a-f]{40}$/i;function EN(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 xN(e,t,r){const n=t.trim();if(CN.test(n))return{fullSha:n.toLowerCase()};if(_N.test(n)){try{const t=await async function(e,t,r){const{stdout:n}=await kN(["ls-remote",e,`refs/heads/${t}`,`refs/tags/${t}`,`refs/tags/${t}^{}`],{sshBatchMode:r?.sshBatchMode,extraGitConfig:r?.extraGitConfig,timeoutMs:r?.timeoutMs});return EN(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 kN(["ls-remote","--symref",e,"HEAD"],{sshBatchMode:r?.sshBatchMode,extraGitConfig:r?.extraGitConfig,timeoutMs:r?.timeoutMs}),n=EN(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 kN(["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=EN(o);if(!s)throw new Error(`git ls-remote did not return a resolvable commit for ref "${n}" (${e})`);return{fullSha:s.toLowerCase()}}const PN=Td.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 IN;function RN(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 TN(e){const t=[];for(const r of e){const e=RN(r);if(null===e)return"all";t.push(e)}return t}async function AN(e,t){const r="all"===e?"all":TN(e),n=t&&"all"!==r&&await(process.env.CURSOR_DISABLE_SPARSE_PLUGIN_CLONES?Promise.resolve(!1):(IN??=(async()=>{try{const{stdout:e}=await kN(["--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}})(),IN));return{materialize:r,sparse:n,sparseDirs:n?(o=r,[...new Set([...PN,...o])]):[]};var o}function $N(e){return e.toLowerCase().includes("filtering not recognized by server")}async function MN(e,t,r){await kN(["sparse-checkout","set","--cone","--",...t],{...r,cwd:e})}async function DN(e){try{await(0,go.access)((0,s.join)(e,".git","info","sparse-checkout"))}catch{return!1}try{const{stdout:t}=await kN(["config","--bool","--get","core.sparseCheckout"],{cwd:e});return"true"===t.trim()}catch{return!1}}async function ON(e,t,r){if("all"!==t&&0===t.length)return;if(!await DN(e))return;const n={...r,cwd:e,sshBatchMode:!0};if("all"===t)return void await kN(["sparse-checkout","disable"],n);const o=TN(t);"all"!==o?await kN(["sparse-checkout","add","--",...o],n):await kN(["sparse-checkout","disable"],n)}(0,gs.J)((function(){IN=void 0}));const FN=/\.git$/i,NN=new Set(["account","dashboard"]);function LN(e){return e.replace(FN,"")}function jN(e){let t;try{t=decodeURIComponent(e)}catch{return}return t.length>0&&!t.includes("/")?t:void 0}function UN(e){const t=e.toLowerCase();return"github.com"===t||t.endsWith(".github.com")}function BN(e){return e.toLowerCase().split(".").includes("gitlab")}function WN(e){const t=e.toLowerCase();return"bitbucket.org"===t||"www.bitbucket.org"===t}function HN(e){const t=e.toLowerCase();return BN(e)?"GitLab":t.includes("bitbucket")?"Bitbucket":t.includes("gitea")||t.includes("codeberg")?"Gitea/Codeberg":t.includes("azure")&&t.includes("dev")?"Azure DevOps":null}function qN(e){return UN(e)?"github":BN(e)?"gitlab":WN(e)?"bitbucket":function(e){const t=e.toLowerCase();return"dev.azure.com"===t||"www.dev.azure.com"===t}(e)?"azure_devops":"generic"}function zN(e){let t;try{const r=e.startsWith("git@")?`ssh://${e.replace(":","/")}`:e;t=new URL(r.includes("://")?r:`https://${r}`)}catch{return null}const r=t.hostname;let n=t.pathname.split("/").filter(Boolean);ba(r)&&"git"===n[0]?.toLowerCase()&&(n=n.slice(1));const o=n[0];void 0!==o&&n.length>=3&&"scm"===o.toLowerCase()&&(n=n.slice(1));const s=function(e){const t=e[0],r=e[1];if(!t||!r)return;const n=LN(r);return n?{owner:t,repo:n,hasSubpath:e.length>2}:void 0}(n);return void 0===s?null:{provider:qN(r),owner:s.owner,repo:s.repo,host:r}}function GN(e){const t=VN(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 VN(e){try{const t=e.startsWith("git@")?`ssh://${e.replace(":","/")}`:e;return new URL(t.includes("://")?t:`https://${t}`)}catch{return null}}function KN(e){const t=e.trim();if(""===t)return{error:"URL cannot be empty"};const r=zN(t);if(null===r)return{error:"Invalid URL format. Expected: github.com/owner/repo or gitlab.com/namespace/repo"};if(BN(r.host)){const e=VN(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=LN(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=VN(e.trim());if(null!==t&&WN(t.hostname))return function(e){const t=e[0],r=e[1];if(void 0===t||void 0===r)return;const n=jN(t),o=jN(r);if(void 0===n||void 0===o||NN.has(n.toLowerCase()))return;const s=LN(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=VN(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=LN(n);if(!o)return;const s=2===t?e[1]:o;return s?{organization:r,project:s,repo:o,hasSubpath:e.length>t+2}:void 0}(e.pathname.split("/").filter(Boolean));if(null===e||void 0===n)return{error:"Invalid Azure DevOps repository URL format. Expected: https://dev.azure.com/{organization}/{project}/_git/{repo}"};const o=r.host.replace(/^www\./i,"");return{url:`https://${o}/${n.organization}/${n.project}/_git/${n.repo}`,owner:n.organization,repo:n.repo,host:o,provider:"azure_devops",project:n.project}}if(function(e){switch(e.provider){case"github":return!0;case"generic":return!ba(e.host)&&null===HN(e.host);case"gitlab":case"bitbucket":case"azure_devops":return!1;default:return e.provider,!1}}(r)){const e=ZN(r.host.replace(/^www\./i,""));return{url:`https://${e}/${GN(t)?"scm/":""}${r.owner}/${r.repo}`,owner:r.owner,repo:r.repo,host:e,provider:"github"}}const n=HN(r.host);return{error:"Only GitHub, GitLab, Bitbucket, and Azure DevOps URLs are currently supported."+(null!==n?` ${n} is not supported yet.`:"")}}function JN(e){const t=KN(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 ZN(e){return UN(e)?"github.com":e}function XN(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 QN(e){return/[\n\r:#[\]{}&*!|>'"%@`]/.test(e)||e.startsWith(" ")||e.endsWith(" ")?`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:e}const YN=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 eL(e){const t=Jh(e).replace(/[. ]+$/g,"");return""===t||"."===t||".."===t?"_":YN.has(t.toLowerCase())?`_${t}`:t}const tL=18e5,rL=6e5,nL={recursive:!0,force:!0,maxRetries:3},oL=["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"],sL=["enotempty: directory not empty, rename","/_staging/"],iL=["upload-pack: not our ref","server does not allow request for unadvertised object"];function aL(e){const t=String(e).toLowerCase().replaceAll("\\","/");return oL.some((e=>t.includes(e)))?"user_git_access":sL.every((e=>t.includes(e)))?"local_cache_race":iL.some((e=>t.includes(e)))?"stale_pinned_ref":"infrastructure"}function cL(e){return"object"==typeof e&&null!==e&&(!0===e.killed||cL(e.cause))}function lL(e){return cL(e)?"killed_by_budget":aL(e)}function uL(e){const t=KN(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=zN(e);if(null===r)throw new Error(`Invalid git URL: ${e}`);return{host:ZN(r.host.replace(/^www\./i,"")).toLowerCase(),pathSegments:[r.owner.toLowerCase(),r.repo.toLowerCase()]}}const dL=new Map;class hL{constructor(e,t){this.cacheRoot=e,this.options=t,this.manifestCache=new Map}get sparsePluginClones(){return this.options?.sparsePluginClones??!1}remoteTimeoutMs(){return this.sparsePluginClones?tL:void 0}localTimeoutMs(){return this.sparsePluginClones?rL:void 0}lsRemoteTimeoutMs(){return this.sparsePluginClones?3e4:void 0}async cloneResolvedRef(e,t,r,n){const o={cwd:e,sshBatchMode:n?.sshBatchMode,extraGitConfig:{...SN(this.options?.extraGitConfig),"safe.directory":e}},{sparse:s,sparseDirs:i}=await AN(n?.materialize??"all",this.sparsePluginClones);await kN(["init"],{...o,timeoutMs:this.localTimeoutMs()}),s&&await MN(e,i,{sshBatchMode:n?.sshBatchMode,extraGitConfig:SN(this.options?.extraGitConfig),timeoutMs:this.localTimeoutMs()});const{stderr:a}=await kN(["fetch","--depth","1",...s?["--filter=blob:none"]:[],t,r],{...o,timeoutMs:this.remoteTimeoutMs()});return await kN(["checkout","FETCH_HEAD"],{...o,timeoutMs:this.remoteTimeoutMs()}),{strategy:s?"sparse":"full",filterIgnoredByServer:s&&$N(a??"")}}async createStagingDir(){const e=(0,s.join)(this.cacheRoot,"_staging",(0,ho.randomUUID)());return await(0,go.mkdir)(e,{recursive:!0}),e}async moveToCanonicalDir(e,t){return await(0,go.mkdir)((0,s.dirname)(t),{recursive:!0}),await(0,go.rm)(t,nL),await(0,go.rename)(e,t),t}async cleanStaleStagingDirs(){const e=(0,s.join)(this.cacheRoot,"_staging");try{const t=await(0,go.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,go.stat)(n);r-o.mtimeMs>hL.STALE_STAGING_THRESHOLD_MS&&await(0,go.rm)(n,nL)}catch{}})))}catch{}}getLegacyCloneDir(e,t){return(0,s.join)(this.cacheRoot,eL(e),eL(t))}getCanonicalCloneDir(e,t){const{host:r,pathSegments:n}=uL(e);return(0,s.join)(this.cacheRoot,eL(r),...n.map(eL),eL(t))}getCanonicalRepoRootDir(e){const{host:t,pathSegments:r}=uL(e);return(0,s.join)(this.cacheRoot,eL(t),...r.map(eL))}async pruneSiblingCloneDirs(e,t,r){const n=this.getCanonicalRepoRootDir(e),o=eL(t);try{const e=await(0,go.readdir)(n,{withFileTypes:!0});await Promise.all(e.filter((e=>e.isDirectory()&&e.name!==o)).map((e=>(0,go.rm)((0,s.join)(n,e.name),nL))))}catch{}if(void 0!==r)try{await(0,go.rm)(r,nL)}catch{}}async ensureCloned(e,t,r,n=mh,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=mh){const n=this.serializedOnRepo((0,s.dirname)(e),(async()=>{const n=performance.now();try{await ON(e,t,{extraGitConfig:SN(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:lL(o)}),r.increment("marketplace_cache_manager.ensure_materialized.error",1,{error_category:lL(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=(dL.get(r)??Promise.resolve()).catch((()=>{})).then(t);dL.set(r,n);try{return await n}finally{dL.get(r)===n&&dL.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:JN(t);if(null!==a)try{i=(await xN(a,s,{sshBatchMode:!0,extraGitConfig:SN(this.options?.extraGitConfig),timeoutMs:this.lsRemoteTimeoutMs()})).fullSha}catch(e){if(this.sparsePluginClones&&cL(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:aL(e)}),a=null,i=(await xN(t,s,{extraGitConfig:SN(this.options?.extraGitConfig),timeoutMs:this.lsRemoteTimeoutMs()})).fullSha}else i=(await xN(t,s,{extraGitConfig:SN(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 DN(c);return e&&await ON(c,o,{extraGitConfig:SN(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,go.utimes)(l,e,e).catch((()=>{}))}),hL.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&&cL(e))throw e;i.log("debug","Falling back to HTTPS clone due to SSH clone failure",{gitUrl:t,ref:s,error:String(e),errorCategory:lL(e)}),await(0,go.rm)(l,nL),await(0,go.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=lL(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,go.rm)(l,nL)}catch{}}}async isCloneComplete(e){try{if(!(await(0,go.stat)(e)).isDirectory())return!1;const t=await(0,go.readdir)(e);if(!t.includes(".git"))return!1;if(t.length>1)return!0;try{return(await(0,go.stat)((0,s.join)(e,".git","info","sparse-checkout"))).isFile()}catch{return!1}}catch{return!1}}getPluginDir(e,t){return fp(e,t)}async copyPluginToDir(e,t){await(0,go.mkdir)(t,{recursive:!0}),await(0,go.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 Td){const n=(0,s.join)(e,r);let o;try{o=await(0,go.readFile)(n,"utf-8")}catch{continue}const i=sh(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=ah(n.source,r.metadata?.pluginRoot);return o&&ch(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=ah(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":ch(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):[]}}hL.STALE_STAGING_THRESHOLD_MS=3e5,hL.STAGING_HEARTBEAT_INTERVAL_MS=6e4;const pL=(0,Ls.debuglog)("cursor-plugins");function fL(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function mL(e){return fL(e)?e:void 0}function gL(e){const t=e.name?.trim();return void 0!==t&&t.length>0?t:e.pluginId}function wL(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 yL(e,t){const r=t?.distributionGitUrl?.trim();return r?t?.gitUrl&&!RL(e,t.gitUrl)?e:r:e}function vL(e){return e?.distributionGitUrl?.trim()||e?.gitUrl}function bL(e,t){if(e.pinnedGitRef)return e.pinnedGitRef;if(e.plugin?.gitRef)return e.plugin.gitRef;const r=wL(e.plugin,t),n=e.plugin?.gitUrl,o=r?.gitUrl;return n&&o&&n!==o||!r?.gitRef?"main":r.gitRef}const SL="backend-git://";function kL(e,t,r){const n=r?`#${encodeURIComponent(r)}`:"";return`${SL}${encodeURIComponent(e)}@${encodeURIComponent(t)}${n}`}function _L(e){if(!e.startsWith(SL))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 CL="backend-release://";function EL(e){const t=e.tag?`@${encodeURIComponent(e.tag)}`:"";return`${CL}${encodeURIComponent(e.repo)}#${encodeURIComponent(e.asset)}${t}`}function xL(e){if(!e.startsWith(CL))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 PL=/^[0-9a-f]{7,40}$/i;function IL(e){let t;try{t=uL(e)}catch{return null}return`${t.host}\0${t.pathSegments.join("\0")}`}function RL(e,t){if(e.trim()===t.trim())return!0;const r=IL(e),n=IL(t);return null!==r&&r===n}const TL=104857600;async function AL(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(!(fL(d=u)&&Array.isArray(d.assets)&&d.assets.every((e=>fL(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>TL)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||!$L(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||!$L(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>TL)throw new Error(`Release asset "${r}" actual download size exceeds maximum of 104857600 bytes (actual: ${g.byteLength})`);if(e.expectedSha256){const t=(0,ho.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,go.mkdir)(n,{recursive:!0});const u=await(0,go.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,go.writeFile)(d,c),await(0,go.mkdir)(h,{recursive:!0});let e=0,t=0;await Zh.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,go.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,go.readdir)(e)).some((e=>Rd.includes(e)))&&(a=e)}const p=await(0,go.readdir)(a);await Promise.all(p.map((e=>(0,go.cp)((0,s.join)(a,e),(0,s.join)(n,e),{recursive:!0,verbatimSymlinks:!0}))))}finally{await(0,go.rm)(u,{recursive:!0,force:!0}).catch((()=>{}))}}function $L(e,t){return!(e!==t&&!e.endsWith(".githubusercontent.com"))||("github.com"===t?"github.com"===e:e.endsWith(`.${t}`))}class ML{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??mh,this.extraGitConfig=s.extraGitConfig,this.awaitAuthReady=s.awaitAuthReady,this.githubToken=s.githubToken,this.sparsePluginClones=s.sparsePluginClones??!1,this.marketplaceCache=s.marketplaceCacheRoot?new hL(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=SN(this.extraGitConfig),s=this.sparsePluginClones?3e4:void 0,i=e.startsWith("git@")||e.startsWith("ssh://")?null:JN(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 xN(e,t,n):await xN(e,t)).fullSha};if(null!==i)try{n=await c(i,!0)}catch(t){if(this.sparsePluginClones&&cL(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=wL(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=gL({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,ho.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:mL(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=yL(c,r),d=bL(e,o),h=vN(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?EL({repo:h.releaseRepo,asset:h.releaseAsset,tag:h.releaseTag}):kL(g,d,t.gitPath??void 0);const w=vL(r);let y=w,v=r?.gitUrl,b=p;if(r?.gitUrl&&w){const e=RL(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:kL(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:mL(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=_L(e.downloadUrl);return!(!r||!RL(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,go.mkdir)(t,{recursive:!0});const i={};if(o.rules&&o.rules.length>0){const e=(0,s.join)(t,"rules");await(0,go.mkdir)(e,{recursive:!0});const r=[];for(const t of o.rules){if(!t.content)continue;if(!1===t.isActive)continue;const n=`${Jh(t.name)}.md`,o=[];o.push(`description: ${QN(t.name)}`),t.globs&&t.globs.length>0&&o.push(`globs: ${QN(t.globs.join(", "))}`),o.push(`alwaysApply: ${!0===t.isRequired}`);const i=`---\n${o.join("\n")}\n---\n\n`;await(0,go.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,go.mkdir)(e,{recursive:!0});const r=[];for(const t of o.commands){if(!t.content)continue;if(!1===t.isActive)continue;const n=`${Jh(t.name)}.md`,o=t.description?`---\ndescription: ${QN(t.description)}\n---\n\n`:"";await(0,go.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,go.mkdir)(e,{recursive:!0});const r={};for(const e of o.hooks){const t=e.hookStep;t&&!1!==e.isActive&&XN(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,go.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,go.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,go.mkdir)(c,{recursive:!0}),await(0,go.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,go.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===xL(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)&&cL(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=mh,n,i){const a=i?.sparsePluginClones??!1,c=a?tL:void 0,l=xL(e.downloadUrl);if(l){if(e.gitPath){const r=await(0,go.mkdtemp)((0,s.join)((0,o.tmpdir)(),"release-plugin-"));try{await AL(l.repo,l.asset,l.tag,r,i?.expectedReleaseAssetSha256,i?.githubToken);const n=fp(r,e.gitPath);await(0,go.mkdir)(t,{recursive:!0}),await(0,go.cp)(n,t,{recursive:!0,verbatimSymlinks:!0})}finally{await(0,go.rm)(r,{recursive:!0,force:!0}).catch((()=>{}))}}else await AL(l.repo,l.asset,l.tag,t,i?.expectedReleaseAssetSha256,i?.githubToken);return}const u=_L(e.downloadUrl);if(!u)throw new Error(`Invalid download URL format for plugin ${e.pluginId}: ${e.downloadUrl}`);const d=await(0,go.mkdtemp)((0,s.join)((0,o.tmpdir)(),"backend-plugin-"));try{let o;if(await async function(e,t,r,n=mh,o,s="all",i=!1){const a=performance.now(),c=PL.test(t),l="HEAD"===t.toUpperCase(),u={...o,"safe.directory":r},d=i?tL:void 0,h=i?rL:void 0,{sparse:p,sparseDirs:f}=await AN(s,i),m=p?["--filter=blob:none","--sparse"]:[],g=!!p||void 0,w=async e=>{p&&await MN(r,f,{extraGitConfig:u,timeoutMs:e,sshBatchMode:!0})},y=async(e,n)=>{let o;return l?(({stderr:o}=await kN(["clone","--depth","1",...m,e,r],{extraGitConfig:u,timeoutMs:d,sshBatchMode:n})),await w(d)):c?(await kN(["init"],{cwd:r,extraGitConfig:u,timeoutMs:h}),await kN(["remote","add","origin",e],{cwd:r,extraGitConfig:u,timeoutMs:h}),await w(h),({stderr:o}=await kN(["fetch","--depth","1",...p?["--filter=blob:none"]:[],"origin",t],{cwd:r,extraGitConfig:u,timeoutMs:d,sshBatchMode:n})),await kN(["checkout","FETCH_HEAD"],{cwd:r,extraGitConfig:u,timeoutMs:d,sshBatchMode:n})):(({stderr:o}=await kN(["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:JN(e);let b;if(null!==v)try{b=await y(v,!0)}catch(t){if(i&&cL(t))throw t;await(0,go.rm)(r,{recursive:!0,force:!0}),await(0,go.mkdir)(r,{recursive:!0}),b=await y(e,g)}else b=await y(e,g);p&&$N(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);pL("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?TN([u.gitPath]):[],a),u.gitPath)o=fp(d,u.gitPath);else{const t=await async function(e,t){for(const r of Td){const n=(0,s.join)(e,r);let o;try{o=await(0,go.readFile)(n,"utf-8")}catch{continue}const i=sh(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=ah(c.source,a.metadata?.pluginRoot);return l&&ch(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 ON(d,TN([t.gitPath]),{extraGitConfig:n,timeoutMs:c}),o=fp(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 ON(d,"all",{extraGitConfig:n,timeoutMs:c}),o=d}}await(0,go.mkdir)(t,{recursive:!0}),await(0,go.cp)(o,t,{recursive:!0,verbatimSymlinks:!0})}finally{await(0,go.rm)(d,{recursive:!0,force:!0}).catch((()=>{}))}}(e,t,this.pluginLogger,SN(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=TN(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?TN([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,TN([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 DL(e,t,r,n,o){return new ML(e,t,r,n,o)}function OL(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 FL extends Error{constructor(e){super(e),this.name="SettingsParseError"}}function NL(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function LL(e){return 65279===e.charCodeAt(0)?e.slice(1):e}async function jL(e){try{return LL(await(0,go.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 UL(e){const t=await jL(e);return void 0===t?[]:function(e){const t=function(e){const t=LL(e);if(0===t.trim().length)return{};const r=[],n=(0,lh.qg)(t,r,{allowTrailingComma:!0});if(r.length>0){const e=r.slice(0,3).map((e=>`${(0,lh._n)(e.error)} at offset ${e.offset}`)).join("; ");throw new FL(`.cursor/settings.json contains syntax errors: ${e}`)}if(!NL(n))return{};const o=n.plugins;if(void 0===o)return{};if(!NL(o))return{};const s={};for(const[e,t]of Object.entries(o))NL(t)&&(s[e]=t);return{plugins:s}}(e);return t.plugins?Object.entries(t.plugins).filter((([,e])=>!0===e.enabled)).filter((([,e])=>!e.gitUrl||OL(e.gitUrl))).map((([e,t])=>({key:e,entry:t}))):[]}(t)}function BL(e){const t=e.indexOf("/");return-1===t?{name:e}:{name:e.slice(t+1),marketplaceName:e.slice(0,t)}}function WL(e={}){const t=e.userHomeDirectory??(0,o.homedir)(),r=e.importThirdPartyPlugins??!1,n=e.pluginLogger??{log(e,t,r){switch(e){case"warn":yM.Jz.warn("[local-plugins-bootstrap]",t,r??{});break;case"error":yM.Jz.error("[local-plugins-bootstrap]",t,r??{})}},increment(){},distribution(){},captureException(e,t){yM.Jz.error("[local-plugins-bootstrap] Unexpected plugin exception:",e,t??{})}},i=HL(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 UL(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)(lN.I,e.dashboardTransport),n=DL((async()=>{try{return await r.getEffectiveUserPlugins(new G$.EwF({}))}catch{return{plugins:[]}}}),t,void 0,void 0,{allowedMarketplaceNames:["cursor-public"]}),o=e.workspacePath,i=DL((async()=>{if(void 0===o)return{plugins:[]};try{const e=await UL(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||OL(t)})).map((({key:e,entry:t})=>{const r=BL(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=BL(e.key);return new G$.vwy({name:t.name,marketplaceName:t.marketplaceName})})),t=await r.resolvePluginsByRef(new G$.WvV({refs:e}));i=t.plugins?.map((e=>({plugin:e,isEnabled:!0})))??[]}catch{}return{plugins:[...s,...i]}}catch{return{plugins:[]}}}),t,void 0,void 0,{allowedMarketplaceNames:["cursor-public"]});return[{client:n,userId:"",cacheManager:new tp(e.userHomeDirectory),pruneOldVersions:!0},{client:i,userId:"",cacheManager:new tp(e.userHomeDirectory),pruneOldVersions:!0}]}({dashboardTransport:e.dashboardTransport,workspacePath:i,userHomeDirectory:t}):void 0),h=HL(d),p=new z$(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:FM,discoveredEntries:l,loadedPlugins:f,loadFailures:p.getLoadFailures(),bootstrapFailures:m,pluginsService:p,async dispose(){}};for(const e of m)yM.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)yM.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 HL(e){return void 0!==e&&(!Array.isArray(e)||e.length>0)}class qL{async getAllCursorRules(e){return[]}reload(e){}dispose(){}onDidChangeRules(e){return()=>{}}}const zL=["projectFolder","terminalsFolder","agentSharedNotesFolder","agentConversationNotesFolder","agentTranscriptsFolder","processWorkingDirectory","artifactsFolder"];function GL(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 VL(e){const t=GL(e).replaceAll("\\","/");return/^[A-Za-z]:\/$/.test(t)?t.slice(0,-1):t}function KL(e){const t=GL(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 JL(e){const t=VL(e.value),r=e.roots.filter((e=>e.host.length>0)).sort(((e,t)=>VL(t.host).length-VL(e.host).length));for(const e of r){const r=VL(e.host);if(t===r)return KL({reportedWorkspacePath:e.reported,suffix:""});const n="/"===r?"/":`${r}/`;if(t.startsWith(n)){const n="/"===r?t:t.slice(r.length);return KL({reportedWorkspacePath:e.reported,suffix:n})}}}const ZL={powershellUtf8Console:!1,powershellUtf8ChildEnv:!1};class XL extends u${constructor(e,t){super(e),this.sessionMcpLease=t}async dispose(){try{await super.dispose()}finally{await uN(this.sessionMcpLease)}}}function QL(e){const t=new fw;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 qL,s=r.workspaceServices.subagentsService??new pm,i=r.workspaceServices.mcpLease??new gP,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 gP:void 0:void 0,l=(u=c??i,0===(d=r.options.extraMcpTools??[]).length?u:"onDidChange"in(h=u)&&"function"==typeof h.onDidChange?new Fg(u,d):new Og(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 ZL;try{const t=await e();return{powershellUtf8Console:t.powershellUtf8Console,powershellUtf8ChildEnv:t.powershellUtf8ChildEnv}}catch{return ZL}}(e.getPowershellUtf8Options),u={pendingDecisionStore:n.pendingDecisionStore,fileChangeTracker:n.fileChangeTracker,gitExecutor:t,ignoreService:e.ignoreService,grepProvider:e.grepProvider,permissionsService:n.permissionsService,workspacePaths:e.workspacePaths,diagnosticsProvider:e.diagnosticsProvider,mcpLease:l,mcpStateAccessor:e.createMcpStateAccessor?.(l),cursorRulesService:o,subagentsService:s,repositoryProvider:e.repositoryProvider,projectDir:e.projectDir,shellManager:e.shellManager,_defaultSandboxPolicy:e.defaultSandboxPolicy??{type:"insecure_none"},_defaultSandboxPolicySources:e.defaultSandboxPolicySources,getSandboxEnabled:e.getSandboxEnabled,getSandboxSupported:e.getSandboxSupported,getNetworkAllowlistInfo:e.getNetworkAllowlistInfo,getSmartModeClassifierAutoModeEnabled:e.getSmartModeClassifierAutoModeEnabled,devForceNextSmartModeClassifierBlockToken:e.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:e.getMockPromptTime,mcpFileOutputThresholdBytes:e.mcpFileOutputThresholdBytes,mcpMetaToolEnabled:e.mcpMetaToolEnabled,getAgentSkills:r.workspaceServices.getAgentSkills,powershellUtf8Console:a.powershellUtf8Console,powershellUtf8ChildEnv:a.powershellUtf8ChildEnv,...i},d=void 0===c?new u$(u):new XL(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=>JL({value:e,roots:o})??e));for(const e of zL){const t=n[e];if(void 0===t||""===t)continue;const r=JL({value:t,roots:o});n[e]="processWorkingDirectory"===e&&void 0!==s?r??GL(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 uN(c),e}}}}const YL=["cursorRulesService","getAgentSkills","subagentsService"],ej=new WeakSet;function tj(e){("object"==typeof e&&null!==e||"function"==typeof e)&&ej.add(e)}function rj(e){return("object"==typeof e&&null!==e||"function"==typeof e)&&ej.has(e)}function nj(e,t){const r=Object.keys(t).filter((e=>!YL.includes(e)));if(r.length>0)throw new Error(`Workspace service contributors may only provide ${YL.join(", ")}. Received unsupported service keys: ${r.join(", ")}.`);for(const r of YL)Object.hasOwn(t,r)&&(e[r]=t[r])}async function oj(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&&(tj(s.cursorRulesService),tj(s.subagentsService),Object.assign(n,s));for(const t of e.workspaceServicesContributors??[]){const e=await t.contributeServices(o());void 0!==e&&nj(n,e)}return n}catch(t){try{await sj(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 sj(e,t){const r=t?.preserveSharedContributorsFrom;let n;const o=async e=>{try{await uN(e)}catch(e){n??=e}};if(e.subagentsService===r?.subagentsService||rj(e.subagentsService)||await o(e.subagentsService),e.cursorRulesService===r?.cursorRulesService||rj(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 uN(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 ij=["project","user","team","mdm","plugins"],aj=new Set([...ij,"all"]);function cj(e){if(void 0===e||0===e.length)return uj([]);for(const t of e)if(!aj.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{...uj(ij),all:!0}}return uj(e.filter((e=>"all"!==e)))}function lj(e,t){return e[t]}function uj(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 dj=Object.freeze({}),hj=Object.freeze({allowMcpServers:!0,allowPlugins:!0,allowBackgroundSessions:!0,requireMcpApproval:!1,maxParallelSessions:void 0,sandboxMode:void 0,metadata:dj});async function pj(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 uN(o)}catch(e){r??=e}}}if(void 0!==r)throw r}async function fj(e={}){const t=function(e={}){return{workspace:e.workspace??mM,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({...hj.metadata,...e.metadata}),r={...hj,...e,metadata:t};return{name:"permissive-sdk-local",resolvePolicy:()=>r}}(),{workspaceState:r});let o=await oj(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 pj(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 pj(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 oj(t,r,n);s?await sj(i,{disposeLocalExtensibility:l}):(o=i,await sj(e,{preserveSharedContributorsFrom:i,disposeLocalExtensibility:l}),await(t.lifecycle?.onWorkspaceReload?.(r)))}))},async dispose(){s||(s=!0,await a((async()=>{try{await sj(o,{disposeLocalExtensibility:l})}finally{await(t.lifecycle?.dispose())}})))}}}class mj{async requestApproval(e){return{approved:!0}}}class gj{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 wj{async open(e,t){}async getDiagnostics(e,t){return[]}}class yj{async getCodebaseReference(e,t){}}class vj{constructor(e){this.inner=e}async getState(e){const t=await this.inner.getState(e);return{...t,servers:t.servers.filter((e=>"needsAuth"!==e.status))}}}class bj{constructor(e){this.subagents=e.map((e=>new dm.zz({fullPath:`sdk-inline://${e.name}`,name:e.name,description:e.description,tools:[],model:e.model,prompt:e.prompt,permissionMode:dm.b$.DEFAULT,isBackground:!1,source:"sdk"})))}async getAllSubagents(){return this.subagents}async reload(){return this.subagents}}class Sj{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 kj(e){return"string"==typeof e&&e.trim().length>0}function _j(e,t){return new fe.jn({command:t.command??"",workingDirectory:t.workingDirectory??"",error:e,isReadonly:!0})}function Cj(e){return{execute:async(t,r)=>new GA.v3({result:{case:"permissionDenied",value:new GA.U7({path:r.path,error:e,isReadonly:!0})}})}}function Ej(e){return{execute:async(t,r)=>new Tg.Pi({result:{case:"permissionDenied",value:new Tg.QG({path:r.path,clientVisibleError:e,isReadonly:!0})}})}}function xj(e){return{execute:async(t,r)=>new Qa.iz({result:{case:"permissionDenied",value:new Qa.HQ({error:`${e} Tool: ${r.name}`,isReadonly:!0})}})}}var Pj=r("../agent-kv/dist/subagent-states.js");let Ij;function Rj(e){const t=process.env.CURSOR_DATA_DIR;if(t?.trim())return mo(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,po.r_)(e.workspacePath)):void 0!==e.homeDir&&function(e){if(""===e.trim())return!1;try{return!!(0,yo.statSync)(e).isDirectory()&&((0,yo.accessSync)(e,yo.constants.W_OK),!0)}catch{return!1}}(e.homeDir)?(0,s.join)(e.homeDir,".cursor","projects",(0,po.r_)(e.workspacePath)):(0,s.join)(e.ensureFallbackRoot(e.tempDir),(0,po.r_)(e.workspacePath))}({workspacePath:e,homeDir:r,tempDir:(0,o.tmpdir)(),ensureFallbackRoot:e=>(void 0===Ij&&(Ij=function(e){return(0,yo.mkdtempSync)((0,s.join)(e,"cursor-transcripts-"))}(e)),Ij)})}async function Tj(e,t){const r=(0,s.dirname)(e);await(0,go.mkdir)(r,{recursive:!0}),await(0,go.writeFile)(e,t,"utf-8")}class Aj{constructor(e){this.writeChain=Promise.resolve(),this.workspacePath=e.workspacePath,this.conversationId=e.conversationId,this.parentConversationId=e.parentConversationId,this.blobStore=e.blobStore,this.projectDir=Rj(this.workspacePath);const t=this.parentConversationId?(e,t)=>{const r=RD({conversationId:e,ext:t,kind:"subagent",parentConversationId:this.parentConversationId});return(0,s.join)(this.projectDir,r)}:void 0;this.transcriptStore=new sO(this.projectDir,e.blobStore,Tj,{writeText:!1,writeJsonl:!0,...t?{pathResolver:t}:{}}),this.nestedSubagentTranscriptStore=new sO(this.projectDir,e.blobStore,Tj,{writeText:!1,writeJsonl:!0,pathResolver:(e,t)=>{const r=RD({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){yM.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,Pj.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=RD({conversationId:this.conversationId,ext:"jsonl",kind:"subagent",parentConversationId:this.parentConversationId});return(0,s.join)(this.projectDir,e)}return function(e,t){const r=RD({conversationId:t,ext:"jsonl",kind:"primary"});return(0,s.join)(Rj(e),r)}(this.workspacePath,this.conversationId)}getProjectDir(){return this.projectDir}}const $j=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Mj="User aborted/interrupted manually.";class Dj{constructor(e){this.sessions=new Map,this.backgroundRuns=new Map,this.activeForegroundExecutions=new Map,this.backgroundPromises=new Set,this.pendingReleaseSessions=new Set,this.childParentIds=new Map,this.parentChildIds=new Map,this.queuedChildCompletions=new Map,this.childCompletionWaiters=new Map,this.agentClient=e.agentClient,this.getResources=e.getResources,this.mcpTools=e.mcpTools??[],this.workspacePath=e.workspacePath,this.parentConversationId=e.parentConversationId,this.headers=e.headers,this.endlessRetries=e.endlessRetries,this.onSessionCreated=e.onSessionCreated,this.onInteractionUpdate=e.onInteractionUpdate,this.onSessionCompleted=e.onSessionCompleted,this.onSessionReleased=e.onSessionReleased,this.onSubagentTokenDelta=e.onSubagentTokenDelta,this.lifecycleStore=new Sj}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(!$j.test(e))throw new Error(`Invalid resumeAgentId format: ${e}`)}(r),r&&!t.prompt)return r;if(r&&kj(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,vM.sh)(e),n=new vM.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 Aj({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:dm.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:dm.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 Qn.a3({status:Qn.jh.ACCEPTED}):new Qn.a3({status:Qn.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){yM.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 Qn.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 Qn.Pw({...r,runInBackground:!1}):new Qn.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}async executeSubagentOnce(e,t,r,n){let o,s=0;const i=new c.QFf({action:{case:"userMessageAction",value:new c.Vtf({userMessage:new c.RGk({text:r.prompt})})}}),a=new c.Gmx({modelId:r.modelId,displayModelId:r.modelId,displayName:r.modelId});void 0!==r.credentials.case&&(a.credentials=r.credentials);const l=new wM,u={sendUpdate:async(e,r)=>{"tokenDelta"===r.message.case&&this.onSubagentTokenDelta?.(t,r.message.value.tokens),"toolCallStarted"!==r.message.case&&"toolCallCompleted"!==r.message.case&&"partialToolCall"!==r.message.case||this.onInteractionUpdate?.(t,r),"toolCallCompleted"===r.message.case&&s++,"textDelta"===r.message.case&&(o=(o??"")+r.message.value.text)},query:async(e,t)=>function(e){const t=e.query.case;switch(t){case"webSearchRequestQuery":return 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)},d={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(),h=r.parentConversationId?.trim(),p=void 0!==c&&""!==c?c:void 0!==h&&""!==h?h:t,f=await this.getResources({agentId:t,parentAgentId:r.parentConversationId}),m=r.readonly?new X(f,function(e){const t=[K(eR,Cj(e.errorMessage)),K(tR,Ej(e.errorMessage)),K(Kn,xj(e.errorMessage))];return e.wrapShell&&t.push(K(ZI,function(e){return{execute:async(t,r)=>new fe.W4({result:{case:"permissionDenied",value:_j(e,r)}})}}(e.errorMessage)),K(re,function(e){return{async*execute(t,r){yield new fe.FI({event:{case:"permissionDenied",value:_j(e,r)}})}}}(e.errorMessage)),K(TR,function(e){return{execute:async(t,r)=>new xo.Lt({result:{case:"permissionDenied",value:_j(e,r)}})}}(e.errorMessage))),e.includeWriteBackgroundShellStdin&&t.push(K(AR,function(e){return{execute:async(t,r)=>new xo.nt({result:{case:"error",value:new xo.Gv({error:e})}})}}(e.errorMessage))),t}({errorMessage:"This operation is not allowed in readonly mode. The subagent was launched with readonly: true, which restricts shell, write, delete, and MCP operations.",wrapShell:!0,includeWriteBackgroundShellStdin:!0})):f;return await this.agentClient.run(e,n.agentStore.getConversationStateStructure(),i,a,u,m,n.agentStore.getBlobStore(),l,d,[...this.mcpTools],{conversationGroupId:p,conversationId:t,...n.transcriptWriter.parentConversationId?{transcriptParentConversationId:n.transcriptWriter.parentConversationId}:{},subagentTypeName:r.subagentType||void 0,headers:SM(n.agentStore.getMetadata("blobEncryptionKey"),this.headers),endlessRetries:this.endlessRetries,subagentModelOverrides:[]}),await n.transcriptWriter.writeTurnEndedFromState(e,n.agentStore.getConversationStateStructure(),e.signal.aborted?{status:"aborted",error:Mj}:{status:"success"}),{status:"completed",finalMessage:o,toolCallCount:s}}catch(r){const o=r instanceof Error?r.message:String(r);return yM.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:Mj}:{status:"error",error:o}}}getTurnEndedFromError(e,t){return e.signal.aborted?{status:"aborted",error:Mj}:{status:"error",error:t}}isAwaitBackgroundMode(e){if(!Boolean(e.resumeAgentId&&!kj(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 Qn.zJ({result:{case:"stillRunning",value:new Qn.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 Qn.zJ({result:{case:"complete",value:new Qn.bE({agentId:r,finalMessage:e.finalMessage,toolCallCount:e.toolCallCount??0})}}):new Qn.zJ({result:{case:"error",value:new Qn.Y({agentId:r,error:e.finalMessage||"Subagent was aborted"})}}):this.isBackgroundRunBusy(r)?new Qn.zJ({result:{case:"stillRunning",value:new Qn.L5({agentId:r})}}):new Qn.zJ({result:{case:"notFound",value:new Qn.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 Qn.zJ({result:{case:"stillRunning",value:new Qn.L5({agentId:r})}}):(this.takeQueuedChildCompletion(r,n.runId),"completed"===i.status?new Qn.zJ({result:{case:"complete",value:new Qn.bE({agentId:r,finalMessage:i.finalMessage,toolCallCount:i.toolCallCount??0})}}):new Qn.zJ({result:{case:"error",value:new Qn.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 Oj=r("../proto/dist/generated/agent/v1/agent_service_connect.js"),Fj=r("../proto/dist/generated/agent/v1/requested_model_pb.js"),Nj=r("../proto/dist/generated/agent/v1/selected_context_pb.js"),Lj=r("./src/agent/analytics.ts"),jj=r("../proto/dist/generated/agent/v1/todo_tool_pb.js");const Uj={[Pm.w3.UNSPECIFIED]:"unspecified",[Pm.w3.LEFT]:"left",[Pm.w3.RIGHT]:"right",[Pm.w3.MIDDLE]:"middle",[Pm.w3.BACK]:"back",[Pm.w3.FORWARD]:"forward"},Bj={[Pm.Dh.UNSPECIFIED]:"unspecified",[Pm.Dh.UP]:"up",[Pm.Dh.DOWN]:"down",[Pm.Dh.LEFT]:"left",[Pm.Dh.RIGHT]:"right"},Wj={[Pm.EB.UNSPECIFIED]:"unspecified",[Pm.EB.TAP]:"tap",[Pm.EB.DOWN]:"down",[Pm.EB.UP]:"up"};function Hj(e){return Uj[e]??"unspecified"}function qj(e){return void 0===e?void 0:{x:e.x,y:e.y}}function zj({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:qj(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 Gj(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 Vj("tool-call-started",e.message.value);case"partialToolCall":return Vj("partial-tool-call",e.message.value);case"toolCallCompleted":return Vj("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=Gj(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 Vj(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:Yj(r)}:{}}:null}case"deleteToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"delete",args:{path:t.path},...r?{result:eU(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:tU(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:rU(r)}:{}}:null}case"readToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"read",args:{path:t.path},...r?{result:oU(r)}:{}}:null}case"editToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"edit",args:{path:t.path},...r?{result:sU(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:iU(r)}:{}}:null}case"readLintsToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"readLints",args:{paths:t.paths},...r?{result:cU(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:lU(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:dU(r)}:{}}:null}case"recordScreenToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"recordScreen",args:{mode:hU(t.mode)},...r?{result:pU(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:uU(r)}:{}}:null}case"createPlanToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"createPlan",args:{plan:t.plan},...r?{result:fU(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:gU(e.status)})))},...r?{result:mU(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:qj(e.value.coordinate)};case"click":return{type:"click",coordinate:qj(e.value.coordinate),button:Hj(e.value.button),count:e.value.count,modifierKeys:e.value.modifierKeys};case"mouseDown":case"mouseUp":return{type:e.case,button:Hj(e.value.button)};case"drag":return{type:"drag",path:e.value.path.map((e=>({x:e.x,y:e.y}))),button:Hj(e.value.button),modifierKeys:e.value.modifierKeys};case"scroll":return{type:"scroll",coordinate:qj(e.value.coordinate),direction:Bj[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:Wj[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?zj(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:Kj(t),...r?{result:Xj(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 Kj(e){return{description:e.description??"",prompt:e.prompt??"",...e.subagentType?{subagentType:Jj(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:Zj(e.mode)}:{},...e.respondingToMessageIds&&e.respondingToMessageIds.length>0?{respondingToMessageIds:e.respondingToMessageIds}:{}}}function Jj(e){const t=e.type.case;return t?"custom"===t?{kind:t,name:e.type.value.name}:{kind:t}:{kind:"unspecified"}}function Zj(e){switch(e){case dm.FL.AGENT:return"agent";case dm.FL.PLAN:return"plan";default:return"unspecified"}}function Xj(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:Qj(t.backgroundReason),...t.transcriptPath?{transcriptPath:t.transcriptPath}:{}}}}case"error":return{status:"error",error:{message:e.result.value.error??"Task failed"}};default:return}}function Qj(e){switch(e){case dm.qL.AGENT_REQUEST:return"agentRequest";case dm.qL.USER_REQUEST:return"userRequest";case dm.qL.QUEUED_FOLLOW_UP:return"queuedFollowUp";default:return"unspecified"}}function Yj(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 eU(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 tU(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 rU(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]=nU(n);return{status:"success",value:{...Object.keys(r).length>0?{workspaceResults:r}:{},...t.activeEditorResult?{activeEditorResult:nU(t.activeEditorResult)}:{}}}}return{status:"error",error:{message:e.result.value.error??e.result.case}}}}function nU(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 oU(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 sU(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 iU(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{directoryTreeRoot:aU(e.result.value.directoryTreeRoot)}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function aU(e){if(e)return{absPath:e.absPath??"",childrenDirs:e.childrenDirs?.map(aU)??[],childrenFiles:e.childrenFiles?.map((e=>({name:e.name})))??[],childrenWereProcessed:e.childrenWereProcessed??!1,fullSubtreeExtensionCounts:e.fullSubtreeExtensionCounts??{},numFiles:e.numFiles??0}}function cU(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:wU(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 lU(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 uU(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 dU(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 hU(e){switch(e){case NT.$u.START_RECORDING:return"START_RECORDING";case NT.$u.SAVE_RECORDING:return"SAVE_RECORDING";case NT.$u.DISCARD_RECORDING:return"DISCARD_RECORDING";default:throw new Error(`Unknown RecordingMode: ${e}`)}}function pU(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 fU(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 mU(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{todos:e.result.value.todos?.map((e=>({content:e.content,status:gU(e.status)})))??[],totalCount:e.result.value.totalCount??0}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function gU(e){switch(e){case jj.Vj.UNSPECIFIED:case jj.Vj.PENDING:return"pending";case jj.Vj.IN_PROGRESS:return"inProgress";case jj.Vj.COMPLETED:return"completed";case jj.Vj.CANCELLED:return"cancelled";default:return"pending"}}function wU(e){switch(e){case qR.h_.UNSPECIFIED:case qR.h_.ERROR:return"error";case qR.h_.WARNING:return"warning";case qR.h_.INFORMATION:return"information";case qR.h_.HINT:return"hint";default:return"error"}}const yU={type:"object",properties:{},additionalProperties:!0};function vU(e){const t={};for(const[r,n]of Object.entries(e))t[r]=n;return t}function bU(e){return"text"===e.type?new Qa._Z({content:{case:"text",value:new Qa.zN({text:e.text})}}):new Qa._Z({content:{case:"image",value:new Qa.do({data:n.Buffer.from(e.data,"base64"),mimeType:e.mimeType??""})}})}function SU(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var kU=r("./src/agent/errors.ts");const _U="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 CU(e){return{async execute(){throw new Error(e)}}}function EU(e){var t;e.register(ZI,CU(_U)),e.register(re,(t=_U,{async*execute(){throw new Error(t)}})),e.register(TR,CU(_U)),e.register(FR,CU(_U)),e.register(AR,CU(_U)),e.register(XI,CU(_U)),e.register(hR,CU("ReadLints is not available when local.fs is set: lint diagnostics come from a host language service, not the FileSystem.")),e.register(nR,CU("Git is not available when local.fs is set: the agent's files live in a FileSystem, not a host git checkout."))}var xU=r("./src/agent/filesystem/executors.ts"),PU=r("./src/agent/filesystem/compose.ts"),IU=r("./src/agent/filesystem/trees.ts"),RU=r("./src/agent/filesystem/walk.ts");const TU="/tmp",AU=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.txt$/i;function $U(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,RU.eI)(e.hostProjectDir),r=(0,RU.eI)(e.writePath);return"/"!==t&&(0,RU.hJ)({path:r,prefix:t})?r.slice(t.length):void 0}(e),n=void 0===r?(0,RU.eI)(e.writePath):(0,RU.eI)(`${TU}/${r}`);if(!(0,RU.hJ)({path:n,prefix:TU}))return;const o=a().posix.basename(n),s=a().posix.join(TU,Ya);return a().posix.dirname(n)===s&&AU.test(o)?a().posix.join(TU,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 MU{constructor(e,t="/"){this.fs=e,this.listeners=new Set,this.workspace=(0,RU.eI)(t)}getAllCursorRules(e){return this.rules??=async function(e,t){const[r,n]=await Promise.all([DU(e,s.posix.join(t,".cursor/rules")),OU(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 DU(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 FU(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 OU(e,t){const r=await FU(e,t);if(void 0!==r)return om({path:t,body:Xr({content:r,filename:"AGENTS.md"}),frontmatter:{alwaysApply:!0}})}async function FU(e,t){try{const r=await e.read(t);return"string"==typeof r?r:(new TextDecoder).decode(r)}catch{return}}const NU={getAllCursorRules:async()=>[],reload(){},onDidChangeRules:()=>()=>{},dispose(){}},LU={async exec(){throw new Error("git is not available in a FileSystem session")}},jU={isIgnoredByAny:async()=>!1,isGitIgnored:async()=>!1,isCursorIgnored:async()=>!1,isRepoBlocked:async()=>!1,listCursorIgnoreFilesByRoot:async()=>[],getCursorIgnoreMapping:async()=>({}),getShellSandboxIgnoreMapping:async()=>({}),getGitIgnoreMapping:async()=>({}),getRepoBlockExcludeGlobs:async()=>[]};function UU(e){return{cursorRulesService:!0===e.includeProjectRules?new MU(e.fs,e.workspace):NU,getAgentSkills:async()=>[],subagentsService:e.subagentsService??new pm,gitExecutor:LU,ignoreService:jU,requestContextIsWorkingDirHomeDir:!1,reportProcessWorkingDirectory:!1}}function BU(e,t){const r=t.workspace??"/",n=(0,xU.c9)(e,{workspace:r});return{localResourceProviderOptions:{overrideReadExecutor:n.read,overrideWriteExecutor:$U({write:n.write,hostProjectDir:t.hostProjectDir}),overrideGrepExecutor:n.grep,overrideLsExecutor:n.ls,overrideDeleteExecutor:n.delete,suppressDefaultShellExecutor:!0,...UU({...t.settings,fs:e,workspace:r})},reportedWorkspacePath:r,reportedProjectFolder:TU,excludeHooks:!0,excludeProjectMcp:!0}}var WU=r("./src/agent/executor-common.ts");class HU{constructor(){this.countsByMode=new Map,this.record=e=>{let t=this.countsByMode.get(e.mode);switch(void 0===t&&(t={mode:e.mode,checked_calls:0,outside_limit_calls:0,settings_unavailable_calls:0,unknown_server_calls:0},this.countsByMode.set(e.mode,t)),e.outcome){case"within_limit":return void(t.checked_calls+=1);case"outside_limit":return t.checked_calls+=1,void(t.outside_limit_calls+=1);case"settings_unavailable":return void(t.settings_unavailable_calls+=1);case"unknown_server":return void(t.unknown_server_calls+=1);default:return e.outcome}}}take(){const e=[...this.countsByMode.values()];return this.countsByMode.clear(),e}}var qU=r("./src/agent/native/vendored-tree-sitter.ts"),zU=r("./src/agent/platform-package-locator.ts"),GU=r("./src/agent/sdk-config.ts"),VU=r("../../node_modules/.pnpm/@statsig+js-client@3.31.0/node_modules/@statsig/js-client/src/index.js"),KU=r("./src/agent/utils/logger.ts");const JU={checkFeatureGate:()=>!1,getDynamicConfigValue:({defaultValue:e})=>e},ZU=new Map;async function XU(e){try{const t=await async function(e){const t=await(0,WU.dC)(e,WU.EV);if(!t)return;const r=WU.EV.endsWith("/")?WU.EV.slice(0,-1):WU.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,WU.tF)(),"x-ghost-mode":(0,WU.U)(e)},body:JSON.stringify({})});if(!n.ok)return void KU.v.log(`Failed to bootstrap SDK Statsig: ${n.status} ${n.statusText}`);const o=await n.json();return QU(o)&&"string"==typeof o.config&&o.config.length>0?o.config:void 0}(e);if(!t)return JU;const r=new VU.StatsigClient("client-Bm4HJ0aDjXHQVsoACMREyLNxm5p6zzuzhO50MgtoT5D",function(e){try{const r=JSON.parse(e);if(QU(r)&&"object"==typeof(t=r.user)&&null!==t&&!Array.isArray(t))return{...r.user,custom:{...r.user.custom,clientType:"sdk",clientVersion:(0,WU.tF)()}}}catch(e){KU.v.log(`Failed to parse SDK Statsig bootstrap user: ${e instanceof Error?e.message:String(e)}`)}var t;return{custom:{clientType:"sdk",clientVersion:(0,WU.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 KU.v.log(`Failed to initialize SDK Statsig: ${e instanceof Error?e.message:String(e)}`),JU}}function QU(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function YU(e){let t;return e?.then((e=>{t=e}),(()=>{})),()=>t?.checkFeatureGate("grok_bot_mcp_app_payment_token_filter",{disableExposureLog:!0})??!1}var eB=r("./src/agent/tools-option.ts");class tB{async requestApproval(){return{approved:!0}}}function rB(e,t){if(!function(e){return void 0!==e&&Object.keys(e).length>0}(t))return;const r=e.resources.base;if(!(r instanceof u$))throw new kU.j1("SDK custom tools require the default local workspace resource provider.",{isRetryable:!1});const n=r.getMcpExecutionPolicyDeps(),o=r.get(Kn),s=function(e,t){return{async execute(r,n,o){const s=n.toolName||function(e){const t=`${jn}-`;return e.startsWith(t)?e.slice(t.length):e}(n.name),i=e[s];if(void 0===i)return new Qa.iz({result:{case:"error",value:new Qa.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:SU(e)?e:void 0};var t}(e),r=void 0!==t.structuredContent?ve.Struct.fromJson(t.structuredContent):void 0;return new Qa.iz({result:{case:"success",value:new Qa.QW({content:t.content.map(bU),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 Qa.iz({result:{case:"error",value:new Qa.Nh({error:e instanceof Error?e.message:String(e)})}})}}}}(t,e.state.sessionId),i=new tB;e.resources.base.register(Kn,{async execute(e,t,r){if(function(e){return e.providerIdentifier===jn}(t)){const o=await LI(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 nB=new Set(["127.0.0.1","localhost","[::1]"]);function oB(e){if(void 0===e)return{};const t=e.resourceProviderOptions;return{...void 0!==t?{localResourceProviderOptions:t}:{},...void 0!==e.reportedWorkspacePath?{reportedWorkspacePath:e.reportedWorkspacePath}:{}}}function sB(){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 iB={warn(){},error(){}},aB={log(){}};class cB{async requestApproval(e){return{approved:!1,reason:`Local SDK runs cannot request interactive approval for ${lB(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 lB(e){switch(e.type){case Rg.Shell:return"this shell command";case Rg.Mcp:return"this MCP tool call";case Rg.Write:return"this file edit";case Rg.Delete:return"this file deletion";default:return"this operation"}}function uB(e){return void 0!==e&&"insecure_none"!==e.type}async function dB(e,t){const r="string"==typeof e||void 0===e?{workingDirectory:e,apiKey:t}:e,i=(0,b.q6)().with(d._O,aB),a=cj(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&&nB.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}`);da=e}((0,GU.Mu)()),/:\/\/(localhost|127\.0\.0\.1)/.test(WU.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,WU.ly)(r.apiKey),(0,WU.mU)(r.apiKey)]),h=performance.now()-e}const p=r.workingDirectory||process.cwd();(0,qU.configureVendoredTreeSitterWorkspaceDir)(p);for(const e of r.dirs??[])(0,qU.configureVendoredTreeSitterWorkspaceDir)(e);const f=(0,po.Rv)((0,o.homedir)(),p),m={hostProjectDir:f,settings:{includeProjectRules:lj(a,"project"),subagentsService:new bj(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,zU.hQ)({binaryName:w,excludedWorkspaceDir:p}),g||(g=(0,Po.xS)()),g&&(0,Po.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,WU.KU)(r.apiKey,r.teamId);const e=(0,be.createClient)(lN.I,v),t=function(e){let t=ZU.get(e);return t||(t=XU(e),ZU.set(e,t),t.then((r=>{r===JU&&ZU.get(e)===t&&ZU.delete(e)}),(()=>{ZU.get(e)===t&&ZU.delete(e)}))),t}(r.apiKey);S=t;const n={getDefaultNetworkAllowlist:async()=>(await t).getDynamicConfigValue({configName:"sandbox_default_network_allowlist",paramName:"allowlist",defaultValue:[]})};k=new pM(new uM(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){KU.v.log(`Failed to initialize authenticated dashboard services: ${e instanceof Error?e.message:String(e)}`)}const _=performance.now(),C=r.apiKey?await(0,Po.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=uB(r)?r:!0===n?.enabled?function(e,t={}){return{type:e,...t}}("workspace_readwrite",{networkPolicy:(0,Po.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,zU.hQ)({binaryName:t,excludedWorkspaceDir:e});r&&(0,Po.St)({sandboxBinaryPath:r})}(t),!(0,Po.K3)(void 0,{ctx:e.initializationCtx}))throw new kU.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,Po.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,I=E?.defaultSandboxPolicySources,R=uB(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=cj(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,Po.K3)(c,{ctx:e.initializationCtx})),u=e.getSandboxEnabled??(()=>"insecure_none"!==c.type&&l()),d=new fw,h=new Va(d,a,n),p=new wj,f=new yj,m=e.getSmartModeClassifierAutoModeEnabled?.(),g=new gj(m?"allowlist":e.approvalMode??"unrestricted",c,a,e.respectAdminControls??!1),w=e.pendingDecisionProvider,y={executeIndexedGrep:void 0},v=()=>!0,b=lj(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=_||lj(i,"project")||lj(i,"user")||b,x=lj(i,"project")||lj(i,"user")||lj(i,"mdm"),P=lj(i,"team"),I=P&&void 0!==e.dashboardTransport,R=lj(i,"project")||lj(i,"user")||P||I||b,T={teamSettingsService:a,initializationCtx:e.initializationCtx,importThirdPartyPlugins:S,ignoreApprovals:!0,includeProjectMcp:lj(i,"project"),includeUserMcp:lj(i,"user"),includePluginMcp:b,isLinkSharedPaymentTokenLogRedactionEnabled:e.isLinkSharedPaymentTokenLogRedactionEnabled},A=s=>fj({workingDirectory:t,...void 0!==o?{workspaceRoots:o}:{},adapters:{...s.includeMcp?{mcp:WM({...T,inlineMcpServers:e.mcpServers})}:{},...b?{pluginBootstrap:WL({importThirdPartyPlugins:S,dashboardTransport:e.dashboardTransport})}:{},...x?{hooks:cN({includeProjectHooks:lj(i,"project"),includeUserHooks:lj(i,"user"),includeEnterpriseHooks:lj(i,"mdm"),useCommandHookStdinTransport:e.useCommandHookStdinTransport})}:{},...R?{localExtensibility:dN({includeProjectExtensibility:lj(i,"project"),includeUserExtensibility:lj(i,"user"),includeManagedSkills:I,includeTeamExtensibility:P,includePluginExtensibility:b,teamSettingsService:a,getThirdPartyExtensibilityEnabled:v,dashboardTransport:e.dashboardTransport,importThirdPartyPlugins:S})}:{},resourceFactory:QL({ignoreService:h,grepProvider:y,workspacePaths:n,diagnosticsProvider:p,repositoryProvider:f,projectDir:r??t,shellManager:void 0,defaultSandboxPolicy:c,defaultSandboxPolicySources:e.defaultSandboxPolicySources,getSandboxEnabled:u,getSandboxSupported:l,getNetworkAllowlistInfo:e.getNetworkAllowlistInfo,getSmartModeClassifierAutoModeEnabled:e.getSmartModeClassifierAutoModeEnabled,devForceNextSmartModeClassifierBlockToken:e.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:e.getMockPromptTime,getPowershellUtf8Options:e.getPowershellUtf8Options,mcpFileOutputThresholdBytes:void 0,mcpMetaToolEnabled:k,createMcpStateAccessor:e=>new vj(new hA(e)),createSessionMcpLease:(t,r)=>WM({...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 mj;return{pendingDecisionStore:n,fileChangeTracker:new $g(t),permissionsService:new RS(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 iN(new YF(e.resources,n.hookExecutor,(()=>function(e,t){const r=rN(t,nN,"conversationId","conversation_id")??e.sessionId??"";return{conversation_id:r,generation_id:rN(t,nN,"generationId","generation_id")??r,model:rN(t,nN,"model")??"unknown",...aD({modelId:rN(t,nN,"modelId","model_id"),modelParams:rN(t,sN,"modelParams","model_params")})}}(e.sessionState,e.metadata)),e.workspaceServices.mcpLease,void 0,void 0,t.hooksConfigLease),n)}}]:[],...C?{workspaceServicesContributors:[{contributeServices:t=>{const r=new bj(e.customSubagents??[]),n=t.services.subagentsService;return{subagentsService:void 0===n?r:new Sm([r,n])}}}]}:{}}});if(!E)return A({includeMcp:!1});try{return await A({includeMcp:!0})}catch(e){return yM.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:I,approvalMode:R?"allowlist":void 0,pendingDecisionProvider:R||!0===r.autoReview?new cB:void 0,getNetworkAllowlistInfo:R?()=>async function(e,t,r){const[n,o]=await Promise.all([e.getDefaultNetworkAllowlist(),e.getNetworkAccessControls()]),s=[...o.allowlist],i=`${t}/.cursor/sandbox.json`,a=await(0,Po.tv)(i,t);if(a&&"insecure_none"!==a.type&&a.networkPolicy?.allow&&s.push(...a.networkPolicy.allow),r){const e=`${r}/.cursor/sandbox.json`,t=await(0,Po.tv)(e,r);t&&"insecure_none"!==t.type&&t.networkPolicy?.allow&&s.push(...t.networkPolicy.allow)}const c=[...new Set(s)];return{hasDefaults:n.available&&n.allowlist.length>0,explicitEntries:c}}(k,(0,o.homedir)(),p):void 0,getSmartModeClassifierAutoModeEnabled:()=>!0===r.autoReview,devForceNextSmartModeClassifierBlockToken:r.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:sB,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:YU(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,Lj.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,yM.ni)(iB,(async()=>{const s=(0,D.VI)((0,b.q6)().withName("sdk.run").with(d._O,aB)),[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:jn,providerIdentifier:jn,toolName:e,name:`${jn}-${e}`,description:t.description??"",inputSchema:t.inputSchema??yU,...void 0===t.outputSchema?{}:{outputSchema:t.outputSchema},...void 0===t.annotations?{}:{annotations:vU(t.annotations)},source:"internal"})));var f;let g;const w={...m,workspace:t.fileSystemWorkspace},y=void 0===t.fileSystem?void 0:(k=await async function(e,t){return"function"==typeof e?await e(t):e}(t.fileSystem,{agentId:l,sessionId:l}),_=k,(0,PU.VL)({"/":_,[TU]:(0,IU.Om)()})),v=void 0===t.onMcpAdminToolLimitCounts?void 0:new HU,S=()=>{for(const e of v?.take()??[])try{t.onMcpAdminToolLimitCounts?.(e)}catch{}};var k,_;g=await M.createSessionRuntime({sessionId:l,mcpServersOverride:u,extraMcpTools:h,onMcpAdminToolLimitCheck:v?.record,...void 0===y?oB(t.sessionResources):BU(y,w)});const C=new Map;try{const s=g.resources.wrapped;rB(g,t.customTools),void 0!==y&&EU(g.resources.base);const d=t.blobStore??new oe.ve;let f=t.initialState??new c.Y9z({});const m=void 0!==t.model?new Fj.G4({modelId:t.model.id,...!0===t.model.maxMode?{maxMode:!0}:{},parameters:(t.model.params??[]).map((e=>new Fj.SR({id:e.id,value:e.value})))}):void 0,b=!0===e.summarize?void 0:e.images,k=Array.isArray(b)?b.map((e=>{const t=(0,ye.C)(),r=new Uint8Array(n.Buffer.from(e.data,"base64")),o=(0,WU.v8)(r);return new Nj.d({uuid:t,...o?{mimeType:o}:{},dataOrBlobId:{case:"data",value:r}})})):[],_=k.length>0?new Nj.xv({selectedImages:k}):void 0,P=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:_,...void 0!==P?{mode:P}:{}})})}}),R={sendUpdate:async(e,t)=>{const r=Gj(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 kU.j1("Missing interaction query type",{isRetryable:!1});default:throw e.query,new kU.j1("Unhandled interaction query type",{isRetryable:!1})}}(t)};if(N!==t.apiKey||!L){await Promise.all([(0,WU.ly)(t.apiKey),(0,WU.mU)(t.apiKey)]);const e=(0,WU.KU)(t.apiKey,r.teamId),n=uo((0,be.createClient)(Oj.N,e),{injectTraceHeaders:!0});L=new Fn(n),N=t.apiKey}const T=(0,WU.Vh)(L,(()=>{const e=(0,WU.KU)(t.apiKey,r.teamId),n=uo((0,be.createClient)(Oj.N,e),{injectTraceHeaders:!0}),o=new Fn(n);return L=o,N=t.apiKey,o})),A=function(e){return{...void 0!==e.allowedTools?{[eB.$$]:e.allowedTools.join(",")}:{},...void 0!==e.disallowedTools&&e.disallowedTools.length>0?{[eB.VJ]:e.disallowedTools.join(",")}:{}}}(t),$=new Dj({agentClient:T,getResources:async({agentId:e})=>{let r=C.get(e);return r||(r=await M.createSessionRuntime({sessionId:e,mcpServersOverride:u,extraMcpTools:h,onMcpAdminToolLimitCheck:v?.record,...void 0===y?oB(t.subagentInherit):BU(y,w)}),rB(r,t.customTools),void 0!==y&&EU(r.resources.base),r.resources.base.register(eo,D),r.resources.base.register(to,O),r.resources.base.register(ro,F),C.set(e,r)),r.resources.wrapped},mcpTools:h,workspacePath:p,parentConversationId:l,...(void 0!==t.subagentInherit||void 0!==y)&&Object.keys(A).length>0?{headers:A}:{},onSessionReleased:e=>{const t=C.get(e);t&&(t.dispose(),C.delete(e))}}),D=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 Qn.vS({result:{case:"error",value:new Qn.od({agentId:o,error:s.error})}}):"aborted"===s.status?new Qn.vS({result:{case:"error",value:new Qn.od({agentId:o,error:s.error??"Subagent was aborted by the user"})}}):"background"===s.status?new Qn.vS({result:{case:"success",value:new Qn.HJ({agentId:o,finalMessage:s.finalMessage,toolCallCount:s.toolCallCount??0,backgroundReason:s.backgroundReason,transcriptPath:s.transcriptPath})}}):new Qn.vS({result:{case:"success",value:new Qn.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 Yn&&e.agentId||e&&"object"==typeof e&&"agentId"in e&&"string"==typeof e.agentId?e.agentId:void 0}(t)??r.resumeAgentId;return new Qn.vS({result:{case:"error",value:new Qn.od({...s?{agentId:s}:{},error:n})}})}}return{execute(e,o,s){const i=function(e){if(e.toolCallId&&e.parentConversationId)return[e.parentConversationId,e.toolCallId,e.resumeAgentId??"",e.forkAgentId??""].join("\0")}(o);if(void 0===i)return n(e,o,s);const a=r.get(i);if(void 0!==a)return Promise.resolve(a);const c=t.get(i);if(void 0!==c)return c;const l=n(e,o,s).then((e=>("success"===e.result.case&&(r.set(i,e),r.size>1e3&&r.delete(r.keys().next().value)),e))).finally((()=>{t.delete(i)}));return t.set(i,l),l}}}($),O=(x=$,{execute:(e,t)=>x.awaitBackgroundRunBounded(e,t)}),F=function(e){return{execute:async(t,r)=>e.forceBackgroundByToolCallId(r.toolCallId)}}($);g.resources.base.register(eo,D),g.resources.base.register(to,O),g.resources.base.register(ro,F);const j=M.services.hooksRuntime,U="object"==typeof(E=j)&&null!==E&&"workspacePath"in E&&"string"==typeof E.workspacePath&&"createSessionRuntime"in E&&"function"==typeof E.createSessionRuntime?j:void 0,B=void 0!==U&&void 0===y&&!0!==e.summarize?function(e){const{workspaceRuntime:t}=e;if(!(t.hooksConfigLease.hasHookForStep(ju.sessionStart)||t.hooksConfigLease.hasHookForStep(ju.sessionEnd)||t.hooksConfigLease.hasHookForStep(ju.stop)||t.hooksConfigLease.hasHookForStep(ju.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(ju.sessionStart))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...aD(e),is_background_agent:!1},r=await n.executeHookForStep(ju.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){yM.Jz.warn("[hooks-adapter] sessionStart hook failed:",e)}},async onSessionEnd(e,t){if(n.hasHooksForStep(ju.sessionEnd))try{const r={conversation_id:o?.conversationId??"",generation_id:o?.generationId??"",model:o?.model??"unknown",...o?aD(o):{},reason:e,duration_ms:t,is_background_agent:!1,final_status:e};await n.executeHookForStep(ju.sessionEnd,r)}catch(e){yM.Jz.warn("[hooks-adapter] sessionEnd hook failed:",e)}finally{n.clearSessionEnvironment()}else n.clearSessionEnvironment()},async onBeforeSubmitPrompt(e){if(n.hasHooksForStep(ju.beforeSubmitPrompt))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...aD(e),prompt:e.promptText??"",attachments:[]};await n.executeHookForStep(ju.beforeSubmitPrompt,t)}catch(e){yM.Jz.warn("[hooks-adapter] beforeSubmitPrompt hook failed:",e)}},async onTurnCompleted(e){if(!n.hasHooksForStep(ju.stop))return;const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...aD(e),status:"completed",loop_count:e.loopCount},r=await n.executeHookForStep(ju.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(ju.stop))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...aD(e),status:"error",loop_count:e.loopCount};await n.executeHookForStep(ju.stop,t)}catch(e){yM.Jz.warn("[hooks-adapter] onTurnError stop hook failed:",e)}},async onTurnAborted(e){if(n.hasHooksForStep(ju.stop))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...aD(e),status:"aborted",loop_count:e.loopCount};await n.executeHookForStep(ju.stop,t)}catch(e){yM.Jz.warn("[hooks-adapter] onTurnAborted stop hook failed:",e)}},async dispose(){await r.dispose()}}}({workspaceRuntime:U,sessionState:g.state,metadata:g.metadata}):void 0,W=new Aj({workspacePath:p,conversationId:l,blobStore:d}),H=function(e,t,r){const{hooks:n}=r,[o,s]=e.withCancel(),i=new wM;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"),EM(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=SM(function(e,t){if((0,vM.TU)(t))return t;const r=kM.get(e);if(void 0!==r)return r;const n=(0,vM.sh)(e).blobEncryptionKey;if(void 0===n)throw new Error("getDefaultAgentMetadata did not seed a blobEncryptionKey");return kM.set(e,n),n}(r.conversationId,r.blobEncryptionKey),r.runOptions?.headers);return{done:(async()=>{const e=CM(r,0,_M(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;yM.Jz.warn("[agent-session-runner] sessionStart hook failed:",e)}let s=t,c=0;for(;s;){const e=CM(r,c,_M(s));try{await(n?.onBeforeSubmitPrompt?.(e))}catch(e){yM.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=xM(t)?"aborted":"error",PM("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=EM(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||xM(r)?"aborted":"error",PM("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){yM.Jz.warn("[agent-session-runner] sessionEnd hook failed:",e)}try{await(n?.dispose?.())}catch(e){yM.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"),yM.Jz.warn("[agent-session-runner] context injection failed:",e),"revert_to_followup"}}}}(i,I,{agentClient:T,interactionListener:R,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(A).length>0?{headers:A}:{},...void 0!==t.systemPrompt?{customSystemPrompt:t.systemPrompt}:{}},hooks:B,async nextAction(e,t){const r=await $.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,W.writeFromState(i,e),await(t.onCheckpoint?.(e))}}),q=H.done.finally((async()=>{try{await $.awaitBackgroundWorkers()}finally{await W.waitForPendingWrites().catch((()=>{}));for(const e of C.values())try{await e.dispose()}catch(e){KU.v.log(`Failed to dispose subagent session runtime: ${e instanceof Error?e.message:String(e)}`)}C.clear();try{await g.dispose()}finally{S()}}})).catch((e=>{throw e}));return{abort(){H.abort(),a()},done:q,steer:e=>H.steer(e)}}catch(e){for(const e of C.values())try{await e.dispose()}catch{}C.clear();try{await g.dispose()}finally{S()}throw e}var E,x})),async reload(){await 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)},"../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:()=>I});var n=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/span_kind.js"),o=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/context-api.js"),s=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace-api.js"),i=r("../context/dist/core.js");const a=(0,i.cF)(Symbol("otel.span"),void 0),c=(0,i.cF)(Symbol("otel.root_span"),void 0),l=(0,i.cF)(Symbol("otel.root_start_ms"),void 0),u=(0,i.cF)(Symbol("otel.suppress_child_spans"),!1),d=(0,i.cF)(Symbol("otel.inheritable_span_attributes"),{});function h(e,t){const r=t.get(d);for(const t in r){const n=r[t];"string"!=typeof n&&"number"!=typeof n&&"boolean"!=typeof n||e.setAttribute(t,n)}}function p(e){return e.name||"anonymous-context"}function f(e,t){return!!t&&(e.get(u)||(p(e),!1))}function m(e="context-tracer"){return s.u.getTracer(e)}function g(e,t){const r=m(),n=e.get(a);if(f(e,n))return e;const i=p(e);let u;if(n){const e=s.u.setSpan(o._.active(),n);u=r.startSpan(i,t,e)}else u=r.startSpan(i,t);h(u,e);const d=Date.now();let g=e.with(a,u);return n||(g=g.with(c,u).with(l,d)),g}function w(e){return e.get(a)}function y(e){return e.with(u,!0)}function v(e,t,r){const n=e.get(d),o=w(e);return o&&null!==r&&o.setAttribute(t,r),e.with(d,{...n,[t]:r})}function b(e){try{const t=w(e);if(!t)return;const r=t.spanContext(),n=e.get(u);return{traceId:r.traceId,spanId:r.spanId,traceFlags:n?0:r.traceFlags,traceState:r.traceState?.serialize()}}catch{return}}const S=Symbol.for("anysphere.context.activeOtelSpanAls");function k(e,t){const r=()=>o._.with(s.u.setSpan(o._.active(),e),t),n=function(){const e=globalThis;if("object"!=typeof(t=e)||null===t||!(S in e))return;var t;const r=e[S];return function(e){return"object"==typeof e&&null!==e&&"run"in e&&"function"==typeof e.run&&"getStore"in e&&"function"==typeof e.getStore}(r)?r:void 0}();return void 0===n?r():n.run(e,r)}function _(e,t){try{const r=m(),n=w(e);if(!n)return;const i=s.u.setSpan(o._.active(),n),a=r.startSpan(t,void 0,i);h(a,e);const u=Date.now(),d=e.get(l),p="number"==typeof d?u-d:0,f=`event.${t}`;(e.get(c)??n).setAttribute(f,p),a.setAttribute(f,p),a.end()}catch{}}function C(e,t,r){const c=m(),l={traceId:e.traceId,spanId:e.spanId,traceFlags:e.traceFlags,isRemote:!0},u=s.u.setSpanContext(o._.active(),l),d=t||"child.span",h=c.startSpan(d,{kind:n.v.INTERNAL},u),p=r??(0,i.q6)();return(t?p.withName(t):p).with(a,h)}function E(e,t,r){const n=s.u.wrapSpanContext({traceId:e.traceId,spanId:e.spanId,traceFlags:e.traceFlags,isRemote:!0}),o=r??(0,i.q6)();return(t?o.withName(t):o).with(a,n)}class x{constructor(e,t,r=!0){this.ctx=e,this.span=t,this.shouldEnd=r}[Symbol.dispose](){this.shouldEnd&&this.span.end()}}function P(e,t){const r=f(e,w(e)),n=g(e,t),o=w(n);return new x(n,o,!r)}function I(e,t,r){const n=w(e);if(!n||f(e,n))return;const o=w(g(e,t));return o.end(r),o}},"../mcp-core/dist/transport/mcp-url-utils.js"(e,t,r){"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>=I&&d.clear();const t=l(e);return d.set(e,t),t}(e);return void 0!==r&&r.version===t.version&&r.value>>t.shift===t.shiftedNetwork}case"subdomainOrBase":return e===t.suffix||e.endsWith(`.${t.suffix}`);case"exact":return e===t.value;default:return t}}(H(e),function(e){const t=u.get(e);if(t)return t;u.size>=I&&u.clear();const r=function(e){const t=H(e);if("*"===t)return{kind:"matchAll"};if(t.includes("/")){const e=t.lastIndexOf("/");if(e<=0||e===t.length-1)return{kind:"invalidCidr"};const r=l(t.slice(0,e));if(!r)return{kind:"invalidCidr"};const n=Number(t.slice(e+1)),o=4===r.version?32:128;if(!Number.isInteger(n)||n<0||n>o)return{kind:"invalidCidr"};const s=BigInt(o-n);return{kind:"cidr",version:r.version,shift:s,shiftedNetwork:r.value>>s}}return t.startsWith("*.")?{kind:"subdomainOrBase",suffix:t.slice(2)}:{kind:"exact",value:t}}(e);return u.set(e,r),r}(t))}new Set(["airtable.com","anysphere.co","api.aws","apify.com","asana.com","ashbyhq.com","atlassian.com","atlassian.net","azuredatabricks.net","box.com","buildkite.com","calendly.com","canva.com","clickhouse.cloud","clickup.com","cloudflare.com","composio.dev","context7.com","cursor.com","cursor.sh","cursorapi.com","databricks.com","datadoghq.com","datadoghq.eu","ddog-gov.com","dropbox.com","elevenlabs.io","exa.ai","figma.com","firecrawl.dev","github.com","githubcopilot.com","gitlab.com","google.com","googleapis.com","granola.ai","hex.tech","hubspot.com","huggingface.co","intercom.com","linear.app","monday.com","neon.tech","notion.com","plain.com","posthog.com","prisma.io","railway.com","ramp.com","render.com","salesforce.com","sentry.dev","sentry.io","slack.com","snowflakecomputing.com","spacelift.io","statsig.com","stripe.com","supabase.com","todoist.net","vercel.com","workos.com","x.ai","x.com","zapier.com"]);const p="Blocked by MCP Network Admin Server Controls";function f(e){return/\s/.test(e)}const m="[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?",g=new RegExp(`^(?:${m}\\.)*${m}$`),w=new RegExp(`^\\*\\.(?:${m}\\.)*${m}$`),y="(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)",v=new RegExp(`^${y}(?:\\.${y}){3}$`),b=/^[0-9a-f:]+$/,S=new RegExp(`^(?:${y}(?:\\.${y}){3}|[0-9a-f:]+)\\/\\d{1,3}$`);function k(e){const t=H(e);return t.length>0&&t.length<=253&&g.test(t)}function _(e){const t=H(e);return v.test(t)||function(e){const t=H(e);if(!b.test(t))return!1;try{return new URL(`https://[${t}]`),!0}catch{return!1}}(t)}function C(e,t){return""===t||"http:"===e&&"80"===t||"https:"===e&&"443"===t}function E(e){const t=new URL(e.pathname||"/",e.origin);if(t.search=e.search,t.pathname.endsWith("/")&&t.pathname.length>1&&(t.pathname=t.pathname.slice(0,-1)),"/"===t.pathname&&""===t.search){const t=e.protocol.toLowerCase();let r=`${t}//${e.hostname.toLowerCase()}`;return C(t,e.port)||(r+=`:${e.port}`),r}const r=e.protocol.toLowerCase();let n=`${r}//${e.hostname.toLowerCase()}`;return C(r,e.port)||(n+=`:${e.port}`),`${n}${t.pathname}${t.search}`}function x(e){if(e.includes("://"))return function(e){try{const t=new URL(e);return("http:"===t.protocol||"https:"===t.protocol)&&!(0===t.hostname.length||t.username.length>0||t.password.length>0)&&""===t.hash&&function(e){const t=e.toLowerCase();return!t.includes("*")&&(k(t)||_(t))}(t.hostname)}catch{return!1}}(e);const t=H(e);return"*"===t||!!w.test(t)||(t.includes("/")?function(e){const t=H(e);if(!S.test(t))return!1;const[r]=t.split("/");return void 0!==r&&h(r,t)}(t):k(t)||_(t))}function P(e){if(R.has(e))return R.get(e);R.size>=I&&R.clear();const t=function(e){const t=e.trim();if(0===t.length)return;const r=t.lastIndexOf("/");if(!t.includes("://")&&r>0&&/^\d+$/.test(t.slice(r+1).trim())){const e=`${H(t.slice(0,r))}/${t.slice(r+1).trim()}`;return x(e)?e:void 0}if(f(t)||t.includes("#")||t.includes("@"))return;const n=t.indexOf("://");if(-1!==n){const e=t.slice(0,n).toLowerCase();if("http"!==e&&"https"!==e)return;try{const e=new URL(t);if(0===e.hostname.length||e.username.length>0||e.password.length>0)return;const r="/"!==e.pathname&&""!==e.pathname,n=""!==e.search;if(e.hostname.includes("*"))return;if(r||n){const t=E(e);if(!x(t))return;return t}{const t=E(e);if(!x(t))return;return t}}catch{return}}else if(t.includes("/"))return;const o=t.trim().toLowerCase(),s=function(e){const t=e.indexOf(":");if(-1===t)return e;const r=e.slice(t+1);return/^\d+$/.test(r)?e.slice(0,t):e}(o);return 0===s.length||!x(s)||s!==o&&"*"===s?void 0:s}(e);return R.set(e,t),t}const I=2048,R=new Map,T=new Map;function A(e,t){if(!e.includes("*"))return e===t;const r=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${r}$`).test(t)}function $(e){return e.endsWith("/")&&e.length>1?e.slice(0,-1):e}function M(e,t){return function(e,t,r){const n=D(t);if(!n)return!1;let o;try{o=new URL(e)}catch{return!1}return""===o.username&&""===o.password&&""===n.username&&""===n.password&&o.protocol===n.protocol&&o.port===n.port&&(s=o.hostname,i=n.hostname,!s.includes("*")&&H(s)===H(i)&&(A(a=o.pathname,c=n.pathname)||A($(a),$(c)))&&function(e,t,r){return""===e?r.allowRequestQueryWhenPatternOmitsQuery||""===t:A(e,t)}(o.search,n.search,r));var s,i,a,c}(e,t,{allowRequestQueryWhenPatternOmitsQuery:!0})}function D(e){const t=e.trim();if(0===t.length||f(t))return;if(function(e){const t=e.indexOf("[");return-1!==t&&-1===e.indexOf("]",t)}(t))return;const r=q(t);if(r&&("http:"===r.protocol||"https:"===r.protocol)&&""===r.username&&""===r.password&&0!==r.hostname.length&&(!H(r.hostname).includes(":")||t.includes("["))){if(t.includes("[")){const e=t.indexOf("["),n=t.indexOf("]",e);if(-1===n)return;const o=t.slice(e+1,n);if(H(r.hostname)!==H(o))return}return r}}function O(e,t){const r=e.toLowerCase(),n=t.toLowerCase();if("*"===r)return!0;if(void 0!==a(n))return A(r,n);if(!r.includes("*"))return r===n;const o=r.slice(1);if(r.startsWith("*.")&&!o.includes("*"))return n.endsWith(o)&&n.length>o.length;const s=r.split("."),i=n.split(".");return s.length===i.length&&!s[s.length-1]?.includes("*")&&A(r,n)}const F=/^([^/?#]+\/\/[^/?#]*):\*(?=[/?#]|$)/,N=/^[^/?#]+\/\/[^/?#]*\*$/;function L(e,t){if("*"===e||e===t)return!0;let r;T.has(t)?r=T.get(t):(T.size>=I&&T.clear(),r=q(t),T.set(t,r));const n=function(e){if(void 0===e||!/[^.]\.$/.test(e.hostname))return;const t=new URL(e.href);return t.hostname=e.hostname.slice(0,-1),t.href}(r);if(void 0!==n&&L(e,n))return!0;const o=function(e){const t=e.trim(),r=t.indexOf("://");if(-1===r)return/^[^/?#]*[^.*/?#]\.$/.test(t)?t.slice(0,-1):void 0;if(!t.includes("*"))return;const n=r+3,o=n+(t.slice(n).split(/[/?#]/,1)[0]??"").replace(/:(?:\d+|\*)$/,"").length;return/[^.*]\.$/.test(t.slice(n,o))?`${t.slice(0,o-1)}${t.slice(o)}`:void 0}(e);return!(void 0===o||!L(o,t))||!!r&&(e.includes("://")?function(e,t){const r=N.test(e),n=r||F.test(e),o=e.indexOf("://"),s=e.slice(0,o).toLowerCase(),i=t.protocol.slice(0,-1),a=q((s.includes("*")&&A(s,i)?`${i}${e.slice(o)}`:e).replace(F,"$1"));if(void 0===a||""!==a.username||""!==a.password||""!==t.username||""!==t.password||a.protocol!==t.protocol||!n&&a.port!==t.port)return!1;const c=a.hostname.replace(/%2a/gi,"*");return(O(c,t.hostname)||r&&O(c.replace(/\*$/,""),t.hostname))&&(r||A(`${a.pathname}${a.search}`,`${t.pathname}${t.search}`))}(e,r):h(r.hostname,e))}function j(e,t){if(A(e,t)||L(e,t))return!0;const r=function(e){const t=e.trim();if(t.includes("*")||!t.includes("://"))return;const r=q(t);return void 0!==r&&""===r.search&&""===r.hash?W(r):void 0}(e);if(void 0===r)return!1;const n=q(t.trim());return void 0!==n&&W(n)===r}const U=/%[0-9a-f]{2}/gi,B=/^[A-Za-z0-9\-._~]$/;function W(e){const t="http:"===e.protocol||"https:"===e.protocol?"http(s):":e.protocol,r=e.hostname.endsWith(".")?e.hostname.slice(0,-1):e.hostname,n=""===e.port?"":`:${e.port}`,o=e.pathname.replace(U,(e=>{const t=String.fromCharCode(Number.parseInt(e.slice(1),16));return B.test(t)?t:e.toUpperCase()})).replace(/\/{2,}/g,"/");return`${t}//${r}${n}${o.endsWith("/")?o.slice(0,-1):o}`}function H(e){const t=e.trim().toLowerCase();return t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t}function q(e){const t=e.trim();if(0===t.length)return;const r=t.includes("://")?t:`https://${t}`;try{return new URL(r)}catch{return}}function z(e){return(e.mcpNetworkAllowlist??[]).flatMap((e=>{const t=P(e);return void 0===t?[]:[t]}))}function G(e,t){if(!0!==t.enabled)return{allowed:!0};if("no_sandbox"===t.mcpNetworkMode)return{allowed:!0};if(!D(e))return{allowed:!1,message:t.blockMessage??p};const r=z(t);return r.length>0&&r.some((t=>function(e,t){const r=D(t);if(!r)return!1;if(!e.includes("://"))return h(H(r.hostname),e);if(M(e,t))return!0;const n=function(e){try{const t=new URL(e);if(""!==t.username||""!==t.password||"/"!==t.pathname||""!==t.search||""!==t.hash)return;return`${t.protocol}//${t.host}/*`}catch{return}}(e);return void 0!==n&&M(n,t)}(t,e)))?{allowed:!0}:{allowed:!1,message:t.blockMessage??p}}function V(e){const t=e?.trim();return t&&t.length>0?t:void 0}function K(e){return V(e)?.toLowerCase()}function J(e,t){const r=K(e.builtinServer),n=K(t.builtinServer);if(void 0!==r||void 0!==n)return void 0!==r&&r===n;const o=V(e.command),s=V(e.serverUrl);if(void 0===o&&void 0===s)return!1;const i=void 0===o||void 0!==t.command&&A(o,t.command),a=void 0===s||void 0!==t.url&&L(s,t.url);return i&&a}function Z(e,t,r){return void 0!==r?.command&&void 0===r.url&&void 0===t&&!0===e?.allowUserOverrideMcpServers}function X({allowedMcpConfiguration:e,server:t,localAgentNetworkAllowlist:r,blockMessage:n,unmatchedServerAllowlist:o,aggregateManagedServerNetworkAllowlists:s=!0,stdioPlatform:i,unsandboxUserExtensionStdio:a}){const c=e?.allowedMcpServers,l=function(e){if(!0!==e?.allowUserOverrideMcpServers)return;const t=(e.deniedMcpServers??[]).flatMap((e=>{const t=V(e.serverUrl),r=void 0===t?void 0:function(e){const t=e.trim();if(0===t.length)return;if(function(e){const t=e.indexOf("://");if(-1===t)return!1;const r=e.slice(t+3),n=r.indexOf("/");return-1===n?r.includes("?"):r.slice(n).includes("*")}(t)){const e=t.indexOf("://");if(-1!==e){const r=t.slice(e+3).split(/[/?#]/,1)[0];if(r?.includes("*")){const e=P(r.replace(/:\d+$/,""));if(void 0!==e)return e}}return}if(!t.includes("://")&&t.includes("*")&&"*"!==t&&!t.startsWith("*."))return;const r=P(e);if(void 0!==r)return r;const n=e.indexOf("://");if(-1===n)return;const o=e.slice(0,n).toLowerCase();if("http"!==o&&"https"!==o)return;const s=e.slice(n+3).split(/[/?#]/,1)[0];if(void 0===s||s.includes("@"))return;const i=P(s.replace(/:\d+$/,""));if(void 0!==i)return i;try{return P(new URL(e).hostname)}catch{return}}(t);return void 0===r?[]:[r]}));return t.length>0?t:void 0}(e),u=void 0===t?void 0:function(e,t){return e?.find((e=>J(e,t)))}(c,t),d=Z(e,u,t),h=function({allowedMcpConfiguration:e,matchedServer:t,server:r}){return void 0===r?(e?.allowedMcpServers?.length??0)>0:void 0!==t||Z(e,t,r)}({allowedMcpConfiguration:e,matchedServer:u,server:t})||void 0===t&&void 0!==l,p=void 0===t?s?c?.flatMap((e=>e.networkAllowlist??[])):void 0:d?[]:function(e,t,r){return void 0===e?r:[...e.networkAllowlist??[],...void 0!==V(e.serverUrl)&&void 0!==t.url?[t.url]:[]]}(u,t,o),f=d&&"win32"===i&&!0===a;let m;m=void 0===t?void 0:f?"no_sandbox":d?"allow_all":function(e,t){var r;if(void 0!==V(e?.command)&&void 0!==t.command&&void 0===t.url)return r=e?.networkMode,("allow_all"===r||"allowlist"===r||"deny_all"===r||"no_sandbox"===r?r:void 0)??"no_sandbox"}(u,t);const g=void 0===t||d?l:void 0;return{enabled:h,mcpNetworkAllowlist:p,...void 0!==m?{mcpNetworkMode:m}:{},...void 0!==g?{mcpNetworkDenylist:g}:{},...void 0!==r?{localAgentNetworkAllowlist:r}:{},...void 0!==n?{blockMessage:n}:{},...f?{win32UserExtensionUnsandbox:!0}:{}}}function Q(e){if(!0===e?.enabled&&"no_sandbox"!==e.mcpNetworkMode)return e}},"../shell-exec/dist/api/index.js"(e,t,r){"use strict";r.d(t,{BM:()=>qn,Ls:()=>p,SandboxUnsupportedError:()=>ar,J:()=>E,St:()=>lr,Fn:()=>Hn,Qw:()=>i,ue:()=>o,r5:()=>Pe,getLastSandboxFailureReason:()=>ir,oG:()=>wn,Ko:()=>R,CG:()=>st,W1:()=>J,G6:()=>Wn,dA:()=>Be,_B:()=>Ze,OK:()=>Ke,$b:()=>Je,K3:()=>hr,tv:()=>nt,wG:()=>dt,fZ:()=>pt,s9:()=>at,XX:()=>ut,T6:()=>Qe,Po:()=>Xe,$6:()=>tt,l7:()=>ot,xS:()=>C,resolveSandboxPolicyForWorkspace:()=>wt,spawnInSandbox:()=>ur,Xw:()=>I});const n=["SSH_CLIENT","SSH2_CLIENT"];function o(e){const t=e||process.env,{ELECTRON_RUN_AS_NODE:r,...o}=t;for(const e of Object.keys(o))e.startsWith("AGENT_HOST_DAEMON_")&&delete o[e];for(const e of n)delete o[e];return o}const s="NODE_COMPILE_CACHE";function i(e){const{[s]:t,...r}=e;return r.NODE_DISABLE_COMPILE_CACHE="1",r}const a=["SSH_AUTH_SOCK","DBUS_SESSION_BUS_ADDRESS","XDG_RUNTIME_DIR","WAYLAND_DISPLAY"];function c(e){const t={...e};for(const e of a)delete t[e];return t}const l=[["core.quotePath","false"]];function u(e){const t=function(e){const t=e.GIT_CONFIG_COUNT;if(void 0===t||""===t)return 0;const r=Number.parseInt(t,10);return Number.isFinite(r)&&r>=0?r:0}(e),r=new Set;for(let n=0;n<t;n++){const t=e[`GIT_CONFIG_KEY_${n}`];void 0!==t&&r.add(t.toLowerCase())}let n=t;for(const[t,o]of l)r.has(t.toLowerCase())||(e[`GIT_CONFIG_KEY_${n}`]=t,e[`GIT_CONFIG_VALUE_${n}`]=o,n++);n!==t&&(e.GIT_CONFIG_COUNT=String(n))}var d,h=r("node:perf_hooks");!function(e){e[e.SampleIntervalMs=250]="SampleIntervalMs",e[e.EventLoopResolutionMs=20]="EventLoopResolutionMs"}(d||(d={})),h.monitorEventLoopDelay;const p="\n[This shell is producing too much output to stream. The command will still run.]\n";var f=r("node:path"),m=r("node:fs"),g=r("../utils/dist/lru-cache.js");const w="undefined"!=typeof process&&"win32"===process.platform,y=new g.q({max:512});function v(e){try{return m.statSync(e)}catch{return null}}function b(e,t){if(e.match(/[\\/]/))return e;const r=t?`${e}\0${t.source}\0${t.flags}`:e,n=y.get(r);if(void 0!==n)return n;const o=f.join(".",e);if(v(o))return y.set(r,o),o;const s=process.env.PATH.split(w?";":":");for(const n of s){const o=f.join(n,e);if(v(o)&&(!t||t.test(o)))return y.set(r,o),o}return y.set(r,e),e}function S(e,t,r){if("win32"!==process.platform)return{cmd:b(e),args:t};if(!m.existsSync(e)){const n=[".exe",".bat",".cmd",".ps1"],o=e.toLowerCase();if(n.some((e=>o.endsWith(e)))){const n=b(e,r);if(m.existsSync(n))return S(n,t,r)}for(const o of n){const n=b(`${e}${o}`,r);if(m.existsSync(n))return S(n,t,r)}}return e.match(/\.ps1$/i)?{cmd:f.join(process.env.SYSTEMROOT,"System32","WindowsPowerShell","v1.0","PowerShell.exe"),args:["-ExecutionPolicy","Unrestricted","-NoLogo","-NonInteractive","-File",e].concat(t)}:e.match(/\.(bat|cmd)$/i)?{cmd:f.join(process.env.SYSTEMROOT,"System32","cmd.exe"),args:["/C",e,...t]}:e.match(/\.(js)$/i)?{cmd:process.execPath,args:[e].concat(t)}:{cmd:e,args:t}}let k;const _=["/usr/local/bin","/usr/bin","/bin"];function C(){const e=S("rg",[]).cmd;return"rg"!==e?e:void 0}function E(e){if(!e)throw new Error("configureRipgrepPath: path must not be empty");k=e}function x(e){const t=Object.keys(e).filter((e=>"path"===e.toLowerCase()));if(0!==t.length)return"win32"===process.platform?t.find((e=>"Path"===e))??t[0]:t.find((e=>"PATH"===e))??t[0]}function P(e,t){const r=(0,f.dirname)(t);if(!r||"."===r)return e;let n=function(e){const t=x(e);return void 0!==t?e[t]??"":""}(e).split(f.delimiter).filter(Boolean);return 0===n.length&&"win32"!==process.platform&&(n=_),function(e,t){const r=x(e)??("win32"===process.platform?"Path":"PATH"),n={...e};for(const e of Object.keys(n))e!==r&&"path"===e.toLowerCase()&&delete n[e];return n[r]=t,n}(e,[r,...n.filter((e=>e!==r))].join(f.delimiter))}function I(e){return k&&(0,f.isAbsolute)(k)?{...P(e,k),CURSOR_RIPGREP_PATH:k}:e}function R(){if(!k)throw new Error("Ripgrep path not configured. Call configureRipgrepPath() at startup.");return k}const T="win32"===process.platform;function A(e){return!T&&!!e?.SUDO_ASKPASS}function $(e){return A(e)?"alias sudo='sudo -A'; ":""}function M(e){const t=[];let r=0;for(;r<e.length;){const n=0===r||"&&"===e.slice(Math.max(0,r-2),r)||"||"===e.slice(Math.max(0,r-2),r)||"|"===e[r-1]||";"===e[r-1],o=Math.max(0,r-10),s=e.slice(o,r),i=/(?:&&|\|\||[|;])\s*$/.test(s)||0===r&&/^\s*$/.test(s);if((n||i)&&"sudo"===e.slice(r,r+4)){const n=r+4;if(n>=e.length||/\s/.test(e[n])){let o=n;for(;o<e.length&&/\s/.test(e[o]);)o++;let s=!1;if(o<e.length&&"-"===e[o]){let t=o+1;for(;t<e.length&&/[^\s]/.test(e[t]);)t++;const r=e.slice(o,t);s=/^-[a-zA-Z]*A[a-zA-Z]*$/.test(r)}s?(t.push("sudo"),r=n):(t.push("sudo -A"),r=n);continue}}t.push(e[r]),r++}return t.join("")}function D(e,t){const r=t.toUpperCase();return Object.entries(e).some((([e,t])=>void 0!==t&&e.toUpperCase()===r))}const O=["PYTHONIOENCODING","PYTHONUTF8","PYTHONLEGACYWINDOWSSTDIO"];function F(e){O.some((t=>D(e,t)))||(e.PYTHONIOENCODING="utf-8:surrogateescape")}function N(e){D(e,"WSL_UTF8")||(e.WSL_UTF8="1")}const L="-Dsun.stdout.encoding=UTF-8 -Dsun.stderr.encoding=UTF-8 -Dstdout.encoding=UTF-8 -Dstderr.encoding=UTF-8",j=["sun.stdout.encoding","sun.stderr.encoding","stdout.encoding","stderr.encoding"],U=`case " \${MAVEN_OPTS-} \${JAVA_TOOL_OPTIONS-} \${JDK_JAVA_OPTIONS-} \${_JAVA_OPTIONS-} " in ${j.map((e=>`*[[:space:]]-D${e}=*`)).join("|")}) ;; *) builtin export MAVEN_OPTS="\${MAVEN_OPTS:+$MAVEN_OPTS }${L}";; esac; `,B=`if ("$env:MAVEN_OPTS $env:JAVA_TOOL_OPTIONS $env:JDK_JAVA_OPTIONS \${env:_JAVA_OPTIONS}" -cnotmatch '(^|\\s)-D(${j.map((e=>e.replace(/\./g,"\\."))).join("|")})=') {\n if ($env:MAVEN_OPTS) { $env:MAVEN_OPTS = "$env:MAVEN_OPTS ${L}" } else { $env:MAVEN_OPTS = '${L}' }\n}`;var W=r("node:crypto"),H=r("node:os"),q=r("../utils/dist/workspace-paths.js"),z=r("../utils/dist/test-resets.js");let G;function V(e,t){const r=(0,m.lstatSync)(e);return r.isDirectory()&&r.uid===t&&!(18&r.mode)}function K(e){try{(0,m.mkdirSync)(e,{mode:448})}catch(e){if(!(e instanceof Error&&"code"in e&&"EEXIST"===e.code))throw e}}function J(e){return Z(e,{create:!1})}function Z(e,{create:t}){const r=process.getuid?.();if(void 0===r)return;const n=(0,f.join)((0,H.tmpdir)(),`cursor-sandbox-${(0,q.r_)((0,f.resolve)(e))}`);try{for(const e of[n,(0,f.join)(n,"tmp")])if(t&&K(e),!V(e,r))return;return n}catch{return}}(0,z.J)((function(){G=void 0}));const X='builtin eval "${__CURSOR_SANDBOX_TEMP_RESTORE:-}" 2>/dev/null; ',Q=["TMPDIR","TMP","TEMP","TMPPREFIX","NODE_COMPILE_CACHE","NODE_DISABLE_COMPILE_CACHE"],Y="builtin export NODE_DISABLE_COMPILE_CACHE=1; builtin unset NODE_COMPILE_CACHE; ";function ee(e=(0,f.join)((0,H.tmpdir)(),"cursor-sandbox-cache",function(){return G||(G=(0,W.randomBytes)(16).toString("hex")),G}())){return{NPM_CONFIG_CACHE:(0,f.join)(e,"npm"),PNPM_STORE_PATH:(0,f.join)(e,"pnpm-store"),GOCACHE:(0,f.join)(e,"go-build"),GOMODCACHE:(0,f.join)(e,"go-mod"),CARGO_TARGET_DIR:(0,f.join)(e,"cargo-target"),PIP_CACHE_DIR:(0,f.join)(e,"pip"),UV_CACHE_DIR:(0,f.join)(e,"uv"),BUN_INSTALL_CACHE_DIR:(0,f.join)(e,"bun"),YARN_CACHE_FOLDER:(0,f.join)(e,"yarn"),npm_config_devdir:(0,f.join)(e,"node-gyp"),PLAYWRIGHT_BROWSERS_PATH:(0,f.join)(e,"playwright"),PUPPETEER_CACHE_DIR:(0,f.join)(e,"puppeteer"),TURBO_CACHE_DIR:(0,f.join)(e,"turbo"),GRADLE_USER_HOME:(0,f.join)(e,"gradle"),CONDA_PKGS_DIRS:(0,f.join)(e,"conda"),POETRY_CACHE_DIR:(0,f.join)(e,"poetry"),GEM_SPEC_CACHE:(0,f.join)(e,"gem-specs"),BUNDLE_PATH:(0,f.join)(e,"bundle"),COMPOSER_HOME:(0,f.join)(e,"composer"),HOMEBREW_CACHE:(0,f.join)(e,"homebrew"),CYPRESS_CACHE_FOLDER:(0,f.join)(e,"cypress"),NX_CACHE_DIRECTORY:(0,f.join)(e,"nx"),NUGET_PACKAGES:(0,f.join)(e,"nuget"),CCACHE_DIR:(0,f.join)(e,"ccache"),CP_HOME_DIR:(0,f.join)(e,"cocoapods")}}var te=r("node:fs/promises"),re=r("../utils/dist/safe-spawn-cwd.js"),ne=r("../../node_modules/.pnpm/ignore@7.0.5/node_modules/ignore/index.js");function oe(){const e=process.env.CURSOR_SANDBOX_POLICY_DIR?.trim();return e?f.resolve(e):f.resolve(f.join(H.homedir(),".cursor","sandbox-policies"))}let se=0;function ie(){const e=oe();m.mkdirSync(e,{recursive:!0,mode:448});try{m.chmodSync(e,448)}catch{}const t=Date.now();return t-se>=9e5&&(se=t,function(e){let t;try{t=m.readdirSync(e)}catch{return}const r=Date.now();for(const n of t){if(!n.startsWith("sandbox-policy-"))continue;const t=f.join(e,n);try{const e=m.statSync(t);if(!e.isFile())continue;r-e.mtimeMs>36e5&&m.unlinkSync(t)}catch{}}}(e)),e}function ae(e){const t=ie(),r=W.randomBytes(8).toString("hex"),n=f.join(t,`sandbox-policy-${r}`);return m.writeFileSync(n,e,{encoding:"utf-8",mode:384}),n}const ce="/tmp/node-compile-cache",le="cursor-compile-cache",ue=Symbol.for("cursor.startupNodeCompileCache"),de=process.platform;function he(e=H.tmpdir(),t=process.platform){if("win32"===t||0===e.length)return[];const r=f.posix.join(e,"node-compile-cache");return r===ce?[]:[r]}function pe(e=H.tmpdir(),t=process.env,r=process.platform){if("win32"===r)return[];const n=new Set(he(e,r));for(const e of["TMPDIR","TMP","TEMP"]){const o=t[e];if(void 0!==o&&f.posix.isAbsolute(o))for(const e of he(f.posix.resolve(o),r))n.add(e)}return[...n]}function fe(e=process.env,t=H.homedir(),r=process.platform){if("darwin"===r)return t.length>0?f.posix.join(t,"Library/Caches",le):void 0;if("linux"!==r)return;const n=e.XDG_CACHE_HOME;return void 0!==n&&f.posix.isAbsolute(n)?f.posix.join(n,le):t.length>0?f.posix.join(t,".cache",le):void 0}function me(e=process.env,t=process.platform){if("win32"===t)return;const r=Object.getOwnPropertyDescriptor(globalThis,ue)?.value,n="string"==typeof r?r:e.NODE_COMPILE_CACHE;if(void 0===n||!f.posix.isAbsolute(n))return;const o=f.posix.resolve(n);return"/"===o?void 0:o}function ge(e=H.homedir(),t=H.tmpdir(),r=process.env,n=process.platform){if("win32"===n)return[];const o=new Set([ce]);e.length>0&&(o.add(f.posix.join(e,".cache",le)),o.add(f.posix.join(e,"Library/Caches",le)));const s=[];for(const i of[...pe(t,r,n),fe(r,e,n),me(r,n)])void 0===i||o.has(i)||(o.add(i),s.push(i));return s}function we(e=H.homedir(),t=H.tmpdir(),r=process.platform,n=process.env){if("win32"===r)return[];const o=[ce,...pe(t,n,r)],s=fe(n,e,r);return void 0===s||o.includes(s)||o.push(s),o}function ye(e,t){return e.isSymbolicLink()?"a link, not followed":e.isDirectory()?e.uid!==t?`owned by uid ${e.uid}`:void 0:"not a folder"}function ve(e){return"object"!=typeof e||null===e?{}:Object.fromEntries(Object.entries(e).filter((e=>"string"==typeof e[1])))}function be(e){return"object"==typeof e&&null!==e&&"code"in e&&"string"==typeof e.code?e.code:"error"}const Se=[".local/bin",".local/share/mise",".local/share/pnpm",".nvm",".volta",".asdf",".pyenv",".rbenv",".rustup",".cargo/bin",".cargo/registry",".cargo/git"],ke=["bin","sbin","lib","opt","Cellar","share","Frameworks","etc/gitconfig","etc/openssl@3/cert.pem","etc/openssl@3/openssl.cnf","etc/ca-certificates"],_e=(e,t)=>t.flatMap((t=>ke.map((r=>({platform:e,scope:"global",path:`${t}/${r}`}))))),Ce={linux:[".cache/node",".cache/yarn"],darwin:[".cache/node","Library/Caches/Yarn"]},Ee=e=>[...Se,...Ce[e]].map((t=>({platform:e,scope:"home-dir",path:t}))),xe=[{platform:"linux",scope:"global",path:"/bin"},{platform:"linux",scope:"global",path:"/sbin"},{platform:"linux",scope:"global",path:"/usr/bin"},{platform:"linux",scope:"global",path:"/usr/sbin"},{platform:"linux",scope:"global",path:"/lib"},{platform:"linux",scope:"global",path:"/lib64"},{platform:"linux",scope:"global",path:"/usr/lib"},{platform:"linux",scope:"global",path:"/usr/lib64"},{platform:"linux",scope:"global",path:"/usr/libexec"},{platform:"linux",scope:"global",path:"/usr/share"},{platform:"linux",scope:"global",path:"/etc/ld.so.cache"},{platform:"linux",scope:"global",path:"/etc/ld.so.conf"},{platform:"linux",scope:"global",path:"/etc/ld.so.conf.d"},{platform:"linux",scope:"global",path:"/etc/ssl/certs"},{platform:"linux",scope:"global",path:"/etc/ssl/openssl.cnf"},{platform:"linux",scope:"global",path:"/etc/ssl/cert.pem"},{platform:"linux",scope:"global",path:"/etc/ssl/ca-bundle.pem"},{platform:"linux",scope:"global",path:"/etc/ssl/certs/ca-certificates.crt"},{platform:"linux",scope:"global",path:"/etc/pki/tls/certs"},{platform:"linux",scope:"global",path:"/etc/pki/tls/openssl.cnf"},{platform:"linux",scope:"global",path:"/etc/pki/ca-trust/extracted"},{platform:"linux",scope:"global",path:"/etc/resolv.conf"},{platform:"linux",scope:"global",path:"/etc/hosts"},{platform:"linux",scope:"global",path:"/etc/nsswitch.conf"},{platform:"linux",scope:"global",path:"/etc/gai.conf"},{platform:"linux",scope:"global",path:"/etc/alternatives"},{platform:"linux",scope:"global",path:"/etc/mime.types"},{platform:"linux",scope:"global",path:"/etc/profile"},{platform:"linux",scope:"global",path:"/etc/bash.bashrc"},{platform:"linux",scope:"global",path:"/etc/zsh/zshenv"},{platform:"linux",scope:"global",path:"/etc/zsh/zprofile"},{platform:"linux",scope:"global",path:"/etc/zsh/zshrc"},{platform:"linux",scope:"global",path:"/etc/zsh/zlogin"},{platform:"linux",scope:"global",path:"/etc/gitconfig"},{platform:"linux",scope:"home",path:".bashrc"},{platform:"linux",scope:"home",path:".bash_profile"},{platform:"linux",scope:"home",path:".profile"},{platform:"linux",scope:"home",path:".zshenv"},{platform:"linux",scope:"home",path:".zprofile"},{platform:"linux",scope:"home",path:".zshrc"},{platform:"linux",scope:"home",path:".zlogin"},{platform:"linux",scope:"home",path:".gitconfig"},{platform:"linux",scope:"home",path:".ssh/known_hosts"},{platform:"linux",scope:"home",path:".config/mise/config.toml"},{platform:"linux",scope:"home-dir",path:".cache/dotslash"},...Ee("linux"),..._e("linux",["/usr/local","/home/linuxbrew/.linuxbrew"]),{platform:"linux",scope:"global",path:"/usr/local/go"},{platform:"linux",scope:"global",path:"/nix/store"},{platform:"linux",scope:"global",path:"/nix/var/nix/profiles"},{platform:"linux",scope:"bundled",path:"ripgrep"},{platform:"darwin",scope:"global",path:"/bin"},{platform:"darwin",scope:"global",path:"/usr/bin"},{platform:"darwin",scope:"global",path:"/usr/lib"},{platform:"darwin",scope:"global",path:"/usr/libexec"},{platform:"darwin",scope:"global",path:"/usr/share"},{platform:"darwin",scope:"global",path:"/System/Library"},{platform:"darwin",scope:"global",path:"/System/Cryptexes"},{platform:"darwin",scope:"global",path:"/Library/Apple"},{platform:"darwin",scope:"global",path:"/Library/Developer/CommandLineTools"},{platform:"darwin",scope:"global",path:"/Applications/Xcode.app"},{platform:"darwin",scope:"global",path:"/Library/Preferences/com.apple.dt.Xcode.plist"},{platform:"darwin",scope:"global",path:"/private/etc/ssl/cert.pem"},{platform:"darwin",scope:"global",path:"/private/etc/ssl/certs"},{platform:"darwin",scope:"global",path:"/private/etc/ssl/openssl.cnf"},{platform:"darwin",scope:"global",path:"/private/etc/hosts"},{platform:"darwin",scope:"global",path:"/private/etc/resolv.conf"},{platform:"darwin",scope:"global",path:"/private/etc/apache2/mime.types"},{platform:"darwin",scope:"global",path:"/etc/profile"},{platform:"darwin",scope:"global",path:"/etc/bashrc"},{platform:"darwin",scope:"global",path:"/etc/zshenv"},{platform:"darwin",scope:"global",path:"/etc/zprofile"},{platform:"darwin",scope:"global",path:"/etc/zshrc"},{platform:"darwin",scope:"global",path:"/etc/zlogin"},{platform:"darwin",scope:"global",path:"/etc/gitconfig"},{platform:"darwin",scope:"home",path:".bashrc"},{platform:"darwin",scope:"home",path:".bash_profile"},{platform:"darwin",scope:"home",path:".profile"},{platform:"darwin",scope:"home",path:".zshenv"},{platform:"darwin",scope:"home",path:".zprofile"},{platform:"darwin",scope:"home",path:".zshrc"},{platform:"darwin",scope:"home",path:".zlogin"},{platform:"darwin",scope:"home",path:".gitconfig"},{platform:"darwin",scope:"home",path:".ssh/known_hosts"},{platform:"darwin",scope:"home",path:"Library/Preferences/.GlobalPreferences.plist"},{platform:"darwin",scope:"home",path:".config/mise/config.toml"},{platform:"darwin",scope:"home-dir",path:"Library/Python"},{platform:"darwin",scope:"home-dir",path:"Library/Caches/dotslash"},...Ee("darwin"),..._e("darwin",["/opt/homebrew","/usr/local"]),{platform:"darwin",scope:"global",path:"/nix/store"},{platform:"darwin",scope:"global",path:"/nix/var/nix/profiles"},{platform:"darwin",scope:"bundled",path:"ripgrep"},{platform:"darwin",scope:"global",path:"/dev/null"},{platform:"darwin",scope:"global",path:"/dev/zero"},{platform:"darwin",scope:"global",path:"/dev/random"},{platform:"darwin",scope:"global",path:"/dev/urandom"}];function Pe(e=process.platform,t=H.homedir(),r={}){const n=[];for(const o of xe){if(o.platform!==e)continue;if("global"===o.scope){n.push(o.path);continue}const s="bundled"===o.scope?r[o.path]:(0,f.join)(t,o.path);if(s)try{let e;switch(o.scope){case"home":e=(0,m.lstatSync)(s).isFile();break;case"home-dir":e=(0,m.lstatSync)(s).isDirectory();break;case"bundled":e=(0,m.statSync)(s).isFile()}e&&n.push(s)}catch{}}return n}const Ie=[{type:"workspace",pattern:"**/.cursor/*.json"},{type:"workspace",pattern:"**/.cursor/**/*.json"},{type:"workspace",pattern:"**/.cursor/.workspace-trusted"},{type:"workspace",pattern:"!**/.cursor/rules"},{type:"workspace",pattern:"!**/.cursor/rules/**"},{type:"workspace",pattern:"!**/.cursor/commands"},{type:"workspace",pattern:"!**/.cursor/commands/**"},{type:"workspace",pattern:"!**/.cursor/worktrees"},{type:"workspace",pattern:"!**/.cursor/worktrees/**"},{type:"workspace",pattern:"!**/.cursor/skills"},{type:"workspace",pattern:"!**/.cursor/skills/**"},{type:"workspace",pattern:"!**/.cursor/agents"},{type:"workspace",pattern:"!**/.cursor/agents/**"},{type:"workspace",pattern:"**/.claude/*.json"},{type:"workspace",pattern:"**/.claude/**/*.json"},{type:"workspace",pattern:"**/.vscode/**"},{type:"workspace",pattern:"**/.idea/**"},{type:"workspace",pattern:"**/.venv/"},{type:"workspace",pattern:"**/venv/"},{type:"workspace",pattern:"**/*.code-workspace"},{type:"workspace",pattern:"**/.cursorignore"},{type:"workspace",pattern:"**/.workspace-trusted"},{type:"workspace",pattern:"**/.cursor/**/cli.json"},{type:"workspace",pattern:"**/.cursor/**/cli-config.json"},{type:"workspace",pattern:"**/.cursor/**/mcp.json"},{type:"workspace",pattern:"**/.cursor/**/mcp-approvals.json"},{type:"workspace",pattern:"**/.cursor/**/permissions.json"},{type:"git",pattern:"**/.git/hooks/**"},{type:"git",pattern:"**/.git/config"},{type:"git",pattern:"**/.git/config.worktree"},{type:"git",pattern:"**/.git/info/attributes"},{type:"git",pattern:"**/.git/commondir"},{type:"git",pattern:"**/.git/worktrees/*/commondir"},{type:"git",pattern:"**/.git/worktrees/*/gitdir"},{type:"worktree",pattern:".git"},{type:"absolute",pattern:"/etc/ssl/cert.pem"},{type:"absolute",pattern:"/etc/ssl/ca-bundle.pem"},{type:"absolute",pattern:"/private/etc/ssl/cert.pem"},{type:"absolute",pattern:"/etc/ssl/certs/ca-certificates.crt"},{type:"absolute",pattern:"/etc/pki/tls/certs/ca-bundle.crt"},{type:"absolute",pattern:"/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem"},{type:"home",pattern:".cursor/sandbox-policies"},{type:"absolute",pattern:"/tmp/node-compile-cache"},{type:"home",pattern:".cache/cursor-compile-cache"},{type:"home",pattern:"Library/Caches/cursor-compile-cache"}];function Re(e){const t=Ie.filter((e=>"workspace"===e.type)).map((e=>e.pattern));return{[e]:t}}function Te(e){const t=Ie.filter((e=>"git"===e.type)).map((e=>e.pattern));return{[e]:t}}function Ae(e){const t=Ie.filter((e=>"worktree"===e.type)).map((e=>e.pattern));return{[e]:t}}Ie.filter((e=>"git"===e.type)).map((e=>e.pattern)),Ie.filter((e=>"workspace"===e.type&&e.pattern.startsWith("!")&&!e.pattern.endsWith("/**"))).map((e=>e.pattern.replace(/^!(\*\*\/)?/,"")));const $e=[];let Me=null,De=null;function Oe(e){if(!(e instanceof Error&&"code"in e&&"string"==typeof e.code)||e.code.startsWith("ERR_"))throw e}async function Fe(e,t=""){const r=await(0,te.lstat)(e).catch(Oe);if(void 0===r||!r.isFile()||r.size>4096)return;const n=await(0,te.readFile)(e,"utf8").catch(Oe),o=n?.split("\n",1)[0]?.replace(/\r$/,"");if(void 0===o||!o.startsWith(t))return;const s=o.slice(t.length);return s.length>0&&!s.includes("\0")?s:void 0}async function Ne(e){if(!(0,re.$f)(e))return(0,te.realpath)(e).catch(Oe)}async function Le(e){const t=await Fe((0,f.join)(e,".git"),"gitdir: ");if(void 0===t)return;const r=await Ne((0,f.resolve)(e,t));if(void 0===r)return;const n=await Fe((0,f.join)(r,"commondir")),o=void 0===n?r:await Ne((0,f.resolve)(r,n));return void 0===o?void 0:{gitDir:r,commonDirLink:n,commonDir:o}}async function je(e){const t=await Le(e);if(void 0===t||void 0===t.commonDirLink||"worktrees"!==(0,f.basename)((0,f.dirname)(t.gitDir)))return;const r=(0,f.dirname)((0,f.dirname)(t.gitDir));if(".git"!==(0,f.basename)(r)||(He?t.commonDir.toLowerCase()!==r.toLowerCase():t.commonDir!==r))return;const n=await Fe((0,f.join)(t.gitDir,"gitdir"));if(void 0===n)return;const o=(0,f.join)(e,".git"),[s,i]=await Promise.all([Ne((0,f.resolve)(t.gitDir,n)),Ne(o)]);return void 0!==s&&void 0!==i&&(He?s.toLowerCase()===i.toLowerCase():s===i)?r:void 0}let Ue=null;function Be(e){return function(){const e=H.homedir();if(null===Ue){const t=[];for(const r of Ie)switch(r.type){case"absolute":t.push(r.pattern);break;case"home":e.length>0&&t.push((0,f.join)(e,r.pattern))}Ue=t}return[...Ue,...ge(e)]}().some((t=>{if(Ge(e,t))return!0;const r=function(e){let t;try{t=m.realpathSync.native((0,f.dirname)(e))}catch(e){const t=e instanceof Error&&"code"in e?e.code:void 0;return"ENOENT"===t||"ENOTDIR"===t?void 0:We}const r=(0,f.join)(t,(0,f.basename)(e));return r===(0,f.dirname)(r)?void 0:r}(t);return r===We||void 0!==r&&Ge(e,r)}))}const We=Symbol("unresolved parent");const He="win32"===process.platform||"darwin"===process.platform;function qe(e){if(!e.endsWith(f.sep))return e;const t=e.slice(0,-1);return""===t||"win32"===process.platform&&/^[a-zA-Z]:$/.test(t)?e:t}function ze(e){return e.endsWith(f.sep)?e:e+f.sep}function Ge(e,t){const r=qe(t);if(He){const t=e.toLowerCase(),n=r.toLowerCase();return t===n||t.startsWith(ze(n))}return e===r||e.startsWith(ze(r))}function Ve(e,t){const r=qe(e);return He?(0,f.relative)(r.toLowerCase(),t.toLowerCase()).replace(/\\/g,"/"):(0,f.relative)(r,t).replace(/\\/g,"/")}async function Ke(e,t){if(Ge(e,t)){const r=Ve(t,e);if((null===Me&&(Me=ne({ignoreCase:!0}),Me.add(Ie.filter((e=>"workspace"===e.type)).map((e=>e.pattern)))),Me).ignores(r))return!0}const{isWorktree:r,gitDirParent:n}=await async function(e){const t=await(0,te.lstat)((0,f.join)(e,".git")).catch(Oe);if(!t?.isFile())return{isWorktree:!1,gitDirParent:e};const r=await async function(e){return(await Le(e))?.commonDir}(e);return{isWorktree:!0,gitDirParent:void 0===r?e:(0,f.dirname)(r)}}(t);for(const r of new Set([n,t]))if(Ge(e,r)){const t=Ve(r,e);if((null===De&&(De=ne({ignoreCase:!0}),De.add(Ie.filter((e=>"git"===e.type)).map((e=>e.pattern)))),De).ignores(t))return!0}return!(!r||!Ge(e,t)||".git"!==Ve(t,e))||Be(e)}function Je(e){return void 0!==e&&("allow"===e.default||void 0!==e.allow&&e.allow.length>0)}function Ze(e){return void 0!==e&&"allow"===e.default}function Xe(){return{version:1,default:"deny"}}function Qe(){return{version:1,default:"allow"}}var Ye=r("../utils/dist/path-utils.js");function et(e){if(!e)return;const t={version:1};if("allow"!==e.default&&"deny"!==e.default||(t.default=e.default),Array.isArray(e.allow)&&e.allow.length>0&&(t.allow=e.allow.filter((e=>"string"==typeof e))),Array.isArray(e.deny)&&e.deny.length>0&&(t.deny=e.deny.filter((e=>"string"==typeof e))),e.logging){const r={};"string"==typeof e.logging.decisionLogPath&&(r.decisionLogPath=e.logging.decisionLogPath),"jsonl"===e.logging.logFormat&&(r.logFormat="jsonl"),Object.keys(r).length>0&&(t.logging=r)}return t}function tt(e){const t=e.type??"workspace_readwrite",r={debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,enableSharedBuildCache:e.enableSharedBuildCache};if("insecure_none"===t)return{type:"insecure_none",...r};let n;if(Array.isArray(e.additionalReadonlyPaths)){const t=e.additionalReadonlyPaths;n=t.length>0?t:void 0}const o={...r,networkAccess:e.networkAccess,networkPolicy:et(e.networkPolicy),networkPolicyStrict:e.networkPolicyStrict,additionalReadonlyPaths:n,readBoundary:e.readBoundary,additionalReadPaths:Array.isArray(e.additionalReadPaths)?e.additionalReadPaths:void 0,disableTmpWrite:e.disableTmpWrite};return"workspace_readonly"===t?{type:"workspace_readonly",...o}:{type:"workspace_readwrite",...o,additionalReadwritePaths:e.additionalReadwritePaths}}function rt(e){if("object"!=typeof e||null===e)return"Expected an object";const t=Object.fromEntries(Object.entries(e));if(void 0!==t.type){const e=["insecure_none","workspace_readwrite","workspace_readonly"];if("string"!=typeof t.type||!e.includes(t.type))return`Invalid type: expected one of ${e.join(", ")}`}const r=["networkAccess","networkPolicyStrict","disableTmpWrite","enableSharedBuildCache","captureDenies"];for(const e of r)if(void 0!==t[e]&&"boolean"!=typeof t[e])return`Invalid ${e}: expected boolean`;const n=["debugOutputDir"];for(const e of n)if(void 0!==t[e]&&"string"!=typeof t[e])return`Invalid ${e}: expected string`;const o=["additionalReadwritePaths","additionalReadonlyPaths","additionalReadPaths"];for(const e of o)if(void 0!==t[e]){if(!Array.isArray(t[e]))return`Invalid ${e}: expected array`;if(!t[e].every((e=>"string"==typeof e)))return`Invalid ${e}: expected array of strings`}if(void 0!==t.readBoundary&&"system"!==t.readBoundary&&"workspace"!==t.readBoundary)return'Invalid readBoundary: expected "system" or "workspace"';if(void 0!==t.networkPolicy){if("object"!=typeof t.networkPolicy||null===t.networkPolicy)return"Invalid networkPolicy: expected object";const e=Object.fromEntries(Object.entries(t.networkPolicy));if(void 0!==e.default&&"allow"!==e.default&&"deny"!==e.default)return'Invalid networkPolicy.default: expected "allow" or "deny"';if(void 0!==e.allow&&!Array.isArray(e.allow))return"Invalid networkPolicy.allow: expected array";if(void 0!==e.deny&&!Array.isArray(e.deny))return"Invalid networkPolicy.deny: expected array"}}async function nt(e,t){const r=await async function(e,t){try{const r=await(0,te.readFile)(e,"utf-8"),n=JSON.parse(r);if(void 0!==rt(n))return{success:!1,error:`Invalid sandbox policy: ${rt(n)??""}`};let o=tt(n);return t&&(o=ot(o,t)),{success:!0,policy:o}}catch(e){return e instanceof Error?"code"in e&&"ENOENT"===e.code?{success:!1,error:"File not found"}:e instanceof SyntaxError?{success:!1,error:`Invalid JSON: ${e.message}`}:{success:!1,error:e.message}:{success:!1,error:"Unknown error"}}}(e,t);if(r.success)return r.policy}function ot(e,t){if("insecure_none"===e.type)return e;const r=e.additionalReadonlyPaths?.map((e=>(0,Ye.o1)(e,t))),n=e.additionalReadPaths?.map((e=>(0,Ye.o1)(e,t)));if("workspace_readonly"===e.type)return{...e,additionalReadonlyPaths:r,additionalReadPaths:n};const o=e.additionalReadwritePaths?.map((e=>(0,Ye.o1)(e,t)));return{...e,additionalReadonlyPaths:r,additionalReadPaths:n,additionalReadwritePaths:o}}function st(e){return e.teamAdmin?.type??e.perRepo?.type??e.perUser?.type??"insecure_none"}function it(...e){return e.some((e=>!0===e))}function at(...e){const t=new Set;for(const r of e)if(r)for(const e of r)t.add(ht(e));return[...t]}const ct=function({defaultValue:e,rank:t}){return{defaultValue:e,merge:(...r)=>{const n=r.filter((e=>void 0!==e));return 0===n.length?e:n.reduce(((e,r)=>t[r]<t[e]?r:e))}}}({defaultValue:"system",rank:{workspace:0,system:1}}),lt=(...e)=>function(...e){const t=e.filter((e=>void 0!==e));if(0===t.length)return[];if(t.some((e=>0===e.length)))return[];if(1===t.length)return function(e){const t=new Set,r=[];for(const n of e){const e=ht(n);t.has(e)||(t.add(e),r.push(n))}return r}(t[0]).map(ht);let r=new Set(t[0].map(ht));for(let e=1;e<t.length;e++){const n=new Set(t[e].map(ht));r=new Set([...r].filter((e=>n.has(e))))}return[...r]}(...e);function ut(...e){return ct.merge(...e)}function dt(...e){return lt(...e)}function ht(e){const t=e.replace(/\\/g,"/").replace(/\/+$/,"");return""===t?"/":/^[a-zA-Z]:$/.test(t)?`${t}/`:t}function pt(...e){const t=e.filter((e=>void 0!==e));if(0===t.length)return;let r;for(const e of t){if("deny"===e.default){r="deny";break}"allow"===e.default&&void 0===r&&(r="allow")}const n=new Set;for(const e of t)if(e.deny)for(const t of e.deny)n.add(t);const o=new Set;for(const e of t)if(e.allow)for(const t of e.allow)o.add(t);const s=o.size>0?[...o]:void 0;let i;for(let e=t.length-1;e>=0;e--)if(void 0!==t[e].logging){i=t[e].logging;break}const a={version:1};return void 0!==r&&(a.default=r),void 0!==s&&(a.allow=s),n.size>0&&(a.deny=[...n]),void 0!==i&&(a.logging=i),void 0!==a.default||void 0!==a.allow&&0!==a.allow.length||void 0!==a.deny&&0!==a.deny.length||void 0!==a.logging?a:void 0}function ft(e,t){if(!e||0===e.length)return[...t];const r=new Set(e);for(const e of t)r.has(e)&&r.delete(e),r.add(e);return[...r]}function mt(...e){const t=e.filter((e=>void 0!==e));if(0===t.length)return;const r={};for(const e of t)for(const[t,n]of Object.entries(e))r[t]=ft(r[t],n);return 0!==Object.keys(r).length?r:void 0}function gt(...e){for(let t=e.length-1;t>=0;t--)if(void 0!==e[t])return e[t]}async function wt(e,t,r={}){if(!t)return{policy:{type:"insecure_none"}};if((0,re.$f)(e))return St(t,{workspaceDir:e});if("workspace_readwrite"!==(bt(t)??"workspace_readwrite"))return St(t,{workspaceDir:e});const n=r.stat??te.stat,o=await async function(e,t){for(let r=e;;r=(0,f.dirname)(r)){if((0,re.$f)(r))return;const e=await yt(r,t);if(void 0!==e)return e;if((0,f.dirname)(r)===r)return}}(e,n);let s=o?.root??e;if(o?.isFile){const e=await je(o.root);void 0!==e&&(s=(0,f.dirname)(e)),t=vt(t,void 0===e?[]:[e],Ae(o.root))}return t=await async function(e,t,r){const n=_t(e,"workspace_readwrite"),o=at(n.perUser?.additionalReadwritePaths,n.perRepo?.additionalReadwritePaths,n.teamAdmin?.additionalReadwritePaths);if(0===o.length)return e;const s=(await Promise.all(o.map((async e=>{if(t.has(ht(e))||(0,re.$f)(e))return[];const n=await yt(e,r);if(void 0===n)return[];const o=[Re(e),Te(e)];if(n.isFile){o.push(Ae(e));const t=await je(e);void 0!==t&&o.push(Te((0,f.dirname)(t)))}return o})))).flat();return 0===s.length?e:vt(e,[],...s)}(t,new Set([ht(e)]),n),St(t,{workspaceDir:e,gitDirParent:s})}async function yt(e,t){const r=await t((0,f.join)(e,".git")).catch(Oe);return r?.isFile()||r?.isDirectory()?{root:e,isFile:r.isFile()}:void 0}function vt(e,t,...r){const n="workspace_readwrite"===e.perRepo?.type||void 0===e.perRepo?e.perRepo:void 0;return{...e,perRepo:{...n,type:"workspace_readwrite",additionalReadwritePaths:t.length>0?[...n?.additionalReadwritePaths??[],...t]:n?.additionalReadwritePaths,writeProtectionMapping:mt(n?.writeProtectionMapping,...r)}}}function bt(e){const{perUser:t,perRepo:r,teamAdmin:n}=e,o=[t,r,n].filter((e=>void 0!==e));if(0===o.length)return;const s=o[0].type;for(const e of o)if(e.type!==s)throw new Error(`Cannot merge policies of different types: found "${s}" and "${e.type}". All policies must be of the same type (all workspace_readwrite, all workspace_readonly, or all insecure_none).`);return s}function St(e,t){return function(e,t){const r=bt(e);if(void 0===r)return xt({},t);switch(r){case"workspace_readwrite":return xt(_t(e,r),t);case"workspace_readonly":return function(e,t){const r=t?.debug,n=Ct(e,t),o={policy:Et({type:"workspace_readonly",disableTmpWrite:n.disableTmpWrite,networkPolicyStrict:n.networkPolicyStrict,readBoundary:n.readBoundary,additionalReadPaths:n.additionalReadPaths,additionalReadonlyPaths:n.additionalReadonlyPaths,networkPolicy:n.networkPolicy,debugOutputDir:n.debugOutputDir,captureDenies:n.captureDenies,enableSharedBuildCache:n.enableSharedBuildCache,ignoreMapping:n.ignoreMapping,writeProtectionMapping:n.writeProtectionMapping},"workspace_readonly")};return r&&(o.debug={fieldSources:n.fieldSources}),o}(_t(e,r),t);case"insecure_none":return function(e,t){const{perUser:r,perRepo:n,teamAdmin:o}=e,s=t?.debug,i={policy:Et({type:"insecure_none",allowlistEscalated:it(r?.allowlistEscalated,n?.allowlistEscalated,o?.allowlistEscalated)||void 0,debugOutputDir:gt(r?.debugOutputDir,n?.debugOutputDir,o?.debugOutputDir),captureDenies:it(r?.captureDenies,n?.captureDenies,o?.captureDenies)||void 0,enableSharedBuildCache:gt(r?.enableSharedBuildCache,n?.enableSharedBuildCache,o?.enableSharedBuildCache)},"insecure_none")};return s&&(i.debug={fieldSources:{}}),i}(_t(e,r),t);default:throw new Error(`Unknown policy type: ${String(r)}`)}}(e,t)}function kt(e,t){return e?.type===t}function _t(e,t){const{perUser:r,perRepo:n,teamAdmin:o}=e;return{perUser:kt(r,t)?r:void 0,perRepo:kt(n,t)?n:void 0,teamAdmin:kt(o,t)?o:void 0}}function Ct(e,t){const r=t?.debug,{perUser:n,perRepo:o,teamAdmin:s}=e,i=t?.workspaceDir??process.cwd(),a=function(e){const t=function(){if(0!==$e.length)return{version:1,deny:[...$e]}}(),r=H.homedir(),n=[];for(const e of Ie)switch(e.type){case"workspace":case"git":case"worktree":break;case"absolute":n.push(e.pattern);break;case"home":r.length>0&&n.push((0,f.join)(r,e.pattern));break;default:{const t=e.type;throw new Error(`Unknown entry type: ${String(t)}`)}}return n.push(...ge(r)),{type:"workspace_readwrite",additionalReadonlyPaths:n,writeProtectionMapping:Re(e),...t&&{networkPolicy:t},networkPolicyStrict:!0}}(i),c={},l=[n,o,s],u=["perUser","perRepo","teamAdmin","hardcoded"],d=(e,t)=>{r&&(c[e]=u[t]??"unknown")},h=it(n?.disableTmpWrite,o?.disableTmpWrite,s?.disableTmpWrite);for(let e=l.length-1;e>=0;e--)if(!0===l[e]?.disableTmpWrite){d("disableTmpWrite",e);break}const p=it(n?.networkPolicyStrict,o?.networkPolicyStrict,s?.networkPolicyStrict,a.networkPolicyStrict);a.networkPolicyStrict&&d("networkPolicyStrict",3);const m=gt(n?.readBoundary,o?.readBoundary,s?.readBoundary)??"system",g=gt(n?.additionalReadPaths,o?.additionalReadPaths),w=!1===s?.allowUserOverrideReadPaths?at(s.additionalReadPaths):at(g,s?.additionalReadPaths),y="workspace"===m?w:void 0,v=at(n?.additionalReadonlyPaths,o?.additionalReadonlyPaths,s?.additionalReadonlyPaths,a.additionalReadonlyPaths),b=v.length>0?v:void 0;let S=pt(n?.networkPolicy,o?.networkPolicy,s?.networkPolicy,a.networkPolicy);const k=s?.networkPolicy?.allow;void 0!==k&&k.length>0&&void 0!==S&&(S={...S,allow:[...k]},r&&(c["networkPolicy.allow"]="teamAdmin (replace)"));const _=void 0!==(C=S)?C:{version:1,default:"deny"};var C;const E=gt(n?.debugOutputDir,o?.debugOutputDir,s?.debugOutputDir),x=it(n?.captureDenies,o?.captureDenies,s?.captureDenies),P=gt(n?.enableSharedBuildCache,o?.enableSharedBuildCache,s?.enableSharedBuildCache),I=mt(n?.ignoreMapping,o?.ignoreMapping,s?.ignoreMapping,a.ignoreMapping),R=Te(t?.gitDirParent??i);return{disableTmpWrite:h||void 0,networkPolicyStrict:p,readBoundary:m,additionalReadPaths:y,additionalReadonlyPaths:b,networkPolicy:_,debugOutputDir:E,captureDenies:x||void 0,enableSharedBuildCache:P,ignoreMapping:I,writeProtectionMapping:mt(n?.writeProtectionMapping,o?.writeProtectionMapping,s?.writeProtectionMapping,a.writeProtectionMapping,R),fieldSources:c}}function Et(e,t){const r={...e,type:t};for(const[e,t]of Object.entries(r))void 0===t&&Reflect.deleteProperty(r,e);return r}function xt(e,t){const{perUser:r,perRepo:n,teamAdmin:o}=e,s=t?.debug,i=Ct(e,t),a=at(r?.additionalReadwritePaths,n?.additionalReadwritePaths,o?.additionalReadwritePaths),c={policy:Et({type:"workspace_readwrite",disableTmpWrite:i.disableTmpWrite,networkPolicyStrict:i.networkPolicyStrict,readBoundary:i.readBoundary,additionalReadPaths:i.additionalReadPaths,additionalReadwritePaths:a.length>0?a:void 0,additionalReadonlyPaths:i.additionalReadonlyPaths,networkPolicy:i.networkPolicy,debugOutputDir:i.debugOutputDir,captureDenies:i.captureDenies,enableSharedBuildCache:i.enableSharedBuildCache,ignoreMapping:i.ignoreMapping,writeProtectionMapping:i.writeProtectionMapping},"workspace_readwrite")};return s&&(c.debug={fieldSources:i.fieldSources}),c}var Pt=r("node:child_process"),It=r("../utils/dist/workload-spawn.js"),Rt=r("../context/dist/logger.js"),Tt=r("../context/dist/core.js");const At=Pt.execFile,$t=new WeakMap;function Mt(e,t,r){return e===t?"related":r?.has(e)?"probably_unrelated":"maybe_related"}const Dt="darwin"===process.platform,Ot="linux"===process.platform,Ft=(0,Rt.h)("shell-exec:sandbox");function Nt(e){const t=ie();return e&&0!==e.length?e.includes(t)?e:[...e,t]:[t]}let Lt,jt=!0,Ut=!1;function Bt(){return Lt}function Wt(e){"linux"===process.platform&&Object.assign(e,I(e))}let Ht=null,qt=null,zt=null,Gt=null,Vt=!1,Kt=null;function Jt(e){return{...e,additionalReadonlyPaths:Nt(e.additionalReadonlyPaths)}}function Zt(e,t,r){let n;e.ignoreMapping&&(n=function(e){return nr(e)}(e.ignoreMapping));const o=function(e,t,r){const n=e&&e.length>0?function(...e){const t={};for(const r of e){let e=!1;try{e=(0,m.existsSync)(r)&&(0,m.statSync)(r).isDirectory()}catch{}if(e)t[r]||(t[r]=[]),t[r].push("**");else{const e=r.lastIndexOf("/"),n=e>0?r.slice(0,e):"/",o=e>=0?r.slice(e+1):r;t[n]||(t[n]=[]),o?t[n].push(o,`${o}/**`):t[n].push("**")}}return t}(...e):{},o=!Ot||rr(r),s={...n};for(const[e,r]of Object.entries(t??{})){const t=e.startsWith("file://")?or(e):e;(o||rr(t))&&(s[e]=ft(s[e],r))}if(0!==Object.keys(s).length)return nr(s)}(e.additionalReadonlyPaths,e.writeProtectionMapping,t),s=(i=e.readBoundary,r?.workspaceReadEnabled??function(){const e=jt;return"function"==typeof e?e():e}()?i??"system":"system");var i;const a=function(e=process.platform){const t=[],r=new Set,n={};try{n.ripgrep=R()}catch{}for(const o of Pe(e,H.homedir(),n))r.has(o)||(r.add(o),t.push(o));return t}(),c="workspace"===s?function(e){const t=[],r=new Set;for(const n of e){let e=n.trim();if(!e)continue;"~"===e?e=H.homedir():(e.startsWith("~/")||e.startsWith("~\\"))&&(e=f.join(H.homedir(),e.slice(2))),e=e.replace(/\/\*\*$/,"").replace(/\/\*$/,""),e=e.replace(/\\\*\*$/,"").replace(/\\\*$/,"");const o=f.basename(e);if((o.includes("*")||o.includes("?"))&&(e=f.dirname(e)),!e||"."===e)continue;const s=f.normalize(e);r.has(s)||(r.add(s),t.push(s))}return t}(e.additionalReadPaths??[]):[],l=[...a],u=new Set(a);for(const e of c)u.has(e)||(u.add(e),l.push(e));const d={cwd:t,readBoundary:s,hardcodedReadPaths:l,additionalReadonlyPaths:o,networkAccess:Je(e.networkPolicy),ignoreMapping:n};return"workspace_readonly"===e.type?{type:e.type,...d}:{type:e.type,...d,additionalReadwritePaths:e.additionalReadwritePaths||[],disableTmpWrite:e.disableTmpWrite||!1}}function Xt(e){const t={sandbox:e};return Ot&&function(){const e=Ut;return"function"==typeof e?e():e}()&&(t.kernelMountBudget=!0),t}function Qt(e){if(null!==Ht)return Ht;try{const t=Bt();return Ft.info(e,`[checkBinaryAvailable] Resolved binary path: ${t}`),t?(Ht=m.existsSync(t),Ht?Ft.info(e,`[checkBinaryAvailable] Binary path exists: ${String(Ht)}`):(qt=new Error(`Sandbox binary not found at ${t}`),Ft.info(e,`[checkBinaryAvailable] Binary not found at: ${t}`)),Ht):(qt=new Error("Sandbox binary path was not configured"),Ht=!1,Ft.info(e,"[checkBinaryAvailable] Binary path not set, returning false"),!1)}catch(t){return qt=t instanceof Error?t:new Error(String(t)),Ht=!1,Ft.info(e,`[checkBinaryAvailable] Exception checking binary: ${String(t)}`),!1}}function Yt(e){if(null!==Gt)return Gt;const t=e??(0,Tt.q6)();if(Ft.info(t,"[isSandboxHelperSupported] Starting sandbox support check..."),!Qt(t)){const e=qt?.message||"Binary check failed";return zt=e,Ft.info(t,`[isSandboxHelperSupported] Binary not available, returning false. Reason: ${e}`),Gt=!1,Gt}if("win32"===process.platform)return zt="Windows sandbox helper only provides network proxy, not filesystem isolation",Ft.info(t,"[isSandboxHelperSupported] win32: returning false (proxy-only, no filesystem sandbox)"),Gt=!1,Gt;if("darwin"===process.platform)return zt=null,Ft.info(t,`[isSandboxHelperSupported] ${process.platform} platform, binary available, sandbox supported!`),Gt=!0,Gt;const{binaryPath:r,args:n,env:o}=function(e,t){const r=Xt(Zt(Jt({type:"workspace_readwrite"}),t)),n=String(Bt());Ft.info(e,`[sandboxPreflight] Running preflight with binary: ${n}`),Ft.info(e,`[sandboxPreflight] CWD: ${t}`);const o={...process.env};return Wt(o),{binaryPath:n,args:["--policy",ae(JSON.stringify(r)),"--preflight-only","--","/bin/true"],env:o}}(t,process.cwd());try{const e=Date.now();(0,It.D9)(Pt.execFileSync,r,n,{stdio:["ignore","ignore","pipe"],timeout:er,env:o,shell:!1});const s=Date.now()-e;return zt=null,Ft.info(t,`[isSandboxHelperSupported] Preflight succeeded in ${s}ms, sandbox supported!`),Gt=!0,Gt}catch(e){return function(e,t){const{message:r,status:n,stderrText:o}=t;return Ft.error(e,`[sandboxPreflight] Preflight failed: ${r}`),Ft.error(e,`[sandboxPreflight] Exit status: ${n}`),o&&Ft.error(e,`[sandboxPreflight] Stderr: ${o}`),zt=2===n?`Linux preflight failed with exit code 2 (unsupported kernel features). stderr: ${o||"none"}`:`Linux preflight failed: ${r||"unknown error"}. Exit status: ${n}. stderr: ${o||"none"}`,Gt=!1,!1}(t,function(e){if("object"!=typeof e||null===e)return{stderrText:""};const t="message"in e&&"string"==typeof e.message?e.message:void 0,r=!("status"in e)||"number"!=typeof e.status&&null!==e.status?void 0:e.status,n="stderr"in e?e.stderr:void 0;return{message:t,status:r,stderrText:Buffer.isBuffer(n)||"string"==typeof n?n.toString():""}}(e))}}(0,z.J)((function(){Gt=null,Vt=!1,Kt=null,zt=null,Ht=null,qt=null}));const er=15e3;function tr(e,t=[],r={},n){const s=(0,Tt.q6)();if(r.env=i(o(r.env)),!Qt(s))throw new Error(`Sandbox binary not available: ${qt?.message||"binary not configured"}. Please build the binary or use 'insecure_none' policy.`);if("insecure_none"===n.type)return(0,It.D9)(Pt.spawn,e,t,{...r,windowsHide:!0});if("workspace_readwrite"===n.type||"workspace_readonly"===n.type)return function(e,t,r,n){if("workspace_readwrite"!==n.type&&"workspace_readonly"!==n.type)throw new Error("Expected workspace_readwrite or workspace_readonly policy");const s=String(r.cwd??process.cwd()),a=n.sandboxWorkspaceRoot??s;let l=e,u=t;r.shell&&("win32"===process.platform?(l="string"==typeof r.shell?r.shell:"cmd.exe",u=["/c",`${e} ${t.join(" ")}`]):(l="string"==typeof r.shell?r.shell:"/bin/sh",u=["-c",`${e} ${t.join(" ")}`]));const d=function({workspaceRoot:e,executionCwd:t}){const r=f.resolve(e),n=f.resolve(t),o=sr(r);if(n===r||n===o)return;const s=e=>(0,Ye.ZU)({basePath:o,targetPath:e})?f.join(r,f.relative(o,e)):void 0,i=(0,Ye.ZU)({basePath:r,targetPath:n})?n:s(n)??n;return{directory:i,fallbackDirectory:s(sr(n))??i}}({workspaceRoot:a,executionCwd:s});"win32"!==process.platform&&void 0!==d&&({command:l,args:u}=(0,re.kO)(l,u,d));const h=Zt(Jt(n),a),p=(0,Tt.q6)();!function({log:e,dirs:t=we(H.homedir(),H.tmpdir(),de),createOnly:r=[me(process.env,de)].filter((e=>void 0!==e)),policyDir:n=oe(),uid:o=process.getuid?.()??-1}){const s=f.join(n,"node-compile-cache-removed-1"),{record:i,problem:a}=function(e){const t=e=>({record:{cleaned:[],kept:{},failed:{}},problem:e});let r,n;try{r=m.readFileSync(e,"utf8")}catch(e){const r=be(e);return t("ENOENT"===r?void 0:r)}try{n=JSON.parse(r)}catch(e){return t(e instanceof SyntaxError?"not JSON":be(e))}if("object"!=typeof n||null===n)return t("not a record");const o="cleaned"in n?n.cleaned:void 0;return{record:{cleaned:Array.isArray(o)?o.filter((e=>"string"==typeof e)):[],kept:ve("kept"in n?n.kept:void 0),failed:ve("failed"in n?n.failed:void 0)}}}(s);void 0!==a&&e(`node compile cache: starting a new cleanup record (${a})`);const c=new Set(i.cleaned),l=new Set(t);let u=!1;for(const n of[...t,...r.filter((e=>!l.has(e)))])try{const t=m.lstatSync(n,{throwIfNoEntry:!1});if(void 0!==t){const r=ye(t,o);if(void 0!==r){i.kept[n]!==r&&(e(`node compile cache: kept ${n} (${r})`),i.kept[n]=r,u=!0);continue}l.has(n)&&!c.has(n)&&(m.rmSync(n,{recursive:!0,force:!0}),e(`node compile cache: removed ${n}`))}m.mkdirSync(n,{recursive:!0,mode:448}),l.has(n)&&!c.has(n)&&(c.add(n),u=!0),void 0===i.kept[n]&&void 0===i.failed[n]||(delete i.kept[n],delete i.failed[n],u=!0)}catch(t){const r=be(t);i.failed[n]!==r&&(e(`node compile cache: could not prepare ${n} (${r})`),i.failed[n]=r,u=!0)}u&&function(e,t){const r=`${e}.${process.pid}.tmp`;try{m.writeFileSync(r,`${JSON.stringify(t)}\n`,{mode:384}),m.renameSync(r,e)}catch{m.rmSync(r,{force:!0})}}(s,{...i,cleaned:[...c]})}({log:e=>Ft.info(p,e)});const g=function(e){if(!("workspace"!==e.readBoundary||"workspace_readwrite"===e.type&&e.disableTmpWrite||"win32"===process.platform))return Z(e.cwd,{create:!0})}(h);g&&(h.additionalReadwritePaths=[...h.additionalReadwritePaths??[],g]);const w=function(e){if("insecure_none"===e.type)return;const t=e.networkPolicy;if(void 0===t)return;if(!Je(t))return;const r=void 0!==t.deny&&t.deny.length>0;return"allow"!==t.default||r?{version:1,...t}:void 0}(n),y=Xt(h);void 0!==w&&(y.networkPolicy=w),!1===n.networkPolicyStrict&&(y.networkPolicyStrict=!1);const v=["--policy",ae(JSON.stringify(y)),"--",l,...u],b=o(process.env),S={..."linux"===process.platform?c(b):b,..."linux"===process.platform&&r.env?c(r.env):r.env,CURSOR_SANDBOX:"native"};Wt(S);const k=new Set(Q);if(g){const e=function(e,t,r){const n=function(e){const t=(0,f.join)(e,"tmp");return{TMPDIR:t,TMP:t,TEMP:t,TMPPREFIX:(0,f.join)(t,"sh-")}}(e);if(r){const r=ee();for(const[o,s]of Object.entries(ee(e)))t[o]===r[o]&&(n[o]=s)}return n}(g,S,n.enableSharedBuildCache);Object.assign(S,e);for(const t of Object.keys(e))k.add(t);S.__CURSOR_SANDBOX_TEMP_RESTORE=Object.entries(e).map((([e,t])=>`builtin export ${e}='${t.replace(/'/g,"'\\''")}'`)).join("; ")}S.__CURSOR_SANDBOX_OWNED_ENV=[...k].join(" ");const _={cwd:r.cwd||s,env:i(S),stdio:r.stdio||["pipe","pipe","pipe"],detached:r.detached,windowsHide:!0};try{const e=new Date,t=(0,It.D9)(Pt.spawn,String(Bt()),v,_);return Dt&&t.pid&&function(e,t){$t.set(e,t)}(t,{startTime:e,pid:t.pid}),t}catch(e){throw new Error(`Failed to spawn sandboxed process: ${String(e)}`)}}(e,t,r,n);throw new Error(`Unsupported sandbox policy: ${String(n)}`)}function rr(e,t=e=>m.existsSync(e)){if((0,re.$f)(e))return!0;let r=f.resolve(e);for(;;){try{if(t(f.join(r,".git")))return!0}catch{}const e=f.dirname(r);if(e===r)return!1;r=e}}function nr(e,t,r,n){const o={};for(const[t,r]of Object.entries(e)){const e=t.startsWith("file://")?or(t):t;o[e]=ft(o[e],r);const n=sr(e);n!==e&&(o[n]=ft(o[n],r))}return o}function or(e){let t=e.replace(/^file:\/\//,"");return t=decodeURIComponent(t),t.length>1&&t.endsWith("/")&&(t=t.slice(0,-1)),t}function sr(e,t){if((0,re.$f)(e))return e;try{return(t??m.realpathSync)(e)}catch{return e}}function ir(){return zt}class ar extends Error{reason;constructor(e,t){super(e),this.reason=t,this.name="SandboxUnsupportedError"}}const cr="darwin"===process.platform;function lr(e){!function(e){R();const{sandboxBinaryPath:t,workspaceReadEnabled:r,kernelMountBudget:n}=e;Lt||(Lt=t),void 0!==r&&(jt=r),void 0!==n&&(Ut=n)}(e)}function ur(e,t=[],r={},n){if(r.env=o(r.env),n.enableSharedBuildCache&&(r={...r,env:{...o(process.env),...ee(),...r.env}}),"insecure_none"!==n.type){if(Yt())return tr(e,t,r,n);const o=ir();throw new ar(`Sandbox policy '${n.type}' is not supported on this system. Ensure the sandbox helper binary is available, or use 'insecure_none'. Reason: ${o||"unknown"}`,o??void 0)}return function(e,t,r,n={spawn:Pt.spawn,spawnWorkload:It.D9}){return n.spawnWorkload(n.spawn,e,t,{...r,env:i(r.env??process.env),windowsHide:!0})}(e,t,r)}function dr(e){return cr?async function(e){const t=$t.get(e);return t?(r=t.pid,n=t.startTime,o=t.unrelatedPids,new Promise((e=>{try{const t=new Date,s=["show","--style","ndjson","--predicate",'process=="kernel" AND eventMessage CONTAINS "Sandbox:" AND eventMessage contains "deny"',"--last",Math.ceil((t.getTime()-n.getTime())/1e3).toString()];(0,It.D9)(At,"/usr/bin/log",s,((t,n)=>{if(t)return void e([{raw:t.message}]);const s=n.split(/\r?\n/).filter((e=>e.trim().length>0)),i=[];for(const e of s)try{const t=JSON.parse(e),n=t?.eventMessage??"";if(!n||"string"!=typeof n)continue;const s=/^Sandbox:\s+([^(]+)\((\d+)\)\s+([a-zA-Z-]+)\((\d+)\)\s+([^\s]+)\s+(.+)$/.exec(n);if(s){const[,e,a,c,l,u,d]=s,h=Number(a);i.push({timestamp:t.timestamp,processName:e.trim(),pid:h,decision:c.toLowerCase(),decisionCode:Number(l),operation:u,target:d,duplicateCount:1,raw:n,relationship:Mt(h,r,o)});continue}const a=/^(\d+) duplicate report for Sandbox: (.+)$/.exec(n);if(a){const e=Number(a[1]),s=a[2],c=/^([^(]+)\((\d+)\)\s+([a-zA-Z-]+)\((\d+)\)\s+([^\s]+)\s+(.+)$/.exec(s);if(c){const[,s,a,l,u,d,h]=c,p=Number(a);i.push({timestamp:t.timestamp,processName:s.trim(),pid:p,decision:l.toLowerCase(),decisionCode:Number(u),operation:d,target:h,duplicateCount:e,raw:n,relationship:Mt(p,r,o)})}else i.push({timestamp:t.timestamp,duplicateCount:e,raw:n});continue}i.push({timestamp:t.timestamp,raw:n})}catch{}e(i)}))}catch(t){e([{raw:String(t)}])}}))):(console.log("No sandbox metadata found on child process"),[]);var r,n,o}(e):Promise.resolve([])}function hr(e,t){if(cr)try{(0,m.accessSync)("/usr/bin/sandbox-exec",m.constants.X_OK)}catch{return!1}return Yt(t?.ctx)}var pr=r("node:stream"),fr=r("../context/dist/otel.js"),mr=r("../utils/dist/writable-iterable.js");const gr="--",wr='builtin eval "$1" 3<&- 4>&-';var yr=r("node:string_decoder");const vr=50,br=262144;class Sr{writable;pending=[];pendingBytes=0;flushTimeout;flushPromise;flushIntervalMs;maxBufferedBytes;constructor(e,t){this.writable=e,this.flushIntervalMs=t?.flushIntervalMs??vr,this.maxBufferedBytes=t?.maxBufferedBytes??br}async push(e,t){0!==t.length&&(this.pending.push({type:e,data:t}),this.pendingBytes+=t.length,this.pendingBytes>=this.maxBufferedBytes?await this.flush():this.scheduleFlush())}async flush(){if(this.clearFlushTimeout(),this.flushPromise)return await this.flushPromise,void(this.pendingBytes>0&&await this.flush());if(0===this.pendingBytes)return;const e=this.pending;this.pending=[],this.pendingBytes=0,this.flushPromise=this.writeBufferedOutput(e);try{await this.flushPromise}finally{this.flushPromise=void 0}}async close(){await this.flush()}scheduleFlush(){void 0===this.flushTimeout&&(this.flushTimeout=setTimeout((()=>{this.flushTimeout=void 0,this.flush()}),this.flushIntervalMs))}clearFlushTimeout(){void 0!==this.flushTimeout&&(clearTimeout(this.flushTimeout),this.flushTimeout=void 0)}async writeBufferedOutput(e){for(const t of function(e){if(0===e.length)return[];const t=[];let r=e[0].type,n=[e[0].data];for(let o=1;o<e.length;o++){const s=e[o];s.type!==r?(t.push({type:r,data:Buffer.concat(n)}),r=s.type,n=[s.data]):n.push(s.data)}return t.push({type:r,data:Buffer.concat(n)}),t}(e))try{await this.writable.write(t)}catch{}}}function kr(e){const t=new re.Zv;if(!e.bufferOutputEvents){const r=(t,r)=>{e.writable.write({type:t,data:r}).catch((()=>{}))};return e.stdout?.on("data",(e=>{const n=t.note(e);void 0!==n&&n.length>0&&r("stdout",n)})),e.stderr?.on("data",(e=>{r("stderr",e)})),{get stdoutBytes(){return t.bytes},get stdoutPrefix(){return t.stdoutPrefix},async waitForOutput(){},async releaseHeldStdout(){const e=t.takeHeld();void 0!==e&&e.length>0&&r("stdout",e)},dropHeldStdout(){t.takeHeld()},async flush(){await this.releaseHeldStdout()}}}const r=new Sr(e.writable,e.outputLimiterOptions);let n;const o=Promise.all([_r(e.stdout,r,t),Cr(e.stderr,"stderr",r)]).then((()=>{})).catch((e=>{n=e}));return{get stdoutBytes(){return t.bytes},get stdoutPrefix(){return t.stdoutPrefix},async waitForOutput(){if(await o,void 0!==n)throw(e=n)instanceof Error?e:new Error(String(e));var e},async releaseHeldStdout(){const e=t.takeHeld();void 0!==e&&e.length>0&&await r.push("stdout",e)},dropHeldStdout(){t.takeHeld()},async flush(){await this.releaseHeldStdout(),await r.flush()}}}async function _r(e,t,r){if(e)for await(const n of e){const e=r.note(n);void 0!==e&&e.length>0&&await t.push("stdout",e)}}async function Cr(e,t,r,n){if(e)for await(const o of e)n?.(o),await r.push(t,o)}var Er;!function(e){e.Zsh="zsh",e.ZshLight="zsh-light",e.Bash="bash",e.PowerShell="powershell",e.Naive="naive"}(Er||(Er={}));const xr={TERM:"dumb",NO_COLOR:"1",FORCE_COLOR:"0",_ZO_DOCTOR:"0"};function Pr(e){return"win32"===e.platform?"windows_tree":e.detached?"process_group":"single_process"}function Ir(e,t,r,n={spawn:Pt.spawn,killPid:process.kill.bind(process)}){const o=e.pid;if(void 0===o)return;const s=()=>{try{e.kill(r)}catch{}};switch(t){case"process_group":try{n.killPid(-o,r)}catch{s()}return;case"windows_tree":try{n.spawn("taskkill",["/pid",String(o),"/t","/f"],{stdio:"ignore",windowsHide:!0}).on("error",s)}catch{s()}return;case"single_process":return void s();default:throw new Error(`Unknown process tree kill mode: ${String(t)}`)}}function Rr(e,t=[],r={},n,o){const s=ur(e,t,{...r,env:I(r.env??process.env)},n);return o&&Tr(s,{detached:!0===r.detached},o),s}function Tr(e,t,r){const n=Pr({platform:process.platform,detached:t.detached}),o=()=>{if(!e.pid)return;Ir(e,n,"SIGTERM");const t=setTimeout((()=>{!e.killed&&e.pid&&Ir(e,n,"SIGKILL")}),1e3);"process_group"!==n&&e.once("exit",(()=>{clearTimeout(t)}))};r.aborted?o():(r.addEventListener("abort",o,{once:!0}),e.once("exit",(()=>{r.removeEventListener("abort",o)})))}function Ar(e,t,r){if(e){try{process.kill(-e,t)}catch{return}"SIGTERM"===t&&void 0!==r&&r>0&&setTimeout((()=>{try{process.kill(-e,"SIGKILL")}catch{}}),r)}}const $r=new Set(["SIGTERM","SIGINT","SIGHUP","SIGQUIT","SIGKILL"]);function Mr(e,t,r){null!==t&&$r.has(t)&&!r&&"win32"!==process.platform&&Ar(e,t)}function Dr(e,{shellName:t,closeGraceMs:r,timeoutMs:n}){const o=r??5e3,s=n??6e4;return new Promise((r=>{const n=[];let i;const a=e=>{n.push(e)},c=()=>{clearTimeout(d),o<=0||(i=setTimeout((()=>{console.warn(`[shell-exec] ${t} state init exited but its stdio did not close within ${o}ms; a startup file left a background process holding the output pipe. Proceeding with the dump received so far.`),u("exit_without_close")}),o))},l=()=>{u("closed")},u=t=>{clearTimeout(d),clearTimeout(i),e.off("exit",c),e.off("close",l),e.stdout?.off("data",a),e.stdout?.resume(),r({outcome:t,stdout:Buffer.concat(n).toString("utf8")})},d=s>0?setTimeout((()=>{console.warn(`[shell-exec] ${t} state init did not exit within ${s}ms; a startup file is blocking. Killing it and falling back to an empty state.`),Ir(e,Pr({platform:process.platform,detached:!0}),"SIGKILL"),u("timed_out")}),s):void 0;e.stdout?.on("data",a),Or(e.stdout),e.on("exit",c),e.on("close",l)}))}function Or(e){e?.on("error",(()=>{}))}function Fr(e){e.removeAllListeners(),e.on("error",(()=>{})),e.stdout?.removeAllListeners("close"),e.stderr?.removeAllListeners("close");for(const t of e.stdio.slice(3))t?.destroy()}const Nr="IFS= builtin read -r -d '' __cursor_command <&5 2>/dev/null || { builtin printf '%s\\n' 'The command did not run: a shell startup file ($BASH_ENV or .zshenv) closed or replaced file descriptor 5, which carries the command. Run it again; this shell now passes commands as arguments.' >&2; builtin exit 126; }; exec 5<&-; builtin set -- \"$__cursor_command\"; builtin unset __cursor_command; ";function Lr(e,t){return 126===e&&""===t}function jr(){return"win32"!==process.platform}function Ur(e,t){const r=e.stdio.at(5);r instanceof pr.Writable&&(Or(r),r.end(`${t}\0`))}function Br(e,t){e&&(Or(e),e.write(t),e.end())}function Wr(e,t){if(!e)return;Or(e);const r=new yr.StringDecoder("utf8");e.on("data",(e=>{const n=r.write(e);""!==n&&t(n)})),e.on("end",(()=>{const e=r.end();""!==e&&t(e)}))}function Hr(e){const t=e.indexOf("\n");return{cwd:Buffer.from(e.substring(0,t),"utf16le").toString("utf16le"),rest:e.substring(t)}}function qr(e,t){const r=`${t}\n`,n=e.indexOf(r);return n>=0?e.slice(n+r.length):e}function zr(e){return!1===e?.isLoginShellEnabled?"-ic":"-ilc"}function Gr(e,t,r){const n=`${t}\n`;if(!e.startsWith(n))return;const o=e.indexOf(`\n${r}\n`,n.length-1);return o<0?void 0:e.slice(n.length,o+1)}const Vr="__CURSOR_BASH_STATE_START__",Kr="__CURSOR_BASH_STATE_END__";var Jr=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function Zr(e){if("win32"===process.platform){const t=/git.*bash/i;if(e&&t.test(e))return e;const r=S("bash",[],t).cmd;return t.test(r)?r:null}const t=process.env.SHELL;return t?.includes("bash")?t:S("bash",[]).cmd}function Xr(e){if("win32"!==process.platform)return e;const t=f.normalize(e),r=t[0]?.toLowerCase();return r&&":"===t[1]&&t[2]===f.sep?`/${r}${t.slice(2).replace(/\\/g,"/")}`:t.replace(/\\/g,"/")}function Qr(e){const t=e.pipeStdin?wr:`${wr} < /dev/null`,r=e.useFileTransport?'snap=$(command cat "$CURSOR_STATE_INPUT_FILE")':"snap=$(command cat <&3)",n=e.useFileTransport?'mkdir -p "$(dirname "$CURSOR_STATE_OUTPUT_FILE")" 2>/dev/null; dump_bash_state > "$CURSOR_STATE_OUTPUT_FILE"':"dump_bash_state >&4";return(e.pipeCommand?Nr:"")+`${r} && builtin shopt -s extglob && builtin eval -- "$snap"; { builtin set +u 2>/dev/null || true; builtin eval "\${__CURSOR_SANDBOX_ENV_RESTORE:-}" 2>/dev/null; `+X+Y+(e.envInjection??"")+`builtin export PWD="$(builtin pwd)"; builtin shopt -s expand_aliases 2>/dev/null; ${e.sudoAliasInjection}${t}; }; `+`COMMAND_EXIT_CODE=$?; ${n}; builtin exit $COMMAND_EXIT_CODE`}class Yr{cwd;state;userTerminalHint;useFileStateTransport;commandPipeUnreadable;constructor(e,t,r,n=!1,o=!1){this.cwd=e,this.state=t,this.userTerminalHint=r,this.useFileStateTransport=n,this.commandPipeUnreadable=o}async getCwd(){return this.cwd}clone(e){return new Yr(e??this.cwd,this.state,this.userTerminalHint,this.useFileStateTransport,this.commandPipeUnreadable)}resetSessionCwdAfterHopCdFailure(e){const{cwd:t,sandboxWorkspaceRoot:r}=e;f.resolve(t)===f.resolve(this.cwd)&&(this.cwd=void 0===r||f.resolve(r)===f.resolve(t)||(0,re.A)(r)?(0,re.D1)():r)}async*execute(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(n,(0,fr.VI)(e.withName("BashState.execute")),!1),s=r?.pipeStdin??!1,a=(0,mr.Jt)(),c=r?.workingDirectory??this.cwd,l=function(e,t=process.platform,r=process.env){const n={...r,...xr,...e?.env};return u(n),"win32"===t&&(F(n),N(n)),i(n)}(r),d=$(l),h=this.useFileStateTransport,p=!h&&!this.commandPipeUnreadable;let m,g,w;if(h){m=await(0,te.mkdtemp)(f.join(H.tmpdir(),"cursor-bash-state-")),g=f.join(m,"state-in"),w=f.join(m,"state-out"),await(0,te.writeFile)(g,this.state,"utf8"),await(0,te.writeFile)(w,"","utf8").catch((()=>{}));const e=Xr(g),t=Xr(w);l.CURSOR_STATE_INPUT_FILE=e,l.CURSOR_STATE_OUTPUT_FILE=t}const y=function(e){return["-O","extglob","-c",e.script,gr,...void 0===e.command?[]:[e.command]]}({script:Qr({pipeCommand:p,useFileTransport:h,sudoAliasInjection:d,pipeStdin:s,envInjection:"win32"===process.platform&&!0===r?.powershellUtf8ChildEnv?U:""}),command:p?void 0:t}),v=Zr(this.userTerminalHint);if(!v)throw new Error("Can't find Bash");const b=r?.sandboxWorkspaceRoot??c,S=(await wt(b,r?.sandboxPolicy)).policy,k="insecure_none"!==S.type?{...S,sandboxWorkspaceRoot:b}:S;let _="";const C=async()=>{if(h){if(!w)return void(_=this.state);try{_=await(0,te.readFile)(w,"utf8")}catch(e){console.warn("[shell-exec] Failed to read bash state file",e),_=this.state}}},E=async()=>{if(m)try{await(0,te.rm)(m,{recursive:!0,force:!0})}catch{}};let x;(0,re.$Y)(c)&&(0,fr.HF)(o.ctx,re.yo);try{x=Rr(v,y,{env:l,stdio:[s?"pipe":"ignore","pipe","pipe","pipe","pipe",p?"pipe":"ignore"],cwd:c,detached:!0},k,r?.signal)}catch(e){throw await E(),e}x.on("spawn",(async()=>{try{await a.write({type:"stdin_ready",stdin:x.stdin??void 0,pid:x.pid,shell:"bash"})}catch(e){}}));const P=kr({stdout:x.stdout,stderr:x.stderr,writable:a,bufferOutputEvents:r?.bufferOutputEvents,outputLimiterOptions:r?.outputLimiterOptions});x.on("error",(async e=>{if((0,re.fK)(e,c)){this.resetSessionCwdAfterHopCdFailure({cwd:c,sandboxWorkspaceRoot:r?.sandboxWorkspaceRoot}),(0,fr.HF)(o.ctx,re.Gq);const e=(0,re.iA)(c);console.warn(`[shell-exec] working directory is not accessible (${e.cwdKind}:${e.cwdHash})`)}await E(),a.throw(e)}));let I=null,R=null,T=null,A=!1;const M=async e=>{if(A)return;if(A=!0,T&&(clearTimeout(T),T=null),(0,fr.HF)(o.ctx,"exit"),e)try{await P.waitForOutput()}catch(e){return await E(),void a.throw(e instanceof Error?e:new Error(String(e)))}const t=(0,re.wz)({exitCode:I,stdoutBytes:P.stdoutBytes,stdoutPrefix:P.stdoutPrefix,cwd:c})&&""===_;if(t&&P.dropHeldStdout(),await P.flush(),p&&Lr(I,_)&&(this.commandPipeUnreadable=!0),t){this.resetSessionCwdAfterHopCdFailure({cwd:c,sandboxWorkspaceRoot:r?.sandboxWorkspaceRoot}),await E(),(0,fr.HF)(o.ctx,re.Gq);const e=(0,re.iA)(c);return console.warn(`[shell-exec] working directory is not accessible (${e.cwdKind}:${e.cwdHash})`),void a.throw((0,re.Vn)(c))}if(!r?.signal?.aborted){await C();const e=`${Vr}\n`,t=`${Kr}\n`;if(_.startsWith(e)&&_.endsWith(t)){let t=_.slice(e.length);t=t.slice(0,-26);const{cwd:r,rest:n}=Hr(t);this.state=n,"win32"!==process.platform&&r?.startsWith("/")&&(this.cwd=r)}}if(k.captureDenies)try{const e=await dr(x);e&&e.length>0&&await a.write({type:"sandbox_denies",events:e})}catch{}try{await a.write({type:"exit",code:I,signal:R??void 0,data:"",aborted:r?.signal?.aborted??!1}),a.close()}catch{a.close()}await E()};x.on("exit",((e,t)=>{I=e,R=t,Mr(x.pid,t,r?.signal?.aborted??!1);const n=r?.closeTimeout??5e3;n>0&&(T=setTimeout((()=>{console.warn(`[shell-exec] Close event did not fire within ${n}ms after exit. This may indicate a background process is holding file descriptors open. Proceeding anyway to prevent hang.`),M(!1).finally((()=>{Fr(x)}))}),n))})),x.on("close",(async()=>{await M(!0)}));const D=x.stdio[3],O=x.stdio[4],L=D instanceof pr.Writable?D:null,j=O instanceof pr.Readable?O:null;p&&Ur(x,t),h||(Br(L,this.state),Wr(j,(e=>{_+=e}))),yield*a}catch(e){n.error=e,n.hasError=!0}finally{Jr(n)}}}async function en(e,t){const r={...process.env,...xr,...e?.env},n="__CURSOR_STATE_MARKER__",o=["-O","extglob",zr(e),`#!/usr/bin/env bash\n\n# Usage:\n# source dump_bash_state.bash\n# dump_bash_state OUTPUT_FILE\n# Or execute directly (captures a subshell's state):\n# ./dump_bash_state.bash OUTPUT_FILE\n\ndump_bash_state() {\n set -euo pipefail\n\n # Helper to log timing, only if DUMP_BASH_STATE_TIMING is set\n if [[ -n "\${DUMP_BASH_STATE_TIMING:-}" ]]; then\n # Timing setup\n if [[ "\${BASH_VERSION%%.*}" -ge 5 ]]; then\n # Use EPOCHREALTIME if available (bash 5+)\n local start_time=\${EPOCHREALTIME}\n local step_start=\${EPOCHREALTIME}\n _log_timing() {\n local step_name="$1"\n local now=\${EPOCHREALTIME}\n local step_duration=$(command awk "BEGIN {printf "%.3f", $now - $step_start}")\n local total_duration=$(command awk "BEGIN {printf "%.3f", $now - $start_time}")\n builtin printf "[TIMING] %-20s: %6.3fs (total: %6.3fs)\n" "$step_name" "$step_duration" "$total_duration" >&2\n step_start=$now\n }\n else\n # Fallback for older bash versions\n local start_time=$(command date +%s.%N)\n local step_start=$(command date +%s.%N)\n _log_timing() {\n local step_name="$1"\n local now=$(command date +%s.%N)\n local step_duration=$(command awk "BEGIN {printf "%.3f", $now - $step_start}")\n local total_duration=$(command awk "BEGIN {printf "%.3f", $now - $start_time}")\n builtin printf "[TIMING] %-20s: %6.3fs (total: %6.3fs)\n" "$step_name" "$step_duration" "$total_duration" >&2\n step_start=$now\n }\n fi\n else\n _log_timing() { :; }\n fi\n\n # Helper to append a line to output file\n _emit() {\n builtin printf '%s\n' "$1"\n }\n\n # Helper to safely encode and emit unsafe values. printf %q quotes the value for eval\n # without starting a process, and every command pays this dump and its restore.\n _emit_encoded() {\n local content="$1"\n local var_name="$2"\n if [[ -n "$content" ]]; then\n local quoted\n builtin printf -v quoted '%q' "$content"\n builtin printf 'cursor_snap_%s=%s\n' "$var_name" "$quoted"\n builtin printf 'builtin eval "$cursor_snap_%s"\n' "$var_name"\n fi\n }\n\n # Aliases replay after the functions, so a user function named alias would run in place of\n # each alias line. Only a line that starts an alias gets builtin: a quoted value can span\n # lines, and a continuation line can start with "alias ". awk reads bytes under LC_ALL=C, so a\n # value that is not valid UTF-8 does not make it warn. Without awk the lines stay as they are.\n _builtin_alias_lines() {\n [[ -n "$1" ]] || return 0\n builtin printf '%s\n' "$1" | LC_ALL=C command awk -v sq="'" '\n !q && /^alias / { $0 = "builtin " $0 }\n {\n print\n for (i = 1; i <= length($0); i++) {\n c = substr($0, i, 1)\n if (q == 1) { if (c == sq) q = 0 }\n else if (q == 2) { if (c == "\\\\") i++; else if (c == sq) q = 0 }\n else if (c == "\\\\") i++\n else if (c == "$" && substr($0, i + 1, 1) == sq) { q = 2; i++ }\n else if (c == sq) q = 1\n }\n }' 2>/dev/null ||\n builtin printf '%s\n' "$1"\n }\n\n # Start fresh\n _log_timing "file_init"\n\n # Emit start marker at the very beginning of the output\n _emit "__CURSOR_BASH_STATE_START__"\n\n # Working directory\n _emit "$PWD"\n _log_timing "working_dir"\n\n # The shell starts in POSIX mode when it inherits POSIXLY_CORRECT. POSIX_MODE\n # turns it back on after the functions if the session had it on.\n _emit "builtin set +o posix; builtin unset POSIXLY_CORRECT"\n\n # Drop ELECTRON_RUN_AS_NODE by exact name so one command exporting it can't\n # bake it into the snapshot that every later command re-evals (IDE-2911:\n # Cypress boots as plain Node until a new chat). Exact unset rather than the\n # line-based grep below, which would also eat vars whose name or multiline\n # value merely contains the token. The shell exits right after the dump.\n builtin unset ELECTRON_RUN_AS_NODE 2>/dev/null || true\n\n # Environment variables (export statements)\n # Filter out: proxy settings plus request/session-scoped vars that must not\n # leak across shell executions.\n local env_vars\n env_vars=$(builtin export -p 2>/dev/null | command grep -viE '_proxy=|CURSOR_SANDBOX|SUDO_ASKPASS|CURSOR_ASKPASS|CURSOR_CONVERSATION_ID|CURSOR_REQUEST_ID|CURSOR_AGENT_STORE' | command grep -vE '^(declare|export)( -[a-zA-Z]+)* POSIXLY_CORRECT(=|$)' || true)\n if [[ -n "\${__CURSOR_SANDBOX_OWNED_ENV:-}" ]]; then\n env_vars=$(builtin printf '%s\n' "$env_vars" | command grep -vE "^(export|declare|typeset)( -[a-zA-Z]+)* (\${__CURSOR_SANDBOX_OWNED_ENV// /|})=" || true)\n fi\n _emit_encoded "$env_vars" "ENV_VARS"\n _log_timing "environment"\n\n # POSIX shell options (replayable as set +/-o lines). Exclude the errexit/nounset/\n # pipefail this function force-enables above, so they are not baked into the restored\n # snapshot and leaked onto every subsequent command (a stray pipefail makes a\n # successful 'cmd | head' report exit 141). Exclude monitor too: the interactive login\n # shell of bash 3.2 reports it on, and a command shell that restored it would run every\n # command in a process group of its own, where a signal to the shell's group misses it.\n local posix_opts\n posix_opts=$(builtin shopt -po 2>/dev/null | command grep -vE '^set [-+]o (errexit|monitor|nounset|pipefail|posix)$' || true)\n _emit_encoded "$posix_opts" "POSIX_OPTS"\n _log_timing "posix_options"\n\n # Bash shopt options (replayable as shopt -s/-u lines)\n local bash_opts\n bash_opts=$(builtin shopt -p 2>/dev/null || true)\n _emit_encoded "$bash_opts" "BASH_OPTS"\n _log_timing "bash_options"\n\n # Functions: capture all functions\n local all_functions\n all_functions=$(builtin declare -f 2>/dev/null || true)\n _emit_encoded "$all_functions" "FUNCTIONS"\n _log_timing "functions"\n\n # Aliases\n local aliases\n aliases=$(_builtin_alias_lines "$(builtin alias -p 2>/dev/null || true)" || true)\n _emit_encoded "$aliases" "ALIASES"\n _log_timing "aliases"\n\n # POSIX mode makes a function name that is not a POSIX identifier, such as my-fn, a\n # fatal error, so it is replayed after the functions. Turning it on resets shopt\n # options such as inherit_errexit, so the shopt state is replayed again after it.\n local posix_mode=""\n if builtin shopt -qo posix; then\n posix_mode=$(builtin printf 'builtin set -o posix\n'; builtin export -p | command grep -E '^(declare|export)( -[a-zA-Z]+)* POSIXLY_CORRECT=' || true; command sed 's/^shopt /builtin shopt /' <<<"$bash_opts")\n fi\n _emit_encoded "$posix_mode" "POSIX_MODE"\n _log_timing "posix_mode"\n\n # Done\n _emit "# end of bash state dump"\n _emit "__CURSOR_BASH_STATE_END__"\n _log_timing "finalize"\n}\n builtin printf '${n}\\n'; dump_bash_state`],s=Zr(e?.userTerminalHint);if(!s)throw new Error("Can't find Bash");const i=Rr(s,o,{env:r,detached:!0,stdio:["ignore","pipe","ignore"]},{type:"insecure_none"},e?.signal);i.on("error",(e=>{console.warn(`[shell-exec] bash state init spawn failed; falling back to empty state: ${e instanceof Error?e.message:String(e)}`)}));const{stdout:a}=await Dr(i,{shellName:"bash",...t}),c=Gr(qr(a,n),Vr,Kr)??`${process.cwd()}\n`,{cwd:l,rest:u}=Hr(c),d="win32"===process.platform,h="win32"===process.platform?process.cwd():l;return new Yr(h,u,e?.userTerminalHint,d)}var tn=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class rn{initializer;promise;constructor(e){this.initializer=e}getExecutor(){return void 0===this.promise&&(this.promise=this.initializer()),this.promise}async getCwd(){return(await this.getExecutor()).getCwd()}clone(e){return new rn((async()=>(await this.getExecutor()).clone(e)))}async*execute(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(n,(0,fr.VI)(e.withName("LazyTerminalExecutor.execute")),!1);const o=await this.getExecutor();for await(const n of o.execute(e,t,r))yield n}catch(e){n.error=e,n.hasError=!0}finally{tn(n)}}}var nn=r("../metrics/dist/index.js");const on="\n Emit $PWD.Path\n #Log-Timing \"working_dir\"\n\n function ShouldPersistEnvVar {\n param([string]$Name)\n if ($Name -eq 'CURSOR_CONVERSATION_ID') {\n return $false\n }\n if ($Name -eq 'CURSOR_REQUEST_ID') {\n return $false\n }\n if ($Name -like 'CURSOR_AGENT_STORE*') {\n return $false\n }\n if ($Name -like '*CURSOR_SANDBOX*') {\n return $false\n }\n if ($Name -eq 'ELECTRON_RUN_AS_NODE') {\n return $false\n }\n return $true\n }\n\n $envVars = Get-ChildItem Env: | Sort-Object Name\n foreach ($var in $envVars) {\n if (-not (ShouldPersistEnvVar -Name $var.Name)) {\n continue\n }\n $encoded = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes([string]$var.Value))\n Emit ('Set-Item -LiteralPath ''Env:{0}'' -Value ([System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String(''{1}'')))' -f $var.Name, $encoded)\n }\n #Log-Timing \"environment\"\n\n $aliases = Get-Alias | Sort-Object Name\n foreach ($alias in $aliases) {\n $definition = $alias.Definition\n\n if ($alias.Options -band [System.Management.Automation.ScopedItemOptions]::ReadOnly) {\n }\n elseif ($alias.Options -band [System.Management.Automation.ScopedItemOptions]::Constant) {\n }\n elseif ($alias.Options -band [System.Management.Automation.ScopedItemOptions]::AllScope) {\n }\n else {\n Emit ('Set-Alias -Name \"{0}\" -Value \"{1}\"' -f $alias.Name, $definition)\n }\n }\n\n #Log-Timing \"finalize\"\n",sn=`\nfunction Dump-PowerShellState {\n param(\n [Parameter(Mandatory = $true)]\n [string]$OutputFile\n )\n\n function Emit {\n param([string]$Content)\n Add-Content -Path $OutputFile -Value $Content -Encoding UTF8\n }\n\n if (Test-Path $OutputFile) {\n Remove-Item $OutputFile -Force\n }\n New-Item -Path $OutputFile -ItemType File -Force | Out-Null\n #Log-Timing "file_init"\n${on}}\n`,an=`\nfunction Dump-PowerShellState {\n param(\n [Parameter(Mandatory = $true)]\n [string]$OutputFile,\n [string]$Trailer\n )\n\n $__cursorDumpText = New-Object System.Text.StringBuilder\n $__cursorDumpNewLine = [Environment]::NewLine\n function Emit {\n param([string]$Content)\n [void]$__cursorDumpText.Append($Content).Append($__cursorDumpNewLine)\n }\n${on}\n if ($Trailer) {\n Emit $Trailer\n }\n [System.IO.File]::WriteAllText($OutputFile, $__cursorDumpText.ToString(), (New-Object System.Text.UTF8Encoding ($PSVersionTable.PSVersion.Major -lt 6)))\n}\n`,cn="# cursor-shell-timings ",ln="[long](([DateTime]::UtcNow.Ticks - 621355968000000000) / 10000)",un="\ntry { [Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false) } catch { }\ntry { [Console]::InputEncoding = [System.Text.UTF8Encoding]::new($false) } catch { }\ntry { $global:OutputEncoding = [System.Text.UTF8Encoding]::new($false) } catch { }\n",dn=e=>e.map((e=>`'${e}'`)).join(", "),hn=`\ntry {\n if ($PSVersionTable.PSVersion.Major -lt 6 -and [Console]::OutputEncoding.CodePage -eq 65001) {\n # Windows PowerShell calls UTF-8 with a BOM 'UTF8'; PowerShell 7 calls it 'utf8BOM' and\n # reaches this block only when a test fakes the version.\n $__cursorUtf8 = if ($PSVersionTable.PSEdition -eq 'Core') { 'utf8BOM' } else { 'UTF8' }\n $__cursorGetContentNames = @('Get-Content') + @(Get-Alias -Definition Get-Content -ErrorAction Ignore | ForEach-Object { $_.Name })\n $__cursorHasEncodingDefault = $false\n foreach ($__cursorKey in @($PSDefaultParameterValues.Keys)) {\n $__cursorKeyParts = "$__cursorKey" -split ':', 2\n if ($__cursorKeyParts.Count -ne 2 -or 'Encoding' -notlike $__cursorKeyParts[1].Trim()) { continue }\n foreach ($__cursorName in $__cursorGetContentNames) {\n if ($__cursorName -like $__cursorKeyParts[0].Trim()) { $__cursorHasEncodingDefault = $true }\n }\n }\n # The body of the proxy for Get-Content. Its param block comes from the cmdlet itself.\n # Every step of its own is guarded, so a failure in the proxy reads the file as the\n # default did.\n $__cursorReaderBody = @'\nbegin {\n $__cursorStopped = $false\n $__cursorLeave = $false\n # A 64 KiB window of the file and the file's length: the first 64 KiB, the window an\n # editor's encoding guess reads, or the last 64 KiB, the end that -Tail reads; $null for a\n # path that is not a file.\n $__cursorWindowOf = {\n param([string]$__cursorFile, [bool]$__cursorFromEnd)\n if (-not [System.IO.File]::Exists($__cursorFile)) { return $null }\n $__cursorHead = New-Object byte[] 65536\n $__cursorCount = 0\n $__cursorStream = [System.IO.File]::Open($__cursorFile, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read, [System.IO.FileShare]::ReadWrite -bor [System.IO.FileShare]::Delete)\n try {\n $__cursorLength = $__cursorStream.Length\n if ($__cursorFromEnd -and $__cursorLength -gt $__cursorHead.Length) { $__cursorStream.Position = $__cursorLength - $__cursorHead.Length }\n while ($__cursorCount -lt $__cursorHead.Length) {\n $__cursorRead = $__cursorStream.Read($__cursorHead, $__cursorCount, $__cursorHead.Length - $__cursorCount)\n if ($__cursorRead -le 0) { break }\n $__cursorCount += $__cursorRead\n }\n } finally { $__cursorStream.Dispose() }\n return @{ Length = $__cursorLength; Head = $__cursorHead; Count = $__cursorCount; FromEnd = $__cursorFromEnd }\n }\n # How a file reads: 'ansi' for text in the code page the cmdlet reads by default, 'either'\n # for a file that reads the same under UTF-8 and under that default, 'utf8' for everything\n # else, which the default for the cmdlet read as UTF-8 before this proxy.\n $__cursorReadingOf = {\n param($__cursorWas, $__cursorAnsi)\n $__cursorHead = $__cursorWas.Head\n $__cursorStart = 0\n $__cursorEnd = $__cursorWas.Count\n # Nothing, or a byte order mark, which the cmdlet reads by whatever encoding it was given.\n if ($__cursorEnd -eq 0) { return 'either' }\n $__cursorFull = $__cursorEnd -eq $__cursorHead.Length\n if ($__cursorWas.FromEnd) {\n # A window from the end may start inside a character; the rest of that character\n # is left out. It ends where the file does.\n while ($__cursorStart -lt 3 -and $__cursorStart -lt $__cursorEnd -and ($__cursorHead[$__cursorStart] -band 0xC0) -eq 0x80) { $__cursorStart++ }\n } else {\n if ($__cursorEnd -ge 3 -and $__cursorHead[0] -eq 0xEF -and $__cursorHead[1] -eq 0xBB -and $__cursorHead[2] -eq 0xBF) { return 'either' }\n if ($__cursorEnd -ge 2 -and (($__cursorHead[0] -eq 0xFF -and $__cursorHead[1] -eq 0xFE) -or ($__cursorHead[0] -eq 0xFE -and $__cursorHead[1] -eq 0xFF))) { return 'either' }\n if ($__cursorFull) {\n # A full window may end inside a character; that character is left out.\n $__cursorAt = $__cursorEnd - 1\n while ($__cursorAt -gt $__cursorEnd - 4 -and ($__cursorHead[$__cursorAt] -band 0xC0) -eq 0x80) { $__cursorAt-- }\n if ($__cursorHead[$__cursorAt] -ge 0xC0) {\n $__cursorNeed = if ($__cursorHead[$__cursorAt] -ge 0xF0) { 4 } elseif ($__cursorHead[$__cursorAt] -ge 0xE0) { 3 } else { 2 }\n if ($__cursorEnd - $__cursorAt -lt $__cursorNeed) { $__cursorEnd = $__cursorAt }\n }\n }\n }\n # Bytes that are not UTF-8 decode to U+FFFD; a decoder that threw instead would leave a\n # record in $Error for every such file. A character beyond ASCII takes more bytes than\n # code units, so all-ASCII content is the one that decodes to as many; it reads the\n # same either way when the window is the whole file, or the end of one.\n $__cursorText = [System.Text.UTF8Encoding]::new($false, $false).GetString($__cursorHead, $__cursorStart, $__cursorEnd - $__cursorStart)\n if ($__cursorText.IndexOf([char]0xFFFD) -lt 0) {\n if ($__cursorStart -eq 0 -and $__cursorText.Length -eq $__cursorEnd -and ($__cursorWas.FromEnd -or $__cursorEnd -eq $__cursorWas.Length)) { return 'either' }\n return 'utf8'\n }\n # A NUL byte is binary content or UTF-16 without a BOM.\n if ($__cursorText.IndexOf([char]0) -ge 0) { return 'utf8' }\n # Of the bytes beyond ASCII, those in a UTF-8 sequence against the rest: text in a legacy\n # code page forms a sequence here and there by chance, UTF-8 text with a stray byte loses\n # that byte, and the file reads as the encoding that keeps more. Counted over a view\n # with one character per byte, where U+FFFD written in UTF-8 is a sequence like any other.\n $__cursorView = [System.Text.Encoding]::GetEncoding(28591).GetString($__cursorHead, $__cursorStart, $__cursorEnd - $__cursorStart)\n $__cursorBeyondAscii = $__cursorView.Length - [regex]::Replace($__cursorView, '[^\\x00-\\x7F]', '').Length\n $__cursorKept = $__cursorView.Length - [regex]::Replace($__cursorView, '[\\xC2-\\xDF][\\x80-\\xBF]|\\xE0[\\xA0-\\xBF][\\x80-\\xBF]|[\\xE1-\\xEC\\xEE\\xEF][\\x80-\\xBF]{2}|\\xED[\\x80-\\x9F][\\x80-\\xBF]|\\xF0[\\x90-\\xBF][\\x80-\\xBF]{2}|[\\xF1-\\xF3][\\x80-\\xBF]{3}|\\xF4[\\x80-\\x8F][\\x80-\\xBF]{2}', '').Length\n if ($__cursorKept * 2 -ge $__cursorBeyondAscii) { return 'utf8' }\n # Text in the code page decodes and encodes back to the same bytes, to no control\n # character but whitespace or an escape (as in a color code), and to no private-use or\n # replacement character, which stand for bytes the code page leaves undefined. A full\n # window may end, or one from the end may start, inside a two-byte character; that\n # byte is left out on a second try.\n foreach ($__cursorCut in @(0, 1)) {\n if ($__cursorCut -gt 0 -and -not $__cursorFull) { break }\n $__cursorFrom = 0\n $__cursorTo = $__cursorEnd - $__cursorCut\n if ($__cursorWas.FromEnd) { $__cursorFrom = $__cursorCut; $__cursorTo = $__cursorEnd }\n $__cursorAnsiText = $__cursorAnsi.GetString($__cursorHead, $__cursorFrom, $__cursorTo - $__cursorFrom)\n $__cursorBack = $__cursorAnsi.GetBytes($__cursorAnsiText)\n if ($__cursorBack.Length -ne $__cursorTo - $__cursorFrom -or [System.Convert]::ToBase64String($__cursorBack) -ne [System.Convert]::ToBase64String($__cursorHead, $__cursorFrom, $__cursorTo - $__cursorFrom)) { continue }\n if ([regex]::IsMatch($__cursorAnsiText, '[\\x00-\\x08\\x0E-\\x1A\\x1C-\\x1F\\x7F-\\x9F\\uE000-\\uF8FF\\uFFFD]')) { return 'utf8' }\n return 'ansi'\n }\n return 'utf8'\n }\n try {\n $__cursorBound = $null\n if ($PSBoundParameters.ContainsKey('Path')) { $__cursorBound = @{ Path = $PSBoundParameters['Path'] } }\n elseif ($PSBoundParameters.ContainsKey('LiteralPath')) { $__cursorBound = @{ LiteralPath = $PSBoundParameters['LiteralPath'] } }\n # The cmdlet takes its -Encoding parameter from the provider of its first path, or of\n # the current location when the path comes from the pipeline; another provider has\n # none, and reads as it did.\n if ($null -eq $__cursorBound) {\n if ($ExecutionContext.SessionState.Path.CurrentLocation.Provider.Name -ne 'FileSystem') { $__cursorLeave = $true }\n } else {\n $__cursorLiteral = $__cursorBound.ContainsKey('LiteralPath')\n $__cursorFiles = New-Object System.Collections.Generic.List[string]\n $__cursorFirst = $true\n foreach ($__cursorPath in @(@($__cursorBound.Values)[0])) {\n $__cursorProvider = $null\n $__cursorDrive = $null\n if ($__cursorLiteral -or -not [System.Management.Automation.WildcardPattern]::ContainsWildcardCharacters("$__cursorPath")) {\n $__cursorResolved = @($ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath("$__cursorPath", [ref]$__cursorProvider, [ref]$__cursorDrive))\n } else {\n $__cursorResolved = @($ExecutionContext.SessionState.Path.GetResolvedProviderPathFromPSPath("$__cursorPath", [ref]$__cursorProvider))\n }\n if ($null -eq $__cursorProvider -or $__cursorProvider.Name -ne 'FileSystem') {\n if ($__cursorFirst) { $__cursorLeave = $true }\n $__cursorFiles = $null\n break\n }\n $__cursorFirst = $false\n $__cursorFiles.AddRange([string[]]$__cursorResolved)\n }\n # -Filter, -Include and -Exclude change which files the cmdlet reads, and -Stream reads\n # another stream than the one the window comes from. The call is left to the cmdlet\n # when a file it names is text in the code page and none reads as UTF-8.\n if ($null -ne $__cursorFiles -and -not $PSBoundParameters.ContainsKey('Stream') -and\n -not $PSBoundParameters.ContainsKey('Filter') -and -not $PSBoundParameters.ContainsKey('Include') -and\n -not $PSBoundParameters.ContainsKey('Exclude')) {\n # The encoding the cmdlet reads a file in when the call names none: the system's\n # ANSI code page on Windows PowerShell. PowerShell 7 reaches this block only when\n # a test fakes the version, and its Default is UTF-8 on every system, so the\n # culture's code page stands in there. A system whose code page is UTF-8 reads\n # every file the same either way.\n $__cursorAnsi = if ($PSVersionTable.PSEdition -eq 'Core') { [System.Text.Encoding]::GetEncoding([System.Globalization.CultureInfo]::CurrentCulture.TextInfo.ANSICodePage) } else { [System.Text.Encoding]::Default }\n $__cursorAnsiFile = $false\n $__cursorUtf8File = $false\n if ($__cursorAnsi.CodePage -ne 65001) {\n foreach ($__cursorFile in $__cursorFiles) {\n $__cursorWas = & $__cursorWindowOf $__cursorFile $false\n if ($null -eq $__cursorWas) { continue }\n $__cursorReading = & $__cursorReadingOf $__cursorWas $__cursorAnsi\n # -Tail reads the end of the file, which a log appended to by more than\n # one program need not write in the code page of its start.\n if ($__cursorReading -eq 'ansi' -and $PSBoundParameters.ContainsKey('Tail') -and $__cursorWas.Length -gt $__cursorWas.Head.Length) {\n if ((& $__cursorReadingOf (& $__cursorWindowOf $__cursorFile $true) $__cursorAnsi) -eq 'utf8') { $__cursorReading = 'utf8' }\n }\n if ($__cursorReading -eq 'ansi') { $__cursorAnsiFile = $true }\n elseif ($__cursorReading -eq 'utf8') { $__cursorUtf8File = $true; break }\n }\n }\n $__cursorLeave = $__cursorAnsiFile -and -not $__cursorUtf8File\n }\n }\n } catch { $__cursorLeave = $false }\n # An -Encoding on the command line or from a default is the caller's, and -AsByteStream\n # (PowerShell 7's -Encoding Byte) reads no text.\n if (-not $__cursorLeave -and -not $PSBoundParameters.ContainsKey('Encoding') -and -not $PSBoundParameters.ContainsKey('AsByteStream')) {\n $PSBoundParameters['Encoding'] = 'UTF8'\n }\n # An error the caller asked to stop on ends the caller too, as it does from the cmdlet.\n # Any other terminating error of the cmdlet ends the statement and the caller goes on, as\n # with the writers' proxy; the pipeline it ended is not stepped again.\n try {\n $outBuffer = $null\n if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { $PSBoundParameters['OutBuffer'] = 1 }\n $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('__CURSORTARGET__', [System.Management.Automation.CommandTypes]::Cmdlet)\n $scriptCmd = { & $wrappedCmd @PSBoundParameters }\n $steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)\n # The cmdlet binds here in a scope under this call's, where the variable the\n # dynamicparam block set keeps the default for the module-qualified call off, so the\n # reading above stands.\n $steppablePipeline.Begin($PSCmdlet)\n } catch [System.Management.Automation.ActionPreferenceStopException] { throw }\n catch { $__cursorStopped = $true; $PSCmdlet.ThrowTerminatingError($_) }\n}\nprocess {\n if ($__cursorStopped) { return }\n try { $steppablePipeline.Process($_) }\n catch [System.Management.Automation.ActionPreferenceStopException] { throw }\n catch { $__cursorStopped = $true; $PSCmdlet.ThrowTerminatingError($_) }\n}\nend {\n if ($__cursorStopped) { return }\n try { $steppablePipeline.End() }\n catch [System.Management.Automation.ActionPreferenceStopException] { throw }\n catch { $__cursorStopped = $true; $PSCmdlet.ThrowTerminatingError($_) }\n}\n'@\n if (-not $__cursorHasEncodingDefault) {\n try {\n # A function of this name that a profile defined stays in charge; the proxy is built on the cmdlet alone.\n $__cursorCmdlet = @(Microsoft.PowerShell.Core\\Get-Command -Name Get-Content -ErrorAction Stop)[0]\n if ($__cursorCmdlet.CommandType -eq 'Cmdlet') {\n $__cursorTarget = "$($__cursorCmdlet.ModuleName)\\$($__cursorCmdlet.Name)"\n $__cursorMetadata = New-Object System.Management.Automation.CommandMetadata $__cursorCmdlet\n $__cursorProxyText = @(\n '<#', ".ForwardHelpTargetName $__cursorTarget", '.ForwardHelpCategory Cmdlet', '#>',\n [System.Management.Automation.ProxyCommand]::GetCmdletBindingAttribute($__cursorMetadata),\n 'param(', [System.Management.Automation.ProxyCommand]::GetParamBlock($__cursorMetadata), ')',\n # The proxy's own -Encoding is bound after this block runs, and must stay unbound\n # unless the caller gave one: the default below is off while this variable is in\n # scope, which it is from here, through the binding of the cmdlet the proxy steps,\n # to the end of the call. It is a variable of the call's own scope, so a call whose\n # body never runs, as when a completer or Get-Command binds the parameters or a\n # bind fails, leaves nothing behind.\n 'dynamicparam {', '$__cursorGetContentBinding = $true',\n [System.Management.Automation.ProxyCommand]::GetDynamicParam($__cursorMetadata), '}',\n $__cursorReaderBody.Replace('__CURSORTARGET__', $__cursorTarget)\n ) -join [Environment]::NewLine\n # Global, as a profile would define it, so that a module's code reaches it too.\n Microsoft.PowerShell.Management\\Set-Item -LiteralPath 'function:global:Get-Content' -Value ([scriptblock]::Create($__cursorProxyText)) -ErrorAction Stop\n }\n } catch { }\n # A call that names the cmdlet by its module, Microsoft.PowerShell.Management\\Get-Content,\n # bypasses a function of the cmdlet's name; this default keeps it reading UTF-8, as the\n # default this proxy replaced did. A default from a script block is not applied when the\n # block returns nothing, which it does while the proxy binds: the block runs in the scope\n # of the call being bound, where the proxy's variable is in scope. The global, never set\n # to anything else, is what the block reads outside such a call, and under strict mode a\n # variable it could not read would be an error. The string is the name of the encoding\n # on Windows PowerShell; PowerShell 7 takes an encoding object from a block.\n try {\n $global:__cursorGetContentBinding = $false\n $PSDefaultParameterValues['Get-Content:Encoding'] = {\n if (-not $__cursorGetContentBinding) {\n if ($PSVersionTable.PSEdition -eq 'Core') { [System.Text.UTF8Encoding]::new($true) } else { 'UTF8' }\n }\n }\n } catch { }\n }\n # The body of the proxy for Set-Content and Export-Csv. Its param block comes from the\n # cmdlet itself. Every step of its own is guarded, so a failure in the proxy leaves the\n # file as the cmdlet writes it.\n $__cursorProxyBody = @'\nbegin {\n # The file system paths the call writes, each with its own 'bom' or 'nobom', and what each\n # held before the call; the call gets -Encoding only when every path has a decision.\n $__cursorFiles = $null\n $__cursorDecisions = @{}\n $__cursorBefore = @{}\n $__cursorDecided = $false\n # The command line asked for UTF8 by name, for files whose readers take it without a BOM.\n $__cursorAsked = $false\n $__cursorStrip = $false\n $__cursorStopped = $false\n $__cursorScopeBound = $null\n $__cursorInvoked = "$($MyInvocation.InvocationName)"\n # The first 8 KiB of the file and its length; $null for a file that does not exist.\n $__cursorHeadOf = {\n param([string]$__cursorFile)\n if (-not [System.IO.File]::Exists($__cursorFile)) { return $null }\n $__cursorHead = New-Object byte[] 8192\n $__cursorCount = 0\n $__cursorStream = [System.IO.File]::Open($__cursorFile, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read, [System.IO.FileShare]::ReadWrite -bor [System.IO.FileShare]::Delete)\n try {\n $__cursorLength = $__cursorStream.Length\n while ($__cursorCount -lt $__cursorHead.Length) {\n $__cursorRead = $__cursorStream.Read($__cursorHead, $__cursorCount, $__cursorHead.Length - $__cursorCount)\n if ($__cursorRead -le 0) { break }\n $__cursorCount += $__cursorRead\n }\n } finally { $__cursorStream.Dispose() }\n return @{ Length = $__cursorLength; Head = $__cursorHead; Count = $__cursorCount }\n }\n # 'bom' or 'nobom' for a file the proxy writes in UTF-8, $null for one it leaves to the\n # cmdlet: the file's own bytes decide when it has content, its extension otherwise.\n $__cursorEncodingOf = {\n param([string]$__cursorFile, $__cursorWas)\n $__cursorExtension = [System.IO.Path]::GetExtension($__cursorFile).ToLowerInvariant()\n if ($__cursorExtension -in @(${dn([".bat",".cmd",".reg",".ini",".inf",".vbs",".vbe",".wsf"])})) { return $null }\n if ([System.IO.Directory]::Exists($__cursorFile)) { return $null }\n if ($null -ne $__cursorWas -and $__cursorWas.Count -gt 0) {\n $__cursorHead = $__cursorWas.Head\n $__cursorEnd = $__cursorWas.Count\n if ($__cursorEnd -ge 3 -and $__cursorHead[0] -eq 0xEF -and $__cursorHead[1] -eq 0xBB -and $__cursorHead[2] -eq 0xBF) { return 'bom' }\n if ($__cursorEnd -ge 2 -and (($__cursorHead[0] -eq 0xFF -and $__cursorHead[1] -eq 0xFE) -or ($__cursorHead[0] -eq 0xFE -and $__cursorHead[1] -eq 0xFF))) { return $null }\n if ($__cursorEnd -eq $__cursorHead.Length) {\n # A full header may end inside a character; that character is left out.\n $__cursorAt = $__cursorEnd - 1\n while ($__cursorAt -gt $__cursorEnd - 4 -and ($__cursorHead[$__cursorAt] -band 0xC0) -eq 0x80) { $__cursorAt-- }\n if ($__cursorHead[$__cursorAt] -ge 0xC0) {\n $__cursorNeed = if ($__cursorHead[$__cursorAt] -ge 0xF0) { 4 } elseif ($__cursorHead[$__cursorAt] -ge 0xE0) { 3 } else { 2 }\n if ($__cursorEnd - $__cursorAt -lt $__cursorNeed) { $__cursorEnd = $__cursorAt }\n }\n }\n # A strict decode throws on bytes that are not UTF-8; a character beyond ASCII takes\n # more bytes than code units, so all-ASCII content is the one that decodes to as many.\n try { $__cursorText = [System.Text.UTF8Encoding]::new($false, $true).GetString($__cursorHead, 0, $__cursorEnd) } catch { return $null }\n if ($__cursorText.Length -lt $__cursorEnd) { return 'nobom' }\n }\n if ($__cursorExtension -in @(${dn([".ps1",".psm1",".psd1"])})) { return 'bom' }\n if ($__cursorExtension -in @(${dn([".py",".pyw",".pyi",".js",".mjs",".cjs",".jsx",".ts",".tsx",".mts",".cts",".go",".rs",".kt",".kts",".scala",".swift",".dart",".rb",".cs",".fs",".fsx",".vb",".razor",".cshtml",".sh",".bash",".zsh",".html",".htm",".css",".scss",".sass",".less",".vue",".svelte",".json",".jsonc",".json5",".yaml",".yml",".toml",".xml",".xsd",".xsl",".xslt",".svg",".csproj",".props",".targets",".graphql",".gql",".proto",".tf",".hcl",".md",".markdown",".mdx",".rst",".adoc",".gitignore",".gitattributes",".gitmodules",".editorconfig",".cursorignore",".cursorindexingignore",".mdc"])})) { return 'nobom' }\n return $null\n }\n # Whether the -Encoding the call bound is the UTF-8 with a BOM that Windows PowerShell names\n # UTF8. PowerShell 7 binds the encoding object of that name, and reaches this only when a\n # test fakes the version.\n $__cursorIsUtf8Bom = {\n param($__cursorEncoding)\n if ($__cursorEncoding -is [System.Text.Encoding]) { return ($__cursorEncoding -is [System.Text.UTF8Encoding] -and $__cursorEncoding.GetPreamble().Length -gt 0) }\n return ("$__cursorEncoding" -eq 'UTF8')\n }\n # Whether a default under $PSDefaultParameterValues can reach this call's -Encoding: under\n # the cmdlet's name, an alias it had when the proxy was built, or the name the call used. A\n # value such a default put in $PSBoundParameters is not one the command line asked for.\n $__cursorHasEncodingDefault = {\n param([string]$__cursorInvoked)\n foreach ($__cursorKey in @($PSDefaultParameterValues.Keys)) {\n $__cursorKeyParts = "$__cursorKey" -split ':', 2\n if ($__cursorKeyParts.Count -ne 2 -or 'Encoding' -notlike $__cursorKeyParts[1].Trim()) { continue }\n foreach ($__cursorName in @(__CURSORNAMES__, $__cursorInvoked)) {\n if ($__cursorName -like $__cursorKeyParts[0].Trim()) { return $true }\n }\n }\n return $false\n }\n # Whether a UTF8 asked for by name is UTF-8 without a BOM for this file: one whose reader\n # rejects a BOM, and that is new, empty or starts with no BOM of any encoding.\n $__cursorTakesNoBom = {\n param([string]$__cursorFile, $__cursorWas)\n if ([System.IO.Directory]::Exists($__cursorFile)) { return $false }\n if ([System.IO.Path]::GetExtension($__cursorFile).ToLowerInvariant() -notin @(${dn([".json",".py",".js",".ts",".sh",".yaml",".toml",".mdc"])}) -and\n [System.IO.Path]::GetFileName($__cursorFile).ToLowerInvariant() -notin @(${dn([".gitignore",".editorconfig"])})) { return $false }\n if ($null -eq $__cursorWas -or $__cursorWas.Count -lt 2) { return $true }\n $__cursorHead = $__cursorWas.Head\n if ($__cursorWas.Count -ge 3 -and $__cursorHead[0] -eq 0xEF -and $__cursorHead[1] -eq 0xBB -and $__cursorHead[2] -eq 0xBF) { return $false }\n if (($__cursorHead[0] -eq 0xFF -and $__cursorHead[1] -eq 0xFE) -or ($__cursorHead[0] -eq 0xFE -and $__cursorHead[1] -eq 0xFF)) { return $false }\n if ($__cursorWas.Count -ge 4 -and $__cursorHead[0] -eq 0 -and $__cursorHead[1] -eq 0 -and $__cursorHead[2] -eq 0xFE -and $__cursorHead[3] -eq 0xFF) { return $false }\n return $true\n }\n # Takes a UTF-8 BOM off the front of the file in place, unless it is to stay and the\n # content has a character beyond ASCII. A file the cmdlet left as it was is not touched.\n $__cursorStripBom = {\n param([string]$__cursorFile, [bool]$__cursorKeepUnlessAscii, $__cursorWas)\n if (-not [System.IO.File]::Exists($__cursorFile)) { return }\n $__cursorStream = $null\n # The cmdlet may still hold the file for a moment after it returns.\n for ($__cursorAttempt = 0; $__cursorAttempt -lt 5 -and $null -eq $__cursorStream; $__cursorAttempt++) {\n try { $__cursorStream = [System.IO.File]::Open($__cursorFile, [System.IO.FileMode]::Open, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None) }\n catch [System.IO.FileNotFoundException] { return }\n catch [System.IO.DirectoryNotFoundException] { return }\n catch [System.IO.IOException] { Start-Sleep -Milliseconds 20 }\n catch { return }\n }\n if ($null -eq $__cursorStream) { return }\n try {\n $__cursorBuffer = New-Object byte[] 65536\n if ($null -ne $__cursorWas -and $__cursorWas.Length -eq $__cursorStream.Length) {\n $__cursorCount = 0\n while ($__cursorCount -lt $__cursorWas.Count) {\n $__cursorRead = $__cursorStream.Read($__cursorBuffer, $__cursorCount, $__cursorWas.Count - $__cursorCount)\n if ($__cursorRead -le 0) { break }\n $__cursorCount += $__cursorRead\n }\n if ($__cursorCount -eq $__cursorWas.Count -and [System.Convert]::ToBase64String($__cursorBuffer, 0, $__cursorCount) -eq [System.Convert]::ToBase64String($__cursorWas.Head, 0, $__cursorCount)) { return }\n $__cursorStream.Position = 0\n }\n if ($__cursorStream.Read($__cursorBuffer, 0, 3) -ne 3 -or $__cursorBuffer[0] -ne 0xEF -or $__cursorBuffer[1] -ne 0xBB -or $__cursorBuffer[2] -ne 0xBF) { return }\n if ($__cursorKeepUnlessAscii) {\n while (($__cursorRead = $__cursorStream.Read($__cursorBuffer, 0, $__cursorBuffer.Length)) -gt 0) {\n if ([regex]::IsMatch([System.Text.Encoding]::UTF8.GetString($__cursorBuffer, 0, $__cursorRead), '[^\\x00-\\x7F]')) { return }\n }\n }\n $__cursorReadAt = 3L\n $__cursorWriteAt = 0L\n while ($__cursorReadAt -lt $__cursorStream.Length) {\n $__cursorStream.Position = $__cursorReadAt\n $__cursorRead = $__cursorStream.Read($__cursorBuffer, 0, $__cursorBuffer.Length)\n if ($__cursorRead -le 0) { break }\n $__cursorStream.Position = $__cursorWriteAt\n $__cursorStream.Write($__cursorBuffer, 0, $__cursorRead)\n $__cursorReadAt += $__cursorRead\n $__cursorWriteAt += $__cursorRead\n }\n $__cursorStream.SetLength($__cursorWriteAt)\n } catch { } finally { $__cursorStream.Dispose() }\n }\n try {\n $__cursorBound = $null\n if ($PSBoundParameters.ContainsKey('Path')) { $__cursorBound = @{ Path = $PSBoundParameters['Path'] } }\n elseif ($PSBoundParameters.ContainsKey('LiteralPath')) { $__cursorBound = @{ LiteralPath = $PSBoundParameters['LiteralPath'] } }\n if ($null -ne $__cursorBound) {\n # The file system paths that -Path or -LiteralPath names; none when one is on another\n # provider or a wildcard matches nothing.\n $__cursorLiteral = $__cursorBound.ContainsKey('LiteralPath')\n $__cursorFiles = New-Object System.Collections.Generic.List[string]\n foreach ($__cursorPath in @(@($__cursorBound.Values)[0])) {\n $__cursorProvider = $null\n $__cursorDrive = $null\n if ($__cursorLiteral -or -not [System.Management.Automation.WildcardPattern]::ContainsWildcardCharacters("$__cursorPath")) {\n $__cursorResolved = @($ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath("$__cursorPath", [ref]$__cursorProvider, [ref]$__cursorDrive))\n } else {\n $__cursorResolved = @($ExecutionContext.SessionState.Path.GetResolvedProviderPathFromPSPath("$__cursorPath", [ref]$__cursorProvider))\n }\n if ($null -ne $__cursorProvider -and $__cursorProvider.Name -in @('Variable', 'Function', 'Alias')) { $__cursorScopeBound = $__cursorProvider.Name }\n if ($null -eq $__cursorProvider -or $__cursorProvider.Name -ne 'FileSystem' -or $__cursorResolved.Count -eq 0) { $__cursorFiles = $null; break }\n $__cursorFiles.AddRange([string[]]$__cursorResolved)\n }\n }\n # -WhatIf sets $WhatIfPreference and -Confirm sets $ConfirmPreference in this scope.\n if ($null -ne $__cursorFiles -and $__cursorFiles.Count -gt 0 -and -not $PSBoundParameters.ContainsKey('Encoding') -and\n -not $WhatIfPreference -and $ConfirmPreference -notin @('Low', 'Medium') -and -not $PSBoundParameters.ContainsKey('Stream') -and\n -not $PSBoundParameters.ContainsKey('Filter') -and -not $PSBoundParameters.ContainsKey('Include') -and\n -not $PSBoundParameters.ContainsKey('Exclude')) {\n $__cursorAppend = ($PSBoundParameters.ContainsKey('Append') -and $PSBoundParameters['Append']) -or ($PSBoundParameters.ContainsKey('NoClobber') -and $PSBoundParameters['NoClobber'])\n $__cursorDecided = $true\n $__cursorStrip = $true\n foreach ($__cursorFile in $__cursorFiles) {\n $__cursorBefore[$__cursorFile] = & $__cursorHeadOf $__cursorFile\n $__cursorDecisions[$__cursorFile] = & $__cursorEncodingOf $__cursorFile $__cursorBefore[$__cursorFile]\n if ($null -eq $__cursorDecisions[$__cursorFile]) { $__cursorDecided = $false; break }\n # An append onto a file with content writes no BOM, so there is none to take off.\n if ($__cursorAppend -and $null -ne $__cursorBefore[$__cursorFile] -and $__cursorBefore[$__cursorFile].Length -gt 0) { $__cursorStrip = $false }\n }\n }\n elseif ($null -ne $__cursorFiles -and $__cursorFiles.Count -gt 0 -and $PSBoundParameters.ContainsKey('Encoding') -and\n (& $__cursorIsUtf8Bom $PSBoundParameters['Encoding']) -and -not (& $__cursorHasEncodingDefault $__cursorInvoked) -and\n -not $WhatIfPreference -and $ConfirmPreference -notin @('Low', 'Medium') -and -not $PSBoundParameters.ContainsKey('Stream') -and\n -not $PSBoundParameters.ContainsKey('Filter') -and -not $PSBoundParameters.ContainsKey('Include') -and\n -not $PSBoundParameters.ContainsKey('Exclude')) {\n # The UTF8 the command line asked for is UTF-8 with a BOM on this shell and without\n # one on PowerShell 7. For a file whose reader rejects a BOM, and that has none, it\n # means what it means there: the cmdlet writes its BOM, and the proxy takes it off.\n $__cursorAsked = $true\n foreach ($__cursorFile in $__cursorFiles) {\n $__cursorBefore[$__cursorFile] = & $__cursorHeadOf $__cursorFile\n if (-not (& $__cursorTakesNoBom $__cursorFile $__cursorBefore[$__cursorFile])) { $__cursorAsked = $false; break }\n $__cursorDecisions[$__cursorFile] = 'nobom'\n }\n $__cursorStrip = $__cursorAsked\n }\n } catch { $__cursorDecided = $false; $__cursorAsked = $false }\n if ($__cursorDecided) { $PSBoundParameters['Encoding'] = '__CURSORUTF8__' }\n if ($null -ne $__cursorScopeBound) {\n Write-Warning "__CURSORNAME__ runs through a function in this shell, so an item it writes to the $__cursorScopeBound provider lives in a scope that ends with the call. Use an assignment, a function definition or Set-Alias instead."\n }\n # An error the caller asked to stop on ends the caller too, as it does from the cmdlet: it\n # goes on as it is, as from the proxy PowerShell itself generates, which rethrows everything\n # with 'throw'. Any other terminating error of the cmdlet ends the statement and the caller\n # goes on; ThrowTerminatingError keeps that rule, where 'throw' would end the caller's whole\n # script, and the pipeline it ended is not stepped again. Of the two, only the cmdlet's own\n # terminating error names this function rather than the cmdlet's type in the suffix of its\n # FullyQualifiedErrorId; the record of an error the caller asked to stop on is the cmdlet's.\n try {\n $outBuffer = $null\n if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { $PSBoundParameters['OutBuffer'] = 1 }\n $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('__CURSORTARGET__', [System.Management.Automation.CommandTypes]::Cmdlet)\n $scriptCmd = { & $wrappedCmd @PSBoundParameters }\n $steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)\n $steppablePipeline.Begin($PSCmdlet)\n } catch [System.Management.Automation.ActionPreferenceStopException] { throw }\n catch { $__cursorStopped = $true; $PSCmdlet.ThrowTerminatingError($_) }\n}\nprocess {\n if ($__cursorStopped) { return }\n try { $steppablePipeline.Process($_) }\n catch [System.Management.Automation.ActionPreferenceStopException] { throw }\n catch { $__cursorStopped = $true; $PSCmdlet.ThrowTerminatingError($_) }\n}\nend {\n if ($__cursorStopped) { return }\n try { $steppablePipeline.End() }\n catch [System.Management.Automation.ActionPreferenceStopException] { throw }\n catch { $__cursorStopped = $true; $PSCmdlet.ThrowTerminatingError($_) }\n if (-not $__cursorStrip -or -not ($__cursorDecided -or $__cursorAsked)) { return }\n try {\n foreach ($__cursorFile in $__cursorFiles) { & $__cursorStripBom $__cursorFile ($__cursorDecisions[$__cursorFile] -eq 'bom') $__cursorBefore[$__cursorFile] }\n } catch { }\n}\n'@\n foreach ($__cursorWriter in @('Set-Content', 'Export-Csv')) {\n $__cursorWriterNames = @($__cursorWriter) + @(Get-Alias -Definition $__cursorWriter -ErrorAction Ignore | ForEach-Object { $_.Name })\n $__cursorHasWriterDefault = $false\n foreach ($__cursorKey in @($PSDefaultParameterValues.Keys)) {\n $__cursorKeyParts = "$__cursorKey" -split ':', 2\n if ($__cursorKeyParts.Count -ne 2 -or 'Encoding' -notlike $__cursorKeyParts[1].Trim()) { continue }\n foreach ($__cursorName in $__cursorWriterNames) {\n if ($__cursorName -like $__cursorKeyParts[0].Trim()) { $__cursorHasWriterDefault = $true }\n }\n }\n if ($__cursorHasWriterDefault) { continue }\n try {\n # A function of this name that a profile defined stays in charge; the proxy is built on the cmdlet alone.\n $__cursorCmdlet = @(Microsoft.PowerShell.Core\\Get-Command -Name $__cursorWriter -ErrorAction Stop)[0]\n if ($__cursorCmdlet.CommandType -eq 'Cmdlet') {\n $__cursorTarget = "$($__cursorCmdlet.ModuleName)\\$($__cursorCmdlet.Name)"\n $__cursorMetadata = New-Object System.Management.Automation.CommandMetadata $__cursorCmdlet\n $__cursorNamesList = @($__cursorWriterNames | ForEach-Object { "'" + $_.Replace("'", "''") + "'" }) -join ', '\n $__cursorProxyText = @(\n '<#', ".ForwardHelpTargetName $__cursorTarget", '.ForwardHelpCategory Cmdlet', '#>',\n [System.Management.Automation.ProxyCommand]::GetCmdletBindingAttribute($__cursorMetadata),\n 'param(', [System.Management.Automation.ProxyCommand]::GetParamBlock($__cursorMetadata), ')',\n 'dynamicparam {', [System.Management.Automation.ProxyCommand]::GetDynamicParam($__cursorMetadata), '}',\n $__cursorProxyBody.Replace('__CURSORTARGET__', $__cursorTarget).Replace('__CURSORNAMES__', $__cursorNamesList).Replace('__CURSORNAME__', $__cursorCmdlet.Name).Replace('__CURSORUTF8__', $__cursorUtf8)\n ) -join [Environment]::NewLine\n # Global, as a profile would define it, so that a module's code reaches it too.\n Microsoft.PowerShell.Management\\Set-Item -LiteralPath "function:global:$__cursorWriter" -Value ([scriptblock]::Create($__cursorProxyText)) -ErrorAction Stop\n }\n } catch { }\n }\n }\n} catch { }\n`,pn=String.raw`
|
|
2
|
-
try {
|
|
3
|
-
if ($PSVersionTable.PSVersion.Major -lt 6 -and [Console]::OutputEncoding.CodePage -eq 65001) {
|
|
4
|
-
function global:__cursorUtf8FromLatin1 {
|
|
5
|
-
param([string]$Text)
|
|
6
|
-
Set-StrictMode -Off
|
|
7
|
-
if ($Text.Length -eq 0 -or $Text -cnotmatch '[\u0080-\u00FF]' -or $Text -cmatch '[\u0100-\uFFFF]') { return $null }
|
|
8
|
-
try {
|
|
9
|
-
$bytes = [System.Text.Encoding]::GetEncoding(28591).GetBytes($Text)
|
|
10
|
-
$decoded = (New-Object System.Text.UTF8Encoding($false, $true)).GetString($bytes)
|
|
11
|
-
} catch { return $null }
|
|
12
|
-
if ($decoded.Length -gt 0 -and $decoded[0] -eq [char]0xFEFF) { $decoded = $decoded.Substring(1) }
|
|
13
|
-
return $decoded
|
|
14
|
-
}
|
|
15
|
-
function global:__cursorDeclaresOtherCharset {
|
|
16
|
-
param([string]$Text)
|
|
17
|
-
Set-StrictMode -Off
|
|
18
|
-
if ($Text.Length -eq 0) { return $false }
|
|
19
|
-
$head = $Text.Substring(0, [Math]::Min($Text.Length, 1024))
|
|
20
|
-
$options = [System.Text.RegularExpressions.RegexOptions]'IgnoreCase, Singleline, CultureInvariant'
|
|
21
|
-
$declared = [regex]::Match($head, '<meta\s.*[^.><]*charset\s*=\s*["''\n]?(?<charset>[A-Za-z].[^\s"''\n<>]*)[\s"''\n>]', $options)
|
|
22
|
-
if (-not $declared.Success) { $declared = [regex]::Match($head, '<\?xml\s.*[^.><]*encoding\s*=\s*["''\n]?(?<charset>[A-Za-z].[^\s"''\n<>]*)[\s"''\n>]', $options) }
|
|
23
|
-
if (-not $declared.Success) { return $false }
|
|
24
|
-
try { return [System.Text.Encoding]::GetEncoding($declared.Groups['charset'].Value).CodePage -ne 65001 } catch { return $false }
|
|
25
|
-
}
|
|
26
|
-
function global:__cursorFixWebResponse {
|
|
27
|
-
param([Parameter(ValueFromPipeline = $true)]$Response)
|
|
28
|
-
process {
|
|
29
|
-
Set-StrictMode -Off
|
|
30
|
-
try {
|
|
31
|
-
if ($null -ne $Response -and $Response.Content -is [string]) {
|
|
32
|
-
$contentType = $null
|
|
33
|
-
try { $contentType = [string]$Response.BaseResponse.ContentType } catch { }
|
|
34
|
-
if (-not $contentType -and $Response.Headers) {
|
|
35
|
-
foreach ($name in @($Response.Headers.Keys)) {
|
|
36
|
-
if ($name -ieq 'Content-Type') { $contentType = [string]$Response.Headers[$name] }
|
|
37
|
-
}
|
|
38
|
-
}
|
|
39
|
-
if ($contentType -notmatch '(?i);\s*charset\s*=' -and -not (__cursorDeclaresOtherCharset $Response.Content)) {
|
|
40
|
-
$content = $Response.Content
|
|
41
|
-
$fixed = __cursorUtf8FromLatin1 $content
|
|
42
|
-
if ($null -ne $fixed) {
|
|
43
|
-
$raw = $Response.RawContent
|
|
44
|
-
$fixedRaw = $null
|
|
45
|
-
if ($raw -is [string] -and $raw.EndsWith($content)) { $fixedRaw = $raw.Substring(0, $raw.Length - $content.Length) + $fixed }
|
|
46
|
-
$Response | Add-Member -NotePropertyName Content -NotePropertyValue $fixed -Force -ErrorAction Stop
|
|
47
|
-
if ($null -ne $fixedRaw) {
|
|
48
|
-
# Content and RawContent change together or not at all.
|
|
49
|
-
try { $Response | Add-Member -NotePropertyName RawContent -NotePropertyValue $fixedRaw -Force -ErrorAction Stop }
|
|
50
|
-
catch { $Response | Add-Member -NotePropertyName Content -NotePropertyValue $content -Force -ErrorAction Stop }
|
|
51
|
-
}
|
|
52
|
-
}
|
|
53
|
-
}
|
|
54
|
-
}
|
|
55
|
-
} catch { }
|
|
56
|
-
,$Response
|
|
57
|
-
}
|
|
58
|
-
}
|
|
59
|
-
function global:__cursorIsRestContainer {
|
|
60
|
-
param($Value)
|
|
61
|
-
Set-StrictMode -Off
|
|
62
|
-
return $Value -is [System.Management.Automation.PSCustomObject] -or $Value -is [System.Collections.IList] -or $Value -is [System.Xml.XmlNode]
|
|
63
|
-
}
|
|
64
|
-
function global:__cursorRestOutputText {
|
|
65
|
-
param($Value)
|
|
66
|
-
Set-StrictMode -Off
|
|
67
|
-
if ($Value -is [string]) { return $Value }
|
|
68
|
-
if ($Value -is [System.Xml.XmlNode]) { return [string]$Value.OuterXml }
|
|
69
|
-
# Windows PowerShell's serializer writes every character above U+007F as a \uXXXX
|
|
70
|
-
# escape, so the text alone would never show one; the escapes are read back, in
|
|
71
|
-
# .NET, before the string test sees the text.
|
|
72
|
-
return [regex]::Unescape([string](ConvertTo-Json -InputObject $Value -Depth 100 -Compress -WarningAction SilentlyContinue))
|
|
73
|
-
}
|
|
74
|
-
function global:__cursorFixRestValue {
|
|
75
|
-
param($Value)
|
|
76
|
-
Set-StrictMode -Off
|
|
77
|
-
if ($Value -is [string]) {
|
|
78
|
-
$fixed = __cursorUtf8FromLatin1 $Value
|
|
79
|
-
if ($null -eq $fixed) { return ,$Value }
|
|
80
|
-
return ,$fixed
|
|
81
|
-
}
|
|
82
|
-
if (-not (__cursorIsRestContainer $Value)) { return ,$Value }
|
|
83
|
-
# A slot is a list and an index, a property or an XML node and no index, or neither
|
|
84
|
-
# for the value itself. Every rewrite is noted against its slot and made at the end,
|
|
85
|
-
# once every string with a character of U+0080-U+00FF has passed the strict round
|
|
86
|
-
# trip: one that does not, or one character above U+00FF, which no Latin-1 read
|
|
87
|
-
# produces, leaves the whole value as the cmdlet returned it.
|
|
88
|
-
$root = $Value
|
|
89
|
-
$edits = New-Object System.Collections.Generic.List[object]
|
|
90
|
-
$pending = New-Object System.Collections.Stack
|
|
91
|
-
$pending.Push(@{ Target = $null; Key = $null; Value = $Value; Depth = 0 })
|
|
92
|
-
while ($pending.Count -gt 0) {
|
|
93
|
-
$entry = $pending.Pop()
|
|
94
|
-
$current = $entry.Value
|
|
95
|
-
if ($entry.Depth -gt 100) { continue }
|
|
96
|
-
if ($current -is [System.Management.Automation.PSCustomObject]) {
|
|
97
|
-
$renamed = $false
|
|
98
|
-
foreach ($property in $current.PSObject.Properties) {
|
|
99
|
-
if ($property.Name -cmatch '[\u0080-\uFFFF]') {
|
|
100
|
-
if ($null -eq (__cursorUtf8FromLatin1 $property.Name)) { return ,$Value }
|
|
101
|
-
$renamed = $true
|
|
102
|
-
}
|
|
103
|
-
}
|
|
104
|
-
if ($renamed) {
|
|
105
|
-
$rebuilt = New-Object System.Management.Automation.PSObject
|
|
106
|
-
foreach ($property in $current.PSObject.Properties) {
|
|
107
|
-
$name = $property.Name
|
|
108
|
-
if ($name -cmatch '[\u0080-\uFFFF]') { $name = __cursorUtf8FromLatin1 $name }
|
|
109
|
-
$rebuilt | Add-Member -NotePropertyName $name -NotePropertyValue $property.Value -ErrorAction Stop
|
|
110
|
-
}
|
|
111
|
-
$edits.Add(@{ Target = $entry.Target; Key = $entry.Key; Value = $rebuilt })
|
|
112
|
-
$current = $rebuilt
|
|
113
|
-
}
|
|
114
|
-
foreach ($property in $current.PSObject.Properties) {
|
|
115
|
-
$item = $property.Value
|
|
116
|
-
if ($item -is [string]) {
|
|
117
|
-
if ($item -cmatch '[\u0080-\uFFFF]') {
|
|
118
|
-
$fixed = __cursorUtf8FromLatin1 $item
|
|
119
|
-
if ($null -eq $fixed) { return ,$Value }
|
|
120
|
-
$edits.Add(@{ Target = $property; Key = $null; Value = $fixed })
|
|
121
|
-
}
|
|
122
|
-
} elseif (__cursorIsRestContainer $item) {
|
|
123
|
-
$pending.Push(@{ Target = $property; Key = $null; Value = $item; Depth = $entry.Depth + 1 })
|
|
124
|
-
}
|
|
125
|
-
}
|
|
126
|
-
} elseif ($current -is [System.Collections.IList]) {
|
|
127
|
-
for ($i = 0; $i -lt $current.Count; $i++) {
|
|
128
|
-
$item = $current[$i]
|
|
129
|
-
if ($item -is [string]) {
|
|
130
|
-
if ($item -cmatch '[\u0080-\uFFFF]') {
|
|
131
|
-
$fixed = __cursorUtf8FromLatin1 $item
|
|
132
|
-
if ($null -eq $fixed) { return ,$Value }
|
|
133
|
-
$edits.Add(@{ Target = $current; Key = $i; Value = $fixed })
|
|
134
|
-
}
|
|
135
|
-
} elseif (__cursorIsRestContainer $item) {
|
|
136
|
-
$pending.Push(@{ Target = $current; Key = $i; Value = $item; Depth = $entry.Depth + 1 })
|
|
137
|
-
}
|
|
138
|
-
}
|
|
139
|
-
} elseif ($current -is [System.Xml.XmlNode]) {
|
|
140
|
-
foreach ($node in $current.SelectNodes('.//text() | .//@* | .//comment()')) {
|
|
141
|
-
if ($node.Value -cmatch '[\u0080-\uFFFF]') {
|
|
142
|
-
$fixed = __cursorUtf8FromLatin1 $node.Value
|
|
143
|
-
if ($null -eq $fixed) { return ,$Value }
|
|
144
|
-
$edits.Add(@{ Target = $node; Key = $null; Value = $fixed })
|
|
145
|
-
}
|
|
146
|
-
}
|
|
147
|
-
}
|
|
148
|
-
}
|
|
149
|
-
foreach ($edit in $edits) {
|
|
150
|
-
if ($null -eq $edit.Target) { $root = $edit.Value }
|
|
151
|
-
elseif ($null -eq $edit.Key) { $edit.Target.Value = $edit.Value }
|
|
152
|
-
else { $edit.Target[$edit.Key] = $edit.Value }
|
|
153
|
-
}
|
|
154
|
-
return ,$root
|
|
155
|
-
}
|
|
156
|
-
function global:__cursorFixRestResponse {
|
|
157
|
-
param([Parameter(ValueFromPipeline = $true)]$Response)
|
|
158
|
-
process {
|
|
159
|
-
Set-StrictMode -Off
|
|
160
|
-
$fixed = $Response
|
|
161
|
-
try {
|
|
162
|
-
if ($Response -is [string] -or (__cursorIsRestContainer $Response)) {
|
|
163
|
-
$text = __cursorRestOutputText $Response
|
|
164
|
-
$declared = ($Response -is [string] -or $Response -is [System.Xml.XmlNode]) -and (__cursorDeclaresOtherCharset $text)
|
|
165
|
-
if (-not $declared -and $null -ne (__cursorUtf8FromLatin1 $text)) { $fixed = __cursorFixRestValue $Response }
|
|
166
|
-
}
|
|
167
|
-
} catch { $fixed = $Response }
|
|
168
|
-
,$fixed
|
|
169
|
-
}
|
|
170
|
-
}
|
|
171
|
-
$__cursorWebProxyTemplate = @'
|
|
172
|
-
__BINDING__
|
|
173
|
-
param(
|
|
174
|
-
__PARAMS__
|
|
175
|
-
)
|
|
176
|
-
begin {
|
|
177
|
-
try {
|
|
178
|
-
$outBuffer = $null
|
|
179
|
-
if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { $PSBoundParameters['OutBuffer'] = 1 }
|
|
180
|
-
if ($PSBoundParameters.ContainsKey('SessionVariable') -and -not $PSBoundParameters.ContainsKey('WebSession')) {
|
|
181
|
-
$sessionName = [string]$PSBoundParameters['SessionVariable']
|
|
182
|
-
$webSession = New-Object Microsoft.PowerShell.Commands.WebRequestSession
|
|
183
|
-
if ($sessionName.Contains(':')) { $ExecutionContext.SessionState.PSVariable.Set($sessionName, $webSession) } else { Set-Variable -Name $sessionName -Value $webSession -Scope 1 }
|
|
184
|
-
[void]$PSBoundParameters.Remove('SessionVariable')
|
|
185
|
-
$PSBoundParameters['WebSession'] = $webSession
|
|
186
|
-
}
|
|
187
|
-
$wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Microsoft.PowerShell.Utility\__CMDLET__', [System.Management.Automation.CommandTypes]::Cmdlet)
|
|
188
|
-
$scriptCmd = { & $wrappedCmd @PSBoundParameters | __FILTER__ }
|
|
189
|
-
$steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)
|
|
190
|
-
$steppablePipeline.Begin($PSCmdlet)
|
|
191
|
-
} catch { $PSCmdlet.ThrowTerminatingError($_) }
|
|
192
|
-
}
|
|
193
|
-
process { try { $steppablePipeline.Process($_) } catch { $PSCmdlet.ThrowTerminatingError($_) } }
|
|
194
|
-
end { try { $steppablePipeline.End() } catch { $PSCmdlet.ThrowTerminatingError($_) } }
|
|
195
|
-
<#
|
|
196
|
-
.ForwardHelpTargetName Microsoft.PowerShell.Utility\__CMDLET__
|
|
197
|
-
.ForwardHelpCategory Cmdlet
|
|
198
|
-
#>
|
|
199
|
-
'@
|
|
200
|
-
foreach ($__cursorWebCmdletName in @('Invoke-WebRequest', 'Invoke-RestMethod')) {
|
|
201
|
-
$__cursorWebCmdlet = $ExecutionContext.InvokeCommand.GetCommand("Microsoft.PowerShell.Utility\$__cursorWebCmdletName", [System.Management.Automation.CommandTypes]::Cmdlet)
|
|
202
|
-
if (-not $__cursorWebCmdlet) { continue }
|
|
203
|
-
if (Test-Path -LiteralPath "Function:\$__cursorWebCmdletName") { continue }
|
|
204
|
-
$__cursorWebMetadata = New-Object System.Management.Automation.CommandMetadata $__cursorWebCmdlet
|
|
205
|
-
$__cursorWebFilter = if ($__cursorWebCmdletName -eq 'Invoke-WebRequest') { '__cursorFixWebResponse' } else { '__cursorFixRestResponse' }
|
|
206
|
-
$__cursorWebProxy = $__cursorWebProxyTemplate.Replace('__BINDING__', [System.Management.Automation.ProxyCommand]::GetCmdletBindingAttribute($__cursorWebMetadata)).Replace('__PARAMS__', [System.Management.Automation.ProxyCommand]::GetParamBlock($__cursorWebMetadata)).Replace('__CMDLET__', $__cursorWebCmdletName).Replace('__FILTER__', $__cursorWebFilter)
|
|
207
|
-
Set-Item -Path "Function:\global:$__cursorWebCmdletName" -Value ([scriptblock]::Create($__cursorWebProxy))
|
|
208
|
-
}
|
|
209
|
-
}
|
|
210
|
-
} catch { }
|
|
211
|
-
`;var fn=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const mn=(0,nn.v5)("shell_exec.powershell.phase_ms",{description:"Time in each phase of one stateful PowerShell command: process start to the wrapper's first statement, state restore, the command, the state dump to process exit, cleanup, and spawn to exit",labelNames:["phase","shell_kind","dump_mode"]});let gn;function wn(){const e=[process.platform,process.env.SHELL,process.env.PATH,process.env.SYSTEMROOT,process.cwd()].join("\0");if(gn?.key===e)return gn.executable;const t=function(){if("win32"!==process.platform){const e=process.env.SHELL;if(e?.includes("pwsh")||e?.includes("powershell"))return e}let e=S("pwsh",[]).cmd;if("pwsh"!==e)return e;if(e=S("powershell",[]).cmd,"powershell"!==e)return e;if("win32"===process.platform&&(e=f.join(process.env.SYSTEMROOT,"System32","WindowsPowerShell","v1.0","powershell.exe"),(0,m.existsSync)(e)))return e;throw new Error("Neither 'pwsh' (PowerShell Core) nor 'powershell' (Windows PowerShell) found in PATH")}();return gn={key:e,executable:t},t}function yn(e,t=process.platform){return"win32"!==t||f.win32.basename(e).toLowerCase().startsWith("pwsh")?"pwsh":"powershell51"}class vn{cwd;state;constructor(e,t){this.cwd=e,this.state=t}async getCwd(){return this.cwd}clone(e){return new vn(e??this.cwd,this.state)}async*execute(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(n,(0,fr.VI)(e.withName("PowerShellState.execute")),!1),s=r?.pipeStdin??!1,a=r?.workingDirectory??this.cwd,c=(0,mr.Jt)(),l=function(e,t=process.platform,r=process.env){const n={...r,...xr,...e?.env};return u(n),"win32"===t&&!0===e?.powershellUtf8ChildEnv&&(F(n),N(n)),i(n)}(r),d=A(l)?M(t):t,h=H.tmpdir(),p=f.join(h,`ps-state-out-${(0,W.randomUUID)()}.txt`),m="win32"===process.platform,g=((e,t,r,n,o)=>{const s=!0!==o?.perLineStateDump;return`${s?`$__cursorTimingStart = ${ln}`:""}\n${o?.utf8Console?un:""}\n${e}\n${hn}${o?.webRequestUtf8?pn:""}\n${o?.envInjection??""}\nSet-Location ${i=t,`'${i.replace(/['\u2018\u2019\u201A\u201B]/g,"$&$&")}'`}\n$env:NODE_DISABLE_COMPILE_CACHE = '1'\n$env:NODE_COMPILE_CACHE = $null${s?`\n$__cursorTimingRestored = ${ln}`:""}\n\n# PowerShell 5.1 does not treat \\" as an escaped quote, so cmd /c "rmdir /s /q \\"D:\\dir\\""\n# hands cmd a bare \\ (the drive root). Refuse double-quoted args that end in \\ and touch the next arg.\n${o?.parseAfterUtf8Switch?(e=>`# The command is parsed here, after the statements above ran, so a syntax error in it is\n# reported in the encoding they set and not in the console's start-up code page.\n$__cursorCommandText = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String('${Buffer.from(e,"utf8").toString("base64")}'))\n$__cursorParseErrors = $null\n$__cursorCommandAst = [System.Management.Automation.Language.Parser]::ParseInput($__cursorCommandText, [ref]$null, [ref]$__cursorParseErrors)\nif ($__cursorParseErrors.Count -gt 0) {\n foreach ($__cursorParseError in $__cursorParseErrors) {\n [Console]::Error.WriteLine($__cursorParseError.ToString())\n }\n exit 1\n}\n$__cursorCommand = $__cursorCommandAst.GetScriptBlock()`)(r):(e=>`$__cursorCommand = {\n${e}\n}`)(r)}\n$__cursorBrokenQuote = $__cursorCommand.Ast.Find({\n param($node)\n if ($node -isnot [System.Management.Automation.Language.CommandAst]) { return $false }\n $elements = $node.CommandElements\n for ($i = 0; $i -lt $elements.Count - 1; $i++) {\n $element = $elements[$i]\n if (($element -is [System.Management.Automation.Language.StringConstantExpressionAst] -or\n $element -is [System.Management.Automation.Language.ExpandableStringExpressionAst]) -and\n $element.StringConstantType -eq 'DoubleQuoted' -and\n $element.Value.EndsWith('\\') -and\n $elements[$i + 1].Extent.StartOffset -eq $element.Extent.EndOffset) {\n return $true\n }\n }\n return $false\n}, $true)\nif ($__cursorBrokenQuote) {\n [Console]::Error.WriteLine('Command refused: PowerShell does not treat \\" as an escaped quote, so a double-quoted string ends at \\" and the rest runs as separate arguments, near: ' + $__cursorBrokenQuote.Extent.Text)\n [Console]::Error.WriteLine('Quote the outer string with single quotes instead, or write a double quote inside a double-quoted string as \`".')\n exit 1\n}\n# Out-Default writes held-back table output before exit, dot-sourcing keeps the command's state for the dump\n. $__cursorCommand | Out-Default\n$COMMAND_EXIT_CODE = $LASTEXITCODE\n${s?`$__cursorTimingCommandDone = ${ln}\n\n${an}\nDump-PowerShellState -OutputFile "${n}" -Trailer ('${cn}{0} {1} {2} {3}' -f $__cursorTimingStart, $__cursorTimingRestored, $__cursorTimingCommandDone, $PSVersionTable.PSVersion.Major)`:`\n${sn}\nDump-PowerShellState -OutputFile "${n}"`}\n\nexit $COMMAND_EXIT_CODE\n`;var i})(this.state,a,d,p,{utf8Console:m&&!0===r?.powershellUtf8Console,parseAfterUtf8Switch:m&&!0===r?.powershellParseAfterUtf8Switch,envInjection:m&&!0===r?.powershellUtf8ChildEnv?B:"",webRequestUtf8:m&&!0===r?.powershellWebRequestUtf8,perLineStateDump:!0===r?.powershellPerLineStateDump}),w=f.join(h,`ps-script-${(0,W.randomUUID)()}.ps1`);await async function(e,t){await te.writeFile(e,"\ufeff"+t,{encoding:"utf8"})}(w,g);const y=["-ExecutionPolicy","Bypass"];s||y.push("-NonInteractive"),y.push("-File",w);const v=wn(),b=r?.sandboxWorkspaceRoot??a,S=(await wt(b,r?.sandboxPolicy)).policy,k="insecure_none"!==S.type?{...S,sandboxWorkspaceRoot:b}:S,_=Date.now();let C,E;const x=Rr(v,y,{env:l,stdio:[s?"pipe":"ignore","pipe","pipe"],cwd:a,detached:!m},k,r?.signal);x.on("spawn",(async()=>{try{await c.write({type:"stdin_ready",stdin:x.stdin??void 0,pid:x.pid,shell:yn(v)})}catch(e){}}));const P=kr({stdout:x.stdout,stderr:x.stderr,writable:c,bufferOutputEvents:r?.bufferOutputEvents,outputLimiterOptions:r?.outputLimiterOptions}),I=async()=>{try{const{state:e,timings:t}=function(e){const t=e.lastIndexOf(`\n${cn}`)+1;if(0===t)return{state:e};const r=e.slice(t+23).trim().split(" ").map(Number);if(4!==r.length||!r.every(Number.isFinite))return{state:e};const[n,o,s,i]=r;return{state:e.slice(0,t),timings:{startedAt:n,restoredAt:o,commandDoneAt:s,majorVersion:i}}}(await te.readFile(p,"utf8"));E=t;const{cwd:r,rest:n}=Hr(e);this.state=n,this.cwd=r.trim(),await(0,te.rm)(p).catch((()=>{}))}catch(e){}await(0,te.rm)(w,{recursive:!0,force:!0,maxRetries:5}).catch((e=>{console.warn(`[shell-exec] Could not remove PowerShell script ${w}`,e)}))};let R=null,T=null,$=null,D=!1;const O=async t=>{if(D)return;if(D=!0,$&&(clearTimeout($),$=null),(0,fr.HF)(o.ctx,"exit"),t)try{await P.waitForOutput()}catch(e){return await I(),void c.throw(e instanceof Error?e:new Error(String(e)))}await P.flush();try{await c.write({type:"exit",code:R,signal:T??void 0,data:"",aborted:r?.signal?.aborted??!1})}catch(e){}const n=Date.now();await I(),void 0!==C&&function(e,t){const r={shell_kind:(void 0!==t.script?t.script.majorVersion>=6:f.basename(t.executable).toLowerCase().startsWith("pwsh"))?"pwsh":"powershell51",dump_mode:t.perLineStateDump?"per_line":"single_write"},n=[["process",t.exitedAt-t.spawnedAt],["cleanup",t.cleanupMs]],o=t.script;if(void 0!==o){const e=[["start",o.startedAt-t.spawnedAt],["restore",o.restoredAt-o.startedAt],["command",o.commandDoneAt-o.restoredAt],["dump",t.exitedAt-o.commandDoneAt]];e.every((([,e])=>e>=0))&&n.push(...e)}for(const[t,o]of n)mn.histogram(e,o,{phase:t,...r})}(e,{executable:v,perLineStateDump:!0===r?.powershellPerLineStateDump,spawnedAt:_,exitedAt:C,cleanupMs:Date.now()-n,script:E}),c.close()};x.on("exit",((e,t)=>{C=Date.now(),R=e,T=t;const n=r?.closeTimeout??5e3;n>0&&($=setTimeout((()=>{console.warn(`[shell-exec] Close event did not fire within ${n}ms after exit. This may indicate a background process is holding file descriptors open. Proceeding anyway to prevent hang.`),O(!1)}),n))})),x.on("close",(async()=>{await O(!0)})),x.on("error",(e=>{var t;t=v,gn?.executable===t&&(gn=void 0),I().catch((()=>{})),c.throw(e)})),yield*c}catch(e){n.error=e,n.hasError=!0}finally{fn(n)}}}async function bn(){return new vn(process.cwd(),"")}var Sn=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function kn(e){const t=f.win32.parse(e).name.toLowerCase();return"powershell"===t||"pwsh"===t}function _n(e,t=process.platform){switch(f.win32.parse(e).name.toLowerCase()){case"pwsh":return"naive_pwsh";case"powershell":return"win32"===t?"naive_powershell51":"naive_pwsh";case"bash":return"naive_bash";case"zsh":return"naive_zsh";default:return"naive_other"}}class Cn{cwd;options;deps;constructor(e,t,r){this.cwd=e,this.options=t,this.deps=r}async getCwd(){return this.cwd}clone(e){return new Cn(e??this.cwd,this.options,this.deps)}async*execute(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(n,(0,fr.VI)(e.withName("NaiveTerminalExecutor.execute")),!1),s=(0,mr.Jt)(),a=r?.pipeStdin??!1,c=this.options?.shell||process.env.SHELL||"/bin/sh",l=r?.powershellUtf8Console??this.options?.powershellUtf8Console,u=r?.powershellUtf8ChildEnv??this.options?.powershellUtf8ChildEnv,d=function(e,t,r=process.platform,n=process.env){const o={...n,...xr,...t?.env};return"win32"!==r||!0!==t?.powershellUtf8ChildEnv&&kn(e)||(F(o),N(o)),i(o)}(c,{env:r?.env,powershellUtf8ChildEnv:u}),h=A(d)?M(t):t,p=function(e,t,r,n=process.platform){return"win32"===n&&kn(e)?`${!0===r?.powershellUtf8Console?un:""}${!0===r?.powershellUtf8ChildEnv?`${B}\n`:""}${t}`:t}(c,h,{powershellUtf8Console:l,powershellUtf8ChildEnv:u}),f=r?.workingDirectory??this.cwd,m=r?.sandboxWorkspaceRoot??f,g=this.deps?.resolveSandboxPolicyForWorkspace??wt,w=(await g(m,r?.sandboxPolicy)).policy,y="insecure_none"!==w.type?{...w,sandboxWorkspaceRoot:m}:w,v="win32"===process.platform,b=this.options?.powerShellSpares,S=void 0!==b&&!a&&"insecure_none"===y.type&&kn(c)?{shell:c,shellArgs:this.options?.shellArgs??[],cwd:f,env:d}:void 0,k=void 0!==S?await(b?.take(S)):void 0,_=this.deps?.spawnWithSignal??Rr,C=k??_(c,[...this.options?.shellArgs??[],"-c",p],{env:d,cwd:f,stdio:[a?"pipe":"ignore","pipe","pipe"],detached:!v},y,r?.signal),E=async()=>{try{await s.write({type:"stdin_ready",stdin:void 0===k?C.stdin??void 0:void 0,pid:C.pid,shell:_n(c)})}catch(e){}};void 0!==k?(r?.signal&&Tr(k,{detached:!v},r.signal),function(e,t){e.stdin?.on("error",(()=>{})),e.stdin?.end(Buffer.from(t,"utf8"))}(k,p),E()):C.on("spawn",E),void 0!==S&&b?.prestart(S);const x=(this.deps?.attachShellOutputStreams??kr)({stdout:C.stdout,stderr:C.stderr,writable:s,bufferOutputEvents:r?.bufferOutputEvents,outputLimiterOptions:r?.outputLimiterOptions});C.on("error",(e=>{s.throw(e)}));const P=new Promise((e=>{C.once("close",(()=>e()))})),I=r?.closeTimeout??250;C.on("exit",(async(e,t)=>{(0,fr.HF)(o.ctx,"exit");const n=r?.signal?.aborted??!1;if(await(0===I?P:async function(e,t){let r;const n=new Promise((e=>{r=setTimeout((()=>setImmediate(e)),t)}));try{await Promise.race([e,n])}finally{clearTimeout(r)}}(P,I)),await x.flush(),y.captureDenies)try{const e=await dr(C);e&&e.length>0&&await s.write({type:"sandbox_denies",events:e})}catch{}try{await s.write({type:"exit",code:e,signal:t??void 0,data:"",aborted:n}),s.close()}catch(e){s.close()}})),yield*s}catch(e){n.error=e,n.hasError=!0}finally{Sn(n)}}}const En="__CURSOR_ZSH_STATE_START__",xn="__CURSOR_ZSH_STATE_END__",Pn=' local tool\n for tool in base64 tr; do\n if ! builtin whence -p "$tool" >/dev/null 2>&1; then\n builtin print -ru2 -- "Shell state not saved: $tool is not on PATH"\n return 0\n fi\n done\n if ! command base64 </dev/null >/dev/null 2>&1; then\n builtin print -ru2 -- "Shell state not saved: the environment is too large to run commands"\n return 0\n fi\n',In=`#!/usr/bin/env zsh\n\n# Usage:\n# source dump_zsh_state.zsh\n# dump_zsh_state\n# Or execute directly (captures a subshell's state):\n# ./dump_zsh_state.zsh\n\n# Define a function so sourcing won't alter caller state; emulate locally inside\nfunction dump_zsh_state() {\n emulate -L zsh -o errreturn -o pipefail\n set -u\n\n\n # Helper to log timing, only if DUMP_ZSH_STATE_TIMING is set\n if [[ -n "\${DUMP_ZSH_STATE_TIMING:-}" ]]; then\n # Timing setup\n typeset start_time=\${EPOCHREALTIME}\n typeset step_start=\${EPOCHREALTIME}\n _log_timing() {\n typeset step_name="$1"\n typeset now=\${EPOCHREALTIME}\n typeset step_duration=$((now - step_start))\n typeset total_duration=$((now - start_time))\n builtin printf "[TIMING] %-20s: %6.3fs (total: %6.3fs)\n" "$step_name" "$step_duration" "$total_duration" >&2\n step_start=$now\n }\n else\n _log_timing() { :; }\n fi\n\n # Ensure parameter arrays are available\n builtin zmodload -F zsh/parameter p:parameters p:options p:functions p:aliases p:galiases p:saliases 2>/dev/null || true\n _log_timing "zmodload"\n\n # Helper to print a line to stdout\n _emit() {\n builtin print -r -- "$1"\n }\n\n # Helper to safely encode and emit unsafe values, then the line that replays them (one eval by default)\n _emit_encoded() {\n local content="$1"\n local var_name="$2"\n if [[ -n "$content" ]]; then\n # Builtin printf, not a here-document: no argument length limit, and no temp file\n builtin printf 'cursor_snap_%s=$(builtin printf %%s '"'"'%s'"'"' | command base64 -d)\n' "$var_name" "$(command base64 <<<"$content" | command tr -d '\n')"\n if [[ -n "\${3:-}" ]]; then\n builtin print -r -- "$3"\n else\n builtin printf 'builtin eval "$cursor_snap_%s"\n' "$var_name"\n fi\n fi\n }\n\n # Aliases replay after the functions, so a user function named alias would run in place of\n # each alias line. Only a line that starts an alias gets builtin: a quoted value can span\n # lines, and a continuation line can start with "alias ". awk reads bytes under LC_ALL=C, so a\n # value that is not valid UTF-8 does not make it warn. Without awk the lines stay as they are.\n _builtin_alias_lines() {\n [[ -n "$1" ]] || return 0\n builtin printf '%s\n' "$1" | LC_ALL=C command awk -v sq="'" '\n !q && /^alias / { $0 = "builtin " $0 }\n {\n print\n for (i = 1; i <= length($0); i++) {\n c = substr($0, i, 1)\n if (q == 1) { if (c == sq) q = 0 }\n else if (q == 2) { if (c == "\\\\") i++; else if (c == sq) q = 0 }\n else if (c == "\\\\") i++\n else if (c == "$" && substr($0, i + 1, 1) == sq) { q = 2; i++ }\n else if (c == sq) q = 1\n }\n }' 2>/dev/null ||\n builtin printf '%s\n' "$1"\n }\n\n _log_timing "init"\n\n${Pn}\n # Emit start marker at the very beginning of the output\n _emit "__CURSOR_ZSH_STATE_START__"\n\n # Header\n _emit "$PWD"\n\n _emit "# zsh state dump generated on $(command date +'%Y-%m-%d %H:%M:%S %z')"\n _log_timing "header"\n\n # Working directory\n _log_timing "working_dir"\n\n # Drop ELECTRON_RUN_AS_NODE by exact name so one command exporting it can't\n # bake it into the snapshot that every later command re-evals (IDE-2911:\n # Cypress boots as plain Node until a new chat). Exact unset rather than the\n # line-based grep below, which would also eat vars whose name or multiline\n # value merely contains the token. The shell exits right after the dump.\n builtin unset ELECTRON_RUN_AS_NODE 2>/dev/null || true\n\n # Environment variables (exported)\n # Filter out: proxy settings plus request/session-scoped vars that must not\n # leak across shell executions.\n # Under a non-UTF-8 locale zsh writes byte 0xa7 inside $'...' as M-', which\n # its own parser reads as the closing quote (zsh 5.9 Src/utils.c quotestring,\n # https://github.com/zsh-users/zsh/blob/zsh-5.9/Src/utils.c); the sed rewrites\n # that one escape to the § form so the restore eval can parse it. It runs\n # only on scalar $'...' lines: a plain-quoted value can hold the same four\n # characters literally, and there they must stay.\n local env_vars\n env_vars=$(builtin typeset -xp 2>/dev/null | command grep -viE '_proxy=|CURSOR_SANDBOX|SUDO_ASKPASS|CURSOR_ASKPASS|CURSOR_CONVERSATION_ID|CURSOR_REQUEST_ID|CURSOR_AGENT_STORE' | command sed "/^export[^=]*=[\\$]'/ s/\\\\\\\\M-'/\\\\\\\\xa7/g" || true)\n if [[ -n "\${__CURSOR_SANDBOX_OWNED_ENV:-}" ]]; then\n env_vars=$(builtin printf '%s\n' "$env_vars" | command grep -vE "^(export|declare|typeset)( -[a-zA-Z]+)* (\${__CURSOR_SANDBOX_OWNED_ENV// /|})=" || true)\n fi\n _emit_encoded "$env_vars" "ENV_VARS_B64"\n _log_timing "env_variables"\n\n # Options (replayable as setopt lines). Exclude the errreturn/nounset/pipefail this\n # function force-enables above, so they are not baked into the restored snapshot and\n # leaked onto every subsequent command (a stray pipefail makes a successful\n # 'cmd | head' report exit 141).\n local zsh_opts\n zsh_opts=$(setopt 2>/dev/null | command grep -vE '^(errreturn|nounset|pipefail)$' | command awk '{printf "builtin setopt %s 2>/dev/null || true\\n", $0}' || true)\n _emit_encoded "$zsh_opts" "ZSH_OPTS_B64"\n _log_timing "options"\n\n # Each function ends in a NUL and gets its own eval, since one eval of all is quadratic in size\n # and one bad definition would drop the rest. typeset +f lists names without zsh/parameter.\n local all_functions fn\n all_functions=$(\n for fn in \${(f)"$(builtin typeset +f)"}; do\n builtin typeset -f -- "$fn"\n builtin print -rn -- $'\\0'\n done 2>/dev/null || true\n )\n local replay_functions='for cursor_snap_fn in "\${(@0)cursor_snap_FUNCTIONS_B64}"; do builtin eval "$cursor_snap_fn" || builtin true; done'\n _emit_encoded "$all_functions" "FUNCTIONS_B64" "$replay_functions"\n _log_timing "functions"\n\n # Aliases (regular, global, and suffix)\n local alias_lines\n alias_lines=$({\n builtin alias -L 2>/dev/null || true\n builtin alias -gL 2>/dev/null || true\n builtin alias -sL 2>/dev/null || true\n })\n _builtin_alias_lines "$alias_lines" || true\n _log_timing "aliases"\n\n # Done\n _emit "# end of zsh state dump"\n _emit "__CURSOR_ZSH_STATE_END__"\n _log_timing "finalize"\n}\n`,Rn="__CURSOR_ZSH_STATE_LIGHT_VALID__",Tn="# end of zsh state dump (light)",An=`#!/usr/bin/env zsh\n\n# Usage:\n# source dump_zsh_state_light.zsh\n# dump_zsh_state_light\n# Or execute directly (captures a subshell's state):\n# ./dump_zsh_state_light.zsh\n\n# Lightweight version that skips function tracking for better performance\n\n# Define a function so sourcing won't alter caller state; emulate locally inside\nfunction dump_zsh_state_light() {\n emulate -L zsh -o errreturn -o pipefail\n set -u\n\n\n # Helper to log timing, only if DUMP_ZSH_STATE_TIMING is set\n if [[ -n "\${DUMP_ZSH_STATE_TIMING:-}" ]]; then\n # Timing setup\n typeset start_time=\${EPOCHREALTIME}\n typeset step_start=\${EPOCHREALTIME}\n _log_timing() {\n typeset step_name="$1"\n typeset now=\${EPOCHREALTIME}\n typeset step_duration=$((now - step_start))\n typeset total_duration=$((now - start_time))\n builtin printf "[TIMING] %-20s: %6.3fs (total: %6.3fs)\n" "$step_name" "$step_duration" "$total_duration" >&2\n step_start=$now\n }\n else\n _log_timing() { :; }\n fi\n\n # Ensure parameter arrays are available\n builtin zmodload -F zsh/parameter p:parameters p:options p:aliases p:galiases p:saliases 2>/dev/null || true\n _log_timing "zmodload"\n\n # Helper to print a line to stdout\n _emit() {\n builtin print -r -- "$1"\n }\n\n # Helper to safely encode and emit unsafe values\n _emit_encoded() {\n local content="$1"\n local var_name="$2"\n if [[ -n "$content" ]]; then\n # Builtin printf, not a here-document: no argument length limit, and no temp file\n builtin printf 'cursor_snap_%s=$(builtin printf %%s '"'"'%s'"'"' | command base64 -d)\n' "$var_name" "$(command base64 <<<"$content" | command tr -d '\n')"\n builtin printf 'eval "$cursor_snap_%s"\n' "$var_name"\n fi\n }\n\n _log_timing "init"\n\n${Pn}\n # Emit validity marker so we can detect if dump_zsh_state_light completed\n _emit "__CURSOR_ZSH_STATE_LIGHT_VALID__"\n\n # Header\n _emit "$PWD"\n\n _emit "# zsh state dump (light) generated on $(command date +'%Y-%m-%d %H:%M:%S %z')"\n _log_timing "header"\n\n # Working directory\n _log_timing "working_dir"\n\n # Drop ELECTRON_RUN_AS_NODE by exact name so one command exporting it can't\n # bake it into the snapshot that every later command re-evals (IDE-2911:\n # Cypress boots as plain Node until a new chat). Exact unset rather than the\n # line-based grep below, which would also eat vars whose name or multiline\n # value merely contains the token. The shell exits right after the dump.\n builtin unset ELECTRON_RUN_AS_NODE 2>/dev/null || true\n\n # Environment variables (exported)\n # Filter out: proxy settings plus request/session-scoped vars that must not\n # leak across shell executions.\n # Under a non-UTF-8 locale zsh writes byte 0xa7 inside $'...' as M-', which\n # its own parser reads as the closing quote (zsh 5.9 Src/utils.c quotestring,\n # https://github.com/zsh-users/zsh/blob/zsh-5.9/Src/utils.c); the sed rewrites\n # that one escape to the § form so the restore eval can parse it. It runs\n # only on scalar $'...' lines: a plain-quoted value can hold the same four\n # characters literally, and there they must stay.\n local env_vars\n env_vars=$(builtin typeset -xp 2>/dev/null | command grep -viE '_proxy=|CURSOR_SANDBOX|SUDO_ASKPASS|CURSOR_ASKPASS|CURSOR_CONVERSATION_ID|CURSOR_REQUEST_ID|CURSOR_AGENT_STORE' | command sed "/^export[^=]*=[\\$]'/ s/\\\\\\\\M-'/\\\\\\\\xa7/g" || true)\n if [[ -n "\${__CURSOR_SANDBOX_OWNED_ENV:-}" ]]; then\n env_vars=$(builtin printf '%s\n' "$env_vars" | command grep -vE "^(export|declare|typeset)( -[a-zA-Z]+)* (\${__CURSOR_SANDBOX_OWNED_ENV// /|})=" || true)\n fi\n _emit_encoded "$env_vars" "ENV_VARS_B64"\n _log_timing "env_variables"\n\n # Options (replayable as setopt lines). Exclude the errreturn/nounset/pipefail this\n # function force-enables above, so they are not baked into the restored snapshot and\n # leaked onto every subsequent command (a stray pipefail makes a successful\n # 'cmd | head' report exit 141).\n local zsh_opts\n zsh_opts=$(setopt 2>/dev/null | command grep -vE '^(errreturn|nounset|pipefail)$' | command awk '{printf "builtin setopt %s 2>/dev/null || true\\n", $0}' || true)\n _emit_encoded "$zsh_opts" "ZSH_OPTS_B64"\n _log_timing "options"\n\n # SKIP FUNCTIONS - this is the key difference for performance\n\n # Aliases (regular, global, and suffix)\n {\n builtin alias -L 2>/dev/null || true\n builtin alias -gL 2>/dev/null || true\n builtin alias -sL 2>/dev/null || true\n }\n _log_timing "aliases"\n\n # Done\n _emit "${Tn}"\n _log_timing "finalize"\n}\n`;var $n=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function Mn(){const e=process.env.SHELL;return e?.includes("zsh")?e:S("zsh",[]).cmd}class Dn{cwd;state;commandPipeUnreadable;constructor(e,t,r=!1){this.cwd=e,this.state=t,this.commandPipeUnreadable=r}async getCwd(){return this.cwd}clone(e){return new Dn(e??this.cwd,this.state,this.commandPipeUnreadable)}async*execute(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(n,(0,fr.VI)(e.withName("ZshLightState.execute")),!1),s=r?.pipeStdin??!1,i=(0,mr.Jt)(),a=r?.workingDirectory??this.cwd,c={...process.env,...xr,...r?.env};u(c);let l='builtin eval "$1"';s||(l+=" < /dev/null");const d=$(c),h=jr()&&!this.commandPipeUnreadable,p=["-c",(h?Nr:"")+"builtin export PATH=\"/usr/bin:/bin:/usr/sbin:/sbin${PATH:+:$PATH}\"; snap=$(command cat <&3); builtin unsetopt aliases 2>/dev/null; builtin unalias -m '*' 2>/dev/null || true; "+`${An} builtin eval "$snap"; { builtin unsetopt nounset 2>/dev/null || true; builtin eval "\${__CURSOR_SANDBOX_ENV_RESTORE:-}" 2>/dev/null; `+X+Y+`builtin export PWD="$(builtin pwd)"; builtin setopt aliases 2>/dev/null; ${d}${l}; }; COMMAND_EXIT_CODE=$?; dump_zsh_state_light >&4; builtin exit $COMMAND_EXIT_CODE`,gr,...h?[]:[t]],f=r?.sandboxWorkspaceRoot??a,m=(await wt(f,r?.sandboxPolicy)).policy,g="insecure_none"!==m.type?{...m,sandboxWorkspaceRoot:f}:m,w=Rr(Mn(),p,{env:c,stdio:[s?"pipe":"ignore","pipe","pipe","pipe","pipe",h?"pipe":"ignore"],cwd:a,detached:!0},g,r?.signal);let y="";w.on("spawn",(async()=>{try{await i.write({type:"stdin_ready",stdin:w.stdin??void 0,pid:w.pid,shell:"zsh_light"})}catch(e){}}));const v=kr({stdout:w.stdout,stderr:w.stderr,writable:i,bufferOutputEvents:r?.bufferOutputEvents,outputLimiterOptions:r?.outputLimiterOptions});w.on("error",(e=>{i.throw(e)}));let b=null,S=null,k=null,_=!1;const C=async e=>{if(!_){if(_=!0,k&&(clearTimeout(k),k=null),(0,fr.HF)(o.ctx,"exit"),e)try{await v.waitForOutput()}catch(e){return void i.throw(e instanceof Error?e:new Error(String(e)))}if(await v.flush(),h&&Lr(b,y)&&(this.commandPipeUnreadable=!0),!r?.signal?.aborted){const e=`${Rn}\n`;if(y.startsWith(e)){const t=y.slice(e.length),{cwd:r,rest:n}=Hr(t);r?.startsWith("/")&&(this.state=n,this.cwd=r)}}if(g.captureDenies)try{const e=await dr(w);e&&e.length>0&&await i.write({type:"sandbox_denies",events:e})}catch{}try{await i.write({type:"exit",code:b,signal:S??void 0,data:"",aborted:r?.signal?.aborted??!1}),i.close()}catch(e){i.close()}}};w.on("exit",((e,t)=>{b=e,S=t,Mr(w.pid,t,r?.signal?.aborted??!1);const n=r?.closeTimeout??5e3;n>0&&(k=setTimeout((()=>{console.warn(`[shell-exec] Close event did not fire within ${n}ms after exit. This may indicate a background process is holding file descriptors open. Proceeding anyway to prevent hang.`),C(!1).finally((()=>{Fr(w)}))}),n))})),w.on("close",(async()=>{await C(!0)}));const E=w.stdio[3],x=w.stdio[4],P=E instanceof pr.Writable?E:null,I=x instanceof pr.Readable?x:null;h&&Ur(w,t),Br(P,this.state),Wr(I,(e=>{y+=e})),yield*i}catch(e){n.error=e,n.hasError=!0}finally{$n(n)}}}async function On(e,t){const r={...process.env,...xr,...e?.env},n="__CURSOR_STATE_MARKER__",o=["-o","extendedglob",zr(e),`${An} builtin printf '${n}\\n'; dump_zsh_state_light`],s=Rr(Mn(),o,{env:r,stdio:["ignore","pipe","ignore"],detached:!0},{type:"insecure_none"},e?.signal);s.on("error",(e=>{console.warn(`[shell-exec] zsh-light state init spawn failed; falling back to empty state: ${e instanceof Error?e.message:String(e)}`)}));const{stdout:i}=await Dr(s,{shellName:"zsh-light",...t}),a=Gr(qr(i,n),Rn,Tn)??`${process.cwd()}\n`,{cwd:c,rest:l}=Hr(a);return new Dn(c,l)}var Fn=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function Nn(){const e=process.env.SHELL;return e?.includes("zsh")?e:S("zsh",[]).cmd}class Ln{cwd;state;commandPipeUnreadable;constructor(e,t,r=!1){this.cwd=e,this.state=t,this.commandPipeUnreadable=r}async getCwd(){return this.cwd}clone(e){return new Ln(e??this.cwd,this.state,this.commandPipeUnreadable)}async*execute(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(n,(0,fr.VI)(e.withName("ZshState.execute")),!1),s=r?.pipeStdin??!1,i=r?.keepBackgroundJobs??!1,a=(0,mr.Jt)(),c=r?.workingDirectory??this.cwd,l={...process.env,...xr,...r?.env};u(l);let d='builtin eval "$1"';i&&(d+=" 3<&- 4>&-"),s||(d+=" < /dev/null");const h=$(l),p=jr()&&!this.commandPipeUnreadable,f=["-c",(p?Nr:"")+"builtin export PATH=\"/usr/bin:/bin:/usr/sbin:/sbin${PATH:+:$PATH}\"; snap=$(command cat <&3); builtin unsetopt aliases 2>/dev/null; builtin unalias -m '*' 2>/dev/null || true; "+`${In} builtin eval "$snap"; { builtin unsetopt nounset 2>/dev/null || true; builtin eval "\${__CURSOR_SANDBOX_ENV_RESTORE:-}" 2>/dev/null; `+X+Y+`builtin export PWD="$(builtin pwd)"; builtin setopt aliases 2>/dev/null; ${h}${d}; }; COMMAND_EXIT_CODE=$?; dump_zsh_state >&4; builtin exit $COMMAND_EXIT_CODE`,gr,...p?[]:[t]],m=r?.sandboxWorkspaceRoot??c,g=(await wt(m,r?.sandboxPolicy)).policy,w="insecure_none"!==g.type?{...g,sandboxWorkspaceRoot:m}:g,y=Rr(Nn(),f,{env:l,stdio:[s?"pipe":"ignore","pipe","pipe","pipe","pipe",p?"pipe":"ignore"],cwd:c,detached:!0},w,r?.signal);let v="";y.on("spawn",(async()=>{try{await a.write({type:"stdin_ready",stdin:y.stdin??void 0,pid:y.pid,shell:"zsh"})}catch(e){}}));const b=kr({stdout:y.stdout,stderr:y.stderr,writable:a,bufferOutputEvents:r?.bufferOutputEvents,outputLimiterOptions:r?.outputLimiterOptions});y.on("error",(e=>{a.throw(e)}));let S=null,k=null,_=null,C=!1;const E=async e=>{if(!C){if(C=!0,_&&(clearTimeout(_),_=null),(0,fr.HF)(o.ctx,"exit"),e)try{await b.waitForOutput()}catch(e){return void a.throw(e instanceof Error?e:new Error(String(e)))}if(await b.flush(),p&&Lr(S,v)&&(this.commandPipeUnreadable=!0),!r?.signal?.aborted){const e=`${En}\n`,t=`${xn}\n`;if(v.startsWith(e)&&v.endsWith(t)){let t=v.slice(e.length);t=t.slice(0,-25);const{cwd:r,rest:n}=Hr(t);r?.startsWith("/")&&(this.state=n,this.cwd=r)}}if(w.captureDenies)try{const e=await dr(y);e&&e.length>0&&await a.write({type:"sandbox_denies",events:e})}catch{}try{await a.write({type:"exit",code:S,signal:k??void 0,data:"",aborted:r?.signal?.aborted??!1}),a.close()}catch(e){a.close()}}};y.on("exit",((e,t)=>{S=e,k=t,Mr(y.pid,t,r?.signal?.aborted??!1);const n=r?.closeTimeout??5e3;n>0&&(_=setTimeout((()=>{if(C)return;const e=`[shell-exec] Close event did not fire within ${n}ms after exit. This may indicate a background process is holding file descriptors open. `;i?console.warn(`${e}Leaving it running because keepBackgroundJobs is set.`):(console.warn(`${e}Killing detached process group.`),Ar(y.pid,"SIGKILL")),E(!1).finally((()=>{Fr(y)}))}),n))})),y.on("close",(async()=>{await E(!0)}));const x=y.stdio[3],P=y.stdio[4],I=x instanceof pr.Writable?x:null,R=P instanceof pr.Readable?P:null;p&&Ur(y,t),Br(I,this.state),Wr(R,(e=>{v+=e})),yield*a}catch(e){n.error=e,n.hasError=!0}finally{Fn(n)}}}async function jn(e,t){const r={...process.env,...xr,...e?.env},n="__CURSOR_STATE_MARKER__",o=["-o","extendedglob",zr(e),`${In} builtin printf '${n}\\n'; dump_zsh_state`],s=Rr(Nn(),o,{env:r,stdio:["ignore","pipe","ignore"],detached:!0},{type:"insecure_none"},e?.signal);s.on("error",(e=>{console.warn(`[shell-exec] zsh state init spawn failed; falling back to empty state: ${e instanceof Error?e.message:String(e)}`)}));const{stdout:i}=await Dr(s,{shellName:"zsh",...t}),a=Gr(qr(i,n),En,xn)??`${process.cwd()}\n`,{cwd:c,rest:l}=Hr(a);return new Ln(c,l)}function Un(e){try{return S(e,[]).cmd!==e}catch(e){return!1}}function Bn(){if("win32"!==process.platform)return;if(!process.env.MSYSTEM)return;const e=process.env.EXEPATH;if(e)return function(e){const t=e.replace(/[\\/]+$/,""),r=f.win32.basename(t).toLowerCase();return"bash.exe"===r?t:"bin"===r?f.win32.join(t,"bash.exe"):f.win32.join(t,"bin","bash.exe")}(e);const t=["C:\\Program Files\\Git\\bin\\bash.exe","C:\\Program Files (x86)\\Git\\bin\\bash.exe"];for(const e of t)try{if(S(e,[]).cmd===e)return e}catch{}return"C:\\Program Files\\Git\\bin\\bash.exe"}function Wn(e){if(e===Er.ZshLight)return Er.ZshLight;const t=e||process.env.SHELL||"",r="win32"===process.platform,n=r&&!e?Bn():void 0,o=void 0!==n||/git.*bash\.exe$/i.test(t)||/program.*git.*bin.*bash\.exe$/i.test(t),s=!r||o;return t.includes("zsh")?Er.Zsh:t.includes("bash")&&s?Er.Bash:t.includes("pwsh")||t.includes("powershell")?Er.PowerShell:n?Er.Bash:r&&(Un("pwsh")||Un("powershell"))?Er.PowerShell:Un("zsh")?Er.Zsh:Un("bash")&&s?Er.Bash:Un("pwsh")||Un("powershell")?Er.PowerShell:Er.Naive}function Hn(e,t){let r=e;if(!e?.userTerminalHint){const t=Bn();t&&(r={...e,userTerminalHint:t})}const n=Wn(r?.userTerminalHint??""),o=t?.initBashState??en,s=t?.initPowerShellState??bn,i=t?.initZshState??jn,a=t?.initZshLightState??On;switch(n){case Er.Zsh:return new rn((()=>i(r)));case Er.Bash:return new rn((()=>o(r)));case Er.PowerShell:return new rn((()=>s()));case Er.ZshLight:return new rn((()=>a(r)));default:{const e=t?.getPowerShellExecutable??wn;return function(e){const t="win32"===process.platform,r=e?.shell??(t?wn():void 0),n=process.cwd();return new Cn(n,{...e,shell:r})}({env:r?.env,shell:"win32"===process.platform?e():void 0})}}}const qn={perUser:{type:"insecure_none"}}},"../utils/dist/lru-cache.js"(e,t,r){"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,I,R,T,A,$,M,D,O,F,N,L,j,U,B,W,H,q,z,G,V,K,J,Z,X,Q=function(e,t,r,n,o){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!o)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!o:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?o.call(e,r):o?o.value=r:t.set(e,r),r},Y=function(e,t,r,n){if("a"===r&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?n:"a"===r?n.call(e):n?n.value:t.get(e)};const ee="object"==typeof performance&&performance&&"function"==typeof performance.now?performance:Date,te=new Set,re="object"==typeof process&&process?process:{},ne=(e,t,r,n)=>{"function"==typeof re.emitWarning?re.emitWarning(e,t,r,n):console.error(`[${r}] ${t}: ${e}`)};let oe,se=globalThis.AbortController;if(void 0===se){oe=class{constructor(){this._onabort=[],this.aborted=!1}addEventListener(e,t){this._onabort.push(t)}},se=class{constructor(){this.signal=new oe,t()}abort(e){if(!this.signal.aborted){this.signal.reason=e,this.signal.aborted=!0;for(const t of this.signal._onabort)t(e);this.signal.onabort?.(e)}}};let e="1"!==re.env?.LRU_CACHE_IGNORE_AC_WARNING;const t=()=>{e&&(e=!1,ne("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",t))}}Symbol("type");const ie=e=>e&&e===Math.floor(e)&&e>0&&Number.isFinite(e),ae=e=>ie(e)?e<=256?Uint8Array:e<=65536?Uint16Array:e<=2**32?Uint32Array:e<=Number.MAX_SAFE_INTEGER?ce:null:null;class ce extends Array{constructor(e){super(e),this.fill(0)}}class le{static create(e){const t=ae(e);if(!t)return[];Q(n,n,!0,"f",o);const r=new n(e,t);return Q(n,n,!1,"f",o),r}constructor(e,t){if(!Y(n,n,"f",o))throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new t(e),this.length=0}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}}n=le,o={value:!1};class ue{get perf(){return Y(this,p,"f")}static unsafeExposeInternals(e){return{starts:Y(e,x,"f"),ttls:Y(e,P,"f"),sizes:Y(e,E,"f"),keyMap:Y(e,g,"f"),keyList:Y(e,w,"f"),valList:Y(e,y,"f"),next:Y(e,v,"f"),prev:Y(e,b,"f"),get head(){return Y(e,S,"f")},get tail(){return Y(e,k,"f")},free:Y(e,_,"f"),isBackgroundFetch:t=>Y(e,s,"m",G).call(e,t),backgroundFetch:(t,r,n,o)=>Y(e,s,"m",z).call(e,t,r,n,o),moveToTail:t=>Y(e,s,"m",K).call(e,t),indexes:t=>Y(e,s,"m",B).call(e,t),rindexes:t=>Y(e,s,"m",W).call(e,t),isStale:t=>Y(e,F,"f").call(e,t)}}get max(){return Y(this,i,"f")}get maxSize(){return Y(this,a,"f")}get calculatedSize(){return Y(this,m,"f")}get size(){return Y(this,f,"f")}get fetchMethod(){return Y(this,d,"f")}get memoMethod(){return Y(this,h,"f")}get dispose(){return Y(this,c,"f")}get onInsert(){return Y(this,l,"f")}get disposeAfter(){return Y(this,u,"f")}constructor(e){s.add(this),i.set(this,void 0),a.set(this,void 0),c.set(this,void 0),l.set(this,void 0),u.set(this,void 0),d.set(this,void 0),h.set(this,void 0),p.set(this,void 0),f.set(this,void 0),m.set(this,void 0),g.set(this,void 0),w.set(this,void 0),y.set(this,void 0),v.set(this,void 0),b.set(this,void 0),S.set(this,void 0),k.set(this,void 0),_.set(this,void 0),C.set(this,void 0),E.set(this,void 0),x.set(this,void 0),P.set(this,void 0),I.set(this,void 0),R.set(this,void 0),T.set(this,void 0),A.set(this,void 0),M.set(this,(()=>{})),D.set(this,(()=>{})),O.set(this,(()=>{})),F.set(this,(()=>!1)),L.set(this,(e=>{})),j.set(this,((e,t,r)=>{})),U.set(this,((e,t,r,n)=>{if(r||n)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0})),this[X]="LRUCache";const{max:t=0,ttl:r,ttlResolution:n=1,ttlAutopurge:o,updateAgeOnGet:B,updateAgeOnHas:W,allowStale:H,dispose:q,onInsert:z,disposeAfter:G,noDisposeOnSet:V,noUpdateTTL:K,maxSize:J=0,maxEntrySize:Z=0,sizeCalculation:re,fetchMethod:oe,memoMethod:se,noDeleteOnFetchRejection:ce,noDeleteOnStaleGet:de,allowStaleOnFetchRejection:he,allowStaleOnFetchAbort:pe,ignoreFetchAbort:fe,perf:me}=e;if(void 0!==me&&"function"!=typeof me?.now)throw new TypeError("perf option must have a now() method if specified");if(Q(this,p,me??ee,"f"),0!==t&&!ie(t))throw new TypeError("max option must be a nonnegative integer");const ge=t?ae(t):Array;if(!ge)throw new Error(`invalid max value: ${t}`);if(Q(this,i,t,"f"),Q(this,a,J,"f"),this.maxEntrySize=Z||Y(this,a,"f"),this.sizeCalculation=re,this.sizeCalculation){if(!Y(this,a,"f")&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if("function"!=typeof this.sizeCalculation)throw new TypeError("sizeCalculation set to non-function")}if(void 0!==se&&"function"!=typeof se)throw new TypeError("memoMethod must be a function if defined");if(Q(this,h,se,"f"),void 0!==oe&&"function"!=typeof oe)throw new TypeError("fetchMethod must be a function if specified");if(Q(this,d,oe,"f"),Q(this,R,!!oe,"f"),Q(this,g,new Map,"f"),Q(this,w,new Array(t).fill(void 0),"f"),Q(this,y,new Array(t).fill(void 0),"f"),Q(this,v,new ge(t),"f"),Q(this,b,new ge(t),"f"),Q(this,S,0,"f"),Q(this,k,0,"f"),Q(this,_,le.create(t),"f"),Q(this,f,0,"f"),Q(this,m,0,"f"),"function"==typeof q&&Q(this,c,q,"f"),"function"==typeof z&&Q(this,l,z,"f"),"function"==typeof G?(Q(this,u,G,"f"),Q(this,C,[],"f")):(Q(this,u,void 0,"f"),Q(this,C,void 0,"f")),Q(this,I,!!Y(this,c,"f"),"f"),Q(this,A,!!Y(this,l,"f"),"f"),Q(this,T,!!Y(this,u,"f"),"f"),this.noDisposeOnSet=!!V,this.noUpdateTTL=!!K,this.noDeleteOnFetchRejection=!!ce,this.allowStaleOnFetchRejection=!!he,this.allowStaleOnFetchAbort=!!pe,this.ignoreFetchAbort=!!fe,0!==this.maxEntrySize){if(0!==Y(this,a,"f")&&!ie(Y(this,a,"f")))throw new TypeError("maxSize must be a positive integer if specified");if(!ie(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");Y(this,s,"m",N).call(this)}if(this.allowStale=!!H,this.noDeleteOnStaleGet=!!de,this.updateAgeOnGet=!!B,this.updateAgeOnHas=!!W,this.ttlResolution=ie(n)||0===n?n:1,this.ttlAutopurge=!!o,this.ttl=r||0,this.ttl){if(!ie(this.ttl))throw new TypeError("ttl must be a positive integer if specified");Y(this,s,"m",$).call(this)}if(0===Y(this,i,"f")&&0===this.ttl&&0===Y(this,a,"f"))throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!Y(this,i,"f")&&!Y(this,a,"f")){const e="LRU_CACHE_UNBOUNDED";(e=>!te.has(e))(e)&&(te.add(e),ne("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",e,ue))}}getRemainingTTL(e){return Y(this,g,"f").has(e)?1/0:0}*entries(){for(const e of Y(this,s,"m",B).call(this))void 0===Y(this,y,"f")[e]||void 0===Y(this,w,"f")[e]||Y(this,s,"m",G).call(this,Y(this,y,"f")[e])||(yield[Y(this,w,"f")[e],Y(this,y,"f")[e]])}*rentries(){for(const e of Y(this,s,"m",W).call(this))void 0===Y(this,y,"f")[e]||void 0===Y(this,w,"f")[e]||Y(this,s,"m",G).call(this,Y(this,y,"f")[e])||(yield[Y(this,w,"f")[e],Y(this,y,"f")[e]])}*keys(){for(const e of Y(this,s,"m",B).call(this)){const t=Y(this,w,"f")[e];void 0===t||Y(this,s,"m",G).call(this,Y(this,y,"f")[e])||(yield t)}}*rkeys(){for(const e of Y(this,s,"m",W).call(this)){const t=Y(this,w,"f")[e];void 0===t||Y(this,s,"m",G).call(this,Y(this,y,"f")[e])||(yield t)}}*values(){for(const e of Y(this,s,"m",B).call(this))void 0===Y(this,y,"f")[e]||Y(this,s,"m",G).call(this,Y(this,y,"f")[e])||(yield Y(this,y,"f")[e])}*rvalues(){for(const e of Y(this,s,"m",W).call(this))void 0===Y(this,y,"f")[e]||Y(this,s,"m",G).call(this,Y(this,y,"f")[e])||(yield Y(this,y,"f")[e])}[(i=new WeakMap,a=new WeakMap,c=new WeakMap,l=new WeakMap,u=new WeakMap,d=new WeakMap,h=new WeakMap,p=new WeakMap,f=new WeakMap,m=new WeakMap,g=new WeakMap,w=new WeakMap,y=new WeakMap,v=new WeakMap,b=new WeakMap,S=new WeakMap,k=new WeakMap,_=new WeakMap,C=new WeakMap,E=new WeakMap,x=new WeakMap,P=new WeakMap,I=new WeakMap,R=new WeakMap,T=new WeakMap,A=new WeakMap,M=new WeakMap,D=new WeakMap,O=new WeakMap,F=new WeakMap,L=new WeakMap,j=new WeakMap,U=new WeakMap,s=new WeakSet,$=function(){const e=new ce(Y(this,i,"f")),t=new ce(Y(this,i,"f"));Q(this,P,e,"f"),Q(this,x,t,"f"),Q(this,O,((r,n,o=Y(this,p,"f").now())=>{if(t[r]=0!==n?o:0,e[r]=n,0!==n&&this.ttlAutopurge){const e=setTimeout((()=>{Y(this,F,"f").call(this,r)&&Y(this,s,"m",J).call(this,Y(this,w,"f")[r],"expire")}),n+1);e.unref&&e.unref()}}),"f"),Q(this,M,(r=>{t[r]=0!==e[r]?Y(this,p,"f").now():0}),"f"),Q(this,D,((o,s)=>{if(e[s]){const i=e[s],a=t[s];if(!i||!a)return;o.ttl=i,o.start=a,o.now=r||n();const c=o.now-a;o.remainingTTL=i-c}}),"f");let r=0;const n=()=>{const e=Y(this,p,"f").now();if(this.ttlResolution>0){r=e;const t=setTimeout((()=>{r=0}),this.ttlResolution);t.unref&&t.unref()}return e};this.getRemainingTTL=o=>{const s=Y(this,g,"f").get(o);if(void 0===s)return 0;const i=e[s],a=t[s];return i&&a?i-((r||n())-a):1/0},Q(this,F,(o=>{const s=t[o],i=e[o];return!!i&&!!s&&(r||n())-s>i}),"f")},N=function(){const e=new ce(Y(this,i,"f"));Q(this,m,0,"f"),Q(this,E,e,"f"),Q(this,L,(t=>{Q(this,m,Y(this,m,"f")-e[t],"f"),e[t]=0}),"f"),Q(this,U,((e,t,r,n)=>{if(Y(this,s,"m",G).call(this,t))return 0;if(!ie(r)){if(!n)throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");if("function"!=typeof n)throw new TypeError("sizeCalculation must be a function");if(r=n(t,e),!ie(r))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}return r}),"f"),Q(this,j,((t,r,n)=>{if(e[t]=r,Y(this,a,"f")){const r=Y(this,a,"f")-e[t];for(;Y(this,m,"f")>r;)Y(this,s,"m",q).call(this,!0)}Q(this,m,Y(this,m,"f")+e[t],"f"),n&&(n.entrySize=r,n.totalCalculatedSize=Y(this,m,"f"))}),"f")},B=function*({allowStale:e=this.allowStale}={}){if(Y(this,f,"f"))for(let t=Y(this,k,"f");Y(this,s,"m",H).call(this,t)&&(!e&&Y(this,F,"f").call(this,t)||(yield t),t!==Y(this,S,"f"));)t=Y(this,b,"f")[t]},W=function*({allowStale:e=this.allowStale}={}){if(Y(this,f,"f"))for(let t=Y(this,S,"f");Y(this,s,"m",H).call(this,t)&&(!e&&Y(this,F,"f").call(this,t)||(yield t),t!==Y(this,k,"f"));)t=Y(this,v,"f")[t]},H=function(e){return void 0!==e&&Y(this,g,"f").get(Y(this,w,"f")[e])===e},Symbol.iterator)](){return this.entries()}find(e,t={}){for(const r of Y(this,s,"m",B).call(this)){const n=Y(this,y,"f")[r],o=Y(this,s,"m",G).call(this,n)?n.__staleWhileFetching:n;if(void 0!==o&&e(o,Y(this,w,"f")[r],this))return this.get(Y(this,w,"f")[r],t)}}forEach(e,t=this){for(const r of Y(this,s,"m",B).call(this)){const n=Y(this,y,"f")[r],o=Y(this,s,"m",G).call(this,n)?n.__staleWhileFetching:n;void 0!==o&&e.call(t,o,Y(this,w,"f")[r],this)}}rforEach(e,t=this){for(const r of Y(this,s,"m",W).call(this)){const n=Y(this,y,"f")[r],o=Y(this,s,"m",G).call(this,n)?n.__staleWhileFetching:n;void 0!==o&&e.call(t,o,Y(this,w,"f")[r],this)}}purgeStale(){let e=!1;for(const t of Y(this,s,"m",W).call(this,{allowStale:!0}))Y(this,F,"f").call(this,t)&&(Y(this,s,"m",J).call(this,Y(this,w,"f")[t],"expire"),e=!0);return e}info(e){const t=Y(this,g,"f").get(e);if(void 0===t)return;const r=Y(this,y,"f")[t],n=Y(this,s,"m",G).call(this,r)?r.__staleWhileFetching:r;if(void 0===n)return;const o={value:n};if(Y(this,P,"f")&&Y(this,x,"f")){const e=Y(this,P,"f")[t],r=Y(this,x,"f")[t];if(e&&r){const t=e-(Y(this,p,"f").now()-r);o.ttl=t,o.start=Date.now()}}return Y(this,E,"f")&&(o.size=Y(this,E,"f")[t]),o}dump(){const e=[];for(const t of Y(this,s,"m",B).call(this,{allowStale:!0})){const r=Y(this,w,"f")[t],n=Y(this,y,"f")[t],o=Y(this,s,"m",G).call(this,n)?n.__staleWhileFetching:n;if(void 0===o||void 0===r)continue;const i={value:o};if(Y(this,P,"f")&&Y(this,x,"f")){i.ttl=Y(this,P,"f")[t];const e=Y(this,p,"f").now()-Y(this,x,"f")[t];i.start=Math.floor(Date.now()-e)}Y(this,E,"f")&&(i.size=Y(this,E,"f")[t]),e.unshift([r,i])}return e}load(e){this.clear();for(const[t,r]of e){if(r.start){const e=Date.now()-r.start;r.start=Y(this,p,"f").now()-e}this.set(t,r.value,r)}}set(e,t,r={}){var n;if(void 0===t)return this.delete(e),this;const{ttl:o=this.ttl,start:a,noDisposeOnSet:d=this.noDisposeOnSet,sizeCalculation:h=this.sizeCalculation,status:p}=r;let{noUpdateTTL:m=this.noUpdateTTL}=r;const S=Y(this,U,"f").call(this,e,t,r.size||0,h);if(this.maxEntrySize&&S>this.maxEntrySize)return p&&(p.set="miss",p.maxEntrySizeExceeded=!0),Y(this,s,"m",J).call(this,e,"set"),this;let E=0===Y(this,f,"f")?void 0:Y(this,g,"f").get(e);if(void 0===E)E=0===Y(this,f,"f")?Y(this,k,"f"):0!==Y(this,_,"f").length?Y(this,_,"f").pop():Y(this,f,"f")===Y(this,i,"f")?Y(this,s,"m",q).call(this,!1):Y(this,f,"f"),Y(this,w,"f")[E]=e,Y(this,y,"f")[E]=t,Y(this,g,"f").set(e,E),Y(this,v,"f")[Y(this,k,"f")]=E,Y(this,b,"f")[E]=Y(this,k,"f"),Q(this,k,E,"f"),Q(this,f,(n=Y(this,f,"f"),++n),"f"),Y(this,j,"f").call(this,E,S,p),p&&(p.set="add"),m=!1,Y(this,A,"f")&&Y(this,l,"f")?.call(this,t,e,"add");else{Y(this,s,"m",K).call(this,E);const r=Y(this,y,"f")[E];if(t!==r){if(Y(this,R,"f")&&Y(this,s,"m",G).call(this,r)){r.__abortController.abort(new Error("replaced"));const{__staleWhileFetching:t}=r;void 0===t||d||(Y(this,I,"f")&&Y(this,c,"f")?.call(this,t,e,"set"),Y(this,T,"f")&&Y(this,C,"f")?.push([t,e,"set"]))}else d||(Y(this,I,"f")&&Y(this,c,"f")?.call(this,r,e,"set"),Y(this,T,"f")&&Y(this,C,"f")?.push([r,e,"set"]));if(Y(this,L,"f").call(this,E),Y(this,j,"f").call(this,E,S,p),Y(this,y,"f")[E]=t,p){p.set="replace";const e=r&&Y(this,s,"m",G).call(this,r)?r.__staleWhileFetching:r;void 0!==e&&(p.oldValue=e)}}else p&&(p.set="update");Y(this,A,"f")&&this.onInsert?.(t,e,t===r?"update":"replace")}if(0===o||Y(this,P,"f")||Y(this,s,"m",$).call(this),Y(this,P,"f")&&(m||Y(this,O,"f").call(this,E,o,a),p&&Y(this,D,"f").call(this,p,E)),!d&&Y(this,T,"f")&&Y(this,C,"f")){const e=Y(this,C,"f");let t;for(;t=e?.shift();)Y(this,u,"f")?.call(this,...t)}return this}pop(){try{for(;Y(this,f,"f");){const e=Y(this,y,"f")[Y(this,S,"f")];if(Y(this,s,"m",q).call(this,!0),Y(this,s,"m",G).call(this,e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(void 0!==e)return e}return}finally{if(Y(this,T,"f")&&Y(this,C,"f")){const e=Y(this,C,"f");let t;for(;t=e?.shift();)Y(this,u,"f")?.call(this,...t)}}}has(e,t={}){const{updateAgeOnHas:r=this.updateAgeOnHas,status:n}=t,o=Y(this,g,"f").get(e);if(void 0!==o){const e=Y(this,y,"f")[o];if(Y(this,s,"m",G).call(this,e)&&void 0===e.__staleWhileFetching)return!1;if(!Y(this,F,"f").call(this,o))return r&&Y(this,M,"f").call(this,o),n&&(n.has="hit",Y(this,D,"f").call(this,n,o)),!0;n&&(n.has="stale",Y(this,D,"f").call(this,n,o))}else n&&(n.has="miss");return!1}peek(e,t={}){const{allowStale:r=this.allowStale}=t,n=Y(this,g,"f").get(e);if(void 0===n||!r&&Y(this,F,"f").call(this,n))return;const o=Y(this,y,"f")[n];return Y(this,s,"m",G).call(this,o)?o.__staleWhileFetching:o}async fetch(e,t={}){const{allowStale:r=this.allowStale,updateAgeOnGet:n=this.updateAgeOnGet,noDeleteOnStaleGet:o=this.noDeleteOnStaleGet,ttl:i=this.ttl,noDisposeOnSet:a=this.noDisposeOnSet,size:c=0,sizeCalculation:l=this.sizeCalculation,noUpdateTTL:u=this.noUpdateTTL,noDeleteOnFetchRejection:d=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:h=this.allowStaleOnFetchRejection,ignoreFetchAbort:p=this.ignoreFetchAbort,allowStaleOnFetchAbort:f=this.allowStaleOnFetchAbort,context:m,forceRefresh:w=!1,status:v,signal:b}=t;if(!Y(this,R,"f"))return v&&(v.fetch="get"),this.get(e,{allowStale:r,updateAgeOnGet:n,noDeleteOnStaleGet:o,status:v});const S={allowStale:r,updateAgeOnGet:n,noDeleteOnStaleGet:o,ttl:i,noDisposeOnSet:a,size:c,sizeCalculation:l,noUpdateTTL:u,noDeleteOnFetchRejection:d,allowStaleOnFetchRejection:h,allowStaleOnFetchAbort:f,ignoreFetchAbort:p,status:v,signal:b},k=Y(this,g,"f").get(e);if(void 0===k){v&&(v.fetch="miss");const t=Y(this,s,"m",z).call(this,e,k,S,m);return t.__returned=t}{const t=Y(this,y,"f")[k];if(Y(this,s,"m",G).call(this,t)){const e=r&&void 0!==t.__staleWhileFetching;return v&&(v.fetch="inflight",e&&(v.returnedStale=!0)),e?t.__staleWhileFetching:t.__returned=t}const o=Y(this,F,"f").call(this,k);if(!w&&!o)return v&&(v.fetch="hit"),Y(this,s,"m",K).call(this,k),n&&Y(this,M,"f").call(this,k),v&&Y(this,D,"f").call(this,v,k),t;const i=Y(this,s,"m",z).call(this,e,k,S,m),a=void 0!==i.__staleWhileFetching&&r;return v&&(v.fetch=o?"stale":"refresh",a&&o&&(v.returnedStale=!0)),a?i.__staleWhileFetching:i.__returned=i}}async forceFetch(e,t={}){const r=await this.fetch(e,t);if(void 0===r)throw new Error("fetch() returned undefined");return r}memo(e,t={}){const r=Y(this,h,"f");if(!r)throw new Error("no memoMethod provided to constructor");const{context:n,forceRefresh:o,...s}=t,i=this.get(e,s);if(!o&&void 0!==i)return i;const a=r(e,i,{options:s,context:n});return this.set(e,a,s),a}get(e,t={}){const{allowStale:r=this.allowStale,updateAgeOnGet:n=this.updateAgeOnGet,noDeleteOnStaleGet:o=this.noDeleteOnStaleGet,status:i}=t,a=Y(this,g,"f").get(e);if(void 0!==a){const t=Y(this,y,"f")[a],c=Y(this,s,"m",G).call(this,t);return i&&Y(this,D,"f").call(this,i,a),Y(this,F,"f").call(this,a)?(i&&(i.get="stale"),c?(i&&r&&void 0!==t.__staleWhileFetching&&(i.returnedStale=!0),r?t.__staleWhileFetching:void 0):(o||Y(this,s,"m",J).call(this,e,"expire"),i&&r&&(i.returnedStale=!0),r?t:void 0)):(i&&(i.get="hit"),c?t.__staleWhileFetching:(Y(this,s,"m",K).call(this,a),n&&Y(this,M,"f").call(this,a),t))}i&&(i.get="miss")}delete(e){return Y(this,s,"m",J).call(this,e,"delete")}clear(){Y(this,s,"m",Z).call(this,"delete")}}X=Symbol.toStringTag,q=function(e){var t;const r=Y(this,S,"f"),n=Y(this,w,"f")[r],o=Y(this,y,"f")[r];return Y(this,R,"f")&&Y(this,s,"m",G).call(this,o)?o.__abortController.abort(new Error("evicted")):(Y(this,I,"f")||Y(this,T,"f"))&&(Y(this,I,"f")&&Y(this,c,"f")?.call(this,o,n,"evict"),Y(this,T,"f")&&Y(this,C,"f")?.push([o,n,"evict"])),Y(this,L,"f").call(this,r),e&&(Y(this,w,"f")[r]=void 0,Y(this,y,"f")[r]=void 0,Y(this,_,"f").push(r)),1===Y(this,f,"f")?(Q(this,S,Q(this,k,0,"f"),"f"),Y(this,_,"f").length=0):Q(this,S,Y(this,v,"f")[r],"f"),Y(this,g,"f").delete(n),Q(this,f,(t=Y(this,f,"f"),--t),"f"),r},z=function(e,t,r,n){const o=void 0===t?void 0:Y(this,y,"f")[t];if(Y(this,s,"m",G).call(this,o))return o;const i=new se,{signal:a}=r;a?.addEventListener("abort",(()=>i.abort(a.reason)),{signal:i.signal});const c={signal:i.signal,options:r,context:n},l=(n,o=!1)=>{const{aborted:a}=i.signal,l=r.ignoreFetchAbort&&void 0!==n;if(r.status&&(a&&!o?(r.status.fetchAborted=!0,r.status.fetchError=i.signal.reason,l&&(r.status.fetchAbortIgnored=!0)):r.status.fetchResolved=!0),a&&!l&&!o)return u(i.signal.reason);const d=h,p=Y(this,y,"f")[t];return(p===h||l&&o&&void 0===p)&&(void 0===n?void 0!==d.__staleWhileFetching?Y(this,y,"f")[t]=d.__staleWhileFetching:Y(this,s,"m",J).call(this,e,"fetch"):(r.status&&(r.status.fetchUpdated=!0),this.set(e,n,c.options))),n},u=n=>{const{aborted:o}=i.signal,a=o&&r.allowStaleOnFetchAbort,c=a||r.allowStaleOnFetchRejection,l=c||r.noDeleteOnFetchRejection,u=h;if(Y(this,y,"f")[t]===h&&(l&&void 0!==u.__staleWhileFetching?a||(Y(this,y,"f")[t]=u.__staleWhileFetching):Y(this,s,"m",J).call(this,e,"fetch")),c)return r.status&&void 0!==u.__staleWhileFetching&&(r.status.returnedStale=!0),u.__staleWhileFetching;if(u.__returned===u)throw n};r.status&&(r.status.fetchDispatched=!0);const h=new Promise(((t,n)=>{const s=Y(this,d,"f")?.call(this,e,o,c);s&&s instanceof Promise&&s.then((e=>t(void 0===e?void 0:e)),n),i.signal.addEventListener("abort",(()=>{r.ignoreFetchAbort&&!r.allowStaleOnFetchAbort||(t(void 0),r.allowStaleOnFetchAbort&&(t=e=>l(e,!0)))}))})).then(l,(e=>(r.status&&(r.status.fetchRejected=!0,r.status.fetchError=e),u(e)))),p=Object.assign(h,{__abortController:i,__staleWhileFetching:o,__returned:void 0});return void 0===t?(this.set(e,p,{...c.options,status:void 0}),t=Y(this,g,"f").get(e)):Y(this,y,"f")[t]=p,p},G=function(e){if(!Y(this,R,"f"))return!1;const t=e;return!!t&&t instanceof Promise&&t.hasOwnProperty("__staleWhileFetching")&&t.__abortController instanceof se},V=function(e,t){Y(this,b,"f")[t]=e,Y(this,v,"f")[e]=t},K=function(e){e!==Y(this,k,"f")&&(e===Y(this,S,"f")?Q(this,S,Y(this,v,"f")[e],"f"):Y(this,s,"m",V).call(this,Y(this,b,"f")[e],Y(this,v,"f")[e]),Y(this,s,"m",V).call(this,Y(this,k,"f"),e),Q(this,k,e,"f"))},J=function(e,t){var r;let n=!1;if(0!==Y(this,f,"f")){const o=Y(this,g,"f").get(e);if(void 0!==o)if(n=!0,1===Y(this,f,"f"))Y(this,s,"m",Z).call(this,t);else{Y(this,L,"f").call(this,o);const n=Y(this,y,"f")[o];if(Y(this,s,"m",G).call(this,n)?n.__abortController.abort(new Error("deleted")):(Y(this,I,"f")||Y(this,T,"f"))&&(Y(this,I,"f")&&Y(this,c,"f")?.call(this,n,e,t),Y(this,T,"f")&&Y(this,C,"f")?.push([n,e,t])),Y(this,g,"f").delete(e),Y(this,w,"f")[o]=void 0,Y(this,y,"f")[o]=void 0,o===Y(this,k,"f"))Q(this,k,Y(this,b,"f")[o],"f");else if(o===Y(this,S,"f"))Q(this,S,Y(this,v,"f")[o],"f");else{const e=Y(this,b,"f")[o];Y(this,v,"f")[e]=Y(this,v,"f")[o];const t=Y(this,v,"f")[o];Y(this,b,"f")[t]=Y(this,b,"f")[o]}Q(this,f,(r=Y(this,f,"f"),--r),"f"),Y(this,_,"f").push(o)}}if(Y(this,T,"f")&&Y(this,C,"f")?.length){const e=Y(this,C,"f");let t;for(;t=e?.shift();)Y(this,u,"f")?.call(this,...t)}return n},Z=function(e){for(const t of Y(this,s,"m",W).call(this,{allowStale:!0})){const r=Y(this,y,"f")[t];if(Y(this,s,"m",G).call(this,r))r.__abortController.abort(new Error("deleted"));else{const n=Y(this,w,"f")[t];Y(this,I,"f")&&Y(this,c,"f")?.call(this,r,n,e),Y(this,T,"f")&&Y(this,C,"f")?.push([r,n,e])}}if(Y(this,g,"f").clear(),Y(this,y,"f").fill(void 0),Y(this,w,"f").fill(void 0),Y(this,P,"f")&&Y(this,x,"f")&&(Y(this,P,"f").fill(0),Y(this,x,"f").fill(0)),Y(this,E,"f")&&Y(this,E,"f").fill(0),Q(this,S,0,"f"),Q(this,k,0,"f"),Y(this,_,"f").length=0,Q(this,m,0,"f"),Q(this,f,0,"f"),Y(this,T,"f")&&Y(this,C,"f")){const e=Y(this,C,"f");let t;for(;t=e?.shift();)Y(this,u,"f")?.call(this,...t)}}},"../utils/dist/path-utils.js"(e,t,r){"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:()=>I,A:()=>P,D1:()=>R,Gq:()=>D,Gw:()=>d,KX:()=>G,KZ:()=>j,N6:()=>w,Vn:()=>H,Zv:()=>m,fK:()=>q,iA:()=>F,kO:()=>A,mM:()=>T,qr:()=>$,wr:()=>V,wz:()=>W,yo:()=>M});var n=r("node:crypto"),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 I(e){const t=a.resolve(e);return t===u||t.startsWith(`${u}/`)}function R(e){const t=e?.processCwd??process.cwd();return"linux"===(e?.platform??process.platform)&&P(t,e)?e?.tmpdir??(0,i.tmpdir)():t}function T(e,t,r,n){const o=n?.platform??process.platform,s=r?.cwd;if("linux"!==o||void 0===s||r?.shell||!P(s,n))return{command:e,args:[...t],options:r,hopped:!1};const i=a.resolve(s),c=R({processCwd:n?.processCwd,tmpdir:n?.tmpdir,platform:o,readMountinfo:n?.readMountinfo});return{command:"/bin/sh",args:["-c",w,d,i,e,...t],options:{...r,cwd:c},hopped:!0,hopCwd:i}}function A(e,t,{directory:r,fallbackDirectory:n=r}){return{command:"/bin/sh",args:["-c",y,"cursor-sandbox-cwd",r,n,e,...t]}}function $(e=process.env){return"1"===e.CURSOR_SPAWN_CWD_HOP}const M="exec_daemon.spawn.cwd_hop",D="exec_daemon.spawn.cwd_hop_cd_failed";function O(e){return(0,n.createHash)("sha256").update(e,"utf8").digest("hex").slice(0,12)}function F(e){return{cwdKind:I(e)?"agent_store_fuse":"fuse",cwdHash:O(e)}}function N(e){return e.isDirectory()?"dir":e.isSymbolicLink()?"symlink":e.isFile()?"file":"other"}async function L(e,t,r){if(void 0===t)return"unchecked";if(t.some((t=>t.mountPoint===e)))return"mount_point";if(t.some((t=>C(t.fstype)&&_(e,t.mountPoint))))return"unchecked";const{root:n}=a.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:()=>u});var n=r("node:fs");function o(e){if(!("linux"!==process.platform||void 0===e||e<=0))try{(0,n.writeFileSync)(`/proc/${e}/oom_score_adj`,"0")}catch{}}var s=r("../utils/dist/safe-spawn-cwd.js");const i=/^\/sys\/fs\/cgroup\/[A-Za-z0-9_/.-]+$/,a=Object.freeze({kind:"direct"});function c({workloadCgroupDir:e,hopCwd:t}){const r=`echo $$ 2>/dev/null > '${e}/cgroup.procs'; echo 0 2>/dev/null > /proc/$$/oom_score_adj; `;return void 0!==t?r+s.N6:`${r}exec "$0" "$@"`}function l(e){try{return!!(0,n.statSync)(e).isDirectory()&&((0,n.accessSync)(`${e}/cgroup.procs`,n.constants.W_OK),!0)}catch{return!1}}const u=function(e,t=o){return function(r,n,o,...i){const a=i[0],l=(0,s.qr)()&&null!==(u=a)&&"object"==typeof u&&!Array.isArray(u)?(0,s.mM)(n,o,a):void 0;var u;let d,h=n,p=[...o],f=i;!0===l?.hopped&&void 0!==l.hopCwd?(f=function(e,t){return[t,...e.slice(1)]}(i,l.options),"armed"===e.kind?(h="/bin/sh",p=["-c",c({workloadCgroupDir:e.workloadCgroupDir,hopCwd:l.hopCwd}),s.Gw,l.hopCwd,n,...o]):(h=l.command,p=l.args)):"armed"===e.kind&&(h=e.executable,p=[...e.argumentPrefix,n,...o]);try{d=r(h,p,...f)}catch(e){throw!0===l?.hopped&&void 0!==l.hopCwd&&(0,s.KX)(e,l.hopCwd),e}return function(e,t){"object"==typeof e&&null!==e&&"pid"in e&&"number"==typeof e.pid?t(e.pid):"object"==typeof e&&null!==e&&"child"in e&&"object"==typeof e.child&&null!==e.child&&"pid"in e.child&&"number"==typeof e.child.pid&&t(e.child.pid)}(d,t),!0===l?.hopped&&void 0!==l.hopCwd?(0,s.wr)(d,l.hopCwd):d}}(function(e,t,r=l){return"linux"===e&&void 0!==t&&i.test(t)&&!t.includes("..")&&r(t)?Object.freeze({kind:"armed",workloadCgroupDir:t,executable:"/bin/sh",argumentPrefix:Object.freeze(["-c",c({workloadCgroupDir:t})])}):a}(process.platform,process.env.CURSOR_WORKLOAD_CGROUP))},"../utils/dist/writable-iterable.js"(e,t,r){"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}))})}}}};
|