@cursor/sdk 1.0.17 → 1.0.18
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/cjs/429.index.js +1 -0
- package/dist/cjs/642.index.js +1 -1
- package/dist/cjs/745.index.js +8 -0
- package/dist/cjs/745.index.js.LICENSE.txt +30 -0
- package/dist/cjs/agent.d.ts +2 -10
- package/dist/cjs/agent.d.ts.map +1 -1
- package/dist/cjs/analytics.d.ts +6 -0
- package/dist/cjs/analytics.d.ts.map +1 -1
- package/dist/cjs/cloud-agent.d.ts.map +1 -1
- package/dist/cjs/cloud-api-client.d.ts +1 -0
- package/dist/cjs/cloud-api-client.d.ts.map +1 -1
- package/dist/cjs/custom-tools.d.ts +29 -0
- package/dist/cjs/custom-tools.d.ts.map +1 -0
- package/dist/cjs/errors.d.ts +11 -1
- package/dist/cjs/errors.d.ts.map +1 -1
- package/dist/cjs/executor-types.d.ts +2 -1
- package/dist/cjs/executor-types.d.ts.map +1 -1
- package/dist/cjs/index.d.ts +3 -3
- package/dist/cjs/index.d.ts.map +1 -1
- package/dist/cjs/index.js +1 -7
- package/dist/cjs/index.js.LICENSE.txt +0 -31
- package/dist/cjs/local-executor.d.ts +2 -0
- package/dist/cjs/local-executor.d.ts.map +1 -1
- package/dist/cjs/options.d.ts +55 -0
- package/dist/cjs/options.d.ts.map +1 -1
- package/dist/cjs/platform.d.ts +2 -0
- package/dist/cjs/platform.d.ts.map +1 -1
- package/dist/cjs/public-api.d.ts +1 -1
- package/dist/cjs/public-api.d.ts.map +1 -1
- package/dist/cjs/run-store-public-types.d.ts +6 -1
- package/dist/cjs/run-store-public-types.d.ts.map +1 -1
- package/dist/cjs/run.d.ts +2 -0
- package/dist/cjs/run.d.ts.map +1 -1
- package/dist/cjs/sdk-statsig.d.ts +5 -1
- package/dist/cjs/sdk-statsig.d.ts.map +1 -1
- package/dist/cjs/store/local-agent-record-conversion.d.ts.map +1 -1
- package/dist/cjs/store/local-agent-store.d.ts +1 -0
- package/dist/cjs/store/local-agent-store.d.ts.map +1 -1
- package/dist/esm/429.index.js +1 -0
- package/dist/esm/642.index.js +1 -1
- package/dist/esm/745.index.js +8 -0
- package/dist/esm/745.index.js.LICENSE.txt +30 -0
- package/dist/esm/agent.d.ts +2 -10
- package/dist/esm/agent.d.ts.map +1 -1
- package/dist/esm/analytics.d.ts +6 -0
- package/dist/esm/analytics.d.ts.map +1 -1
- package/dist/esm/cloud-agent.d.ts.map +1 -1
- package/dist/esm/cloud-api-client.d.ts +1 -0
- package/dist/esm/cloud-api-client.d.ts.map +1 -1
- package/dist/esm/custom-tools.d.ts +29 -0
- package/dist/esm/custom-tools.d.ts.map +1 -0
- package/dist/esm/errors.d.ts +11 -1
- package/dist/esm/errors.d.ts.map +1 -1
- package/dist/esm/executor-types.d.ts +2 -1
- package/dist/esm/executor-types.d.ts.map +1 -1
- package/dist/esm/index.d.ts +3 -3
- package/dist/esm/index.d.ts.map +1 -1
- package/dist/esm/index.js +1 -7
- package/dist/esm/index.js.LICENSE.txt +0 -31
- package/dist/esm/local-executor.d.ts +2 -0
- package/dist/esm/local-executor.d.ts.map +1 -1
- package/dist/esm/options.d.ts +55 -0
- package/dist/esm/options.d.ts.map +1 -1
- package/dist/esm/platform.d.ts +2 -0
- package/dist/esm/platform.d.ts.map +1 -1
- package/dist/esm/public-api.d.ts +1 -1
- package/dist/esm/public-api.d.ts.map +1 -1
- package/dist/esm/run-store-public-types.d.ts +6 -1
- package/dist/esm/run-store-public-types.d.ts.map +1 -1
- package/dist/esm/run.d.ts +2 -0
- package/dist/esm/run.d.ts.map +1 -1
- package/dist/esm/sdk-statsig.d.ts +5 -1
- package/dist/esm/sdk-statsig.d.ts.map +1 -1
- package/dist/esm/store/local-agent-record-conversion.d.ts.map +1 -1
- package/dist/esm/store/local-agent-store.d.ts +1 -0
- package/dist/esm/store/local-agent-store.d.ts.map +1 -1
- package/package.json +11 -18
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const __webpack_esm_id__=429;export const __webpack_esm_ids__=[429];export const __webpack_esm_modules__={"./src/agent/local-executor.ts"(e,t,r){r.d(t,{createLocalExecutor:()=>oy});var o=r("node:buffer?4cd4"),n=r("node:crypto?8af2"),s=r("node:fs"),i=r("node:os"),a=r("node:path"),l=r("../context/dist/index.js"),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 o,n=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===n)return n=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var s=o.dispose.call(o.value);if(o.async)return n|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else n|=1}catch(e){r(e)}if(1===n)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var o=new Error(r);return o.name="SuppressedError",o.error=e,o.suppressed=t,o});class u{checkpointStream;checkpointHandler;ctx;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 o,n;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");o=t[Symbol.asyncDispose]}if(void 0===o){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");o=t[Symbol.dispose],r&&(n=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");n&&(o=function(){try{n.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:o,async:r})}else r&&e.stack.push({async:!0});return t}(e,(0,l.VI)(this.ctx.withName("CheckpointController.run")),!1).ctx,r=[];for await(const e of this.checkpointStream)r.push(this.checkpointHandler.handleCheckpoint(t,e));await Promise.all(r)}catch(t){e.error=t,e.hasError=!0}finally{c(e)}}}var d=r("../metrics/dist/index.js"),p=r("../proto/dist/generated/agent/v1/exec_pb.js"),h=r("../utils/dist/index.js");const m=(0,l.h)("SimpleControlledExecManager"),f=(0,d.v5)("agent_exec.controlled.exec.duration_ms",{description:"Duration of controlled exec operations in milliseconds",labelNames:["exec_case"]}),g=(0,d.Pu)("agent_exec.controlled.exec.success",{description:"Count of successful controlled exec operations",labelNames:["exec_case"]}),v=(0,d.Pu)("agent_exec.controlled.exec.error",{description:"Count of failed controlled exec operations",labelNames:["exec_case"]});class y extends Error{constructor(e){super(e),this.name="ControlledExecDisposedError"}}function w(e){return e instanceof y?"EXEC_BACKEND_UNAVAILABLE":e instanceof Error&&"AgentExecStreamStartTimeoutError"===e.name?"AGENT_EXEC_STREAM_START_TIMEOUT":void 0}class b{exec;deserializeArgs;serializeResult;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:o,args:n}=r;return async function*(r){const s=performance.now(),i=await r.exec.execute(e,n,{execId:t.execId}),a=r.serializeResult(o,i);a.localExecutionTimeMs=Math.round(Math.max(0,performance.now()-s)),yield a}(this)}}class S{exec;deserializeArgs;serializeStream;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:o,args:n}=r;return async function*(r){const s=performance.now(),i=r.exec.execute(e,n,{execId:t.execId});for await(const e of i){const t=r.serializeStream(o,e);t.localExecutionTimeMs=Math.round(Math.max(0,performance.now()-s)),yield t}}(this)}}class k{handlers=[];runningExecs=new Map;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){var r;const[o,n]=e.withCancel();this.runningExecs.set(t.id,n);const s=null!==(r=t.message.case)&&void 0!==r?r:"unknown";for(const e of this.handlers){const r=e.handle(o,t);if(void 0===r)continue;const n=r,i=(0,h.Jt)();let a;const l=()=>{a=setTimeout((()=>{i.write(new p.$Y({message:{case:"heartbeat",value:new p.VA({id:t.id})}})).then(l).catch((()=>{}))}),3e3)};l();const c=performance.now();return(async()=>{try{for await(const e of n)await i.write(e);await i.write(new p.$Y({message:{case:"streamClose",value:new p.D9({id:t.id})}})),g.increment(o,1,{exec_case:s})}catch(e){if(e instanceof h.W2)return;v.increment(o,1,{exec_case:s}),await i.write(new p.$Y({message:{case:"throw",value:new p.Fu({id:t.id,error:e instanceof Error?e.message:"Unknown error",stackTrace:e instanceof Error?e.stack:void 0,errorCode:w(e)})}}))}finally{const e=performance.now()-c;f.histogram(o,e,{exec_case:s}),clearTimeout(a),i.close(),this.runningExecs.delete(t.id)}})(),i}this.runningExecs.delete(t.id);const i=`No handler found for server message of type ${t.message.case}`;return m.error(e,i,{messageCase:t.message.case}),v.increment(e,1,{exec_case:s}),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){const t=new k;for(const[r,o]of e.entries())r.registerControlledImplementation(o,t);return t}}var E=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var o,n;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");o=t[Symbol.asyncDispose]}if(void 0===o){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");o=t[Symbol.dispose],r&&(n=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");n&&(o=function(){try{n.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:o,async:r})}else r&&e.stack.push({async:!0});return t},x=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var o,n=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===n)return n=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var s=o.dispose.call(o.value);if(o.async)return n|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else n|=1}catch(e){r(e)}if(1===n)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var o=new Error(r);return o.name="SuppressedError",o.error=e,o.suppressed=t,o});const _=(0,l.h)("ExecutorResource");class C{execManager;serializeArgs;deserializeResult;constructor(e,t,r){this.execManager=e,this.serializeArgs=t,this.deserializeResult=r}async execute(e,t,r){const o={stack:[],error:void 0,hasError:!1};try{const n=E(o,(0,l.VI)(e.withName("ExecutorResource.execute")),!1),s=n.ctx;void 0!==(null==r?void 0:r.execId)&&n.span.setAttribute("exec.id",r.execId);const i=(0,l.mJ)(s),a=i?new p.Kg(i):void 0,c=this.execManager.createExecInstance(s,(e=>{const o=this.serializeArgs(e,t);return new p.Ye({id:o.id,message:o.message,execId:null==r?void 0:r.execId,spanContext:a})})),u=await(0,l.uj)(s.withName("ExecutorResource.sendAndAwaitFirstResult"),(()=>(0,h.ue)(c)));if(void 0===u)throw new Error("No exec result");const{firstItem:d,rest:m}=u;(0,l.uj)(s.withName("ExecutorResource.drainResultStream"),(async()=>{try{for await(const e of m);}catch(e){_.info(s,"Ignoring exec stream shutdown during detached drain",{error:e})}})).catch((()=>{}));const f=this.deserializeResult(d);if(void 0===f)throw new Error("No result value");return f}catch(e){o.error=e,o.hasError=!0}finally{x(o)}}}class P{execManager;serializeArgs;deserializeStream;constructor(e,t,r){this.execManager=e,this.serializeArgs=t,this.deserializeStream=r}async*execute(e,t,r){const o={stack:[],error:void 0,hasError:!1};try{const n=E(o,(0,l.VI)(e.withName("StreamExecutorResource.execute")),!1).ctx,s=(0,l.mJ)(n),i=s?new p.Kg(s):void 0,a=this.execManager.createExecInstance(n,(e=>{const o=this.serializeArgs(e,t);return new p.Ye({id:o.id,message:o.message,execId:null==r?void 0:r.execId,spanContext:i})}));for await(const e of a){const t=this.deserializeStream(e);void 0!==t&&(yield t)}}catch(e){o.error=e,o.hasError=!0}finally{x(o)}}}function R(e,t){return{symbol:Symbol(),remoteImplementation:e,registerControlledImplementation:t}}class T{resource;value;constructor(e,t){this.resource=e,this.value=t}}class I{resources=new Map;register(e,t){this.resources.set(e.symbol,new T(e,t))}get(e){var t;return null===(t=this.resources.get(e.symbol))||void 0===t?void 0:t.value}entries(){return Array.from(this.resources.values()).map((e=>[e.resource,e.value]))}}class A{remoteAccessor;localResources=new Map;constructor(e,t){this.remoteAccessor=e;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?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 O(e){return function(t,r){return new p.Ye({id:t,message:{case:e,value:r}})}}function D(e){return t=>{if(t.message.case===e)return t.message.value}}function M(e){return function(t,r){const o={case:e,value:r};return new p.yT({id:t,message:o})}}function j(e){return function(t){if(t.message.case===e)return{id:t.id,args:t.message.value}}}const N=R((e=>new C(e,O("backgroundShellSpawnArgs"),D("backgroundShellSpawnResult"))),((e,t)=>{t.register(new b(e,j("backgroundShellSpawnArgs"),M("backgroundShellSpawnResult")))})),$=R((e=>new C(e,O("writeShellStdinArgs"),D("writeShellStdinResult"))),((e,t)=>{t.register(new b(e,j("writeShellStdinArgs"),M("writeShellStdinResult")))}));function F(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}var L=r("../proto/dist/generated/agent/v1/agent_pb.js");const U=R((e=>new C(e,O("canvasDiagnosticsArgs"),D("canvasDiagnosticsResult"))),((e,t)=>{t.register(new b(e,j("canvasDiagnosticsArgs"),M("canvasDiagnosticsResult")))}));Error;const B=R((e=>new C(e,O("computerUseArgs"),D("computerUseResult"))),((e,t)=>{t.register(new b(e,j("computerUseArgs"),M("computerUseResult")))})),H=R((e=>new C(e,O("deleteArgs"),D("deleteResult"))),((e,t)=>{t.register(new b(e,j("deleteArgs"),M("deleteResult")))})),z=R((e=>new C(e,O("diagnosticsArgs"),D("diagnosticsResult"))),((e,t)=>{t.register(new b(e,j("diagnosticsArgs"),M("diagnosticsResult")))})),W=R((e=>new C(e,O("fetchArgs"),D("fetchResult"))),((e,t)=>{t.register(new b(e,j("fetchArgs"),M("fetchResult")))})),q=(R((e=>new C(e,O("gitDiffRequest"),D("gitDiffResponse"))),((e,t)=>{t.register(new b(e,j("gitDiffRequest"),M("gitDiffResponse")))})),R((e=>new C(e,O("grepArgs"),D("grepResult"))),((e,t)=>{t.register(new b(e,j("grepArgs"),M("grepResult")))}))),G={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"},V={PreToolUse:G.preToolUse,PermissionRequest:null,PostToolUse:G.postToolUse,UserPromptSubmit:G.beforeSubmitPrompt,Stop:G.stop,SubagentStop:G.subagentStop,SessionStart:G.sessionStart,SessionEnd:G.sessionEnd,PreCompact:G.preCompact,Notification:null},J=Object.fromEntries(Object.entries(V).filter((e=>null!==e[1])).map((([e,t])=>[t,e]))),K={Bash:"Shell",Read:"Read",Write:"Write",Edit:"Write",Glob:null,Grep:"Grep",WebFetch:"WebFetch",WebSearch:"WebSearch",Task:"Task"},Z=["Glob"],Y=["Notification","PermissionRequest"],X={warn:()=>{},info:()=>{}};function Q(e,t){const r={loop_limit:null,failClosed:!1};return t&&"*"!==t&&(r.matcher=t),void 0!==e.timeout&&(r.timeout=e.timeout),"prompt"===e.type?e.prompt?Object.assign({type:"prompt",prompt:e.prompt},r):null:e.command?Object.assign({type:"command",command:e.command},r):null}function ee(e,t,r=X){const o=[];let n;if("PreToolUse"===t||"PostToolUse"===t){const t=function(e,t=X){if(""===e||"*"===e)return"*";const r=e.split("|"),o=[],n=[];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("__");o.push(`MCP:${t}`);continue}}const r=K[t];null!==r?void 0!==r?o.includes(r)||o.push(r):o.push(t):Z.includes(t)&&n.push(`Tool "${t}" is not supported in Cursor and will be ignored`)}for(const e of n)t.warn(e);return 0===o.length?null:o.join("|")}(e.matcher,r);if(null===t)return r.warn(`All tools in matcher "${e.matcher}" are unsupported, skipping hooks`),[];n="*"===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`),n=void 0):n=void 0;for(const t of e.hooks){const e=Q(t,n);e&&o.push(e)}return o}function te(e,t=X){const r={};for(const[o,n]of Object.entries(e)){const e=o;if(Y.includes(e)){t.warn(`Claude Code event "${e}" is not supported in Cursor and will be ignored`);continue}const s=V[e];if(!s){t.warn(`Unknown Claude Code event "${e}", skipping`);continue}const i=[];if(Array.isArray(n))for(const r of n){const o=ee(r,e,t);i.push(...o)}else void 0!==n&&t.warn(`Claude Code event "${e}" has invalid value (expected array), skipping`);if(i.length>0){const e=r[s]||[];r[s]=[...e,...i]}}return{version:1,hooks:r}}function re(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(e){return!0}}(e,t)))}const oe=e=>"string"==typeof e,ne=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),se=(e,t=[])=>({isValid:e,errors:t});function ie(e,t,r){void 0===e||oe(e)||r.push(`${t} must be a string if provided`)}const ae=e=>{const t=[];return ne(e)?se(!0):(t.push("Expected an object"),se(!1,t))},le=e=>{const t=[],r=ae(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"),se(0===t.length,t)};function ce(e){const t=e.modelId,r=e.modelParams;return Object.assign(Object.assign({},void 0!==t&&{model_id:t}),void 0!==r&&r.length>0?{model_params:r.map((e=>({id:e.id,value:e.value})))}:{})}const ue=new Set([G.sessionStart,G.beforeSubmitPrompt,G.preToolUse,G.postToolUse,G.postToolUseFailure]);function de(e){return"prompt"===e.type}const pe={[G.beforeShellExecution]:le,[G.beforeMCPExecution]:le,[G.afterShellExecution]:e=>{const t=ae(e);return t.isValid,t},[G.afterMCPExecution]:e=>{const t=ae(e);return t.isValid,t},[G.beforeReadFile]:e=>{const t=[],r=ae(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"),se(0===t.length,t)},[G.afterFileEdit]:e=>{const t=ae(e);return t.isValid,t},[G.beforeTabFileRead]:e=>{const t=[],r=ae(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"),se(0===t.length,t)},[G.afterTabFileEdit]:e=>ae(e),[G.beforeSubmitPrompt]:e=>{const t=ae(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||oe(e.additional_context)||r.push("additional_context must be a string if provided"),se(0===r.length,r)},[G.stop]:e=>{const t=ae(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"),se(0===r.length,r)},[G.afterAgentResponse]:e=>{const t=ae(e);return t.isValid,t},[G.afterAgentThought]:e=>{const t=ae(e);return t.isValid,t},[G.sessionStart]:e=>{const t=ae(e);if(!t.isValid)return t;const r=[];if(void 0!==e.env)if(ne(e.env))for(const[t,o]of Object.entries(e.env))oe(t)||r.push(`env key "${t}" must be a string`),oe(o)||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||oe(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||oe(e.user_message)||r.push("user_message must be a string if provided"),se(0===r.length,r)},[G.sessionEnd]:e=>{const t=ae(e);return t.isValid?se(!0,[]):t},[G.preCompact]:e=>{const t=ae(e);if(!t.isValid)return t;if(null==e||0===Object.keys(e).length)return se(!0,[]);const r=[];if(!ne(e))return r.push("PreCompact response must be an object"),se(!1,r);const o=e;return void 0===o.user_message||(e=>"string"==typeof e)(o.user_message)||r.push("user_message must be a string"),se(0===r.length,r)},[G.subagentStart]:e=>{const t=ae(e);if(!t.isValid)return t;const r=[],o=e;if(void 0!==o.permission){const e=["allow","deny","ask"];e.includes(o.permission)||r.push(`Invalid permission value. Expected one of: ${e.join(", ")}, or undefined`)}return void 0===o.user_message||oe(o.user_message)||r.push("user_message must be a string if provided"),se(0===r.length,r)},[G.subagentStop]:e=>{const t=ae(e);if(!t.isValid)return t;const r=[];return void 0!==e&&"object"==typeof e&&null!==e&&void 0!==e.followup_message&&"string"!=typeof e.followup_message&&r.push("followup_message must be a string if provided"),se(0===r.length,r)},[G.preToolUse]:e=>{const t=[],r=ae(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"),ie(e.additional_context,"additional_context",t),se(0===t.length,t)},[G.postToolUse]:e=>{const t=[],r=ae(e);return r.isValid?(ie(e.additional_context,"additional_context",t),se(0===t.length,t)):r},[G.postToolUseFailure]:e=>{const t=ae(e);if(!t.isValid)return t;const r=[];return ie(e.additional_context,"additional_context",r),se(0===r.length,r)},[G.workspaceOpen]:e=>{const t=ae(e);if(!t.isValid)return t;const r=[];return void 0!==e.pluginPaths&&(Array.isArray(e.pluginPaths)?e.pluginPaths.forEach(((e,t)=>{oe(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")),se(0===r.length,r)}},he=(e,t,r)=>{const o=function(e,t,r){let o;return o=e===G.preToolUse?function(e,t){if(!ke(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(!Se(t))return r;const o=Ee(e);if(!xe(o,"PreToolUse"))return r;const n=Object.assign({},r);let s=!1;return void 0!==o.permissionDecision&&(n.permission=o.permissionDecision,s=!0),"string"==typeof o.permissionDecisionReason&&(n.user_message=o.permissionDecisionReason,s=!0),ke(o.updatedInput)&&(n.updated_input=o.updatedInput,s=!0),s?n:r}(t,r):e===G.stop?_e(t,r,"Stop"):e===G.subagentStop?_e(t,r,"SubagentStop"):t,function(e,t,r,o){var n;if(!ue.has(e)||!ke(r)||void 0!==r.additional_context)return r;const s=ke(t)?null!==(n=function(e){return"string"==typeof e.additionalContext?e.additionalContext:void 0}(t))&&void 0!==n?n:function(e,t,r){if(!Se(r))return;const o=J[e];if(void 0===o)return;const n=Ee(t);return xe(n,o)&&"string"==typeof n.additionalContext?n.additionalContext:void 0}(e,t,o):void 0;return void 0===s?r:Object.assign(Object.assign({},r),{additional_context:s})}(e,t,o,r)}(e,t,r),n=(0,pe[e])(o);return n.isValid?{success:!0,data:o}:{success:!1,errors:n.errors}},me=[G.beforeShellExecution,G.beforeMCPExecution,G.beforeReadFile,G.beforeTabFileRead,G.subagentStart,G.preToolUse],fe=[G.workspaceOpen];function ge(e,t){const r=[];return(null==e?void 0:e.trim())&&r.push(e.trim()),(null==t?void 0:t.trim())&&r.push(t.trim()),r.length>0?r.join("\n\n---\n\n"):void 0}function ve(e,t){if(e||t)return Object.assign(Object.assign({},e||{}),t||{})}function ye(e){return me.includes(e)}function we({step:e,command:t,failClosed:r,kind:o}){const n=ye(e);if(!r&&!n)return{shouldNotifyUser:!1};const s=r?"Tool blocked because this hook is configured to fail closed (block when it fails). "+("invalid_json"===o?`Hook "${t}" returned invalid JSON.`:`Hook "${t}" returned invalid response.`):"invalid_json"===o?`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:be(e,s),cause:r?"script_fail_closed":"permission_hook_invalid_output",reason:s,shouldNotifyUser:n&&!r}}function be(e,t){return ye(e)?{permission:"deny",user_message:t}:e===G.beforeSubmitPrompt||e===G.sessionStart?{continue:!1,user_message:t}:e===G.stop?{}:void 0}function Se(e){var t;return null!==(t=null==e?void 0:e.enableClaudeNestedHookSpecificOutputCompatibility)&&void 0!==t&&t}function ke(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function Ee(e){if(!ke(e))return;const t=e.hookSpecificOutput;return ke(t)?t:void 0}function xe(e,t){if(!e)return!1;const r=e.hookEventName;return void 0===r||""===r||r===t}function _e(e,t,r){if(!ke(e))return e;const o=e;if(void 0!==o.followup_message)return o;if("block"===o.decision&&"string"==typeof o.reason&&o.reason.trim().length>0)return Object.assign(Object.assign({},o),{followup_message:o.reason.trim()});if(!Se(t))return o;const n=Ee(e),s=xe(n,r)?n:void 0,i=void 0!==s?Object.assign(Object.assign({},o),s):o;return"block"===i.decision&&"string"==typeof i.reason&&i.reason.trim().length>0?Object.assign(Object.assign({},i),{followup_message:i.reason.trim()}):o}const Ce=["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass"],Pe=e=>{const t=[];if(!ne(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)"),se(!1,t);const r=e.type;return"prompt"===r?((e,t)=>{oe(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&&(oe(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)=>{oe(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)=>{var r;if(void 0!==e.matcher)if(oe(e.matcher)){if(""!==e.matcher&&"*"!==e.matcher)try{new RegExp(e.matcher)}catch(o){t.push(`Hook script matcher "${e.matcher}" is not a valid regex: ${null!==(r=null==o?void 0:o.message)&&void 0!==r?r:String(o)}`)}}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),se(0===t.length,t)},Re=(e,t)=>{const r=[];if(!Array.isArray(e))return r.push(`${t} must be an array of hook scripts`),se(!1,r);for(let o=0;o<e.length;o++){const n=Pe(e[o]);n.isValid||r.push(`${t}[${o}]: ${n.errors.join(", ")}`)}return se(0===r.length,r)},Te=e=>{const t=[];if(!ne(e))return t.push("Hooks config must be an object"),se(!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"),!ne(e.hooks))return t.push("Config hooks must be an object"),se(!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(G),o=e.hooks;for(const[e,n]of Object.entries(o))if(r.includes(e)){if(void 0!==n){const r=Re(n,e);r.isValid||t.push(...r.errors)}}else t.push(`Unknown hook type: ${e}. Valid types are: ${r.join(", ")}`);return se(0===t.length,t)},Ie=R((e=>new C(e,O("executeHookArgs"),D("executeHookResult"))),((e,t)=>{t.register(new b(e,j("executeHookArgs"),M("executeHookResult")))}));class Ae{hookExecutor;constructor(e){this.hookExecutor=e}hasFailClosedHooksForStep(e,t){var r,o,n;return null!==(n=null===(o=(r=this.hookExecutor).hasFailClosedHooksForStep)||void 0===o?void 0:o.call(r,e,t))&&void 0!==n&&n}async execute(e,t){var r,o,n,s,i,a,l,c,u,d,h,m,f,g,v,y,w,b,S;const k=t.request;if(!k)return new p.S1({response:void 0});switch(k.request.case){case"preCompact":{const e=k.request.value,t=Object.assign(Object.assign({conversation_id:null!==(r=e.conversationId)&&void 0!==r?r:"",generation_id:null!==(o=e.generationId)&&void 0!==o?o:"",model:null!==(n=e.model)&&void 0!==n?n:""},ce(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}),s=await this.hookExecutor.executeHookForStep(G.preCompact,t);return new p.S1({response:new p.w5({response:{case:"preCompact",value:new L.$_({userMessage:null==s?void 0:s.user_message})}})})}case"subagentStart":{const e=k.request.value,t=Object.assign(Object.assign({conversation_id:null!==(s=e.conversationId)&&void 0!==s?s:"",generation_id:null!==(i=e.generationId)&&void 0!==i?i:"",model:null!==(a=e.model)&&void 0!==a?a:""},ce(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}),r=await this.hookExecutor.executeHookForStep(G.subagentStart,t);return new p.S1({response:new p.w5({response:{case:"subagentStart",value:new L.W0({permission:null==r?void 0:r.permission,userMessage:null==r?void 0:r.user_message,additionalContext:null==r?void 0:r.additional_context})}})})}case"subagentStop":{const e=k.request.value,t=Object.assign(Object.assign({conversation_id:null!==(l=e.conversationId)&&void 0!==l?l:"",generation_id:null!==(c=e.generationId)&&void 0!==c?c:"",model:null!==(u=e.model)&&void 0!==u?u:""},ce(e)),{subagent_id:e.subagentId,subagent_type:e.subagentType,status: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:null!==(d=e.loopCount)&&void 0!==d?d:0,task:e.task,description:e.description}),r=await this.hookExecutor.executeHookForStep(G.subagentStop,t);return new p.S1({response:new p.w5({response:{case:"subagentStop",value:new L.AH({followupMessage:null==r?void 0:r.followup_message,additionalContext:null==r?void 0:r.additional_context})}})})}case"preToolUse":{const e=k.request.value,t=e.toolInput?e.toolInput.toJson():{},r=Object.assign(Object.assign({conversation_id:null!==(h=e.conversationId)&&void 0!==h?h:"",generation_id:null!==(m=e.generationId)&&void 0!==m?m:"",model:null!==(f=e.model)&&void 0!==f?f:""},ce(e)),{tool_name:e.toolName,tool_input:t,tool_use_id:e.toolUseId,cwd:e.cwd}),o=await this.hookExecutor.executeHookForStep(G.preToolUse,r);return new p.S1({response:new p.w5({response:{case:"preToolUse",value:new L.D2({permission:null==o?void 0:o.permission,userMessage:null==o?void 0:o.user_message,agentMessage:null==o?void 0:o.agent_message,updatedInput:(null==o?void 0:o.updated_input)?JSON.stringify(o.updated_input):void 0,additionalContext:null==o?void 0:o.additional_context})}})})}case"postToolUse":{const e=k.request.value,t=e.toolInput?e.toolInput.toJson():{},r=Object.assign(Object.assign({conversation_id:null!==(g=e.conversationId)&&void 0!==g?g:"",generation_id:null!==(v=e.generationId)&&void 0!==v?v:"",model:null!==(y=e.model)&&void 0!==y?y:""},ce(e)),{tool_name:e.toolName,tool_input:t,tool_output:e.toolOutput,duration:Number(e.durationMs),tool_use_id:e.toolUseId,cwd:e.cwd}),o=await this.hookExecutor.executeHookForStep(G.postToolUse,r);return new p.S1({response:new p.w5({response:{case:"postToolUse",value:new L.uB({additionalContext:null==o?void 0:o.additional_context})}})})}case"postToolUseFailure":{const e=k.request.value,t=e.toolInput?e.toolInput.toJson():{},r=Object.assign(Object.assign({conversation_id:null!==(w=e.conversationId)&&void 0!==w?w:"",generation_id:null!==(b=e.generationId)&&void 0!==b?b:"",model:null!==(S=e.model)&&void 0!==S?S:""},ce(e)),{tool_name:e.toolName,tool_input:t,error_message:e.errorMessage,failure_type:e.failureType,duration:Number(e.durationMs),tool_use_id:e.toolUseId,is_interrupt:e.isInterrupt}),o=await this.hookExecutor.executeHookForStep(G.postToolUseFailure,r);return new p.S1({response:new p.w5({response:{case:"postToolUseFailure",value:new L.U1({additionalContext:null==o?void 0:o.additional_context})}})})}default:return new p.S1({response:void 0})}}}(0,l.cF)(Symbol("execHookConversationId"),void 0),(0,l.cF)(Symbol("execHookGenerationId"),void 0),(0,l.cF)(Symbol("execHookModel"),void 0);const Oe=(0,l.cF)(Symbol("execHookWorkspaceRoots"),void 0),De=R((e=>new C(e,O("lsArgs"),D("lsResult"))),((e,t)=>{t.register(new b(e,j("lsArgs"),M("lsResult")))})),Me="custom-user-tools";var je;new Set(["cursor-dev-control","cursor-ide-browser"]),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"}(je||(je={}));const Ne=R((e=>new C(e,O("mcpArgs"),D("mcpResult"))),((e,t)=>{t.register(new b(e,j("mcpArgs"),M("mcpResult")))})),$e=R((e=>new C(e,O("listMcpResourcesExecArgs"),D("listMcpResourcesExecResult"))),((e,t)=>{t.register(new b(e,j("listMcpResourcesExecArgs"),M("listMcpResourcesExecResult")))})),Fe=R((e=>new C(e,O("readMcpResourceExecArgs"),D("readMcpResourceExecResult"))),((e,t)=>{t.register(new b(e,j("readMcpResourceExecArgs"),M("readMcpResourceExecResult")))})),Le=R((e=>new C(e,O("mcpStateExecArgs"),D("mcpStateExecResult"))),((e,t)=>{t.register(new b(e,j("mcpStateExecArgs"),M("mcpStateExecResult")))}));var Ue=r("../proto/dist/generated/agent/v1/mcp_allowlist_precheck_exec_pb.js");const Be=R((e=>new C(e,O("mcpAllowlistPrecheckArgs"),D("mcpAllowlistPrecheckResult"))),((e,t)=>{t.register(new b(e,j("mcpAllowlistPrecheckArgs"),M("mcpAllowlistPrecheckResult")))})),He=R((e=>new C(e,O("readArgs"),D("readResult"))),((e,t)=>{t.register(new b(e,j("readArgs"),M("readResult")))})),ze=R((e=>new C(e,O("redactedReadArgs"),D("redactedReadResult"))),((e,t)=>{t.register(new b(e,j("redactedReadArgs"),M("redactedReadResult")))}));var We=r("../proto/dist/generated/agent/v1/background_shell_exec_pb.js"),qe=r("../proto/dist/generated/agent/v1/delete_exec_pb.js"),Ge=r("../proto/dist/generated/agent/v1/mcp_exec_pb.js"),Ve=r("../proto/dist/generated/agent/v1/shell_exec_pb.js"),Je=r("../proto/dist/generated/agent/v1/write_exec_pb.js");const Ke=R((e=>new C(e,O("shellArgs"),D("shellResult"))),((e,t)=>{t.register(new b(e,j("shellArgs"),M("shellResult")))})),Ze=R((e=>new P(e,O("shellStreamArgs"),D("shellStream"))),((e,t)=>{t.register(new S(e,j("shellStreamArgs"),M("shellStream")))})),Ye=R((e=>new C(e,O("writeArgs"),D("writeResult"))),((e,t)=>{t.register(new b(e,j("writeArgs"),M("writeResult")))}));function Xe(e,t){var r,o;return new Ve.jn({command:null!==(r=t.command)&&void 0!==r?r:"",workingDirectory:null!==(o=t.workingDirectory)&&void 0!==o?o:"",error:e,isReadonly:!0})}function Qe(e){return{execute:async(t,r)=>new Ve.W4({result:{case:"permissionDenied",value:Xe(e,r)}})}}function et(e){return{async*execute(t,r){yield new Ve.FI({event:{case:"permissionDenied",value:Xe(e,r)}})}}}function tt(e){return{execute:async(t,r)=>new We.Lt({result:{case:"permissionDenied",value:Xe(e,r)}})}}function rt(e){return{execute:async(t,r)=>new qe.Pi({result:{case:"permissionDenied",value:new qe.QG({path:r.path,clientVisibleError:e,isReadonly:!0})}})}}function ot(e){return{execute:async(t,r)=>new Ge.iz({result:{case:"permissionDenied",value:new Ge.HQ({error:`${e} Tool: ${r.name}`,isReadonly:!0})}})}}function nt(e){return{execute:async(t,r)=>new We.nt({result:{case:"error",value:new We.Gv({error:e})}})}}const st=R((e=>new C(e,O("recordScreenArgs"),D("recordScreenResult"))),((e,t)=>{t.register(new b(e,j("recordScreenArgs"),M("recordScreenResult")))})),it=R((e=>new C(e,O("requestContextArgs"),D("requestContextResult"))),((e,t)=>{t.register(new b(e,j("requestContextArgs"),M("requestContextResult")))}));var at=r("../proto/dist/generated/agent/v1/shell_allowlist_precheck_exec_pb.js");const lt=R((e=>new C(e,O("shellAllowlistPrecheckArgs"),D("shellAllowlistPrecheckResult"))),((e,t)=>{t.register(new b(e,j("shellAllowlistPrecheckArgs"),M("shellAllowlistPrecheckResult")))})),ct=R((e=>new C(e,O("forceBackgroundShellArgs"),D("forceBackgroundShellResult"))),((e,t)=>{t.register(new b(e,j("forceBackgroundShellArgs"),M("forceBackgroundShellResult")))}));function ut(e,t){e.hookApprovalRequirement=void 0!==t?new Ve.In(t):void 0}function dt(e){return e.hookApprovalRequirement}function pt(e){return(null==e?void 0:e.kind)===Ve.b.FORCE_PROMPT}r("../proto/dist/generated/agent/v1/smart_mode_classifier_exec_pb.js"),R((e=>new C(e,O("smartModeClassifierArgs"),D("smartModeClassifierResult"))),((e,t)=>{t.register(new b(e,j("smartModeClassifierArgs"),M("smartModeClassifierResult")))}));var ht=r("../proto/dist/generated/agent/v1/subagent_exec_pb.js");class mt extends Error{name="SubagentHostError";agentId;cause;constructor(e,t){super(e),this.agentId=null==t?void 0:t.agentId,this.cause=null==t?void 0:t.cause}}const ft=R((e=>new C(e,O("subagentArgs"),D("subagentResult"))),((e,t)=>{t.register(new b(e,j("subagentArgs"),M("subagentResult")))}));R((e=>new C(e,O("subagentAwaitArgs"),D("subagentAwaitResult"))),((e,t)=>{t.register(new b(e,j("subagentAwaitArgs"),M("subagentAwaitResult")))})),R((e=>new C(e,O("forceBackgroundSubagentArgs"),D("forceBackgroundSubagentResult"))),((e,t)=>{t.register(new b(e,j("forceBackgroundSubagentArgs"),M("forceBackgroundSubagentResult")))}));class gt{options;states=new Map;runCounterBySession=new Map;dispatchQueueBySession=new Map;dispatchInProgress=new Set;releaseRequestedBySession=new Set;constructor(e={}){this.options=e}getState(e){var t;return null!==(t=this.states.get(e))&&void 0!==t?t:{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:null==t?void 0: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){var t;const r=(null!==(t=this.runCounterBySession.get(e))&&void 0!==t?t:0)+1;return this.runCounterBySession.set(e,r),r}enqueueEvent(e,t){var r;const o=null!==(r=this.dispatchQueueBySession.get(e))&&void 0!==r?r:[];o.push(t),this.dispatchQueueBySession.set(e,o),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 o=r.shift();if(o)try{this.processEvent(e,o)}catch(e){null!=t||(t=e)}}}finally{this.dispatchQueueBySession.delete(e),this.dispatchInProgress.delete(e)}if(t)throw t}processEvent(e,t){var r,o,n,s,i;const a=this.getState(e),{nextState:l,effects:c}=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:Object.assign(Object.assign({},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:[]}}}(a,t);this.states.set(e,l),null===(o=(r=this.options).onStateChange)||void 0===o||o.call(r,{sessionId:e,previousState:a,nextState:l});for(const t of c)switch(t.type){case"abortActiveRun":null===(n=t.abort)||void 0===n||n.call(t);break;case"startQueuedRun":null===(i=(s=this.options).onQueuedRunReady)||void 0===i||i.call(s,{sessionId:e,sourceRunId:t.sourceRunId,queuedResume:t.queuedResume});break;default:throw new Error(`Unhandled lifecycle manager effect: ${String(t)}`)}const u=this.getState(e);"release"===t.type&&"idle"!==u.status&&this.releaseRequestedBySession.add(e),"idle"!==u.status||"release"!==t.type&&!this.releaseRequestedBySession.has(e)||(this.states.delete(e),this.runCounterBySession.delete(e),this.releaseRequestedBySession.delete(e))}}function vt(e){return"string"==typeof e&&e.trim().length>0}var yt=r("../proto/dist/generated/agent/v1/web_fetch_allowlist_precheck_exec_pb.js");const wt=R((e=>new C(e,O("webFetchAllowlistPrecheckArgs"),D("webFetchAllowlistPrecheckResult"))),((e,t)=>{t.register(new b(e,j("webFetchAllowlistPrecheckArgs"),M("webFetchAllowlistPrecheckResult")))}));var bt=r("../proto/dist/generated/agent/v1/request_context_exec_pb.js"),St=r("../proto/dist/generated/aiserver/v1/utils_pb.js");const kt=e=>String(e).replace(/[\r\n]/g,""),Et=(0,l.h)("ControlledConversationActionManager");class xt{abortCallbacks=[];abortController=new AbortController;clientStream;abortStarted=!1;runActive=!1;unprocessedUserMessages=[];get signal(){return this.abortController.signal}constructor(){this.clientStream=(0,h.Jt)()}addAbortCallback(e){this.abortCallbacks.push(e)}abort(e,t){if(this.abortController.signal.aborted||this.abortStarted)return;const r=null==t?void 0: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 o=this.abortController,n=[...this.abortCallbacks];this.abortCallbacks.length=0,this.submitConversationAction(new L.QF({action:{case:"cancelAction",value:new L.TT({reason:e,interruptedPendingToolCallResolutions:r})}})).catch((()=>{})).finally((()=>{o.abort(e);for(const e of n)e();if(this.abortController===o){const e=[...this.abortCallbacks];this.abortCallbacks.length=0;for(const t of e)t()}}))}async submitConversationAction(e){if("userMessageAction"===e.action.case){const t=e.action.value.userMessage;t&&this.unprocessedUserMessages.push(t)}await this.clientStream.write(e)}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(){var e;null===(e=this.clientStream)||void 0===e||e.close()}resetStream(){var e;null===(e=this.clientStream)||void 0===e||e.close(),this.clientStream=(0,h.Jt)(),this.abortController=new AbortController,this.abortStarted=!1;for(const e of this.unprocessedUserMessages)this.clientStream.write(new L.QF({action:{case:"userMessageAction",value:new L.Vt({userMessage:e})}}))}async run(e,t){this.runActive=!0;try{for await(const r of this.clientStream)try{await t.write(r)}catch(t){Et.error(e,"Error writing conversation action",t)}}finally{this.runActive=!1}}dispose(){}}(0,l.h)("RemoteConversationActionManager");const _t=BigInt(0),Ct=BigInt(8),Pt=BigInt(16),Rt=BigInt(65535);function Tt(e){const t=e.trim().toLowerCase();return t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t}function It(e){const t=e.split(".");if(4!==t.length)return;let r=_t;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<<Ct|BigInt(t)}return{version:4,value:r}}function At(e){if(0===e.length)return[];const t=[],r=e.split(":");for(let e=0;e<r.length;e++){const o=r[e];if(0===o.length)return;if(o.includes(".")){if(e!==r.length-1)return;const n=It(o);if(!n)return;t.push(Number(n.value>>Pt&Rt)),t.push(Number(n.value&Rt))}else{if(!/^[0-9a-f]{1,4}$/i.test(o))return;t.push(Number.parseInt(o,16))}}return t}function Ot(e){var t;return null!==(t=It(e))&&void 0!==t?t:function(e){const t=Tt(e);if(0===t.length||t.includes(":::"))return;const r=t.indexOf("::");if(-1===r){const e=At(t);if(!e||8!==e.length)return;return{version:6,value:e.reduce(((e,t)=>e<<Pt|BigInt(t)),_t)}}if(-1!==t.indexOf("::",r+1))return;const o=t.slice(0,r),n=t.slice(r+2),s=At(o),i=At(n);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<<Pt|BigInt(t)),_t)}}(e)}var Dt=r("../proto/dist/generated/agent/v1/ask_question_tool_pb.js"),Mt=r("../proto/dist/generated/agent/v1/create_plan_tool_pb.js"),jt=r("../proto/dist/generated/agent/v1/pr_management_tool_pb.js"),Nt=r("../proto/dist/generated/agent/v1/replace_env_tool_pb.js"),$t=r("../proto/dist/generated/agent/v1/setup_vm_environment_tool_pb.js"),Ft=r("../proto/dist/generated/agent/v1/generate_image_tool_pb.js"),Lt=r("../proto/dist/generated/agent/v1/mcp_auth_tool_pb.js"),Ut=r("../proto/dist/generated/agent/v1/switch_mode_tool_pb.js"),Bt=r("../proto/dist/generated/agent/v1/web_fetch_tool_pb.js"),Ht=r("../proto/dist/generated/agent/v1/web_search_tool_pb.js");Error;const zt=e=>new L.Y5({id:e,result:{case:"webSearchRequestResponse",value:new Ht.lI({result:{case:"approved",value:new Ht.XJ}})}}),Wt=(e,t)=>new L.Y5({id:e,result:{case:"webSearchRequestResponse",value:new Ht.lI({result:{case:"rejected",value:new Ht.yc({reason:null!=t?t:""})}})}}),qt=e=>new L.Y5({id:e,result:{case:"webFetchRequestResponse",value:new Bt.fS({result:{case:"approved",value:new Bt.Hs}})}}),Gt=(e,t)=>new L.Y5({id:e,result:{case:"webFetchRequestResponse",value:new Bt.fS({result:{case:"rejected",value:new Bt.m$({reason:null!=t?t:""})}})}}),Vt=(e,t)=>new L.Y5({id:e,result:{case:"askQuestionInteractionResponse",value:new L.zT({result:t})}}),Jt=e=>new L.Y5({id:e,result:{case:"switchModeRequestResponse",value:new Ut.w$({result:{case:"approved",value:new Ut.q5}})}}),Kt=(e,t)=>new L.Y5({id:e,result:{case:"switchModeRequestResponse",value:new Ut.w$({result:{case:"rejected",value:new Ut.rA({reason:null!=t?t:""})}})}}),Zt=(e,t)=>new L.Y5({id:e,result:{case:"createPlanRequestResponse",value:new Mt.gz({result:t})}}),Yt=(e,t)=>new L.Y5({id:e,result:{case:"setupVmEnvironmentResult",value:t}}),Xt=(e,t)=>new L.Y5({id:e,result:{case:"replaceEnvResult",value:t}}),Qt=(e,t)=>new L.Y5({id:e,result:{case:"prManagementResult",value:t}}),er=(e,t)=>new L.Y5({id:e,result:{case:"mcpAuthRequestResponse",value:new Lt.h({result:{case:"rejected",value:new Lt.OI({reason:null!=t?t:"Authentication was rejected"})}})}}),tr=(e,t)=>new L.Y5({id:e,result:{case:"generateImageRequestResponse",value:new Ft.vW({result:{case:"approved",value:new Ft.l3({description:null!=t?t:""})}})}});Error;const rr=e=>new L.Uq({message:{case:"shellOutputDelta",value:new L.Nn({event:e})}});var or=r("../agent-kv/dist/index.js"),nr=r("../proto/dist/generated/agent/v1/agent_service_pb.js"),sr=r("../proto/dist/generated/agent/v1/mcp_pb.js"),ir=r("@bufbuild/protobuf"),ar=r("@connectrpc/connect"),lr=r("../../node_modules/.pnpm/@connectrpc+connect@1.6.1_patch_hash=a4b9a5e69295313832387f25b708426bcf53041a2f50bc7b95_d0a2f6c9e28298af3d10922a7e4db69f/node_modules/@connectrpc/connect/dist/esm/protocol/async-iterable.js");class cr extends Error{cause;requestId;displayInfo;constructor(e,t={}){super(e),this.name=this.constructor.name,this.cause=t.cause,this.requestId=t.requestId,this.displayInfo=t.displayInfo,Object.setPrototypeOf(this,new.target.prototype)}}class ur extends cr{}class dr extends cr{action;constructor(e,t,r={}){super(e,r),this.action=t}}class pr extends cr{}class hr extends cr{}const mr=new Set([St.yM.NOT_LOGGED_IN,St.yM.AGENT_REQUIRES_LOGIN,St.yM.AUTH_TOKEN_NOT_FOUND,St.yM.AUTH_TOKEN_EXPIRED,St.yM.INVALID_AUTH_ID,St.yM.UNAUTHORIZED,St.yM.GITHUB_NO_USER_CREDENTIALS,St.yM.GITHUB_USER_NO_ACCESS]),fr=new Set([St.yM.FREE_USER_USAGE_LIMIT,St.yM.FREE_USER_RATE_LIMIT_EXCEEDED,St.yM.PRO_USER_ONLY,St.yM.PRO_USER_USAGE_LIMIT,St.yM.PRO_USER_RATE_LIMIT_EXCEEDED,St.yM.RATE_LIMITED,St.yM.RATE_LIMITED_CHANGEABLE,St.yM.GENERIC_RATE_LIMIT_EXCEEDED]),gr=new Set([St.yM.USAGE_PRICING_REQUIRED,St.yM.USAGE_PRICING_REQUIRED_CHANGEABLE]),vr=new Set([St.yM.BAD_API_KEY,St.yM.BAD_USER_API_KEY,St.yM.OUTDATED_CLIENT]),yr=new Set([St.yM.USER_ABORTED_REQUEST,St.yM.DEBOUNCED]),wr=new Set([St.yM.CUSTOM_MESSAGE]),br=["NGHTTP2","ECONNRESET","ECONNREFUSED","ETIMEDOUT","EPIPE","socket hang up","Premature close","ERR_STREAM","protocol error","http/2 stream","ERR_HTTP2_SESSION_ERROR","Session closed with error code","connection aborted"];function Sr(e,t={}){const{requestId:r}=t;if(e instanceof cr)return e;if(function(e){return null!==e&&"object"==typeof e&&"code"in e&&"name"in e&&"ConnectError"===e.name}(e))return function(e,t){var r,o,n,s,i,a,l;const c=function(e){var t,r;const o=e.findDetails(St.vj);if(o.length>0)return o[0];try{const o=null===(r=null===(t=e.cause)||void 0===t?void 0:t.findDetails)||void 0===r?void 0:r.call(t,St.vj);return null==o?void 0:o[0]}catch(e){return}}(e),u={cause:e,requestId:t,displayInfo:{title:null===(r=null==c?void 0:c.details)||void 0===r?void 0:r.title,detail:null===(o=null==c?void 0:c.details)||void 0===o?void 0:o.detail,isRetryable:null===(n=null==c?void 0:c.details)||void 0===n?void 0:n.isRetryable,connectCode:e.code,errorCode:null==c?void 0:c.error,errorDetails:c}};if(e.code===ar.Code.Canceled||e.code===ar.Code.Aborted)return Er(e)?new ur(e.message,u):new hr(e.message,u);if(void 0!==(null==c?void 0:c.error)){const t=c.error;if(yr.has(t))return new hr(kr(e,c),u);const r=null===(i=null===(s=c.details)||void 0===s?void 0:s.analyticsMetadata)||void 0===i?void 0:i.actionRequired;if(void 0!==r&&""!==r)return new dr(kr(e,c),r,u);if(mr.has(t))return new dr(kr(e,c),"login",u);if(fr.has(t))return new dr(kr(e,c),"upgrade",u);if(gr.has(t))return new dr(kr(e,c),"payment",u);if(vr.has(t))return new dr(kr(e,c),"config",u);if(wr.has(t)&&!0!==(null===(a=c.details)||void 0===a?void 0:a.isRetryable))return new pr(kr(e,c),u);if(!1===(null===(l=c.details)||void 0===l?void 0:l.isRetryable))return new pr(kr(e,c),u)}return e.code===ar.Code.Unauthenticated?new dr(e.message,"login",u):new ur(e.message,u)}(e,r);if(e instanceof Error){if("AbortError"===e.name)return new hr(e.message,{cause:e,requestId:r});if(Er(e))return new ur(e.message,{cause:e,requestId:r})}const o=e instanceof Error?e.message:String(e);return new ur(o,{cause:e instanceof Error?e:void 0,requestId:r})}function kr(e,t){if(null==t?void 0:t.details){const{title:r,detail:o}=t.details;return r&&o?`${r} ${o}`:r||o||e.message}return e.message}function Er(e){let t=e;for(;t instanceof Error;){const e=`${t.name}: ${t.message}`;if(br.some((t=>e.includes(t))))return!0;const r=t.code;if("string"==typeof r&&br.some((e=>r.includes(e))))return!0;t=t.cause}return!1}function xr(e){return e.cause instanceof Error?Er(e.cause):br.some((t=>e.message.includes(t)))}var _r=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var o,n;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");o=t[Symbol.asyncDispose]}if(void 0===o){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");o=t[Symbol.dispose],r&&(n=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");n&&(o=function(){try{n.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:o,async:r})}else r&&e.stack.push({async:!0});return t},Cr=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 o,n=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===n)return n=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var s=o.dispose.call(o.value);if(o.async)return n|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else n|=1}catch(e){r(e)}if(1===n)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var o=new Error(r);return o.name="SuppressedError",o.error=e,o.suppressed=t,o});class Pr extends Error{constructor(e){super(e),this.name="LostConnection"}}class Rr{serverStream;clientStream;controlledExecManager;constructor(e,t,r){this.serverStream=e,this.clientStream=t,this.controlledExecManager=r}async run(e){const t={stack:[],error:void 0,hasError:!1};try{_r(t,(0,l.VI)(e.withName("ClientExecController.run")),!1);const r=[];try{for await(const t of this.serverStream){if(t instanceof nr.Nv){this.controlledExecManager.handleControlMessage(t);continue}const o=(async()=>{var r;const o={stack:[],error:void 0,hasError:!1};try{let n,s;if(t.spanContext){const o=t.spanContext;n=(0,l.V5)({traceId:o.traceId,spanId:o.spanId,traceFlags:null!==(r=o.traceFlags)&&void 0!==r?r:1},"exec.handle",e),s=(0,l.fU)(n)}else n=e;_r(o,s?new l.r2(n,s):void 0,!1);const i=this.controlledExecManager.handle(n,t);for await(const e of i)await this.clientStream.write(e)}catch(e){o.error=e,o.hasError=!0}finally{Cr(o)}})();r.push(o)}await Promise.all(r)}catch(e){if(e instanceof ar.ConnectError&&"protocol error: missing EndStreamResponse"===e.rawMessage)throw new Pr(e.message);if(e instanceof ar.ConnectError&&e.code===ar.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 Pr(e.message)}else{if(e instanceof h.W2)throw new Pr(e.message);if(e instanceof ar.ConnectError&&e.code===ar.Code.Internal){const t=e.cause;if(t instanceof Error&&t.message.includes("NGHTTP2_PROTOCOL_ERROR"))throw new Pr(e.message)}}}}catch(e){t.error=e,t.hasError=!0}finally{Cr(t)}}}var Tr=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 o,n=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===n)return n=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var s=o.dispose.call(o.value);if(o.async)return n|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else n|=1}catch(e){r(e)}if(1===n)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var o=new Error(r);return o.name="SuppressedError",o.error=e,o.suppressed=t,o});const Ir=(0,l.h)("ClientInteractionController");class Ar{interactionStream;interactionListener;queryResponseStream;constructor(e,t,r){this.interactionStream=e,this.interactionListener=t,this.queryResponseStream=r}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 o,n;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");o=t[Symbol.asyncDispose]}if(void 0===o){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");o=t[Symbol.dispose],r&&(n=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");n&&(o=function(){try{n.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:o,async:r})}else r&&e.stack.push({async:!0});return t}(t,(0,l.VI)(e.withName("ClientInteractionController.run")),!1);e=r.ctx;let o,n=Promise.resolve();for await(const t of this.interactionStream)"interactionQuery"===t.case?this.handleInteractionQuery(e,t.value):"interactionUpdate"===t.case&&(n=n.then((()=>this.handleInteractionUpdate(e,t.value))).catch((t=>{Ir.error(e,"Error handling interaction update",t),null!=o||(o=t)})));if(await n,void 0!==o)throw o}catch(e){t.error=e,t.hasError=!0}finally{Tr(t)}}async handleInteractionUpdate(e,t){await this.interactionListener.sendUpdate(e,t)}handleInteractionQuery(e,t){this.interactionListener.query(e,t).then((e=>this.queryResponseStream.write(e))).catch((t=>{Ir.error(e,"Error handling interaction query",t)}))}}const Or=(0,l.h)("@anysphere/agent-client:stall-detector"),Dr=(0,d.Pu)("agent_client.stream.stall.count",{description:"Number of bidirectional stream stalls detected",labelNames:["activity_type","message_type"]}),Mr=(0,d.v5)("agent_client.stream.stall.duration_ms",{description:"Duration of stream stalls in milliseconds",labelNames:["activity_type"]}),jr=(0,d.Pu)("agent_client.stream.did_stall",{description:"Number of streams that experienced at least one stall"}),Nr=(0,d.Pu)("agent_client.stream.total",{description:"Total number of streams monitored"});class $r{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(){var e;const t=Date.now(),r={};for(const[o,n]of this.handlers)r[o]={state:n.state,durationMs:(null!==(e=n.endedAt)&&void 0!==e?e:t)-n.startedAt,error:n.error};return r}}class Fr{timer;advisoryTimer;heartbeatOnlyTimer;lastActivityTime=Date.now();lastMeaningfulActivityTime=Date.now();hasLogged=!1;hasLoggedAdvisory=!1;hasLoggedHeartbeatOnly=!1;hasEverStalled=!1;lastClientSentHeartbeatAt;lastServerSentHeartbeatAt;streamEndedAt;abortedAt;disposedAt;lastActivity;lastInboundMessage;lastOutboundMessage;activityHistory=[];thresholdMs;advisoryThresholdMs;heartbeatOnlyThresholdMs;onStall;onStallCallback;handlerTracker;constructor(e,t,r){var o;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.thresholdMs=t.thresholdMs,this.advisoryThresholdMs=t.advisoryThresholdMs,this.heartbeatOnlyThresholdMs=null!==(o=t.heartbeatOnlyThresholdMs)&&void 0!==o?o:3*t.thresholdMs,this.onStall=t.onStall,this.onStallCallback=t.onStallCallback,this.handlerTracker=t.handlerTracker),this.startTimer(),this.startAdvisoryTimer(),this.startHeartbeatOnlyTimer(),Nr.increment(this.ctx,1),e.signal.addEventListener("abort",(()=>{this.trackActivity("ctx.signal","abort"),this.abortedAt=Date.now(),this.emitLifecycleLog("[NAL client stall detector] Stream aborted while stall detector active","aborted")}))}ctx;trackActivity(e,t){var r;const o={type:e,messageType:t};this.lastActivity=o,"inbound_message"===e?this.lastInboundMessage=o:"outbound_write"===e&&(this.lastOutboundMessage=o);const n=this.activityHistory.at(-1);(null==n?void 0:n.type)===e&&n.messageType===t?n.repeat=(null!==(r=n.repeat)&&void 0!==r?r:1)+1:(this.activityHistory.push(o),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,o=this.hasLoggedHeartbeatOnly;e&&(this.hasLogged=!1,this.emitLogAndMetric()),o&&r&&(this.hasLoggedHeartbeatOnly=!1),t&&(this.hasLoggedAdvisory=!1),this.lastActivityTime=Date.now(),r&&(this.lastMeaningfulActivityTime=Date.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=Date.now()}onClientSentHeartbeat(){this.lastClientSentHeartbeatAt=Date.now()}onServerSentHeartbeat(){this.lastServerSentHeartbeatAt=Date.now()}startTimer(){if(this.thresholdMs<=0||void 0!==this.timer)return;const e=()=>{const t=this.thresholdMs-(Date.now()-this.lastActivityTime);if(t<=0)return this.timer=void 0,void this.onStallDetected("no_activity");this.timer=setTimeout(e,t)};this.timer=setTimeout(e,this.thresholdMs)}startAdvisoryTimer(){if(void 0===this.advisoryThresholdMs||this.advisoryThresholdMs<=0||void 0!==this.advisoryTimer)return;const e=this.advisoryThresholdMs,t=()=>{const r=e-(Date.now()-this.lastActivityTime);if(r<=0)return this.advisoryTimer=void 0,void this.onAdvisoryDetected();this.advisoryTimer=setTimeout(t,r)};this.advisoryTimer=setTimeout(t,e)}startHeartbeatOnlyTimer(){if(this.thresholdMs<=0||this.heartbeatOnlyThresholdMs<=0||void 0!==this.heartbeatOnlyTimer)return;const e=()=>{const t=this.heartbeatOnlyThresholdMs-(Date.now()-this.lastMeaningfulActivityTime);if(t<=0)return this.heartbeatOnlyTimer=void 0,void this.onStallDetected("heartbeat_only");this.heartbeatOnlyTimer=setTimeout(e,t)};this.heartbeatOnlyTimer=setTimeout(e,this.heartbeatOnlyThresholdMs)}buildLogMetadata(e){var t;const r=this.ctx.get(Br),o=Object.assign({},e);(null===(t=null==r?void 0:r.modelDetails)||void 0===t?void 0:t.displayName)&&(o.model_name=r.modelDetails.displayName),this.abortedAt&&(o.aborted_ago_ms=Date.now()-this.abortedAt),this.disposedAt&&(o.disposed_ago_ms=Date.now()-this.disposedAt),this.lastClientSentHeartbeatAt&&(o.last_client_sent_heartbeat_ago_ms=Date.now()-this.lastClientSentHeartbeatAt),this.lastServerSentHeartbeatAt&&(o.last_server_sent_heartbeat_ago_ms=Date.now()-this.lastServerSentHeartbeatAt),this.streamEndedAt&&(o.stream_ended_ago_ms=Date.now()-this.streamEndedAt),this.lastInboundMessage&&(o.last_inbound_message_type=this.lastInboundMessage.messageType),this.lastOutboundMessage&&(o.last_outbound_message_type=this.lastOutboundMessage.messageType);const n=[];let s;for(let e=this.activityHistory.length-1;e>=0;e--){const{type:t,messageType:r,repeat:o}=this.activityHistory[e];s!==t&&(s?n.push(`[${t}]`):n.push(`[${t}] (MOST RECENT)`),s=t),n.push(`${r}${o?` (x${o})`:""}`)}return o.activities=n.join("\n"),{reqId:null==r?void 0:r.requestId,stall:o}}onAdvisoryDetected(){if(this.hasLogged||this.hasLoggedAdvisory)return;if(void 0===this.advisoryThresholdMs||this.advisoryThresholdMs<=0)return;const e=Date.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"});Or.warn(this.ctx,"[NAL client stall detector] 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=Date.now(),r=t-this.lastActivityTime,o=t-this.lastMeaningfulActivityTime;if(r<this.thresholdMs&&o>=this.heartbeatOnlyThresholdMs){if(this.hasLoggedHeartbeatOnly)return;this.hasLoggedHeartbeatOnly=!0,this.reportStall(e,o)}return}if(this.hasLogged)return;this.hasLogged=!0,this.hasLoggedAdvisory=!0;const t=Date.now()-this.lastActivityTime;this.reportStall(e,t)}reportStall(e,t){var r,o,n,s,i;const a=this.lastActivity,l=this.lastInboundMessage,c=this.lastOutboundMessage,u=this.ctx.get(Br);try{const n=this.buildLogMetadata({duration_ms:t,threshold_ms:"heartbeat_only"===e?this.heartbeatOnlyThresholdMs:this.thresholdMs,stall_type:e}),d="heartbeat_only"===e?"[NAL client stall detector] Stream receiving heartbeats only - no meaningful data for threshold period":"[NAL client stall detector] Bidirectional stream stall detected - no activity for threshold period";if(Or.warn(this.ctx,d,n),Dr.increment(this.ctx,1,{activity_type:null!==(s=null==a?void 0:a.type)&&void 0!==s?s:"unknown",message_type:null!==(i=null==a?void 0:a.messageType)&&void 0!==i?i:"unknown"}),this.hasEverStalled||(this.hasEverStalled=!0,jr.increment(this.ctx,1)),this.onStallCallback){const t=Date.now(),n={type:e,lastActivityAgoMs:t-this.lastActivityTime,lastMeaningfulActivityAgoMs:t-this.lastMeaningfulActivityTime,lastActivityType:null==a?void 0:a.messageType,lastInboundMessageType:null==l?void 0:l.messageType,lastOutboundMessageType:null==c?void 0:c.messageType,requestId:null==u?void 0:u.requestId,modelName:null===(r=null==u?void 0:u.modelDetails)||void 0===r?void 0:r.displayName,streamEnded:void 0!==this.streamEndedAt,aborted:void 0!==this.abortedAt,lastServerHeartbeatAgoMs:this.lastServerSentHeartbeatAt?t-this.lastServerSentHeartbeatAt:void 0,lastClientHeartbeatAgoMs:this.lastClientSentHeartbeatAt?t-this.lastClientSentHeartbeatAt:void 0,thresholdMs:"heartbeat_only"===e?this.heartbeatOnlyThresholdMs:this.thresholdMs,handlers:null===(o=this.handlerTracker)||void 0===o?void 0:o.getHandlerStates()};try{this.onStallCallback(n)}catch(e){console.error("Error in stall callback:",e)}}}catch(e){console.error("Error in stall detection:",e)}try{null===(n=this.onStall)||void 0===n||n.call(this)}catch(e){console.error("Error in onStall callback:",e)}}emitLifecycleLog(e,t){const r=Date.now()-this.lastActivityTime;try{const o=this.buildLogMetadata({duration_ms:r,event_type:t});Or.info(this.ctx,e,o)}catch(e){console.error("Error logging stream lifecycle:",e)}}emitLogAndMetric(){var e,t;const r=Date.now()-this.lastActivityTime;this.emitLifecycleLog("[NAL client stall detector] Stream activity resumed after stall","recovered"),Mr.histogram(this.ctx,r,{activity_type:null!==(t=null===(e=this.lastActivity)||void 0===e?void 0:e.type)&&void 0!==t?t:"unknown"})}[Symbol.dispose](){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.trackActivity("disposed","disposed"),this.disposedAt=Date.now(),this.emitLifecycleLog("[NAL client stall detector] Stream stall detector disposed","disposed")}}var Lr=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var o,n;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");o=t[Symbol.asyncDispose]}if(void 0===o){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");o=t[Symbol.dispose],r&&(n=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");n&&(o=function(){try{n.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:o,async:r})}else r&&e.stack.push({async:!0});return t},Ur=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 o,n=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===n)return n=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var s=o.dispose.call(o.value);if(o.async)return n|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else n|=1}catch(e){r(e)}if(1===n)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var o=new Error(r);return o.name="SuppressedError",o.error=e,o.suppressed=t,o});const Br=(0,l.cF)(Symbol("agentStreamMetadata"),void 0),Hr=(0,l.h)("@anysphere/agent-client:abort"),zr=(0,l.h)("@anysphere/agent-client:retry"),Wr=e=>{var t,r;const o=[];switch(o.push(e.message.case),e.message.case){case"conversationAction":o.push(e.message.value.action.case);break;case"execClientMessage":case"execClientControlMessage":case"kvClientMessage":case"execServerMessage":case"execServerControlMessage":o.push(e.message.value.message.case);break;case"interactionResponse":o.push(e.message.value.result.case);break;case"interactionUpdate":switch(o.push(e.message.value.message.case),e.message.value.message.case){case"partialToolCall":case"toolCallCompleted":case"toolCallStarted":o.push(null===(t=e.message.value.message.value.toolCall)||void 0===t?void 0:t.tool.case);break;case"toolCallDelta":o.push(null===(r=e.message.value.message.value.toolCallDelta)||void 0===r?void 0:r.delta.case)}break;case"interactionQuery":o.push(e.message.value.query.case)}return o.filter((e=>void 0!==e)).join(":")};async function qr(e,t,r){for await(const o of t)switch(o.event.case){case"stdout":await r.sendUpdate(e,rr({case:"stdout",value:new Ve.o0({data:o.event.value.data})}));break;case"stderr":await r.sendUpdate(e,rr({case:"stderr",value:new Ve.Db({data:o.event.value.data})}));break;case"exit":await r.sendUpdate(e,rr({case:"exit",value:new Ve.vb({code:o.event.value.code,aborted:o.event.value.aborted})}))}}function Gr(e,t,r){return{sendUpdate:async(o,n)=>{var s;if(t===r())return e.sendUpdate(o,n);"toolCallCompleted"===(null===(s=n.message)||void 0===s?void 0:s.case)&&zr.warn(o,"nal.await_stall.stale_completion_dropped",{attemptGen:t,currentGen:r()})},query:async(o,n)=>{if(t!==r())throw new hr("Stale query from previous attempt");return e.query(o,n)},enqueuePostTurnEndedWork:e.enqueuePostTurnEndedWork?t=>e.enqueuePostTurnEndedWork(t):void 0,flushPostTurnEndedWork:e.flushPostTurnEndedWork?t=>e.flushPostTurnEndedWork(t):void 0}}const Vr=e=>"number"==typeof e&&Number.isFinite(e)?e:void 0;async function Jr(e,t,r,o){const n=r?100:1e3,s=null!=o?o:Math.min(n*Math.pow(2,e),6e4),i=void 0!==o?0:.2*s*Math.random();await new Promise(((e,r)=>{if(null==t?void 0:t.aborted)return void r(new hr("Cancelled during backoff"));const o=setTimeout(e,s+i);null==t||t.addEventListener("abort",(()=>{clearTimeout(o),r(new hr("Cancelled during backoff"))}),{once:!0})}))}function Kr(e){return null!==e&&"object"==typeof e&&"code"in e&&"name"in e&&"ConnectError"===e.name}function Zr(e){if(null!==e&&"object"==typeof e&&"cause"in e)return e.cause}function Yr(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}function Xr(e){return e instanceof Error?e.name:void 0}function Qr(e){let t=e;for(let e=0;e<10&&void 0!==t;e++){if(Kr(t)){const e=Zr(t),r=Yr(e),o=Xr(e);return{underlyingConnectError:{code:t.code,codeName:ar.Code[t.code],cause:void 0!==r||void 0!==o?{code:r,name:o}:void 0}}}t=Zr(t)}return{}}function eo(e,t,r,o,n,s,i,a){const l=s||i,c=a?2:10,u=e instanceof cr?e:Sr(e,{requestId:n});return t?l?!i&&o>=c?{action:"throw",error:new ur("Connection stalled repeatedly",{cause:u.cause,requestId:n,displayInfo:{title:"Connection stalled",detail:`The connection stalled ${o} times. Please check your network connection and try again.`,isRetryable:!0}})}:{action:"retry",countAsServerError:!1,countAsTransportError:!0}:{action:"throw",error:new ur("Connection stalled",{cause:u.cause,requestId:n,displayInfo:{title:"Connection stalled",detail:"The connection stalled. Please try again.",isRetryable:!0}})}:u instanceof hr||u instanceof dr||u instanceof pr?{action:"throw",error:u}:u instanceof ur&&xr(u)?l?!i&&o>=c?{action:"throw",error:new ur("Connection failed repeatedly",{cause:u.cause,requestId:n,displayInfo:{title:"Connection failed",detail:`The connection failed ${o} times. Please check your network connection and try again.`,isRetryable:!0}})}:{action:"retry",countAsServerError:!1,countAsTransportError:!0}:{action:"throw",error:u}:l?!i&&r>=3?{action:"throw",error:u}:{action:"retry",countAsServerError:!0,countAsTransportError:!1}:{action:"throw",error:u}}class to{client;constructor(e){this.client=e}async run(e,t,r,o,n,s,i,a,c,u,d){var p,h,m,f,g,v,y,w,b,S,k,E,x;const _={stack:[],error:void 0,hasError:!1};try{const C=null!==(w=d.generationUUID)&&void 0!==w?w:crypto.randomUUID();let P=C;const{onConnectionStateChange:R}=d;let T=t,I=r,A=0,O=0,D=0;const M={value:!1},j={value:!1},N={value:!1},$={sources:[],abortReasonName:void 0,abortReasonMessage:void 0},F=(e,t)=>{null==R||R({state:"reconnecting",attempt:e,trigger:t}),M.value=!0},U=()=>{M.value&&(null==R||R({state:"connected"}),M.value=!1)},B=()=>{if(!N.value)return;const e=c.getLatestCheckpoint();e&&(T=e,I=new L.QF({action:{case:"resumeAction",value:new L.qK}}),a.resetStream())},H={handleCheckpoint:async(e,t)=>(N.value=!0,c.handleCheckpoint(e,t)),getLatestCheckpoint:()=>c.getLatestCheckpoint()};let z=0;try{null===(p=d.onNetworkPhaseStart)||void 0===p||p.call(d)}catch(t){zr.warn(e,"onNetworkPhaseStart callback failed",{error:String(t)})}for(Lr(_,(0,l.VI)(e.withName("networkPhase")),!1);!e.canceled;){j.value=!1,N.value=!1,$.sources=[],$.abortReasonName=void 0,$.abortReasonMessage=void 0;const t=++z;A>0?(P=crypto.randomUUID(),await(null===(h=d.onRetryStarting)||void 0===h?void 0:h.call(d,A,{actionCase:I.action.case,conversationState:T,isResume:"resumeAction"===I.action.case,attemptRequestId:P})),zr.info(e,`[nal_agent_retries] Retrying attempt ${A}`,{attempt:A,actionCase:I.action.case,requestId:P,originalRequestId:C})):zr.info(e,"[nal_agent_retries] Initial request",{attempt:A,actionCase:I.action.case,requestId:P}),"resumeAction"===I.action.case&&d.onRetryResuming&&(await d.onRetryResuming({checkpointState:T,nextAttempt:A,reason:"resume_action"}),zr.info(e,"[nal_agent_retries] Resuming from checkpoint",{nextAttempt:A,reason:"resume_action"}));const r=Gr(n,t,(()=>z));try{return await this.runInternal(e,T,I,o,r,s,i,a,H,u,d,P,C,F,j,$,U,A),void zr.info(e,"[nal_agent_retries] Request successful",{attempt:A,actionCase:I.action.case,requestId:P,originalRequestId:C})}catch(t){const r=null!==(b=null===(m=d.endlessRetries)||void 0===m?void 0:m.call(d))&&void 0!==b&&b,o=Qr(t),n=eo(t,j.value,O,D,P,null!==(S=d.enableAgentRetries)&&void 0!==S&&S,r,d.isRunningInTest),s="retry"===n.action?`RETRY (countAsServerError=${n.countAsServerError}, countAsTransportError=${n.countAsTransportError})`:`THROW ${n.error.constructor.name}`;if(zr.warn(e,`[AGENT_ERROR_DIAGNOSTICS] requestId=${P} originalRequestId=${C} decision=${s}`,Object.assign({decision:s,willRetry:"retry"===n.action,enableAgentRetries:null!==(k=d.enableAgentRetries)&&void 0!==k&&k,endlessRetries:r,isRunningInTest:null!==(E=d.isRunningInTest)&&void 0!==E&&E,stallAborted:j.value,serverErrorRetries:O,transportErrorRetries:D,attempt:A,requestId:P,originalRequestId:C},o)),"throw"===n.action){if(0===A){const t={attempt:A,actionCase:I.action.case,error:n.error,requestId:P,originalRequestId:C,enableAgentRetries:null!==(x=d.enableAgentRetries)&&void 0!==x&&x,endlessRetries:r,stallAborted:j.value,abortSources:[...$.sources],abortReasonName:$.abortReasonName,abortReasonMessage:$.abortReasonMessage};try{await(null===(f=d.onErrorNotRetried)||void 0===f?void 0:f.call(d,t))}catch(t){zr.warn(e,"[nal_agent_retries] onErrorNotRetried callback failed",{error:String(t),requestId:P,originalRequestId:C})}}throw zr.warn(e,"[nal_agent_retries] Error not retryable",{attempt:A,actionCase:I.action.case,error:n.error,serverErrorRetries:O,transportErrorRetries:D}),n.error}const i=A+1,a=t instanceof cr?t:Sr(t,{requestId:P});F(i,{errorClass:a.name,connectCode:null===(g=o.underlyingConnectError)||void 0===g?void 0:g.code,connectCodeName:null===(v=o.underlyingConnectError)||void 0===v?void 0:v.codeName,errorCode:null===(y=a.displayInfo)||void 0===y?void 0:y.errorCode,countAsServerError:n.countAsServerError,countAsTransportError:n.countAsTransportError,stallAborted:j.value,originatingRequestId:C,attemptRequestId:P}),B(),n.countAsServerError&&O++,n.countAsTransportError&&D++,A=i,await Jr(A,e.signal,d.isRunningInTest,d.fixedRetryDelayMs)}}throw new hr("Request cancelled")}catch(e){_.error=e,_.hasError=!0}finally{Ur(_)}}async runInternal(e,t,r,o,n,s,i,a,c,d,m,f,g,v,y,w,b,S){var E,x,_,C,P,R,T,I,A;const O={stack:[],error:void 0,hasError:!1};try{const D=Lr(O,(0,l.VI)(e.withName("agent.request.attempt")),!1);D.span.setAttribute("agent.attempt",S),D.span.setAttribute("agent.request_id",f),D.span.setAttribute("agent.original_request_id",g),e=D.ctx,e=(0,l.Mf)(e,"agent.request_id",f),e=(e=(0,l.Mf)(e,"agent.original_request_id",g)).with(Br,{requestId:f,rootParentRequestId:m.rootParentRequestId,modelDetails:o});const M=new Set(w.sources);let j=void 0!==w.abortReasonName||void 0!==w.abortReasonMessage;const N=(t,r)=>{if(M.has(t))return;M.add(t),w.sources=[...M];const o=(e=>{const t="string"==typeof(null==e?void 0:e.abortReasonName)?e.abortReasonName:void 0,r="string"==typeof(null==e?void 0:e.abortReasonMessage)?e.abortReasonMessage:void 0;if(void 0!==t||void 0!==r)return{abortReasonName:t,abortReasonMessage:r}})(r);j||void 0===o||(j=!0,w.abortReasonName=o.abortReasonName,w.abortReasonMessage=o.abortReasonMessage),Hr.error(e,"Agent client stream abort",new Error(t),Object.assign({abortSource:t,requestId:f,conversationId:m.conversationId},null!=r?r:{}))};if(e.signal.aborted){const t=e.signal.reason;N("ctx_signal_abort",(0,l.R5)(t))}else e.signal.addEventListener("abort",(()=>{const t=e.signal.reason;N("ctx_signal_abort",(0,l.R5)(t))}),{once:!0});const[$,F]=e.withCancel();if(null===(E=a.signal)||void 0===E?void 0:E.aborted){const e=null===(_=a.signal)||void 0===_?void 0:_.reason;N("conversation_action_abort",(0,l.R5)(e)),F()}else null===(x=a.signal)||void 0===x||x.addEventListener("abort",(()=>{var e;const t=null===(e=a.signal)||void 0===e?void 0:e.reason;N("conversation_action_abort",(0,l.R5)(t)),F()}),{once:!0});if(e.canceled||$.canceled){const t={ctxCanceled:e.canceled,softCancel:$.canceled};throw N("pre_run_cancel",t),new hr("User aborted request")}const U=(0,l.VI)(e.withName("createControlledExecManager")),B=k.fromResources(s);U[Symbol.dispose]();const[H,z]=e.withCancel(),W=new $r,{failThresholdMs:q,advisoryThresholdMs:G}=(e=>{var t;const r=null!==(t=Vr(null==e?void 0:e.failTimeoutMs))&&void 0!==t?t:3e4,o=Vr(null==e?void 0:e.advisoryTimeoutMs);return{failThresholdMs:r,advisoryThresholdMs:void 0!==o&&o>0&&(r<=0||o<r)?o:void 0}})(m.stallDetectorConfig),V=Lr(O,new Fr(H,{thresholdMs:q,advisoryThresholdMs:G,onStall:()=>{y.value=!0,N("stall_detector",{thresholdMs:q,advisoryThresholdMs:G}),z()},onStallCallback:m.onStall,handlerTracker:W}),!1),J=void 0!==m.prewarmedStream;let K,Z,Y,X;if(J){K=m.prewarmedStream.requestStream,Z=m.prewarmedStream.responseIterator;const e=m.prewarmedStream.abortController;if(H.signal.aborted){const t=null!==(R=H.signal.reason)&&void 0!==R?R:"stall_cancel_already_aborted";e.abort(t)}else H.signal.addEventListener("abort",(()=>{var t;const r=null!==(t=H.signal.reason)&&void 0!==t?t:"stall_cancel_aborted";e.abort(r)}),{once:!0});m.prewarmedStream=void 0}else K=(0,lr.Jt)();const Q=new h.F8(K,(e=>(V.reset("outbound_write",Wr(e)),e))),ee=(0,l.VI)(e.withName("writeInitialRequest"));let te;if(J)te=Q.write(new nr.KS({message:{case:"conversationAction",value:r}}));else{const n=d.map((e=>({name:e.name,providerIdentifier:e.providerIdentifier,toolName:e.toolName,description:e.description,inputSchema:e.inputSchema?ir.Value.fromJson(e.inputSchema):void 0}))),s=new L.Mp({conversationState:t,action:r,modelDetails:o,requestedModel:m.requestedModel,mcpTools:new sr.Or({mcpTools:n}),conversationGroupId:m.conversationGroupId,conversationId:m.conversationId,mcpFileSystemOptions:m.mcpFileSystemOptions,customSystemPrompt:m.customSystemPrompt,harness:m.harness,suggestNextPrompt:m.suggestNextPrompt,subagentTypeName:m.subagentTypeName,excludeWorkspaceContext:m.excludeWorkspaceContext,devRawModelSlug:m.devRawModelSlug,selectedSubagentModels:m.selectedSubagentModels,subagentModelOverrides:null!==(T=m.subagentModelOverrides)&&void 0!==T?T:[],selectedSubagentModelDetails:m.selectedSubagentModelsLegacy,preFetchedBlobs:null!==(I=m.preFetchedBlobs)&&void 0!==I?I:[],clientSupportsInlineImages:m.clientSupportsInlineImages,canCreateCloudSubagents:m.canCreateCloudSubagents,suppressSubagentProgressUpdateTool:m.suppressSubagentProgressUpdateTool});if(te=Q.write(new nr.KS({message:{case:"runRequest",value:s}})),$.canceled){const t={ctxCanceled:e.canceled,softCancel:$.canceled};throw N("post_write_cancel",t),ee[Symbol.dispose](),new hr("User aborted request")}const i=Object.assign(Object.assign({"x-request-id":f,"x-original-request-id":g},function(e){return Object.assign(Object.assign(Object.assign(Object.assign({},void 0!==e.parentRequestId?{"x-parent-request-id":kt(e.parentRequestId)}:{}),void 0!==e.rootParentRequestId?{"x-root-parent-request-id":kt(e.rootParentRequestId)}:{}),void 0!==e.parentAgentToolCallId?{"x-parent-agent-tool-call-id":kt(e.parentAgentToolCallId)}:{}),!0===e.directMetaParentChildSubagent?{"x-direct-meta-parent-child-subagent":"true"}:{})}(m)),null!==(A=m.headers)&&void 0!==A?A:{});Y=(0,l.VI)(e.withName("handshakeEstablishment")),Z=this.client.run(e,K,{signal:H.signal,headers:i,onHeader:m.onHeader,onNetworkStarted:()=>{void 0===X&&(X=performance.now())}})}const re=performance.now(),oe=()=>{var e,t;Y&&(Y[Symbol.dispose](),Y=void 0),b();const r=performance.now();null===(e=m.onFirstMessage)||void 0===e||e.call(m,r-re),void 0!==X&&(null===(t=m.onFirstMessageNetwork)||void 0===t||t.call(m,r-X))},ne=m.onFirstNonHeartbeatResponse?()=>{m.onFirstNonHeartbeatResponse(performance.now()-re,S)}:void 0,{interactionStream:se,execStream:ie,checkpointStream:ae,kvStream:le,done:ce}=function(e,t,r,o,n,s,i){const a=(0,lr.Jt)(),l=(0,lr.Jt)(),c=(0,lr.Jt)(),u=(0,lr.Jt)();let d=!1,p=!1;return{interactionStream:a,execStream:l,checkpointStream:c,kvStream:u,done:async function(){let h,m,f=!1,g=!1;try{for await(const n of t){if(d||(d=!0,o()),"interactionUpdate"===n.message.case&&"heartbeat"===n.message.value.message.case)r.onServerSentHeartbeat(),r.reset("inbound_message","heartbeat");else{if(!p){p=!0;try{null==i||i()}catch(t){zr.warn(e,"onFirstNonHeartbeatMessage callback failed",{error:String(t)})}}r.reset("inbound_message",Wr(n))}"interactionUpdate"===n.message.case&&"turnEnded"===n.message.value.message.case&&(f=!0),"interactionUpdate"!==n.message.case&&"interactionQuery"!==n.message.case||await a.write(n.message).catch((()=>{})),"execServerMessage"!==n.message.case&&"execServerControlMessage"!==n.message.case||await l.write(n.message.value),"conversationCheckpointUpdate"===n.message.case&&(f&&(g=!0),await c.write(n.message.value)),"kvServerMessage"===n.message.case&&await u.write(n.message.value)}r.onStreamEnded()}catch(e){h=e}finally{if(m=h,f&&g&&void 0!==h&&!(null==n?void 0:n.aborted)&&!(null==s?void 0:s.aborted)&&(e=>{const t=e instanceof cr?e:Sr(e);return t instanceof ur&&xr(t)})(h)&&(zr.warn(e,"Ignoring transport close after terminal agent stream",{caughtError:h instanceof Error?`${h.name}: ${h.message}`:String(h)}),r.onStreamEnded(),m=void 0),f||(null==n?void 0:n.aborted)||(null==s?void 0:s.aborted)){if(!f&&!(null==n?void 0:n.aborted)){const t=`Stream ended without turnEnded, abort signals: signal.aborted=${null==n?void 0:n.aborted}, parentSignal.aborted=${null==s?void 0:s.aborted}; firstMessageFired=${d}`;zr.warn(e,t)}}else{const t="Stream ended without turnEnded — connection likely dropped mid-stream";void 0===h?(zr.warn(e,t),m=new ur(t)):h instanceof Error&&"[aborted] aborted"===h.message?(zr.warn(e,`${t}; retrying caught [aborted] aborted error`),m=new ur(t,{cause:h})):zr.warn(e,`${t}; caught non-retriable stream error, rethrowing as-is`,{caughtError:h instanceof Error?`${h.name}: ${h.message}`:String(h)})}a.close(),l.close(),c.close(),u.close()}if(void 0!==m)throw m}()}}(e,Z,V,oe,$.signal,e.signal,ne);ee[Symbol.dispose]();const ue=5e3;let de;const pe=()=>{de=setTimeout((()=>{Q.write(new nr.KS({message:{case:"clientHeartbeat",value:new nr.kA}})).then((()=>V.onClientSentHeartbeat()),(()=>{})),pe()}),ue)},he=()=>{void 0!==de&&(clearTimeout(de),de=void 0)};pe();try{let t;if("shellCommandAction"===r.action.case&&r.action.value.execId){const o=r.action.value,i=new Ve.a({command:(null===(C=o.shellCommand)||void 0===C?void 0:C.command)||"",parsingResult:new Ve.HO,skipApproval:!0}),a=s.get(Ze).execute(e,i,{execId:o.execId}),l=new Ar(se,n,new h.F8(Q,(e=>new nr.KS({message:{case:"interactionResponse",value:e}}))));t={run:async e=>{await Promise.all([W.track("handleShellStream",qr(e,a,n)),W.track("interactionController",l.run(e))])}}}else{const e=new Ar(se,n,new h.F8(Q,(e=>new nr.KS({message:{case:"interactionResponse",value:e}}))));t={run:async t=>{await W.track("interactionController",e.run(t))}}}void 0!==te&&await te;const l=new h.F8(Q,(e=>{if(e instanceof p.yT)return new nr.KS({message:{case:"execClientMessage",value:e}});if(e instanceof p.$Y)return new nr.KS({message:{case:"execClientControlMessage",value:e}});throw new Error("Unknown exec message")})),S=new Rr(ie,l,B),k=new or.hC(le,new h.F8(Q,(e=>new nr.KS({message:{case:"kvClientMessage",value:e}}))),i),E=new u(ae,c,e);let x,_;const R={promise:new Promise(((e,t)=>{x=e,_=t})),resolve:x,reject:_};$.canceled?(R.resolve(),se.close()):$.signal.addEventListener("abort",(()=>{R.resolve(),se.close()}),{once:!0}),S.run($).then(R.resolve).catch(R.reject);const T=Promise.allSettled([W.track("streamSplitter",ce.finally((()=>{he(),a.close(),l.close()}))),W.track("execHandler",R.promise),t.run(e),W.track("checkpointController",E.run()),W.track("kvHandler",k.run(e)),W.track("conversationActionManager",a.run(e,new h.F8(Q,(e=>new nr.KS({message:{case:"conversationAction",value:e}})))))]);let I,A;const O={promise:new Promise(((e,t)=>{I=e,A=t})),resolve:I,reject:A};T.then(O.resolve).catch(O.reject),e.canceled?O.reject(new hr("User aborted request")):e.signal.addEventListener("abort",(()=>O.reject(new hr("User aborted request"))),{once:!0}),$.canceled?(z(),O.reject(new hr("User aborted request"))):$.signal.addEventListener("abort",(()=>{z(),O.reject(new hr("User aborted request"))}),{once:!0});const D=await O.promise,M=D[0],j=D[1];if(!0===(null===(P=m.shouldUseAgentExecStreamStartTimeoutRecovery)||void 0===P?void 0:P.call(m))){if("rejected"===M.status)throw M.reason;if("rejected"===j.status)throw j.reason}if("rejected"===j.status)throw j.reason;if("rejected"===M.status)throw M.reason;$.canceled||await this.processUnprocessedMessages(e,a,c,o,n,s,i,d,m,f,g,v,y,w,V,b)}finally{he(),Y&&(Y[Symbol.dispose](),Y=void 0)}}catch(e){O.error=e,O.hasError=!0}finally{Ur(O)}}async processUnprocessedMessages(e,t,r,o,n,s,i,a,l,c,u,d,p,h,m,f){if(!t.hasUnprocessedMessages())return;const g=t.getUnprocessedUserMessages(),v=r.getLatestCheckpoint();if(!v||0===g.length)return;const y=g[0];t.markMessageAsProcessed(y),t.resetStream(),m[Symbol.dispose]();const w=r.getLatestCheckpoint();try{await this.runInternal(e,v,new L.QF({action:{case:"userMessageAction",value:new L.Vt({userMessage:y})}}),o,n,s,i,t,r,a,l,c,u,d,p,h,f,0)}catch(e){throw w===r.getLatestCheckpoint()&&t.requeueMessage(y),e}}}r("../proto/dist/generated/agent/v1/delete_tool_pb.js");var ro=r("../proto/dist/generated/agent/v1/grep_exec_pb.js"),oo=(r("../proto/dist/generated/agent/v1/grep_tool_pb.js"),r("../proto/dist/generated/agent/v1/ls_exec_pb.js"));r("../proto/dist/generated/agent/v1/ls_tool_pb.js"),r("../proto/dist/generated/agent/v1/read_tool_pb.js"),r("../proto/dist/generated/agent/v1/shell_tool_pb.js");var no=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/status.js"),so=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/span_kind.js");function io(e){return null!==e&&"object"==typeof e&&Symbol.asyncIterator in e}function ao(e,t,r){return{[Symbol.asyncIterator](){const o=e[Symbol.asyncIterator]();let n=!1;const s=e=>{n||(n=!0,e?(null==t||t.recordException(e instanceof Error?e:new Error(String(e))),null==t||t.setStatus({code:no.s.ERROR,message:e instanceof Error?e.message:"Stream failed"})):null==t||t.setStatus({code:no.s.OK}),null==t||t.end(),null==r||r())};return{async next(){try{const e=await o.next();return e.done&&s(),e}catch(e){throw s(e),e}},return:async e=>(s(),o.return?o.return(e):{done:!0,value:void 0}),async throw(e){if(s(e),o.throw)return o.throw(e);throw e}}}}}function lo(...e){const t=new Headers;for(const r of e)r&&(r instanceof Headers?r.forEach(((e,r)=>{t.set(r,e)})):Object.entries(r).forEach((([e,r])=>{t.set(e,r)})));return t}function co(e,t){const{injectTraceHeaders:r=!0,extractHeaders:o}=t;return new Proxy(e,{get(e,n){const s=e[n];return"function"!=typeof s?s:(i,a,c={})=>{const u=(0,l.fR)(i.withName(`rpc.${String(n)}`),{kind:so.v.CLIENT,attributes:{"rpc.method":String(n),"rpc.system":"connect"}}),d=(0,l.fU)(u);let p;try{let n;if(r&&(n=function(e){var t,r;const o=new Headers;try{const n=(0,l.fU)(e),s=null===(t=null==n?void 0:n.spanContext)||void 0===t?void 0:t.call(n);if((null==s?void 0:s.traceId)&&s.spanId){const e=null!==(r=s.traceFlags)&&void 0!==r?r:0,t=`00-${s.traceId}-${s.spanId}-${e.toString(16).padStart(2,"0")}`;if(o.set("traceparent",t),o.set("backend-traceparent",t),s.traceState){const e="function"==typeof s.traceState.serialize?s.traceState.serialize():String(s.traceState);o.set("tracestate",e)}}}catch(e){}return o}(u)),o){const e=o(u);e&&(n=lo(n,e))}const i=lo(c.headers,n),{signal:m,cleanup:f}=!0===t.enableAbortSignal?function(e,t){if(void 0===t||t===e)return{signal:e};const r=new AbortController,o=()=>{r.abort(e.reason)},n=()=>{r.abort(t.reason)};e.addEventListener("abort",o,{once:!0}),t.addEventListener("abort",n,{once:!0}),e.aborted?o():t.aborted&&n();return{signal:r.signal,cleanup:()=>{e.removeEventListener("abort",o),t.removeEventListener("abort",n)}}}(u.signal,c.signal):{signal:c.signal,cleanup:void 0};p=f;const g=Object.assign(Object.assign({},c),{headers:i,signal:m}),v=s.call(e,a,g);return io(v)?ao(v,d,p):null!==(h=v)&&"object"==typeof h&&"then"in h&&"function"==typeof h.then?v.then((e=>io(e)?ao(e,d,p):(null==d||d.setStatus({code:no.s.OK}),null==d||d.end(),null==p||p(),e))).catch((e=>{throw null==d||d.recordException(e instanceof Error?e:new Error(String(e))),null==d||d.setStatus({code:no.s.ERROR,message:e instanceof Error?e.message:"RPC call failed"}),null==d||d.end(),null==p||p(),e})):(null==d||d.setStatus({code:no.s.OK}),null==d||d.end(),null==p||p(),v)}catch(e){throw null==d||d.recordException(e instanceof Error?e:new Error(String(e))),null==d||d.setStatus({code:no.s.ERROR,message:e instanceof Error?e.message:"RPC call failed"}),null==d||d.end(),null==p||p(),e}var h}}})}var uo=r("../../node_modules/.pnpm/undici@6.23.0/node_modules/undici/index.js");const po=process.env.HTTPS_PROXY||process.env.https_proxy||void 0;let ho;try{ho=void 0!==po&&po.length>0?new uo.kT(po):void 0}catch(e){ho=void 0}process.env.CURSOR_WEBSITE_URL,process.env.CURSOR_API_BASE_URL,Error;var mo=r("../proto/dist/generated/aiserver/v1/dashboard_connect.js");r("@connectrpc/connect-node"),new L.Gm({modelId:"gpt-5",displayModelId:"gpt-5",displayName:"GPT-5",displayNameShort:"GPT-5",aliases:["gpt-5"]});var fo=r("node:fs/promises"),go=r("../../node_modules/.pnpm/re2js@1.2.2/node_modules/re2js/build/index.esm.js");const vo="CURSOR_FORCED_SHELL_EGRESS_NETWORK_DEFAULT",yo="CURSOR_FORCED_SHELL_EGRESS_DEPENDENCY_DENY_DOMAINS",wo=/\$\(|`|<\(|>\(/,bo=/[;&|]/;let So,ko,Eo,xo;function _o(){if(void 0===So){const e=(process.env.CURSOR_FORCED_SHELL_EGRESS??"").trim().toLowerCase();So=""!==e&&"0"!==e&&"false"!==e&&"off"!==e}return So}function Co(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 Po(e){return(process.env[e]??"").split(",").map((e=>e.trim())).filter((e=>e.length>0))}function Ro(e){const t=(process.env[e]??"").split(":").map((e=>e.trim())).filter((e=>e.length>0)),r=t.filter((e=>e.startsWith("/"))),o=t.length-r.length;return o>0&&console.error(`[forced-egress] ignoring ${o} non-absolute path(s) in ${e}.`),r}function To(){if(void 0===xo){const e=(process.env[vo]??"").trim().toLowerCase();let t="deny";"allow"===e||"deny"===e?t=e:""!==e&&console.error(`[forced-egress] ignoring invalid value in ${vo} (expected "allow" or "deny"); using "deny".`);const r=Po("CURSOR_FORCED_SHELL_EGRESS_DENY_DOMAINS"),o=(process.env[yo]??"").trim();let n=r;"none"===o.toLowerCase()?n=[]:""!==o&&(n=Po(yo)),xo={networkDefault:t,denyDomains:r,dependencyDenyDomains:n,allowDomains:Po("CURSOR_FORCED_SHELL_EGRESS_ALLOW_DOMAINS"),writablePaths:Ro("CURSOR_FORCED_SHELL_EGRESS_WRITABLE_PATHS")}}return xo}function Io(e,t,r={}){const o=[Co(e),Co(t)].filter((e=>void 0!==e)).map((e=>`(?:${e})`));if(0===o.length)return null;const n=o.join("|"),s=r.anchorToExecutable?`^\\s*(?:[A-Za-z_][A-Za-z0-9_]*=[^\\s]*\\s+)*(?:${n})`:n;return new RegExp(s,"i")}function Ao(e,t){const r=function(){const e=To();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}}(),o=(void 0===ko&&(ko=Io("CURSOR_FORCED_SHELL_EGRESS_DEPENDENCY_REGEX","CURSOR_FORCED_SHELL_EGRESS_EXTRA_DEPENDENCY_REGEX",{anchorToExecutable:!0})),ko);if(null===o)return r;const n=t?.executableCommands??[];if(t?.parsingFailed||0===n.length)return r;if(wo.test(e))return r;const s=(void 0===Eo&&(Eo=Io("CURSOR_FORCED_SHELL_EGRESS_SOURCE_REGEX","CURSOR_FORCED_SHELL_EGRESS_EXTRA_SOURCE_REGEX")),Eo);for(const e of n){const t=e.fullText?.trim()||e.name?.trim()||"";if(!t||s?.test(t)||bo.test(t))return r}return n.every((e=>o.test(e.fullText?.trim()||e.name?.trim()||"")))?function(){const e=To();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}var Oo=r("../proto/dist/generated/agent/v1/sandbox_pb.js"),Do=r("../shell-exec/dist/index.js");function Mo(e){if(!e)return;let t;return"allow"===e.default?t=Oo.h1.ALLOW:"deny"===e.default&&(t=Oo.h1.DENY),new Oo.RB({version:e.version,defaultAction:t,deny:e.deny??[],allow:e.allow??[],logging:e.logging?(r=e.logging,new Oo.Qq({decisionLogPath:r.decisionLogPath,logFormat:r.logFormat})):void 0});var r}function jo(e){const t=function(e){if(!e)return;const t={};if(void 0!==e.version&&(t.version=e.version),void 0!==e.defaultAction)switch(e.defaultAction){case Oo.h1.ALLOW:t.default="allow";break;case Oo.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,Do.T6)():(0,Do.Po)())}function No(e){if(!e)return{type:"insecure_none"};switch(e.type){case Oo.vc.INSECURE_NONE:case Oo.vc.UNSPECIFIED:return{type:"insecure_none",allowlistEscalated:e.allowlistEscalated,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies};case Oo.vc.WORKSPACE_READWRITE:return{type:"workspace_readwrite",networkPolicy:jo(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};case Oo.vc.WORKSPACE_READONLY:return{type:"workspace_readonly",networkPolicy:jo(e),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadonlyPaths:e.additionalReadonlyPaths,disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicyStrict:e.networkPolicyStrict};default:return{type:"insecure_none"}}}function $o(e){if(e)return"insecure_none"===e.type?new Oo.Mw({type:Oo.vc.INSECURE_NONE,allowlistEscalated:e.allowlistEscalated,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies}):"workspace_readwrite"===e.type?new Oo.Mw({type:Oo.vc.WORKSPACE_READWRITE,networkAccess:(0,Do.$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:Mo(e.networkPolicy),networkPolicyStrict:e.networkPolicyStrict}):"workspace_readonly"===e.type?new Oo.Mw({type:Oo.vc.WORKSPACE_READONLY,networkAccess:(0,Do.$b)(e.networkPolicy),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadonlyPaths:e.additionalReadonlyPaths??[],disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicy:Mo(e.networkPolicy),networkPolicyStrict:e.networkPolicyStrict}):new Oo.Mw({type:Oo.vc.INSECURE_NONE})}async function Fo(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"unsafeResolution":return t.onPermissionDenied(e.message);default:{const t=e;throw new Error(`Unhandled block reason type: ${JSON.stringify(t)}`)}}}function Lo(e){switch(e.type){case"userRejected":return e.reason;case"unsafeResolution":return e.message;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)})`}}}var Uo=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 o,n=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===n)return n=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var s=o.dispose.call(o.value);if(o.async)return n|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else n|=1}catch(e){r(e)}if(1===n)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var o=new Error(r);return o.name="SuppressedError",o.error=e,o.suppressed=t,o});const Bo=(0,l.h)("local-exec:background-shell");function Ho(e,t,r){return"permissionsConfig"===r.type&&r.isReadonly?new We.Lt({result:{case:"permissionDenied",value:new Ve.jn({command:e,workingDirectory:t,error:"Command blocked by permissions configuration",isReadonly:!0})}}):new We.Lt({result:{case:"rejected",value:new Ve.pZ({command:e,workingDirectory:t,reason:Lo(r)})}})}class zo{id;abortController;disposed=!1;completed=!1;completionListeners=[];completion;stdin;pid;constructor(e,t){this.id=e,this.abortController=t}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 Wo(e,t){let r;try{for(let o=await t.next();!o.done;o=await t.next())"stdin_ready"===o.value.type?(e.stdin=o.value.stdin,e.pid=o.value.pid):"exit"===o.value.type&&(r={code:o.value.code,aborted:o.value.aborted,outputPath:o.value.outputLocation?.filePath})}catch(e){}finally{e.markCompleted(r??{code:null,aborted:e.signal.aborted})}}function qo(e){e().catch((()=>{}))}const Go=65536;class Vo{args;regex;limit;carryover="";matchedOccurrences=0;emittedNotifications=0;pendingBatch;flushTimer;finished=!1;constructor(e){if(this.args=e,this.limit=e.config.notificationLimit??100,e.config.pattern.length>500)throw new Error("Output notification pattern exceeds 500 characters");this.regex=go.L3.compile(e.config.pattern,go.L3.MULTILINE)}observe(e){if(this.finished||this.matchedOccurrences>=this.limit||0===e.length)return;if(e.length>Go){for(let t=0;t<e.length&&this.matchedOccurrences<this.limit;t+=Go)this.observe(e.slice(t,t+Go));return}const t=this.carryover.length,r=`${this.carryover}${e}`,o=this.regex.matcher(r);for(;this.matchedOccurrences<this.limit&&o.find();){const e=o.group()??"";o.end()>t&&this.queueMatch(e)}this.carryover=r.slice(-1024)}finish(){this.finished||(this.finished=!0,this.flushPendingBatch("finish"),this.clearFlushTimer())}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}),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,o=void 0!==e.matchedTextDetail?` ${e.matchedTextDetail}.`:"",n=1===e.count?`Shell output has pattern /${r}/. This is occurrence number ${e.startOccurrence}.${o} 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.${o}`,s=`${this.args.shellId}:task_progress:${this.emittedNotifications}`;var i;this.args.registry.enqueueCompletion({taskId:s,kind:"shell",status:"success",title:(i=t,i.length<=500?i:`${i.slice(0,500)}...`),detail:n,outputPath:this.args.outputPath,reason:"task_progress"})}emitLimitReachedNotification(){this.emittedNotifications+=1;const e=this.args.config.pattern,t=`${this.args.shellId}:task_progress:${this.emittedNotifications}`;this.args.registry.enqueueCompletion({taskId:t,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"})}}class Jo{innerFactory;projectDir;backgroundWorkRegistry;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.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,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){if(!this.backgroundWorkRegistry||!r)return;if(0===r.pattern.trim().length)return;const o=a.join(this.projectDir,"terminals",`${t}.txt`);try{return new Vo({shellId:t,outputPath:o,config:r,registry:this.backgroundWorkRegistry})}catch(r){return void(void 0!==e&&Bo.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,o){try{for await(const n of r(e,o))"stdout"===n.type||"stderr"===n.type?t.observe(n.data):"exit"===n.type&&t.finish(),yield n}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 Ko{async spawn(e,t){const r=new AbortController,o=new zo(e.shellId,r),n=t.execute(e.ctx,{command:e.command,workingDirectory:e.workingDirectory,signal:r.signal,toolCallId:e.toolCallId,conversationId:e.conversationId,sandboxPolicy:e.sandboxPolicy,pipeStdin:e.enableWriteShellStdinTool,showElapsedTime:!0})[Symbol.asyncIterator]();try{for(let e=await n.next();!e.done;e=await n.next())if("stdin_ready"===e.value.type){o.stdin=e.value.stdin,o.pid=e.value.pid;break}}catch(e){}return qo((()=>Wo(o,n))),o}async adopt(e){const t=new zo(e.shellId,e.abortController);return t.stdin=e.stdin,t.pid=e.pid,qo((()=>Wo(t,e.eventIterator))),t}}function Zo(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`}function Yo(e){const t=String(e.runningForMs).padEnd(9," ");let r="---\n";return void 0!==e.pid&&0!==e.pid&&(r+=`pid: ${e.pid}\n`),r+=`cwd: ${Zo(e.cwd)}\n`,r+=`command: ${Zo(e.command)}\n`,r+=`started_at: ${e.startedAt}\n`,r+=`running_for_ms: ${t}\n`,r+="---\n",r}class Xo{innerFactory;projectDir;constructor(e,t){this.innerFactory=e,this.projectDir=t}async spawn(e,t){const r=a.join(this.projectDir,"terminals");await(0,fo.mkdir)(r,{recursive:!0});const o=this.createLoggingExecutor(t,e,r);return this.innerFactory.spawn(e,o)}createLoggingExecutor(e,t,r){const n=e.execute.bind(e);return{...e,execute:async function*(e,i){let l,c,u,d=!1,p=!1;const h=Date.now(),m=new Date(h).toISOString();let f;const g=async e=>{if(c)try{await c.write(e)}catch(e){}},v=t.shellId,y=a.join(r,`${v}.txt`),w=()=>{void 0!==u&&(clearInterval(u),u=void 0)},b=async e=>{if(p)return;p=!0,f=e;const r=Date.now()-h,o=Yo({pid:e,cwd:t.workingDirectory,command:t.command,startedAt:m,runningForMs:r});await(0,fo.writeFile)(y,o,"utf8"),u=setInterval((()=>{(async()=>{if(!l)return;const e=Date.now()-h,r=Yo({pid:f,cwd:t.workingDirectory,command:t.command,startedAt:m,runningForMs:e});try{await l.write(r,0,"utf8")}catch(e){}})()}),5e3)},S=async()=>{l||(l=await s.promises.open(y,"r+")),c||(c=await s.promises.open(y,"a"))};try{for await(const t of n(e,i)){if("stdout"===t.type)p||(await b(),await S()),await g(t.data);else if("stderr"===t.type)p||(await b(),await S()),await g(t.data);else if("stdin_ready"!==t.type||d){if("exit"===t.type){w(),p||(await b(),await S());const e=Date.now()-h,r=i.showElapsedTime?`\n---\nexit_code: ${t.code??"unknown"}\nelapsed_ms: ${e}\nended_at: ${(new Date).toISOString()}\n---\n`:`\n---\nexit_code: ${t.code??"unknown"}\nended_at: ${(new Date).toISOString()}\n---\n`;await g(r)}}else{d=!0,p||(await b(t.pid),await S());const e=t.stdin;if(e){const t=e=>{if(null==e)return;const t="string"==typeof e?e:o.Buffer.isBuffer(e)?e.toString():String(e);if(!t)return;const r=t.endsWith("\n")?t:`${t}\n`;g(`[stdin] ${r}`)},r=e.write.bind(e);if(e.write=(e,o,n)=>(t(e),r(e,o,n)),"function"==typeof e.end){const r=e.end.bind(e);e.end=(e,o,n)=>(void 0!==e&&t(e),r(e,o,n))}}}yield t}}catch(e){w();const t=i.signal?.aborted??!1;if(!t&&(p||(await b(),await S()),c)){const t=Date.now()-h,r=Zo(e instanceof Error?e.message:"Unknown error"),o=i.showElapsedTime?`\n---\nerror: ${r}\nelapsed_ms: ${t}\nended_at: ${(new Date).toISOString()}\n---\n`:`\n---\nerror: ${r}\nended_at: ${(new Date).toISOString()}\n---\n`;await g(o)}if(!t)throw e}finally{if(w(),l)try{await l.close()}catch{}if(c)try{await c.close()}catch{}}}}}async adopt(e){const t=a.join(this.projectDir,"terminals");await(0,fo.mkdir)(t,{recursive:!0});const r=a.join(t,`${e.shellId}.txt`),o=e.startTime,n=new Date(o).toISOString(),i=Date.now()-o,l=Yo({pid:e.pid,cwd:e.workingDirectory,command:e.command,startedAt:n,runningForMs:i})+(e.initialOutput??"");await(0,fo.writeFile)(r,l,"utf8");const c=await s.promises.open(r,"r+");let u;try{u=await s.promises.open(r,"a")}catch(e){throw await c.close(),e}let d=!1,p=setInterval((()=>{const t=Date.now()-o,r=Yo({pid:e.pid,cwd:e.workingDirectory,command:e.command,startedAt:n,runningForMs:t});c.write(r,0,"utf8").catch((()=>{}))}),5e3);const h=async()=>{if(!d){d=!0,void 0!==p&&(clearInterval(p),p=void 0);try{await c.close()}catch{}try{await u.close()}catch{}}},m=async e=>{try{await u.write(e)}catch(e){}},f={next:async()=>{try{const t=await e.eventIterator.next();if(!t.done){const r=t.value;if("stdout"===r.type)await m(r.data);else if("stderr"===r.type)await m(r.data);else if("exit"===r.type){const t=Date.now()-o,n=e.showElapsedTime?`\n---\nexit_code: ${r.code??"unknown"}\nelapsed_ms: ${t}\nended_at: ${(new Date).toISOString()}\n---\n`:`\n---\nexit_code: ${r.code??"unknown"}\nended_at: ${(new Date).toISOString()}\n---\n`;await m(n),await h()}}return t}catch(e){throw await h(),e}},return:async()=>(await h(),e.eventIterator.return?e.eventIterator.return():{done:!0,value:void 0})};return this.innerFactory.adopt({...e,eventIterator:f})}}class Qo{factory;backgroundWorkRegistry;runningShells=new Map;constructor(e,t){this.factory=e,this.backgroundWorkRegistry=t}registerShellWork(e,t){const r=String(e.id);this.backgroundWorkRegistry?.upsertWork({id:r,kind:"shell",state:"running",metadata:F(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){if(!this.backgroundWorkRegistry)return;const o=r.aborted?"aborted":0===r.code?"success":"error",n=r.aborted||null===r.code||0===r.code?void 0:`exit_code=${r.code}`;this.backgroundWorkRegistry.enqueueCompletion({taskId:String(e),kind:"shell",status:o,title:t,...n?{detail:n}:{},...r.outputPath?{outputPath:r.outputPath}:{},reason:"task_finished"})}async spawn(e,t){const r=await this.factory.spawn(e,t);return this.runningShells.set(r.id,r),this.registerShellWork(r,{title:e.description||e.command,cwd:e.workingDirectory,startTimeMs:Date.now()}),r.signal.addEventListener("abort",(()=>{this.cleanupShell(r.id)})),r.onComplete?.((t=>{this.enqueueShellCompletion(r.id,e.description||e.command,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)})),t.onComplete?.((r=>{this.enqueueShellCompletion(t.id,e.description||e.command,r),this.cleanupShell(t.id)})),{shellId:t.id,pid:e.pid}}generateShellId(){return Math.floor(999e3*Math.random())+1e3}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 o=t.indexOf(""),n=-1!==o?o:t.indexOf("\\u0004");if(-1!==n){const e=t.substring(0,n);e.length>0&&await new Promise(((t,o)=>{r.stdin.write(e,(e=>{e?o(e):t(void 0)}))})),r.stdin.end()}else await new Promise(((e,o)=>{r.stdin.write(t,(t=>{t?o(t):e(void 0)}))}))}}class en{permissionsService;coreExecutor;ignoreService;backgroundShellManager;constructor(e,t,r,o,n,s){this.permissionsService=e,this.coreExecutor=t,this.ignoreService=r;const i=n??function(e){const t=new Ko;return new Xo(t,e)}(o),a=new Jo(i,o,s);this.backgroundShellManager=new Qo(a,s)}getManager(){return this.backgroundShellManager}dispose(){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 o,n;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");o=t[Symbol.asyncDispose]}if(void 0===o){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");o=t[Symbol.dispose],r&&(n=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");n&&(o=function(){try{n.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:o,async:r})}else r&&e.stack.push({async:!0})}(r,(0,l.VI)(e.withName("LocalBackgroundShellExecutor.execute")),!1);const o=t.command,n=t.sandboxPolicy?No(t.sandboxPolicy):void 0,s=t.workingDirectory||await this.coreExecutor.getCwd(),i=(0,h.o1)(s);if(!t.parsingResult)return new We.Lt({result:{case:"error",value:new We.Of({command:o,workingDirectory:i,error:"Parsing result is required"})}});let a=n;if(Bo.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:n?.type??"undefined",parserCommandCount:t.parsingResult.executableCommands.length,classifierCommandCount:t.classifierResult?.commands.length??0,commandLength:o.length}),t.skipApproval){const r=await this.permissionsService.shouldEnforceShellInvariantBlocks(e,{workingDirectory:i},n);if("block"===r.kind)return Bo.info(e,"Background shell: invariant blocked command",{toolCallId:t.toolCallId,blockReasonType:r.reason.type,skipApproval:t.skipApproval}),Ho(o,i,r.reason);Bo.info(e,"Background shell: skipped local approval",{toolCallId:t.toolCallId,requestedPolicyType:n?.type??"undefined"})}else{const r=await this.permissionsService.shouldBlockShellCommand(e,o,{workingDirectory:i,timeout:0,parsingResult:t.parsingResult,toolCallId:t.toolCallId,classifierResult:t.classifierResult,smartModeApprovalReason:t.smartModeApproval?.reason,smartModeApprovalRequestId:t.smartModeApproval?.requestId,hookApprovalRequirement:dt(t)},n);if("block"===r.kind)return Bo.info(e,"Background shell: approval gate blocked command",{toolCallId:t.toolCallId,blockReasonType:r.reason.type,hasSmartModeApproval:void 0!==t.smartModeApproval,skipApproval:t.skipApproval}),Ho(o,i,r.reason);a=r.policy,Bo.info(e,"Background shell: approval gate allowed command",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,effectivePolicyType:a.type})}if(_o()&&(a=Ao(o,t.parsingResult),"insecure_none"!==a.type)){const e=await this.ignoreService.getCursorIgnoreMapping();a={...a,ignoreMapping:e}}try{const r=this.backgroundShellManager.generateShellId(),n=a?{perRepo:a}:void 0,s={ctx:e,command:o,workingDirectory:i,toolCallId:t.toolCallId,conversationId:t.conversationId,sandboxPolicy:n,shellId:r,enableWriteShellStdinTool:t.enableWriteShellStdinTool,description:t.description,outputNotification:t.outputNotification},l=await this.backgroundShellManager.spawn(s,this.coreExecutor);return new We.Lt({result:{case:"success",value:new We.Po({shellId:r,command:o,workingDirectory:i,pid:l.pid})}})}catch(e){return new We.Lt({result:{case:"error",value:new We.Of({command:o,workingDirectory:i,error:e instanceof Error?e.message:"Unknown error"})}})}}catch(e){r.error=e,r.hasError=!0}finally{Uo(r)}}writeStdin(e,t){return this.backgroundShellManager.writeStdin(e,t)}}var tn=r("node:async_hooks?2c30"),rn=r("../proto/dist/generated/agent/v1/agent_skills_pb.js"),on=r("../proto/dist/generated/agent/v1/cursor_rules_pb.js"),nn=r("../proto/dist/generated/agent/v1/subagents_pb.js"),sn=r("../../node_modules/.pnpm/gray-matter@4.0.3/node_modules/gray-matter/index.js"),an=r("../../node_modules/.pnpm/ignore@7.0.5/node_modules/ignore/index.js"),ln=(r("../../node_modules/.pnpm/minimatch@10.2.5/node_modules/minimatch/dist/esm/index.js"),r("node:util?085f")),cn=r("zod");const un={log:()=>{},increment:()=>{},distribution:()=>{},captureException:()=>{}},dn=cn.z.object({command:cn.z.string().optional(),args:cn.z.array(cn.z.string()).optional(),env:cn.z.record(cn.z.string(),cn.z.string()).optional(),url:cn.z.string().optional(),headers:cn.z.record(cn.z.string(),cn.z.string()).optional(),cwd:cn.z.string().optional(),envFile:cn.z.string().optional(),auth:cn.z.object({CLIENT_ID:cn.z.string(),CLIENT_SECRET:cn.z.string().optional(),scopes:cn.z.array(cn.z.string()).optional()}).optional(),enabledTools:cn.z.array(cn.z.string()).optional()}),pn=cn.z.object({mcpServers:cn.z.record(cn.z.string(),dn).optional()});function hn(e){return`user-settings:${t=e,(0,n.createHash)("sha256").update(t).digest("hex").slice(0,16)}`;var t}class mn extends Error{constructor(e,t){super(`Invalid Claude Code plugin identifier "${t}": ${e}`),this.raw=t,this.name="CCPluginIdentifierError"}}function fn(e){const t=e.trim();if(!t)throw new mn("Empty identifier",e);const r=/^[a-zA-Z0-9_-]+$/,o=t.indexOf("@");if(o!==t.lastIndexOf("@"))throw new mn("Plugin identifier cannot contain multiple @ symbols",e);if(-1===o){if(!r.test(t))throw new mn("Plugin name must contain only alphanumeric characters, dashes, and underscores",e);if(t.length>100)throw new mn("Plugin name must be 100 characters or less",e);return{name:t,sourceType:"marketplace",marketplace:"claude-plugins-official",raw:e}}const n=t.slice(0,o).trim(),s=t.slice(o+1).trim();if(!n)throw new mn("Missing plugin name before @",e);if(!s)throw new mn("Missing source after @",e);if(!r.test(n))throw new mn("Plugin name must contain only alphanumeric characters, dashes, and underscores",e);if(n.length>100)throw new mn("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 mn("Invalid GitHub repo format, expected 'org/repo' (e.g., 'anthropics/claude-plugins')",e);return{name:n,sourceType:"github",githubRepo:t,raw:e}}if(s.startsWith("local:")){const t=s.slice(6).trim();if(!t)throw new mn("Missing path after 'local:'",e);return{name:n,sourceType:"local",localPath:t,raw:e}}if(s.startsWith("url:")){const t=s.slice(4).trim();if(!t)throw new mn("Missing Git URL after 'url:'",e);try{new URL(t)}catch(t){throw new mn("Invalid Git URL format",e)}return{name:n,sourceType:"url",gitUrl:t,raw:e}}const i=s.indexOf("#");let a,l;if(-1!==i?(a=s.slice(0,i).trim(),l=s.slice(i+1).trim()):a=s,!a)throw new mn("Missing marketplace name",e);if(!r.test(a))throw new mn("Marketplace name must contain only alphanumeric characters, dashes, and underscores",e);return{name:n,sourceType:"marketplace",marketplace:a,version:l,raw:e}}function gn(e){if("claude-plugin"===e.source)return e.sourceInfo.raw;if("user-local"===e.source)return`user-local:${e.sourceInfo.name}`;if("user-settings"===e.source)return hn(e.sourceInfo.localPath);if("extension"===e.source){const t=e.sourceInfo;return`extension:${t.extensionId}:${t.localPath}`}const t=e.sourceInfo;return`${t.name}-${t.version}`}function vn(e){return e.sourceInfo.name}function yn(e){switch(e.source){case"claude-plugin":case"cursor-first-party":case"cursor-third-party":return e.sourceInfo.marketplace;default:return}}function wn(e){switch(e.source){case"cursor-first-party":case"cursor-third-party":return e.sourceInfo.pluginDbId;default:return}}function bn(e){switch(e.source){case"cursor-first-party":case"cursor-third-party":return e.sourceInfo.marketplaceDbId;default:return}}var Sn=r("../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/ajv.js");const kn=10485760,En=/^[a-z0-9]([a-z0-9.-]*[a-z0-9])?$/,xn=[".cursor-plugin/plugin.json",".claude-plugin/plugin.json"],_n=[".cursor-plugin",".claude-plugin"],Cn=[".cursor-plugin/marketplace.json",".claude-plugin/marketplace.json"],Pn=cn.z.object({source:cn.z.literal("github"),repo:cn.z.string().regex(/^[^/]+\/[^/]+$/,"Must be in owner/repo format"),ref:cn.z.string().optional(),sha:cn.z.string().length(40,"SHA must be 40 characters").regex(/^[a-f0-9]+$/,"SHA must be hexadecimal").optional()}),Rn=cn.z.object({source:cn.z.literal("url"),url:cn.z.string().url().endsWith(".git","URL must end with .git"),ref:cn.z.string().optional(),sha:cn.z.string().length(40,"SHA must be 40 characters").regex(/^[a-f0-9]+$/,"SHA must be hexadecimal").optional()}),Tn=cn.z.object({source:cn.z.literal("git-subdir"),url:cn.z.string().url().endsWith(".git","URL must end with .git"),path:cn.z.string().min(1),ref:cn.z.string().optional(),sha:cn.z.string().length(40,"SHA must be 40 characters").regex(/^[a-f0-9]+$/,"SHA must be hexadecimal").optional()}),In=cn.z.union([cn.z.string(),Pn,Rn,Tn]),An=cn.z.object({name:cn.z.string().min(1,"Author name is required"),email:cn.z.string().email().optional()}),On=(cn.z.object({name:cn.z.string().min(1,"Owner name is required"),email:cn.z.string().email().optional()}),cn.z.enum(["string","number","integer","boolean","object","array","null"])),Dn=cn.z.union([On,cn.z.array(On).nonempty().superRefine(((e,t)=>{new Set(e).size!==e.length&&t.addIssue({code:cn.z.ZodIssueCode.custom,message:"Schema type arrays must not contain duplicates"})}))]);function Mn(e,t){if(void 0!==e.required)if(void 0===e.properties)for(const r of e.required)t.addIssue({code:cn.z.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:cn.z.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:cn.z.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:cn.z.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:cn.z.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:cn.z.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:cn.z.ZodIssueCode.custom,message:"minProperties must be less than or equal to maxProperties",path:["minProperties"]})}const jn=cn.z.lazy((()=>cn.z.object({type:Dn.optional(),title:cn.z.string().optional(),description:cn.z.string().optional(),default:cn.z.unknown().optional(),enum:cn.z.array(cn.z.any()).nonempty().optional(),const:cn.z.unknown().optional(),properties:cn.z.record(cn.z.string(),jn).optional(),required:cn.z.array(cn.z.string()).optional(),additionalProperties:cn.z.union([cn.z.boolean(),jn]).optional(),items:cn.z.union([jn,cn.z.array(jn)]).optional(),minLength:cn.z.number().int().nonnegative().optional(),maxLength:cn.z.number().int().nonnegative().optional(),minimum:cn.z.number().optional(),maximum:cn.z.number().optional(),exclusiveMinimum:cn.z.number().optional(),exclusiveMaximum:cn.z.number().optional(),multipleOf:cn.z.number().positive().optional(),minItems:cn.z.number().int().nonnegative().optional(),maxItems:cn.z.number().int().nonnegative().optional(),uniqueItems:cn.z.boolean().optional(),minProperties:cn.z.number().int().nonnegative().optional(),maxProperties:cn.z.number().int().nonnegative().optional()}).strict().superRefine(Mn)));function Nn(e){const t=jn.superRefine(((e,t)=>{"object"!==e.type&&t.addIssue({code:cn.z.ZodIssueCode.custom,message:'Plugin variable schemas must declare type "object"',path:["type"]})})).safeParse(e);return t.success?{success:!0,data:t.data}:t}const $n=cn.z.unknown().superRefine(((e,t)=>{const r=Nn(e);if(!r.success)for(const e of r.error.issues)t.addIssue(e)})).transform((e=>e)),Fn=(cn.z.object({name:cn.z.string().min(1).transform((e=>e.toLowerCase())).refine((e=>En.test(e)),"Name must be kebab-case (lowercase alphanumeric with hyphens and periods)"),displayName:cn.z.string().optional(),source:In,description:cn.z.string().optional(),version:cn.z.string().optional(),author:An.optional(),publisher:cn.z.string().min(1).optional(),homepage:cn.z.string().url().optional(),repository:cn.z.string().url().optional(),license:cn.z.string().optional(),keywords:cn.z.array(cn.z.string()).optional(),logo:cn.z.string().optional(),category:cn.z.string().optional(),tags:cn.z.array(cn.z.string()).optional(),strict:cn.z.boolean().default(!0),commands:cn.z.union([cn.z.string(),cn.z.array(cn.z.string())]).optional(),agents:cn.z.union([cn.z.string(),cn.z.array(cn.z.string())]).optional(),skills:cn.z.union([cn.z.string(),cn.z.array(cn.z.string())]).optional(),rules:cn.z.union([cn.z.string(),cn.z.array(cn.z.string())]).optional(),hooks:cn.z.union([cn.z.string(),cn.z.record(cn.z.unknown())]).optional(),variables:$n.optional(),mcpServers:cn.z.union([cn.z.string(),cn.z.record(cn.z.unknown()),cn.z.array(cn.z.union([cn.z.string(),cn.z.record(cn.z.unknown())]))]).optional()}),cn.z.object({description:cn.z.string().optional(),version:cn.z.string().optional(),pluginRoot:cn.z.string().optional()}),cn.z.object({name:cn.z.string().min(1).regex(En,"Name must be kebab-case (lowercase alphanumeric with hyphens and periods)"),displayName:cn.z.string().optional(),description:cn.z.string().optional(),version:cn.z.string().optional(),author:An.optional(),publisher:cn.z.string().min(1).optional(),homepage:cn.z.string().url().optional(),repository:cn.z.string().url().optional(),license:cn.z.string().optional(),logo:cn.z.string().optional(),keywords:cn.z.array(cn.z.string()).optional(),commands:cn.z.union([cn.z.string(),cn.z.array(cn.z.string())]).optional(),agents:cn.z.union([cn.z.string(),cn.z.array(cn.z.string())]).optional(),skills:cn.z.union([cn.z.string(),cn.z.array(cn.z.string())]).optional(),rules:cn.z.union([cn.z.string(),cn.z.array(cn.z.string())]).optional(),hooks:cn.z.union([cn.z.string(),cn.z.record(cn.z.unknown())]).optional(),variables:$n.optional(),mcpServers:cn.z.union([cn.z.string(),cn.z.record(cn.z.unknown()),cn.z.array(cn.z.union([cn.z.string(),cn.z.record(cn.z.unknown())]))]).optional()}));function Ln(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Un(e){return e.trim().toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")}function Bn(e,t){if(Ln(e)&&"string"==typeof e.name){const t=Un(e.name);if(t.length>0)return t}return function(e){var t;const r=void 0!==e.repoName?Un(e.repoName):"";return r.length>0?r:`cursor-marketplace-${null!==(t=e.fallbackId)&&void 0!==t?t:(0,n.randomUUID)()}`}(t)}function Hn(e){if(Ln(e)&&Ln(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 Object.assign({name:t},void 0!==r?{email:r}:{})}return{name:"Unknown"}}function zn(e){return"string"==typeof e?e:void 0}function Wn(e){if(!Array.isArray(e))return;const t=e.filter((e=>"string"==typeof e));return t.length>0?t:void 0}function qn(e){return"string"==typeof e?e:Wn(e)}function Gn(e){if(!Ln(e)||!Ln(e.metadata))return;const t={description:zn(e.metadata.description),version:zn(e.metadata.version),pluginRoot:zn(e.metadata.pluginRoot)};return void 0!==t.description||void 0!==t.version||void 0!==t.pluginRoot?t:void 0}function Vn(e){if(!Ln(e))return;const t=zn(e.name);if(void 0===t||0===t.length)return;const r=zn(e.email);return Object.assign({name:t},void 0!==r?{email:r}:{})}function Jn(e){if("string"==typeof e||Ln(e))return e;if(Array.isArray(e)){const t=e.filter((e=>"string"==typeof e||Ln(e)));return t.length>0?t:void 0}}function Kn(e){if("string"==typeof e||Ln(e))return e}function Zn(e){if(void 0===e)return;const t=Nn(e);return t.success?t.data:void 0}function Yn(e,t={}){if(e.length>kn)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(!Ln(r))return{success:!1,error:"Invalid marketplace manifest: expected a JSON object"};const o=[],n=[],s=new Set;return(Array.isArray(r.plugins)?r.plugins:[]).forEach(((e,t)=>{const r=function(e,t){if(!Ln(e))return{skippedEntry:{index:t,error:`Plugin entry at index ${t} is not an object`}};const r="string"==typeof(o=e.source)?o:Ln(o)?"github"===o.source&&"string"==typeof o.repo&&o.repo.length>0?{source:"github",repo:o.repo,ref:zn(o.ref),sha:zn(o.sha)}:("url"===o.source||void 0===o.source)&&"string"==typeof o.url&&o.url.length>0?{source:"url",url:o.url,ref:zn(o.ref),sha:zn(o.sha)}:"git-subdir"===o.source&&"string"==typeof o.url&&o.url.length>0&&"string"==typeof o.path&&o.path.length>0?{source:"git-subdir",url:o.url,path:o.path,ref:zn(o.ref),sha:zn(o.sha)}:"string"==typeof o.repo&&o.repo.length>0?{source:"github",repo:o.repo,ref:zn(o.ref),sha:zn(o.sha)}:void 0:void 0;var o;if(void 0===r){const r=zn(e.name);return{skippedEntry:Object.assign(Object.assign({index:t},void 0!==r&&r.length>0?{name:r}:{}),{error:`Plugin entry at index ${t} has no usable source`})}}const n=("string"==typeof e.name?Un(e.name):"")||function(e){var t;if("string"==typeof e){const t=Un((0,a.basename)(e));return t.length>0?t:void 0}if("github"===e.source){const r=Un(null!==(t=e.repo.split("/").at(-1))&&void 0!==t?t:"");return r.length>0?r:void 0}if("git-subdir"===e.source){const t=Un((0,a.basename)(e.path));return t.length>0?t:void 0}let r=e.url;try{r=new URL(e.url).pathname}catch(e){}for(;r.endsWith("/");)r=r.slice(0,-1);r.toLowerCase().endsWith(".git")&&(r=r.slice(0,-4));const o=Un((0,a.basename)(r));return o.length>0?o:void 0}(r);return void 0===n?{skippedEntry:{index:t,error:`Plugin entry at index ${t} has no usable name`}}:{entry:{name:n,displayName:zn(e.displayName),source:r,description:zn(e.description),version:zn(e.version),author:Vn(e.author),publisher:zn(e.publisher),homepage:zn(e.homepage),repository:zn(e.repository),license:zn(e.license),keywords:Wn(e.keywords),logo:zn(e.logo),category:zn(e.category),tags:Wn(e.tags),strict:"boolean"!=typeof e.strict||e.strict,commands:qn(e.commands),agents:qn(e.agents),skills:qn(e.skills),rules:qn(e.rules),hooks:Kn(e.hooks),variables:Zn(e.variables),mcpServers:Jn(e.mcpServers)}}}(e,t);"skippedEntry"in r?n.push(r.skippedEntry):s.has(r.entry.name)?n.push({index:t,name:r.entry.name,error:`Duplicate plugin name "${r.entry.name}" at index ${t}`}):(s.add(r.entry.name),o.push(r.entry))})),{success:!0,data:{name:Bn(r,t),owner:Hn(r),description:zn(r.description),plugins:o,metadata:Gn(r),skippedPluginEntries:n}}}function Xn(e){if(e.length>kn)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=Fn.safeParse(t);return r.success?{success:!0,data:r.data}:{success:!1,error:`Invalid plugin manifest: ${r.error.errors.map((e=>`${e.path.join(".")}: ${e.message}`)).join(", ")}`,details:r.error}}function Qn(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 es(e){return!e.includes("..")&&!(0,a.isAbsolute)(e)&&!e.includes("://")}new Sn.Ajv({allErrors:!0,strict:!1,validateSchema:!0});var ts=r("../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/main.js");const rs=/\$\{([^:}]+)(?::-([^}]*))?\}/g;function os(e,t){const r="function"==typeof t?t:function(e){const t=new Map(Object.entries(e).map((([e,t])=>[e.toLowerCase(),t])));return r=>{var o;return null!==(o=e[r])&&void 0!==o?o:t.get(r.toLowerCase())}}(t);return ns(e,r)}function ns(e,t){if("string"==typeof e)return e.replace(rs,((e,r,o)=>{const n=t(r);return void 0!==n?n:void 0!==o?o:e}));if(Array.isArray(e))return e.map((e=>ns(e,t)));if(null!==e&&"object"==typeof e){const r={};for(const[o,n]of Object.entries(e))r[o]=ns(n,t);return r}return e}function ss(e,t){return e.replace(/\$\{CLAUDE_PLUGIN_ROOT\}/g,(()=>t)).replace(/\$\{CURSOR_PLUGIN_ROOT\}/g,(()=>t))}const is=[".mcp.json","mcp.json"],as=new Set(["author","owner","source","metadata"].map((e=>e.toLowerCase())));function ls(e,t){if(!function(e){return as.has(e.toLowerCase())}(e))return!1;if("object"!=typeof t||null===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 cs(e){return"object"==typeof e&&null!==e&&("command"in e||"url"in e)}function us(e,t,r){if(!e.mcpServers)return e;const o={};for(const[r,n]of Object.entries(e.mcpServers)){const e=Object.assign({},n);if("string"==typeof n.command&&(e.command=ss(n.command,t)),Array.isArray(n.args)&&(e.args=n.args.map((e=>"string"==typeof e?ss(e,t):e))),n.env&&"object"==typeof n.env){const r={};for(const[e,o]of Object.entries(n.env))r[e]="string"==typeof o?ss(o,t):o;e.env=r}"string"==typeof n.cwd&&(e.cwd=ss(n.cwd,t)),o[r]=e}return function(e,t){const r=null==t?void 0:t.cloudAgentEnvLookup,o=null==t?void 0:t.configuredVariables;return os(e,void 0!==r?r:e=>{const t=process.env[e];if(void 0!==t)return t;const r=null==o?void 0:o[e];return null!=r?"string"==typeof r?r:String(r):void 0})}(Object.assign(Object.assign({},e),{mcpServers:o}),r)}function ds(e,t,r){try{const o=(0,ts.qg)(e),n=pn.safeParse(o);if(n.success&&n.data.mcpServers&&Object.keys(n.data.mcpServers).length>0)return us(n.data,t,r);const s={};for(const[e,t]of Object.entries(o))"mcpServers"!==e&&!ls(e,t)&&cs(t)&&(s[e]=t);if(Object.keys(s).length>0){const e=pn.safeParse({mcpServers:s});if(e.success)return us(e.data,t,r)}return null}catch(e){return null}}function ps(e,t,r,o,n,s){var i,a;const l=[],c=e.mcpServers;if(!c)return l;for(const[e,u]of Object.entries(c)){const c=u,d=`plugin-${o}-${e}`,p=e;c.url?l.push({identifier:d,name:p,marketplace:t,marketplaceId:r,pluginName:o,pluginId:n,pluginSource:s,type:"streamableHttp",url:c.url,headers:c.headers,auth:c.auth,enabledTools:c.enabledTools,projectManaged:!1,pluginManaged:!0}):c.command&&l.push({identifier:d,name:p,marketplace:t,marketplaceId:r,pluginName:o,pluginId:n,pluginSource:s,type:"stdio",command:c.command,args:null!==(i=c.args)&&void 0!==i?i:[],env:null!==(a=c.env)&&void 0!==a?a:{},cwd:c.cwd,envFile:c.envFile,enabledTools:c.enabledTools,projectManaged:!1,pluginManaged:!0})}return l}var hs=r("node:stream?a812"),ms=r("node:stream/promises"),fs=r("node:zlib?825c"),gs=r("../../node_modules/.pnpm/tar@7.5.7/node_modules/tar/dist/esm/index.js"),vs=function(e,t,r,o){return new(r||(r=Promise))((function(n,s){function i(e){try{l(o.next(e))}catch(e){s(e)}}function a(e){try{l(o.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(i,a)}l((o=o.apply(e,t||[])).next())}))};const ys=".cache-complete";function ws(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_")}function bs(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_")}function Ss(e){return(0,h.Nz)(e)}class ks{constructor(e,t){var r,o;const n=null!==(r=null!=e?e:process.env.HOME)&&void 0!==r?r:"";this.cacheRoot=null!==(o=null==t?void 0:t.cacheRoot)&&void 0!==o?o:(0,a.join)(n,".cursor","plugins/cache")}getCacheDir(e){return function(e,t){return function(e,t,r,o){const n=[e,t,r];return void 0!==o&&n.push(o),(0,a.join)(...n)}(e,ws(t.marketplaceSlug),bs(t.pluginId),void 0!==t.version?Ss(t.version):void 0)}(this.cacheRoot,e)}isCached(e){return vs(this,void 0,void 0,(function*(){const t=this.getCacheDir(e);try{const e=(0,a.join)(t,ys);return(yield(0,fo.stat)(e)).isFile()}catch(e){return!1}}))}extractToCache(e){return vs(this,void 0,void 0,(function*(){const t=this.getCacheDir(e);yield(0,fo.mkdir)(t,{recursive:!0});const r=hs.Readable.from(e.tarball);return yield(0,ms.pipeline)(r,(0,fs.createGunzip)(),(0,gs.o6)({cwd:t,strip:1})),yield this.markCacheComplete(e),t}))}listCachedVersions(e){return vs(this,void 0,void 0,(function*(){const t=ws(e.marketplaceSlug),r=bs(e.pluginId),o=(0,a.join)(this.cacheRoot,t,r);try{return(yield(0,fo.readdir)(o,{withFileTypes:!0})).filter((e=>e.isDirectory())).map((e=>e.name))}catch(e){return[]}}))}removeVersion(e){return vs(this,void 0,void 0,(function*(){const t=this.getCacheDir(e);try{yield(0,fo.rm)(t,{recursive:!0,force:!0})}catch(e){}}))}pruneOldVersions(e){return vs(this,void 0,void 0,(function*(){const t=yield this.listCachedVersions({marketplaceSlug:e.marketplaceSlug,pluginId:e.pluginId}),r=new Set(e.keepVersions.map((e=>Ss(e))));for(const o of t)r.has(o)||(yield this.removeVersion({marketplaceSlug:e.marketplaceSlug,pluginId:e.pluginId,version:o}))}))}markCacheComplete(e){return vs(this,void 0,void 0,(function*(){const t=this.getCacheDir(e);yield(0,fo.writeFile)((0,a.join)(t,ys),"")}))}}function Es(e,t){var r;const o=null!==(r=e.releaseTag)&&void 0!==r?r:t;if(e.releaseRepo&&e.releaseAsset&&o)return{kind:"release",releaseRepo:e.releaseRepo,releaseAsset:e.releaseAsset,releaseTag:o}}var xs=r("node:child_process");const _s=(0,ln.promisify)(xs.execFile);function Cs(e,t){return r=this,o=void 0,s=function*(){const r=function(e){var t;const r=Object.assign(Object.assign({},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(delete r.GIT_CONFIG_NOSYSTEM,!0===(null==e?void 0:e.sshBatchMode)){const e=(null===(t=process.env.GIT_SSH_COMMAND)||void 0===t?void 0:t.trim())||"ssh";r.GIT_SSH_COMMAND=`${e} -oBatchMode=yes`}if(void 0!==(null==e?void 0:e.extraGitConfig)){const t=Object.entries(e.extraGitConfig);r.GIT_CONFIG_COUNT=String(t.length);for(const[e,[o,n]]of t.entries())r[`GIT_CONFIG_KEY_${e}`]=o,r[`GIT_CONFIG_VALUE_${e}`]=n}return{cwd:null==e?void 0:e.cwd,env:r}}({cwd:null==t?void 0:t.cwd,sshBatchMode:null==t?void 0:t.sshBatchMode,extraGitConfig:null==t?void 0:t.extraGitConfig});return _s("git",["-c","credential.interactive=false",...e],r)},new((n=void 0)||(n=Promise))((function(e,t){function i(e){try{l(s.next(e))}catch(e){t(e)}}function a(e){try{l(s.throw(e))}catch(e){t(e)}}function l(t){var r;t.done?e(t.value):(r=t.value,r instanceof n?r:new n((function(e){e(r)}))).then(i,a)}l((s=s.apply(r,o||[])).next())}));var r,o,n,s}var Ps=function(e,t,r,o){return new(r||(r=Promise))((function(n,s){function i(e){try{l(o.next(e))}catch(e){s(e)}}function a(e){try{l(o.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(i,a)}l((o=o.apply(e,t||[])).next())}))};const Rs=/^[0-9a-f]{7,40}$/i,Ts=/^[0-9a-f]{40}$/i;function Is(e){var t,r;if(void 0===e||""===e)return;const o=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));return 0!==o.length?null!==(r=null===(t=o.find((e=>e.refName.endsWith("^{}"))))||void 0===t?void 0:t.sha)&&void 0!==r?r:o[0].sha:void 0}function As(e,t,r){return Ps(this,void 0,void 0,(function*(){const o=t.trim();if(Ts.test(o))return{fullSha:o.toLowerCase()};if(Rs.test(o)){try{const t=yield function(e,t,r){return Ps(this,void 0,void 0,(function*(){var o;const{stdout:n}=yield Cs(["ls-remote",e,`refs/heads/${t}`,`refs/tags/${t}`,`refs/tags/${t}^{}`],{sshBatchMode:null==r?void 0:r.sshBatchMode,extraGitConfig:null==r?void 0:r.extraGitConfig});return null===(o=Is(n))||void 0===o?void 0:o.toLowerCase()}))}(e,o,r);if(t)return{fullSha:t}}catch(e){}return{fullSha:o.toLowerCase()}}let n;try{if("HEAD"===o.toUpperCase()){const t=yield Cs(["ls-remote","--symref",e,"HEAD"],{sshBatchMode:null==r?void 0:r.sshBatchMode,extraGitConfig:null==r?void 0:r.extraGitConfig}),o=Is(t.stdout);if(!o)throw new Error(`git ls-remote did not return a resolvable commit for HEAD (${e})`);return{fullSha:o.toLowerCase(),headSymrefStdout:t.stdout}}n=(yield Cs(["ls-remote",e,o],{sshBatchMode:null==r?void 0:r.sshBatchMode,extraGitConfig:null==r?void 0:r.extraGitConfig})).stdout}catch(t){const r=t instanceof Error?t.message:String(t),n=new Error(`Failed to resolve git ref "${o}" for ${e}: ${r}`);throw n.cause=t,n}const s=Is(n);if(!s)throw new Error(`git ls-remote did not return a resolvable commit for ref "${o}" (${e})`);return{fullSha:s.toLowerCase()}}))}function Os(e){const t=e.toLowerCase();return"github.com"===t||t.endsWith(".github.com")?"github":"gitlab.com"===t||t.endsWith(".gitlab.com")?"gitlab":"bitbucket.org"===t||t.endsWith(".bitbucket.org")?"bitbucket":"generic"}function Ds(e){let t;try{const r=e.startsWith("git@")?`ssh://${e.replace(":","/")}`:e;t=new URL(r.includes("://")?r:`https://${r}`)}catch(e){return null}const r=t.pathname.replace(/\.git$/,"").split("/").filter(Boolean);if(r.length<2)return null;const[o,n]=r,s=t.hostname;return{provider:Os(s),owner:o,repo:n,host:s}}function Ms(e){const t=e.toLowerCase();return"github.com"===t||t.endsWith(".github.com")?"github.com":e}function js(e){return!e.operatingSystems||0===e.operatingSystems.length||e.operatingSystems.includes(function(){const e=(0,i.platform)();return"win32"===e?"Windows":"darwin"===e?"Macintosh":"Linux"}())}function Ns(e){return/[\n\r:#[\]{}&*!|>'"%@`]/.test(e)||e.startsWith(" ")||e.endsWith(" ")?`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:e}function $s(e,t){const r=(0,a.resolve)(e),o=(0,a.resolve)(e,t),n=(0,a.relative)(r,o);if(n.startsWith("..")||(0,a.isAbsolute)(n))throw new Error(`Invalid subPath: path traversal not allowed (${JSON.stringify(t)})`);return o}var Fs=function(e,t,r,o){return new(r||(r=Promise))((function(n,s){function i(e){try{l(o.next(e))}catch(e){s(e)}}function a(e){try{l(o.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(i,a)}l((o=o.apply(e,t||[])).next())}))};const Ls=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 Us(e){const t=(0,h.Nz)(e).replace(/[. ]+$/g,"");return""===t||"."===t||".."===t?"_":Ls.has(t.toLowerCase())?`_${t}`:t}const Bs=["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"],Hs=["enotempty: directory not empty, rename","/_staging/"],zs=["upload-pack: not our ref","server does not allow request for unadvertised object"];function Ws(e){const t=String(e).toLowerCase().replaceAll("\\","/");return Bs.some((e=>t.includes(e)))?"user_git_access":Hs.every((e=>t.includes(e)))?"local_cache_race":zs.some((e=>t.includes(e)))?"stale_pinned_ref":"infrastructure"}function qs(e){const t=Ds(e);if(null===t)throw new Error(`Invalid git URL: ${e}`);return{host:Ms(t.host.replace(/^www\./i,"")),owner:t.owner.toLowerCase(),repo:t.repo.toLowerCase()}}const Gs=new Map;class Vs{constructor(e,t){this.cacheRoot=e,this.options=t,this.manifestCache=new Map}cloneResolvedRef(e,t,r,o){return Fs(this,void 0,void 0,(function*(){var n;const s={cwd:e,sshBatchMode:null==o?void 0:o.sshBatchMode,extraGitConfig:null===(n=this.options)||void 0===n?void 0:n.extraGitConfig};yield Cs(["init"],s),yield Cs(["fetch","--depth","1",t,r],s),yield Cs(["checkout","FETCH_HEAD"],s)}))}createStagingDir(){return Fs(this,void 0,void 0,(function*(){const e=(0,a.join)(this.cacheRoot,"_staging",(0,n.randomUUID)());return yield(0,fo.mkdir)(e,{recursive:!0}),e}))}moveToCanonicalDir(e,t){return Fs(this,void 0,void 0,(function*(){return yield(0,fo.mkdir)((0,a.dirname)(t),{recursive:!0}),yield(0,fo.rm)(t,{recursive:!0,force:!0}),yield(0,fo.rename)(e,t),t}))}cleanStaleStagingDirs(){return Fs(this,void 0,void 0,(function*(){const e=(0,a.join)(this.cacheRoot,"_staging");try{const t=yield(0,fo.readdir)(e,{withFileTypes:!0}),r=Date.now();yield Promise.all(t.filter((e=>e.isDirectory())).map((t=>Fs(this,void 0,void 0,(function*(){try{const o=(0,a.join)(e,t.name),n=yield(0,fo.stat)(o);r-n.mtimeMs>Vs.STALE_STAGING_THRESHOLD_MS&&(yield(0,fo.rm)(o,{recursive:!0,force:!0}))}catch(e){}})))))}catch(e){}}))}getLegacyCloneDir(e,t){return(0,a.join)(this.cacheRoot,Us(e),Us(t))}getCanonicalCloneDir(e,t){const{host:r,owner:o,repo:n}=qs(e);return(0,a.join)(this.cacheRoot,Us(r),Us(o),Us(n),Us(t))}getCanonicalRepoRootDir(e){const{host:t,owner:r,repo:o}=qs(e);return(0,a.join)(this.cacheRoot,Us(t),Us(r),Us(o))}pruneSiblingCloneDirs(e,t,r){return Fs(this,void 0,void 0,(function*(){const o=this.getCanonicalRepoRootDir(e),n=Us(t);try{const e=yield(0,fo.readdir)(o,{withFileTypes:!0});yield Promise.all(e.filter((e=>e.isDirectory()&&e.name!==n)).map((e=>(0,fo.rm)((0,a.join)(o,e.name),{recursive:!0,force:!0}))))}catch(e){}if(void 0!==r)try{yield(0,fo.rm)(r,{recursive:!0,force:!0})}catch(e){}}))}ensureCloned(e,t,r){return Fs(this,arguments,void 0,(function*(e,t,r,o=un){const n=this.ensureClonedSerialized(e,t,r,o);return(0,h.wj)(n,3e4,`ensureCloned timed out after 30000ms for ${t} @ ${r}`)}))}ensureClonedSerialized(e,t,r,o){return Fs(this,void 0,void 0,(function*(){const n=this.getCanonicalRepoRootDir(t),s=`${this.cacheRoot}:${n}`,i=Gs.get(s),a=(null!=i?i:Promise.resolve("")).catch((()=>{})).then((()=>this.ensureClonedImpl(e,t,r,o)));Gs.set(s,a);try{return yield a}finally{Gs.get(s)===a&&Gs.delete(s)}}))}ensureClonedImpl(e,t,r,o){return Fs(this,void 0,void 0,(function*(){var n,s,i;o.log("info",`MarketplaceCacheManager: Ensuring cloned ${e} at ${t}@${r}`,{marketplaceId:e,gitUrl:t,ref:r});const a=r.trim();let l,c=t.startsWith("git@")||t.startsWith("ssh://")?null:function(e){const t=Ds(e);return null!==t&&function(e){switch(e.provider){case"github":return!0;case"generic":return null===function(e){const t=e.toLowerCase();return t.includes("gitlab")?"GitLab":t.includes("bitbucket")?"Bitbucket":t.includes("gitea")||t.includes("codeberg")?"Gitea/Codeberg":t.includes("azure")&&t.includes("dev")?"Azure DevOps":null}(e.host);case"gitlab":case"bitbucket":return!1;default:return e.provider,!1}}(t)?`git@${t.host}:${t.owner}/${t.repo}.git`:null}(t);if(null!==c)try{l=(yield As(c,a,{sshBatchMode:!0,extraGitConfig:null===(n=this.options)||void 0===n?void 0:n.extraGitConfig})).fullSha}catch(e){o.log("error","Failed to resolve remote ref using SSH URL, falling back to HTTPS",{gitUrl:t,ref:r,error:String(e),errorCategory:Ws(e)}),c=null,l=(yield As(t,a,{extraGitConfig:null===(s=this.options)||void 0===s?void 0:s.extraGitConfig})).fullSha}else l=(yield As(t,a,{extraGitConfig:null===(i=this.options)||void 0===i?void 0:i.extraGitConfig})).fullSha;const u=this.getCanonicalCloneDir(t,l),d=this.getLegacyCloneDir(e,a);o.log("info",`MarketplaceCacheManager: Resolved clone directory for ${e} at ${t}@${r} to ${u}`,{marketplaceId:e,resolvedRef:l,originalRef:a});const p=performance.now(),h=(e,t)=>{o.increment(`marketplace_cache_manager.ensure_cloned.${e}`,1,t),o.distribution(`marketplace_cache_manager.ensure_cloned.${e}.duration`,performance.now()-p,t)};return(yield this.isCloneComplete(u))?(yield this.pruneSiblingCloneDirs(t,l,d),h("cache_hit"),u):(o.increment("marketplace_cache_manager.ensure_cloned.cache_miss",1),this.cloneViaStaging(u,t,c,l,d,r,o,h))}))}cloneViaStaging(e,t,r,o,n,s,i,a){return Fs(this,void 0,void 0,(function*(){yield this.cleanStaleStagingDirs();const l=yield this.createStagingDir();i.log("info",`MarketplaceCacheManager: Cloning ${t}@${s} into staging directory: ${l}`,{gitUrl:t,ref:s,cloneDir:e});try{if(null!==r)try{yield this.cloneResolvedRef(l,r,o,{sshBatchMode:!0})}catch(e){i.log("error","Falling back to HTTPS clone due to SSH clone failure",{gitUrl:t,ref:s,error:String(e),errorCategory:Ws(e)}),yield(0,fo.rm)(l,{recursive:!0,force:!0}),yield(0,fo.mkdir)(l,{recursive:!0}),yield this.cloneResolvedRef(l,t,o)}else yield this.cloneResolvedRef(l,t,o);const c=yield this.moveToCanonicalDir(l,e);return yield this.pruneSiblingCloneDirs(t,o,n),a("cache_write_success"),c}catch(e){const r=Ws(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{try{yield(0,fo.rm)(l,{recursive:!0,force:!0})}catch(e){}}}))}isCloneComplete(e){return Fs(this,void 0,void 0,(function*(){try{if(!(yield(0,fo.stat)(e)).isDirectory())return!1;const t=yield(0,fo.readdir)(e);return t.includes(".git")&&t.length>1}catch(e){return!1}}))}getPluginDir(e,t){return $s(e,t)}copyPluginToDir(e,t){return Fs(this,void 0,void 0,(function*(){yield(0,fo.mkdir)(t,{recursive:!0}),yield(0,fo.cp)(e,t,{recursive:!0,verbatimSymlinks:!0})}))}readManifest(e){return Fs(this,arguments,void 0,(function*(e,t={}){var r;const o=function(e,t){var r,o;return JSON.stringify({clonePath:e,repoName:null!==(r=t.repoName)&&void 0!==r?r:null,fallbackId:null!==(o=t.fallbackId)&&void 0!==o?o:null})}(e,t);if(this.manifestCache.has(o))return null!==(r=this.manifestCache.get(o))&&void 0!==r?r:null;for(const r of Cn){const n=(0,a.join)(e,r);let s;try{s=yield(0,fo.readFile)(n,"utf-8")}catch(e){continue}const i=Yn(s,t);if(i.success)return this.manifestCache.set(o,i.data),i.data}return this.manifestCache.set(o,null),null}))}resolvePluginPath(e,t){return Fs(this,void 0,void 0,(function*(){var r;const o=yield this.readManifest(e);if(!o)return null;const n=o.plugins.find((e=>e.name===t.toLowerCase()));if(!n)return null;const s=Qn(n.source,null===(r=o.metadata)||void 0===r?void 0:r.pluginRoot);return s&&es(s)?s:null}))}discoverPlugins(e){return Fs(this,void 0,void 0,(function*(){var t;const r=yield this.readManifest(e);if(!r)return[];const o=[],n=function(e,t){var r,o,n;const s=[];for(const i of e){const e=i.source;if("string"!=typeof e)switch(e.source){case"github":s.push({entry:i,kind:"external-github",externalUrl:`https://github.com/${e.repo}.git`,externalRef:e.ref,externalSha:e.sha,effectiveRef:null!==(r=e.sha)&&void 0!==r?r:e.ref});break;case"url":s.push({entry:i,kind:"external-url",externalUrl:e.url,externalRef:e.ref,externalSha:e.sha,effectiveRef:null!==(o=e.sha)&&void 0!==o?o:e.ref});break;case"git-subdir":s.push({entry:i,kind:"external-git-subdir",externalUrl:e.url,externalRef:e.ref,externalSha:e.sha,effectiveRef:null!==(n=e.sha)&&void 0!==n?n:e.ref,subdirPath:e.path})}else{const r=Qn(e,t);null!==r?s.push({entry:i,kind:"local",localPath:r}):s.push({entry:i,kind:"unresolvable",rawSource:e})}}return s}(r.plugins,null===(t=r.metadata)||void 0===t?void 0:t.pluginRoot);for(const e of n){const{name:t,displayName:r,description:n,version:s}=e.entry,i={name:t,displayName:r,description:n,version:s};switch(e.kind){case"local":es(e.localPath)&&o.push(Object.assign(Object.assign({},i),{sourceType:"local",gitPath:e.localPath}));break;case"external-github":o.push(Object.assign(Object.assign({},i),{sourceType:"github",gitUrl:e.externalUrl,gitRef:e.externalRef,sha:e.externalSha}));break;case"external-url":o.push(Object.assign(Object.assign({},i),{sourceType:"url",gitUrl:e.externalUrl,gitRef:e.externalRef,sha:e.externalSha}));break;case"external-git-subdir":o.push(Object.assign(Object.assign({},i),{sourceType:"git-subdir",gitUrl:e.externalUrl,gitRef:e.externalRef,sha:e.externalSha,subdirPath:e.subdirPath}))}}return o}))}}Vs.STALE_STAGING_THRESHOLD_MS=3e5;var Js=function(e,t,r,o){return new(r||(r=Promise))((function(n,s){function i(e){try{l(o.next(e))}catch(e){s(e)}}function a(e){try{l(o.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(i,a)}l((o=o.apply(e,t||[])).next())}))};const Ks=(0,ln.debuglog)("cursor-plugins");function Zs(e){var t;const r=null===(t=e.name)||void 0===t?void 0:t.trim();return void 0!==r&&r.length>0?r:e.pluginId}function Ys(e,t){return void 0!==(null==e?void 0:e.marketplace)?e.marketplace:void 0!==(null==e?void 0:e.marketplaceId)?(null!=t?t:[]).find((t=>void 0!==t.id&&String(t.id)===String(e.marketplaceId))):void 0}function Xs(e,t){var r,o;if(e.pinnedGitRef)return e.pinnedGitRef;if(null===(r=e.plugin)||void 0===r?void 0:r.gitRef)return e.plugin.gitRef;const n=Ys(e.plugin,t),s=null===(o=e.plugin)||void 0===o?void 0:o.gitUrl,i=null==n?void 0:n.gitUrl;return s&&i&&s!==i||!(null==n?void 0:n.gitRef)?"main":n.gitRef}const Qs="backend-git://";function ei(e,t,r){const o=r?`#${encodeURIComponent(r)}`:"";return`${Qs}${encodeURIComponent(e)}@${encodeURIComponent(t)}${o}`}const ti="backend-release://";function ri(e){const t=e.tag?`@${encodeURIComponent(e.tag)}`:"";return`${ti}${encodeURIComponent(e.repo)}#${encodeURIComponent(e.asset)}${t}`}function oi(e){if(!e.startsWith(ti))return null;const t=e.slice(18),r=t.indexOf("#");if(r<0)return null;const o=decodeURIComponent(t.slice(0,r)),n=t.slice(r+1),s=n.lastIndexOf("@");return{repo:o,asset:s>=0?decodeURIComponent(n.slice(0,s)):decodeURIComponent(n),tag:s>=0?decodeURIComponent(n.slice(s+1)):void 0}}const ni=/^[0-9a-f]{7,40}$/i;function si(e){const t=Ds(e);return t?`${Ms(t.host.replace(/^www\./i,"")).toLowerCase()}\0${t.owner.toLowerCase()}\0${t.repo.toLowerCase()}`:null}function ii(e,t){if(e.trim()===t.trim())return!0;const r=si(e),o=si(t);return null!==r&&r===o}const ai=104857600;function li(e,t,r,o,s,l){return Js(this,void 0,void 0,(function*(){const c=yield function(e){return Js(this,void 0,void 0,(function*(){const{repo:t,asset:r,tag:o}=e,{apiBase:s,ownerRepo:i,host:a}=function(e){const t=e.split("/");if(3===t.length)return{apiBase:`https://${t[0]}/api/v3`,ownerRepo:`${t[1]}/${t[2]}`,host:t[0]};if(2===t.length)return{apiBase:"https://api.github.com",ownerRepo:e,host:"github.com"};throw new Error(`Invalid release repo format: ${e}`)}(t),l="github.com"===a&&void 0!==e.githubToken&&e.githubToken.length>0?{Authorization:`token ${e.githubToken}`}:{},c=o?`${s}/repos/${i}/releases/tags/${encodeURIComponent(o)}`:`${s}/repos/${i}/releases/latest`,u=yield fetch(c,{headers:Object.assign({Accept:"application/vnd.github.v3+json","User-Agent":"CursorPluginInstaller"},l)});if(!u.ok)throw new Error(`Failed to fetch release from ${c}: ${u.status} ${u.statusText}`);const d=yield u.json(),p=d.assets.find((e=>e.name===r));if(!p){const e=d.assets.map((e=>e.name)).join(", ");throw new Error(`Release asset "${r}" not found. Available assets: ${e}`)}if(p.size>ai)throw new Error(`Release asset "${r}" exceeds maximum size of 104857600 bytes (actual: ${p.size})`);const h=new URL(p.browser_download_url);if("https:"!==h.protocol||!ci(h.hostname,a))throw new Error(`Refusing to download release asset from untrusted host: ${h.hostname}`);const m=yield fetch(p.browser_download_url,{headers:Object.assign({"User-Agent":"CursorPluginInstaller",Accept:"application/octet-stream"},l)});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||!ci(e.hostname,a))throw new Error(`Refusing to download release asset: redirected to untrusted host: ${e.hostname}`)}const f=Buffer.from(yield m.arrayBuffer());if(f.byteLength>ai)throw new Error(`Release asset "${r}" actual download size exceeds maximum of 104857600 bytes (actual: ${f.byteLength})`);if(e.expectedSha256){const t=(0,n.createHash)("sha256").update(f).digest("hex");if(t!==e.expectedSha256)throw new Error(`Release asset "${r}" integrity check failed: expected SHA-256 ${e.expectedSha256}, got ${t}`)}return f}))}({repo:e,asset:t,tag:r,expectedSha256:s,githubToken:l}),u=c.byteLength;yield(0,fo.mkdir)(o,{recursive:!0});const d=yield(0,fo.mkdtemp)((0,a.join)((0,i.tmpdir)(),"release-asset-")),p=(0,a.join)(d,"asset.tar.gz"),h=(0,a.join)(d,"extracted");try{yield(0,fo.writeFile)(p,c),yield(0,fo.mkdir)(h,{recursive:!0});let e=0,t=0;yield gs.x({file:p,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(u>0&&e/u>100)throw new Error("Release archive has suspicious compression ratio (>100x).")}});const r=yield(0,fo.readdir)(h,{withFileTypes:!0}),n=r.filter((e=>e.isDirectory())),s=r.filter((e=>e.isFile()));let i=h;if(1===n.length&&0===s.length){const e=(0,a.join)(h,n[0].name);(yield(0,fo.readdir)(e)).some((e=>_n.includes(e)))&&(i=e)}const l=yield(0,fo.readdir)(i);yield Promise.all(l.map((e=>(0,fo.cp)((0,a.join)(i,e),(0,a.join)(o,e),{recursive:!0,verbatimSymlinks:!0}))))}finally{yield(0,fo.rm)(d,{recursive:!0,force:!0}).catch((()=>{}))}}))}function ci(e,t){return!(e!==t&&!e.endsWith(".githubusercontent.com"))||("github.com"===t?"github.com"===e:e.endsWith(`.${t}`))}class ui{constructor(e,t,r,o,n){var s,i,a,l,c,u;this.getEffectiveUserPlugins=e;const d="string"==typeof t||void 0===t?{marketplaceCacheRoot:t,pluginLogger:r,marketplaceCacheOptions:o,listOptions:n}:t,p=null!==(s=d.marketplaceCacheOptions)&&void 0!==s?s:o;this.pluginLogger=null!==(a=null!==(i=d.pluginLogger)&&void 0!==i?i:r)&&void 0!==a?a:un,this.extraGitConfig=d.extraGitConfig,this.githubToken=d.githubToken,this.marketplaceCache=d.marketplaceCacheRoot?new Vs(d.marketplaceCacheRoot,Object.assign(Object.assign({},p),{extraGitConfig:null!==(l=null==p?void 0:p.extraGitConfig)&&void 0!==l?l:d.extraGitConfig})):void 0;const h=null!==(c=d.listOptions)&&void 0!==c?c:n;this.allowedMarketplaceNames=(null==h?void 0:h.allowedMarketplaceNames)?new Set(h.allowedMarketplaceNames):void 0,this.enableInlinePlugins=null!==(u=null==h?void 0:h.enableInlinePlugins)&&void 0!==u&&u}isMarketplaceAllowed(e){return void 0===this.allowedMarketplaceNames||void 0!==(null==e?void 0:e.name)&&this.allowedMarketplaceNames.has(e.name)}listEnabledPlugins(e,t){return Js(this,void 0,void 0,(function*(){var e,t,r,o,s,i,a,l,c,u,d,p,h,m,f;const g=yield this.getEffectiveUserPlugins(),v=null!==(e=g.plugins)&&void 0!==e?e:[],y=null!==(t=g.marketplaces)&&void 0!==t?t:[],w=[],b=[],S=new Map,k=(e,t)=>Js(this,void 0,void 0,(function*(){const r=`${e}\0${t}`;let o=S.get(r);if(!o){const n=void 0!==this.extraGitConfig?{extraGitConfig:this.extraGitConfig}:void 0;o=(void 0!==n?yield As(e,t,n):yield As(e,t)).fullSha,S.set(r,o)}return o}));for(const e of v){if(!e.isEnabled||!(null===(r=e.plugin)||void 0===r?void 0:r.name))continue;const t=e.plugin,g=Ys(t,y);if(!this.isMarketplaceAllowed(g)){this.pluginLogger.log("info",`Skipping plugin ${t.name} because marketplace ${null!==(o=null==g?void 0:g.name)&&void 0!==o?o:"<none>"} is not allowed`,{pluginId:t.name,marketplaceName:null==g?void 0:g.name,allowedMarketplaceNames:void 0!==this.allowedMarketplaceNames?Array.from(this.allowedMarketplaceNames):void 0});continue}const v=Zs({name:t.name,pluginId:void 0!==t.id?String(t.id):null!==(s=t.name)&&void 0!==s?s:""}),S=v;if(!t.gitUrl){if(!this.enableInlinePlugins){this.pluginLogger.log("info",`Skipping plugin ${v} without gitUrl (enableInlinePlugins=false)`,{pluginId:S});continue}const r=e.inlineContentJson;if(!r){this.pluginLogger.log("info",`Skipping DB-inline plugin ${v}: no inline content provided`,{pluginId:S});continue}const o=(0,n.createHash)("sha256").update(`${null!==(i=t.id)&&void 0!==i?i:"0"}:${null!==(a=t.updatedAt)&&void 0!==a?a:"0"}`).digest("hex").slice(0,40),s=(null==g?void 0:g.name)?{id:void 0!==g.id?`${g.name}-${g.id}`:`${g.name}-inline`,name:g.name}:void 0;this.pluginLogger.log("info",`BackendMarketplaceClient: Adding DB-inline plugin: ${S}`,{pluginId:S,marketplaceId:null!==(l=null==s?void 0:s.id)&&void 0!==l?l:"unknown",version:o}),w.push({pluginId:S,pluginDbId:void 0!==t.id?String(t.id):void 0,configuredVariables:e.configuredVariables,isTeamRequired:e.isTeamRequired,name:v,version:o,downloadUrl:`inline://${null!==(c=t.id)&&void 0!==c?c:S}`,marketplaceDbId:void 0!==(null==g?void 0:g.id)?String(g.id):void 0,marketplace:s,inlineContentJson:r});continue}const E=t.gitUrl,x=Xs(e,y),_=Es(t,x);let C;C=void 0!==_?ri({repo:_.releaseRepo,asset:_.releaseAsset,tag:_.releaseTag}):ei(E,x,null!==(u=t.gitPath)&&void 0!==u?u:void 0);const P=null!==(d=null==g?void 0:g.gitRef)&&void 0!==d?d:x;let R;try{R=void 0!==_?`release/${_.releaseTag}`:yield k(E,x)}catch(e){this.pluginLogger.captureException(e,{error_type:"resolve_version_sha"}),this.pluginLogger.log("error",`Failed to resolve version for plugin ${v}@${x}, skipping plugin`,{pluginId:S,ref:x,error:String(e)});const t=e instanceof Error?e.message:String(e);b.push({pluginName:v,pluginId:S,marketplaceName:null==g?void 0:g.name,errorMessage:t,errorType:/timed?\s*out/i.test(t)?"timeout":"clone"});continue}let T=P;if(null==g?void 0:g.gitUrl){const e=ii(E,g.gitUrl),t=e?E:g.gitUrl,r=e?x:P;try{T=yield k(t,r)}catch(e){this.pluginLogger.captureException(e,{error_type:"resolve_marketplace_cache_ref"}),this.pluginLogger.log("warn",`Failed to resolve marketplace cache ref for plugin ${v} from ${t}@${r}, falling back to raw ref`,{pluginId:S,cacheRepoUrl:t,cacheRef:r,error:String(e)})}}const I=(null==g?void 0:g.name)?Object.assign({id:void 0!==g.id?`${g.name}-${g.id}`:`${g.name}-${encodeURIComponent(null!==(p=g.gitUrl)&&void 0!==p?p:"project")}`,name:g.name},g.gitUrl&&{gitUrl:g.gitUrl,gitRef:T}):void 0;this.pluginLogger.log("info",`BackendMarketplaceClient: Adding enabled plugin: ${S} from ${T} at ${t.gitPath}`,{pluginId:S,marketplaceId:null!==(h=null==I?void 0:I.id)&&void 0!==h?h:"unknown",gitPath:null!==(m=t.gitPath)&&void 0!==m?m:void 0,gitRef:T}),w.push({pluginId:S,pluginDbId:void 0!==t.id?String(t.id):void 0,configuredVariables:e.configuredVariables,isTeamRequired:e.isTeamRequired,name:v,version:R,downloadUrl:C,marketplaceDbId:void 0!==(null==g?void 0:g.id)?String(g.id):void 0,marketplace:I,gitPath:null!==(f=t.gitPath)&&void 0!==f?f:void 0})}return{plugins:w,listFailures:b}}))}installPlugin(e,t){return Js(this,void 0,void 0,(function*(){if(e.inlineContentJson)yield function(e){return t=this,r=void 0,n=function*(){var t,r;const{targetDir:o,inlineContentJson:n,pluginName:s}=e,i=JSON.parse(n);yield(0,fo.mkdir)(o,{recursive:!0});const l={};if(i.rules&&i.rules.length>0){const e=(0,a.join)(o,"rules");yield(0,fo.mkdir)(e,{recursive:!0});const t=[];for(const r of i.rules){if(!r.content)continue;if(!1===r.isActive)continue;const o=`${(0,h.Nz)(r.name)}.md`,n=[];n.push(`description: ${Ns(r.name)}`),r.globs&&r.globs.length>0&&n.push(`globs: ${Ns(r.globs.join(", "))}`),n.push(`alwaysApply: ${!0===r.isRequired}`);const s=`---\n${n.join("\n")}\n---\n\n`;yield(0,fo.writeFile)((0,a.join)(e,o),s+r.content,"utf-8"),t.push(`rules/${o}`)}t.length>0&&(l.rules=t)}if(i.commands&&i.commands.length>0){const e=(0,a.join)(o,"commands");yield(0,fo.mkdir)(e,{recursive:!0});const t=[];for(const r of i.commands){if(!r.content)continue;if(!1===r.isActive)continue;const o=`${(0,h.Nz)(r.name)}.md`,n=r.description?`---\ndescription: ${Ns(r.description)}\n---\n\n`:"";yield(0,fo.writeFile)((0,a.join)(e,o),n+r.content,"utf-8"),t.push(`commands/${o}`)}t.length>0&&(l.commands=t)}if(i.hooks&&i.hooks.length>0){const e=(0,a.join)(o,"hooks");yield(0,fo.mkdir)(e,{recursive:!0});const n={};for(const e of i.hooks){const o=e.hookStep;o&&!1!==e.isActive&&js(e)&&(n[o]||(n[o]=[]),"prompt"===e.hookType?n[o].push(Object.assign({type:"prompt",prompt:null!==(t=e.promptContent)&&void 0!==t?t:""},e.promptModel?{model:e.promptModel}:{})):n[o].push({type:"command",command:null!==(r=e.scriptContent)&&void 0!==r?r:""}))}yield(0,fo.writeFile)((0,a.join)(e,"hooks.json"),JSON.stringify({version:1,hooks:n},null,2),"utf-8")}if(i.mcpServers&&i.mcpServers.length>0){const e={};for(const t of i.mcpServers)t.config&&(e[t.name]=t.config);Object.keys(e).length>0&&(yield(0,fo.writeFile)((0,a.join)(o,".mcp.json"),JSON.stringify({mcpServers:e},null,2),"utf-8"))}const c=Object.assign({name:s},l),u=(0,a.join)(o,".cursor-plugin");yield(0,fo.mkdir)(u,{recursive:!0}),yield(0,fo.writeFile)((0,a.join)(u,"plugin.json"),JSON.stringify(c,null,2),"utf-8")},new((o=void 0)||(o=Promise))((function(e,s){function i(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(t){var r;t.done?e(t.value):(r=t.value,r instanceof o?r:new o((function(e){e(r)}))).then(i,a)}l((n=n.apply(t,r||[])).next())}));var t,r,o,n}({targetDir:t,inlineContentJson:e.inlineContentJson,pluginName:e.name});else{if(null===oi(e.downloadUrl))try{if(yield this.tryInstallFromMarketplaceCache(e,t))return}catch(t){this.pluginLogger.captureException(t,{error_type:"install_plugin_from_marketplace_cache"}),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)})}yield function(e,t){return Js(this,arguments,void 0,(function*(e,t,r=un,o,n){const s=oi(e.downloadUrl);if(s){if(e.gitPath){const r=yield(0,fo.mkdtemp)((0,a.join)((0,i.tmpdir)(),"release-plugin-"));try{yield li(s.repo,s.asset,s.tag,r,null==n?void 0:n.expectedReleaseAssetSha256,null==n?void 0:n.githubToken);const o=$s(r,e.gitPath);yield(0,fo.mkdir)(t,{recursive:!0}),yield(0,fo.cp)(o,t,{recursive:!0,verbatimSymlinks:!0})}finally{yield(0,fo.rm)(r,{recursive:!0,force:!0}).catch((()=>{}))}}else yield li(s.repo,s.asset,s.tag,t,null==n?void 0:n.expectedReleaseAssetSha256,null==n?void 0:n.githubToken);return}const l=function(e){if(!e.startsWith(Qs))return null;const t=e.slice(14),r=t.indexOf("#"),o=r>=0?t.slice(0,r):t,n=r>=0?t.slice(r+1):void 0,s=o.lastIndexOf("@");return s<0?null:{gitUrl:decodeURIComponent(o.slice(0,s)),ref:decodeURIComponent(o.slice(s+1)),gitPath:n?decodeURIComponent(n):void 0}}(e.downloadUrl);if(!l)throw new Error(`Invalid download URL format for plugin ${e.pluginId}: ${e.downloadUrl}`);const c=yield(0,fo.mkdtemp)((0,a.join)((0,i.tmpdir)(),"backend-plugin-"));try{let n;if(yield function(e,t,r){return Js(this,arguments,void 0,(function*(e,t,r,o=un,n){const s=performance.now(),i=ni.test(t);"HEAD"===t.toUpperCase()?yield Cs(["clone","--depth","1",e,r],{extraGitConfig:n}):i?(yield Cs(["init"],{cwd:r,extraGitConfig:n}),yield Cs(["remote","add","origin",e],{cwd:r,extraGitConfig:n}),yield Cs(["fetch","--depth","1","origin",t],{cwd:r,extraGitConfig:n}),yield Cs(["checkout","FETCH_HEAD"],{cwd:r,extraGitConfig:n})):yield Cs(["clone","--depth","1","--branch",t,e,r],{extraGitConfig:n});const a=(performance.now()-s).toFixed(1);Ks("shallowClone %s@%s completed in %sms",e,t,a),o.log("info",`shallowClone ${e}@${t} completed in ${a}ms`)}))}(l.gitUrl,l.ref,c,r,o),l.gitPath)n=$s(c,l.gitPath);else{const t=yield function(e,t){return Js(this,void 0,void 0,(function*(){var r;for(const o of Cn){const n=(0,a.join)(e,o);let s;try{s=yield(0,fo.readFile)(n,"utf-8")}catch(e){continue}const i=Yn(s);if(!i.success)return{type:"manifest-unresolved",reason:`Invalid marketplace manifest at ${o}: ${i.error}`};const l=i.data,c=l.plugins.find((e=>e.name===t.toLowerCase()));if(!c)return{type:"manifest-unresolved",reason:`Plugin ${JSON.stringify(t)} not found in ${o}`};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 u=Qn(c.source,null===(r=l.metadata)||void 0===r?void 0:r.pluginRoot);return u&&es(u)?{type:"resolved",gitPath:u}:{type:"manifest-unresolved",reason:`Plugin ${JSON.stringify(t)} has unresolved or unsafe source path`}}return{type:"no-manifest"}}))}(c,e.name);if("resolved"===t.type)n=$s(c,t.gitPath);else{if("manifest-unresolved"===t.type)throw new Error(`Unable to install plugin ${JSON.stringify(e.name)} without gitPath: ${t.reason}`);n=c}}yield(0,fo.mkdir)(t,{recursive:!0}),yield(0,fo.cp)(n,t,{recursive:!0,verbatimSymlinks:!0})}finally{yield(0,fo.rm)(c,{recursive:!0,force:!0}).catch((()=>{}))}}))}(e,t,this.pluginLogger,this.extraGitConfig,{githubToken:this.githubToken})}}))}tryInstallFromMarketplaceCache(e,t){return Js(this,void 0,void 0,(function*(){var r,o,n,s;const i=this.marketplaceCache,a=e.marketplace;if(!i||!a||!a.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:null===(r=e.marketplace)||void 0===r?void 0:r.id}),!1;const l=yield i.ensureCloned(a.id,a.gitUrl,null!==(o=a.gitRef)&&void 0!==o?o:"main",this.pluginLogger),c=null!==(n=e.gitPath)&&void 0!==n?n:yield i.resolvePluginPath(l,e.name);if(!c)return this.pluginLogger.log("info","No git path found for plugin, skipping cache check",{pluginId:e.pluginId,name:e.name,version:e.version,marketplaceId:null===(s=e.marketplace)||void 0===s?void 0:s.id}),!1;const u=i.getPluginDir(l,c);return yield i.copyPluginToDir(u,t),!0}))}discoverMarketplacePlugins(e,t,r){return Js(this,void 0,void 0,(function*(){const o=this.marketplaceCache;if(!o)throw new Error("discoverMarketplacePlugins requires a MarketplaceCacheManager (marketplaceCacheRoot)");const n=yield o.ensureCloned(e,t,r);return o.discoverPlugins(n)}))}}function di(e,t,r,o,n){return new ui(e,t,r,o,n)}function pi(e){return e.replace(/\\/g,"/").replace(/\/+$/,"")||"/"}var hi=r("../../node_modules/.pnpm/js-yaml@4.1.0/node_modules/js-yaml/dist/js-yaml.mjs"),mi=function(e,t,r,o){return new(r||(r=Promise))((function(n,s){function i(e){try{l(o.next(e))}catch(e){s(e)}}function a(e){try{l(o.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(i,a)}l((o=o.apply(e,t||[])).next())}))};const fi=[".md",".mdc",".markdown"],gi=[...fi,".txt"],vi=/^---\s*\n([\s\S]*?)\n---/,yi="";function wi(e){return e.trim().toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9.-]/g,"")}function bi(e){var t,r;const o=e.match(vi);if(!o)return{};try{const e=hi.Ay.load(o[1],{schema:hi.Ay.JSON_SCHEMA});if(!e||"object"!=typeof e)return{};const n=null!==e.metadata&&"object"==typeof e.metadata?e.metadata:void 0,s=Si(null!==(t=e.environments)&&void 0!==t?t:null==n?void 0:n.environments);return{disabledEnvironments:Si(null!==(r=e["disabled-environments"])&&void 0!==r?r:null==n?void 0:n.disabledEnvironments),environments:s,name:"string"==typeof e.name?e.name:void 0,description:"string"==typeof e.description?e.description:void 0}}catch(e){const t=o[1],r=t.match(/^name:\s*(.+)$/m),n=t.match(/^description:\s*(.+)$/m);return r||n?{name:r?r[1].trim():void 0,description:n?n[1].trim():void 0}:{}}}function Si(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 ki(e){return wi((0,a.basename)(e).replace(/\.(md|mdc|markdown|txt)$/i,""))}function Ei(e){const t=new Set,r=[];for(const o of e)t.has(o.name)||(t.add(o.name),r.push(o));return r}class xi{constructor(e){this.fetcher=e}discoverComponents(){return mi(this,arguments,void 0,(function*(e={}){var t,r;const o=null!==(t=e.basePath)&&void 0!==t?t:"",n=o?`${o}/`:"",s=null!==(r=e.metadataOnly)&&void 0!==r&&r,i=e.manifest;let a;try{a=yield this.fetcher.listDirectory(o)}catch(e){a=[]}const l=new Set(a.filter((e=>"dir"===e.type)).map((e=>e.name.toLowerCase()))),c=new Set(a.filter((e=>"file"===e.type)).map((e=>e.name))),u=is.filter((e=>c.has(e))),d=a.some((e=>"file"===e.type&&"SKILL.md"===e.name)),[p,h,m,f,g,v,...y]=yield Promise.all([d&&void 0===(null==i?void 0:i.skills)?this.discoverRootSkill(n,s):Promise.resolve(null),void 0!==(null==i?void 0:i.skills)?this.discoverFromManifestPaths(n,i.skills,!0,fi,s):l.has("skills")?this.discoverSkills(`${n}skills`,s):Promise.resolve([]),void 0!==(null==i?void 0:i.agents)?this.discoverFromManifestPaths(n,i.agents,!1,fi,s):l.has("agents")?this.discoverMarkdownComponents(`${n}agents`,fi,s):Promise.resolve([]),void 0!==(null==i?void 0:i.hooks)?this.discoverHooksFromManifest(n,i.hooks,s):l.has("hooks")?this.discoverHooksFromJson(`${n}hooks/hooks.json`,s):Promise.resolve([]),void 0!==(null==i?void 0:i.commands)?this.discoverFromManifestPaths(n,i.commands,!1,gi,s):l.has("commands")?this.discoverMarkdownComponents(`${n}commands`,gi,s):Promise.resolve([]),void 0!==(null==i?void 0:i.rules)?this.discoverFromManifestPaths(n,i.rules,!1,fi,s):l.has("rules")?this.discoverMarkdownComponents(`${n}rules`,fi,s):Promise.resolve([]),...u.map((e=>this.discoverMcpServers(`${n}${e}`)))]);let w=[];void 0!==(null==i?void 0:i.mcpServers)&&(w=yield this.extractMcpServersFromManifest(n,i.mcpServers));const b=this.mergeMcpServers(...y,w);return{skills:Ei(p?[p,...h]:h),agents:Ei(m),hooks:f,commands:Ei(g),rules:Ei(v),mcpServers:b}}))}discoverHooksFromJson(e){return mi(this,arguments,void 0,(function*(e,t=!1){try{if(!(yield this.fetcher.fileExists(e)))return[];const{content:r}=yield this.fetcher.fetchFile(e),o=JSON.parse(r);return!o.hooks||"object"!=typeof o.hooks||Array.isArray(o.hooks)?[]:Object.keys(o.hooks).map((r=>({name:wi(r),path:e,description:t?yi:`Hook: ${r}`})))}catch(e){return[]}}))}discoverHooksFromManifest(e,t){return mi(this,arguments,void 0,(function*(e,t,r=!1){var o;if("string"==typeof t){if(!es(t))return[];const o=`${e}${t.replace(/^\.\//,"")}`;return o.endsWith(".json")?this.discoverHooksFromJson(o,r):this.discoverHooksFromJson(`${o}/hooks.json`,r)}const n=null!==(o=t.hooks)&&void 0!==o?o:t;return!n||"object"!=typeof n||Array.isArray(n)?[]:Object.keys(n).map((e=>({name:wi(e),path:"manifest",description:r?yi:`Hook: ${e}`})))}))}discoverFromManifestPaths(e,t){return mi(this,arguments,void 0,(function*(e,t,r=!1,o=fi,n=!1){var s,i;if("string"==typeof t){if(!es(t))return[];const s=`${e}${t.replace(/^\.\//,"")}`.replace(/\/$/,"");return r?this.discoverSkills(s,n):this.discoverMarkdownComponents(s,o,n)}const a=[];for(const o of t)try{if(!es(o))continue;const t=`${e}${o.replace(/^\.\//,"")}`;if(r){const e=t.endsWith("SKILL.md")?t:`${t.replace(/\/$/,"")}/SKILL.md`;if(!(yield this.fetcher.fileExists(e))){const e=t.replace(/\/$/,""),r=yield this.discoverSkills(e,n);a.push(...r);continue}let r=ki(t.endsWith("SKILL.md")?t.slice(0,-8).replace(/\/$/,""):t),o=n?yi:void 0;if(!n){const{content:t}=yield this.fetcher.fetchFile(e),n=bi(t);if(r=null!==(s=n.name)&&void 0!==s?s:r,o=n.description,r){const t={disabledEnvironments:n.disabledEnvironments,environments:n.environments,name:wi(r),path:e};void 0!==o&&(t.description=o),a.push(t)}continue}if(r){const t={name:wi(r),path:e};void 0!==o&&(t.description=o),a.push(t)}}else{if(!(yield this.fetcher.fileExists(t)))continue;let e=ki(t),r=n?yi:void 0;if(!n){const{content:o}=yield this.fetcher.fetchFile(t),n=bi(o);e=null!==(i=n.name)&&void 0!==i?i:e,r=n.description}if(e){const o={name:wi(e),path:t};void 0!==r&&(o.description=r),a.push(o)}}}catch(e){}return a}))}extractMcpServersFromManifest(e,t){return mi(this,void 0,void 0,(function*(){const r=[];if("string"==typeof t){const o=yield this.loadMcpServersFromPath(e,t);r.push(...o)}else if(Array.isArray(t)){for(const o of t)if("string"==typeof o){const t=yield this.loadMcpServersFromPath(e,o);r.push(...t)}else if("object"==typeof o&&null!==o){const e=this.extractServersFromInlineConfig(o,"manifest");r.push(...e)}}else if("object"==typeof t&&null!==t){const e=this.extractServersFromInlineConfig(t,"manifest");r.push(...e)}return r}))}loadMcpServersFromPath(e,t){return mi(this,void 0,void 0,(function*(){var r;if(!es(t))return[];const o=`${e}${t}`;try{const{content:e}=yield this.fetcher.fetchFile(o),t=JSON.parse(e),n=null!==(r=t.mcpServers)&&void 0!==r?r:t;return"object"!=typeof n||null===n?[]:this.extractServersFromInlineConfig(n,o)}catch(e){return[]}}))}extractServersFromInlineConfig(e,t){const r=[];for(const[o,n]of Object.entries(e))"mcpServers"!==o&&!ls(o,n)&&cs(n)&&r.push({name:wi(o),path:t});return r}mergeMcpServers(...e){const t=new Set,r=[];for(const o of e)for(const e of o)t.has(e.name)||(t.add(e.name),r.push(e));return r}discoverMarkdownComponents(e){return mi(this,arguments,void 0,(function*(e,t=fi,r=!1,o=new Set){let n;try{n=yield this.fetcher.listDirectory(e,o)}catch(e){return[]}const s=n.filter((e=>"file"===e.type&&t.some((t=>e.name.endsWith(t))))),i=n.filter((e=>"dir"===e.type)),[a,l]=yield Promise.all([Promise.all(s.map((e=>mi(this,void 0,void 0,(function*(){try{let t=ki(e.name),o=r?yi:void 0;if(!r){const{content:r}=yield this.fetcher.fetchFile(e.path),n=bi(r);t=n.name?wi(n.name):t,o=n.description}if(!t)return null;const n={name:t,path:e.path};return void 0!==o&&(n.description=o),n}catch(e){return null}}))))),Promise.all(i.map((e=>this.discoverMarkdownComponents(e.path,t,r,o))))]);return[...a.filter((e=>null!==e)),...l.flat()]}))}discoverRootSkill(e){return mi(this,arguments,void 0,(function*(e,t=!1){try{const r=`${e}SKILL.md`,o=(0,a.basename)(e.replace(/[\\/]+$/,""));let n=wi(t?o||ki(r):o),s=t?yi:void 0;if(!t){const{content:e}=yield this.fetcher.fetchFile(r),t=bi(e);if(n=t.name?wi(t.name):n,s=t.description,!n)return null;const o={disabledEnvironments:t.disabledEnvironments,environments:t.environments,name:n,path:r};return void 0!==s&&(o.description=s),o}return n?Object.assign({name:n,path:r},void 0!==s?{description:s}:{}):null}catch(e){return null}}))}discoverSkills(e){return mi(this,arguments,void 0,(function*(e,t=!1){let r;try{r=yield this.fetcher.listDirectory(e)}catch(e){return[]}const o=r.filter((e=>"dir"===e.type));return(yield Promise.all(o.map((e=>mi(this,void 0,void 0,(function*(){try{const r=`${e.path}/SKILL.md`;if(!(yield this.fetcher.fileExists(r)))return null;if(t){const t=wi(e.name);return t?{name:t,path:r,description:yi}:null}const{content:o}=yield this.fetcher.fetchFile(r),n=bi(o),s=n.name?wi(n.name):wi(e.name);if(!s)return null;const i={disabledEnvironments:n.disabledEnvironments,environments:n.environments,name:s,path:r};return void 0!==n.description&&(i.description=n.description),i}catch(e){return null}})))))).filter((e=>null!==e))}))}discoverMcpServers(e){return mi(this,void 0,void 0,(function*(){try{const{content:t}=yield this.fetcher.fetchFile(e),r=JSON.parse(t);if(r.mcpServers&&"object"==typeof r.mcpServers&&null!==r.mcpServers)return Object.keys(r.mcpServers).map((t=>({name:wi(t),path:e})));const o=[];for(const[e,t]of Object.entries(r))"mcpServers"!==e&&!ls(e,t)&&cs(t)&&o.push(e);return o.map((t=>({name:wi(t),path:e})))}catch(e){return[]}}))}}var _i=function(e,t,r,o){return new(r||(r=Promise))((function(n,s){function i(e){try{l(o.next(e))}catch(e){s(e)}}function a(e){try{l(o.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(i,a)}l((o=o.apply(e,t||[])).next())}))};function Ci(e){var t;const r=null!==(t=null!=e?e:process.env.HOME)&&void 0!==t?t:"";return(0,a.join)(r,".claude")}var Pi=function(e,t,r,o){return new(r||(r=Promise))((function(n,s){function i(e){try{l(o.next(e))}catch(e){s(e)}}function a(e){try{l(o.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(i,a)}l((o=o.apply(e,t||[])).next())}))};const Ri=[".cursor-plugin",".claude-plugin"];class Ti extends Error{constructor(e){super(e),this.name="UserSettingsParseError"}}function Ii(e){return Pi(this,void 0,void 0,(function*(){const t=yield function(e){return Pi(this,void 0,void 0,(function*(){try{return yield(0,fo.readFile)(function(e){return(0,a.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}}))}(e);return void 0===t?{}:function(e){const t=[],r=(0,ts.qg)(e,t,{allowTrailingComma:!0});if(t.length>0){const e=t.slice(0,3).map((e=>`${(0,ts._n)(e.error)} at offset ${e.offset}`)).join("; ");throw new Ti(`~/.cursor/settings.json contains syntax errors: ${e}`)}if("object"!=typeof r||null===r||Array.isArray(r))return{};const o=r;return void 0!==o.enabled_plugins?Array.isArray(o.enabled_plugins)?{enabled_plugins:o.enabled_plugins.filter((e=>"string"==typeof e&&""!==e.trim()))}:{}:o}(t)}))}function Ai(e){return Pi(this,void 0,void 0,(function*(){for(const t of Ri){const r=(0,a.join)(e,t);try{if((yield(0,fo.stat)(r)).isDirectory())return!0}catch(e){}}return!1}))}function Oi(e,t){const r=(0,a.resolve)(t);return $s(r,(0,a.resolve)((0,a.join)(r,e)))}function Di(e,t){const r=e.trim();if((0,a.isAbsolute)(r))return(0,a.resolve)(r);if(r.startsWith("~/"))try{return Oi(r.slice(2),t)}catch(e){return}try{return Oi(r,t)}catch(e){return}}var Mi=function(e,t,r,o){return new(r||(r=Promise))((function(n,s){function i(e){try{l(o.next(e))}catch(e){s(e)}}function a(e){try{l(o.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(i,a)}l((o=o.apply(e,t||[])).next())}))};function ji(e){return Mi(this,void 0,void 0,(function*(){try{return(yield(0,fo.lstat)(e)).isSymbolicLink()}catch(e){return!1}}))}function Ni(e){return Mi(this,void 0,void 0,(function*(){if(yield ji(e))throw new Error(`Refusing to read symlink: ${e}`);return(0,fo.readFile)(e,"utf-8")}))}function $i(e){return Mi(this,void 0,void 0,(function*(){if((yield(0,fo.stat)(e)).size>10485760)throw new Error(`File ${e} exceeds maximum size of 10485760 bytes`)}))}function Fi(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"}function Li(e){return Mi(this,void 0,void 0,(function*(){var t;for(const r of xn){const o=(0,a.join)(e,r);try{if(yield ji(o))continue;if(!(yield(0,fo.stat)(o)).isFile())continue;yield $i(o);const e=Xn(yield Ni(o));if(!e.success)continue;const r=e.data,n=r.commands,s=r.agents,i=r.skills,a=r.rules,l=r.hooks,c=r.mcpServers,u=void 0!==n||void 0!==s||void 0!==i||void 0!==a||void 0!==l||void 0!==c,d="string"==typeof r.displayName?r.displayName:void 0,p="string"==typeof r.description?r.description:void 0,h=null===(t=r.author)||void 0===t?void 0:t.name,m=r.variables,f=void 0!==d||void 0!==p||void 0!==h||void 0!==m;if(!u&&!f)continue;return Object.assign(Object.assign({manifestFilePath:o},u&&{manifestOptions:{commands:n,agents:s,skills:i,rules:a,hooks:l,mcpServers:c}}),f&&{metadata:{displayName:d,description:p,authorName:h,variables:m}})}catch(e){}}}))}function Ui(e,t){return Mi(this,void 0,void 0,(function*(){const r=function(e,t){var r;const o=new Map,n=(0,a.resolve)(e),s=(0,a.resolve)(null!==(r=null==t?void 0:t.symlinkTargetRoot)&&void 0!==r?r:n),i=(0,fo.realpath)(s).catch((()=>s));function l(e){const t=(0,a.resolve)(e);try{return $s(n,t)}catch(t){throw new Error(`Path escapes plugin directory: ${e}`)}}function c(e){return Mi(this,void 0,void 0,(function*(){const t=l(e),r=yield i,o=yield(0,fo.realpath)(t);try{return $s(r,o)}catch(t){throw new Error(`Path escapes plugin directory via symlink: ${e}`)}}))}return{listDirectory(t,r){return Mi(this,void 0,void 0,(function*(){const o=l(t?(0,a.join)(e,t):e);try{const e=yield c(o);if(null==r?void 0:r.has(e))return[];null==r||r.add(e);const n=yield(0,fo.readdir)(e,{withFileTypes:!0}),s=[];for(const e of n){const r=(0,a.join)(o,e.name);let n=e.isDirectory()?"dir":"file";if(e.isSymbolicLink())try{const e=yield c(r);n=(yield(0,fo.stat)(e)).isDirectory()?"dir":"file"}catch(e){continue}s.push({name:e.name,type:n,path:t?`${t}/${e.name}`:e.name})}return s}catch(e){return[]}}))},fetchFile(t){return Mi(this,void 0,void 0,(function*(){const r=o.get(t);if(void 0!==r)return{content:r};const n=l((0,a.join)(e,t)),s=yield c(n);yield $i(s);const i=yield(0,fo.readFile)(s,"utf-8");return o.set(t,i),{content:i}}))},fileExists(t){return Mi(this,void 0,void 0,(function*(){try{const r=l((0,a.join)(e,t)),o=yield c(r);return(yield(0,fo.stat)(o)).isFile()}catch(e){return!1}}))}}}(e),o=new xi(r),n=yield o.discoverComponents({manifest:t}),[s,i,l,c]=yield Promise.all([Bi(r,n.skills,e),zi(r,n.agents,e),Wi(r,n.commands,e),Hi(r,n.rules,e)]);return{skills:s,agents:i,commands:l,rules:c}}))}function Bi(e,t,r){return Mi(this,void 0,void 0,(function*(){const o=[];for(const n of t)try{const{content:t}=yield e.fetchFile(n.path),s=Gi({content:ss(t,r),relativePath:n.path});s&&o.push(s)}catch(e){}return o}))}function Hi(e,t,r){return Mi(this,void 0,void 0,(function*(){const o=[];for(const n of t)try{const{content:t}=yield e.fetchFile(n.path),s=Gi({content:ss(t,r),relativePath:n.path});s&&o.push(Object.assign(Object.assign({},s),{name:n.name}))}catch(e){}return o}))}function zi(e,t,r){return Mi(this,void 0,void 0,(function*(){const o=[];for(const n of t)try{const{content:t}=yield e.fetchFile(n.path),s=Vi({content:ss(t,r),relativePath:n.path});s&&o.push(s)}catch(e){}return o}))}function Wi(e,t,r){return Mi(this,void 0,void 0,(function*(){const o=[];for(const n of t)try{const{content:t}=yield e.fetchFile(n.path),s=Ji({content:ss(t,r),relativePath:n.path});s&&o.push(s)}catch(e){}return o}))}function qi(e){if("string"==typeof e){const t=e.split(",").map((e=>e.trim())).filter(Boolean);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 Gi({content:e,relativePath:t}){var r,o,n,s,i;try{const a=sn(e),l=t.replace(/\\/g,"/"),c=l.split("/").filter((e=>e.length>0)),u=c.length>=2?c[c.length-2]:void 0,d=null!==(r=c[c.length-1])&&void 0!==r?r:l,p=null!=u?u:d.replace(/\.md$/i,""),h="string"==typeof a.data.name?a.data.name.trim():void 0,m=Si(null!==(o=a.data.environments)&&void 0!==o?o:null===(n=a.data.metadata)||void 0===n?void 0:n.environments),f=Si(null!==(s=a.data["disabled-environments"])&&void 0!==s?s:null===(i=a.data.metadata)||void 0===i?void 0:i.disabledEnvironments);return{path:t,name:h&&h.length>0?h:p,description:"string"==typeof a.data.description?a.data.description:void 0,globs:qi(a.data.globs),alwaysApply:!0===a.data.alwaysApply,content:e,environments:m,disabledEnvironments:f}}catch(e){return null}}function Vi({content:e,relativePath:t}){var r,o;try{const n=sn(e),s=n.content.trim();if(!s)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 l=null!==(r=n.data.permissionMode)&&void 0!==r?r:n.data.permissionmode,c=(0,a.basename)(t);return{path:t,name:"string"==typeof n.data.name?n.data.name:(0,a.basename)(c,(0,a.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:s,permissionMode:(o=l,"readonly"===(null!=o?o:"").trim().toLowerCase()?"readonly":"default")}}catch(e){return null}}function Ji({content:e,relativePath:t}){try{const r=sn(e);let o;const n=r.data["argument-hint"];"string"==typeof n?o=n:Array.isArray(n)&&(o=`[${n.join(" ")}]`);const s=(0,a.basename)(t);return{path:t,name:"string"==typeof r.data.name?r.data.name:(0,a.basename)(s,(0,a.extname)(s)),description:"string"==typeof r.data.description?r.data.description:void 0,argumentHint:o,content:r.content.trim()}}catch(e){return null}}function Ki(e){if(void 0!==e)return{configuredVariables:e.configuredVariables}}function Zi(e,t,r){return Mi(this,void 0,void 0,(function*(){const o=e.replace(/^\.\//,"");if(!es(o))return null;const n=(0,a.join)(t,o);try{if(yield ji(n))return null;if(!(yield(0,fo.stat)(n)).isFile())return null;yield $i(n);const e=ds(yield Ni(n),t,r);return(null==e?void 0:e.mcpServers)&&0!==Object.keys(e.mcpServers).length?{config:e,sourcePath:n}:null}catch(e){return null}}))}function Yi(e,t,r){if(t.mcpServers)for(const[o,n]of Object.entries(t.mcpServers))e.mcpServers[o]=n,e.mcpServerSourcePaths[o]=r}function Xi(e,t,r,o){return Mi(this,void 0,void 0,(function*(){const n={mcpServers:{},mcpServerSourcePaths:{}};if("string"==typeof e){const r=yield Zi(e,t,o);r&&Yi(n,r.config,r.sourcePath)}else if(Array.isArray(e))for(const s of e)if("string"!=typeof s){if("object"==typeof s&&null!==s){const e=ds(JSON.stringify(s),t,o);(null==e?void 0:e.mcpServers)&&Yi(n,e,r)}}else{const e=yield Zi(s,t,o);e&&Yi(n,e.config,e.sourcePath)}else if("object"==typeof e&&null!==e){const s=ds(JSON.stringify(e),t,o);(null==s?void 0:s.mcpServers)&&Yi(n,s,r)}return 0===Object.keys(n.mcpServers).length?null:n}))}function Qi(e,t,r){return Mi(this,void 0,void 0,(function*(){let o={},n={};const s=null!=r?r:Ki(t);for(const t of is.map((e=>e))){const r=(0,a.join)(e,t);try{if((yield(0,fo.stat)(r)).isFile()){const t=ds(yield Ni(r),e,s);if(null==t?void 0:t.mcpServers)for(const[e,s]of Object.entries(t.mcpServers))void 0===o[e]&&(o[e]=s,n[e]=r)}}catch(e){}}for(const t of[".cursor-plugin",".claude-plugin"]){const r=(0,a.join)(e,t,"plugin.json");try{if(!(yield(0,fo.stat)(r)).isFile())continue;const t=Xn(yield Ni(r));if(t.success){if(void 0!==t.data.mcpServers){const i=yield Xi(t.data.mcpServers,e,r,s);(null==i?void 0:i.mcpServers)&&(o=Object.assign(Object.assign({},o),i.mcpServers),n=Object.assign(Object.assign({},n),i.mcpServerSourcePaths))}break}}catch(e){}}return 0===Object.keys(o).length?null:Object.assign({mcpServers:o},Object.keys(n).length>0&&{mcpServerSourcePaths:n})}))}function ea(e,t){return Mi(this,void 0,void 0,(function*(){var r;const o=yield Qi(e);if(o)return o;for(const o of Cn){const n=(0,a.join)(e,o);try{if(!(yield(0,fo.stat)(n)).isFile())continue;const o=yield(0,fo.readFile)(n,"utf-8"),s=JSON.parse(o).plugins;if(!Array.isArray(s))continue;const i=t.name,l=s.find((e=>e.name===i));if(!(null===(r=null==l?void 0:l.mcpServers)||void 0===r?void 0:r.length))continue;for(const t of l.mcpServers){const r=t.replace(/^\.\//,"");if(!es(r))continue;const o=(0,a.join)(e,r);try{yield $i(o);const t=ds(yield Ni(o),e);if((null==t?void 0:t.mcpServers)&&Object.keys(t.mcpServers).length>0){const e=Object.fromEntries(Object.keys(t.mcpServers).map((e=>[e,o])));return Object.assign(Object.assign({},t),{mcpServerSourcePaths:e})}}catch(e){}}return null}catch(e){}}return null}))}function ta(e,t){const r={};for(const[o,n]of Object.entries(e.hooks))Array.isArray(n)&&(r[o]=n.map((e=>"command"in e&&"string"==typeof e.command?Object.assign(Object.assign({},e),{command:ss(e.command,t)}):"prompt"in e&&"string"==typeof e.prompt?Object.assign(Object.assign({},e),{prompt:ss(e.prompt,t)}):e)));return Object.assign(Object.assign({},e),{hooks:r})}function ra(e,t,r,o){return Mi(this,void 0,void 0,(function*(){if("object"==typeof r){const n=oa(r,t);return n&&"config"in n?Object.assign({config:ta(n.config,e)},void 0!==o&&{sourcePath:o}):n}let n,s,i;if("string"==typeof r){const t=r.replace(/^\.\//,"");if(!es(t))return;n=t.endsWith(".json")?(0,a.join)(e,t):(0,a.join)(e,t,"hooks.json")}else n=(0,a.join)(e,"hooks","hooks.json");try{if(yield ji(n))return;if(!(yield(0,fo.stat)(n)).isFile())return}catch(e){return}try{yield $i(n),s=yield(0,fo.readFile)(n,"utf-8")}catch(e){return}try{i=JSON.parse(s)}catch(e){return{error:{source:"claude-plugin",message:`Plugin ${t} ${n}: invalid JSON`}}}const l=oa(i,t);return l&&"config"in l?{config:ta(l.config,e),sourcePath:n}:l}))}function oa(e,t){const r=function(e){if("object"!=typeof e||null===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("object"!=typeof t||null===t)continue;const r=t;if("hooks"in r&&Array.isArray(r.hooks))return"claude-code";if("command"in r||"prompt"in r||"type"in r)return"cursor"}return"unknown"}(e);if("cursor"===r){const r=e,o=Te(r);return o.isValid?{config:r}:{error:{source:"claude-plugin",message:`Plugin ${t} hooks: ${o.errors.join("; ")}`}}}if("claude-code"===r){const r=null==e?void 0:e.hooks;if(!r||0===Object.keys(r).length)return;const o=te(r),n=Te(o);return n.isValid?{config:o}:{error:{source:"claude-plugin",message:`Plugin ${t} hooks: ${n.errors.join("; ")}`}}}}function na(e,t,r,o){return Mi(this,void 0,void 0,(function*(){var n,s,i,a,l,c;const u=yield Li(e),d=null!==(n=Ki(r))&&void 0!==n?n:(null==o?void 0:o.configuredVariables)?{configuredVariables:o.configuredVariables}:void 0,[p,h,m]=yield Promise.all([Ui(e,null==u?void 0:u.manifestOptions),Qi(e,r,d),ra(e,t,null===(s=null==u?void 0:u.manifestOptions)||void 0===s?void 0:s.hooks,null==u?void 0:u.manifestFilePath)]);return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},p),void 0!==(null===(i=null==u?void 0:u.metadata)||void 0===i?void 0:i.displayName)&&{displayName:u.metadata.displayName}),void 0!==(null===(a=null==u?void 0:u.metadata)||void 0===a?void 0:a.description)&&{description:u.metadata.description}),void 0!==(null===(l=null==u?void 0:u.metadata)||void 0===l?void 0:l.authorName)&&{authorName:u.metadata.authorName}),{variablesSchema:null===(c=null==u?void 0:u.metadata)||void 0===c?void 0:c.variables,mcpConfig:h,hooks:m})}))}function sa(e,t){return Mi(this,void 0,void 0,(function*(){var r,o,n,s;const i=yield Li(e),[a,l,c]=yield Promise.all([Ui(e,null==i?void 0:i.manifestOptions),ea(e,t),ra(e,t.raw,null===(r=null==i?void 0:i.manifestOptions)||void 0===r?void 0:r.hooks,null==i?void 0:i.manifestFilePath)]),u={source:"claude-plugin",sourceInfo:t};return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({identifier:u,installPath:e},void 0!==(null===(o=null==i?void 0:i.metadata)||void 0===o?void 0:o.displayName)&&{displayName:i.metadata.displayName}),void 0!==(null===(n=null==i?void 0:i.metadata)||void 0===n?void 0:n.description)&&{description:i.metadata.description}),void 0!==(null===(s=null==i?void 0:i.metadata)||void 0===s?void 0:s.authorName)&&{authorName:i.metadata.authorName}),a),{mcpConfig:null!=l?l:void 0,hooks:c})}))}function ia(e,t,r){return Mi(this,void 0,void 0,(function*(){const o=`${r.name}@${r.version}`,{displayName:n,description:s,authorName:i,variablesSchema:a,skills:l,rules:c,agents:u,commands:d,mcpConfig:p,hooks:h}=yield na(e,o,r),m={source:t,sourceInfo:r};return Object.assign(Object.assign(Object.assign(Object.assign({identifier:m,installPath:e},void 0!==n&&{displayName:n}),void 0!==s&&{description:s}),void 0!==i&&{authorName:i}),{variablesSchema:a,skills:l,rules:c,agents:u,commands:d,mcpConfig:null!=p?p:void 0,hooks:h})}))}function aa(e,t){return Mi(this,arguments,void 0,(function*(e,t,r={}){var o,n;const s=null!==(o=r.log)&&void 0!==o?o:un,i=performance.now(),l=yield function(e){return _i(this,void 0,void 0,(function*(){const t=Ci(e),r=(0,a.join)(t,"plugins","installed_plugins.json");try{const e=yield(0,fo.readFile)(r,"utf-8");return JSON.parse(e)}catch(e){return e.code,null}}))}(r.userHomeDir);if(!(null==l?void 0:l.plugins))return s.log("info",`loadAllEnabledPlugins: no installed plugins metadata found (${(performance.now()-i).toFixed(1)}ms)`),[];const c=yield function(e){return _i(this,void 0,void 0,(function*(){const t=Ci(e),r=(0,a.join)(t,"settings.json");try{const e=yield(0,fo.readFile)(r,"utf-8");return JSON.parse(e)}catch(e){return e.code,null}}))}(r.userHomeDir),u=e?(0,a.resolve)(e):void 0,d=function(e,t,r,o){var n;const s=null==e?void 0:e.plugins;if(!s||"object"!=typeof s)return[];const i=null!==(n=null==t?void 0:t.enabledPlugins)&&void 0!==n?n:{},a={};(null==r?void 0:r.enabledPlugins)&&Object.assign(a,r.enabledPlugins);const l=void 0!==o?pi(o):void 0,c=new Set,u=[];for(const[e,t]of Object.entries(s)){if(!Array.isArray(t)||0===t.length)continue;if(void 0!==l&&!1===a[e])continue;let r;void 0!==l&&(r=t.find((t=>!("project"!==t.scope&&"local"!==t.scope||!t.projectPath)&&pi(t.projectPath)===l&&!0===a[e]))),r||!0!==i[e]||(r=t.find((e=>"user"===e.scope))),(null==r?void 0:r.installPath)&&!c.has(e)&&(u.push({pluginId:e,installPath:r.installPath}),c.add(e))}return u}(l,c,u?yield function(e){return _i(this,void 0,void 0,(function*(){const t={enabledPlugins:{}};let r=!1;const o=(0,a.join)(e,".claude","settings.json");try{const e=yield(0,fo.readFile)(o,"utf-8"),n=JSON.parse(e);n.enabledPlugins&&(Object.assign(t.enabledPlugins,n.enabledPlugins),r=!0)}catch(e){}const n=(0,a.join)(e,".claude","settings.local.json");try{const e=yield(0,fo.readFile)(n,"utf-8"),o=JSON.parse(e);o.enabledPlugins&&(Object.assign(t.enabledPlugins,o.enabledPlugins),r=!0)}catch(e){}return r?t:null}))}(u):null,u),p=[],h=r.onError;for(const{pluginId:e,installPath:t}of d)try{const r=performance.now(),o=fn(e),n=yield sa(t,o);p.push(n),s.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(h)try{h(fn(e),r)}catch(t){h({name:null!==(n=e.split("@")[0])&&void 0!==n?n:e,sourceType:"marketplace",marketplace:"unknown",raw:e},r)}}return s.log("info",`loadAllEnabledPlugins completed in ${(performance.now()-i).toFixed(1)}ms (${d.length} resolved, ${p.length} loaded)`),p}))}Error;function la(e){return Mi(this,arguments,void 0,(function*(e,t={}){var r,o,n,s,i,l;const c=null!==(r=t.log)&&void 0!==r?r:un,u=performance.now(),d=null===(o=t.loadClaude)||void 0===o||o,p=null===(n=t.loadUserLocal)||void 0===n||n,h=null!==(s=t.loadUserSettings)&&void 0!==s&&s,m=null!==(i=t.marketplaceSources)&&void 0!==i?i:[],f=null!==(l=t.loadCursorFirstParty)&&void 0!==l?l:m.length>0,g=[],v=[];let y;d&&g.push(aa(e,void 0,{userHomeDir:t.userHomeDir,onError:t.onError,log:c})),f&&m.length>0&&(y=Promise.all(m.map((e=>{var r,o;return function(e){return Mi(this,void 0,void 0,(function*(){var t,r,o,n,s,i,a,l;const c=null!==(t=e.log)&&void 0!==t?t:un,u=performance.now(),{client:d,userId:p,teamId:h,onCursorError:m,pruneOldVersions:f}=e,g=[],v=null!==(r=e.cacheManager)&&void 0!==r?r:new ks(e.userHomeDir),y=performance.now(),w=yield d.listEnabledPlugins(p,h);c.log("info",`marketplace listEnabledPlugins completed in ${(performance.now()-y).toFixed(1)}ms (${w.plugins.length} plugins)`);const b=[];if(w.listFailures){g.push(...w.listFailures);for(const e of w.listFailures)b.push({identifier:{source:e.marketplaceName&&"cursor-public"!==e.marketplaceName?"cursor-third-party":"cursor-first-party",sourceInfo:{name:e.pluginName,version:"",marketplace:e.marketplaceName}},installPath:"",loadError:e.errorMessage,skills:[],rules:[],agents:[],commands:[]})}const S=new Map;for(const e of w.plugins)try{const t=null===(o=e.marketplace)||void 0===o?void 0:o.name;if(!t){const t=new Error(`Plugin ${e.name} has no marketplace metadata — cannot determine cache path`);g.push({pluginName:e.name,pluginId:e.pluginId,marketplaceName:void 0,errorMessage:t.message,errorType:"manifest"}),m&&m(e,t);continue}const r=`${t}/${e.pluginId}`;let a,l=S.get(r);if(l||(l={slug:t,pluginId:e.pluginId,versions:[]},S.set(r,l)),l.versions.push(e.version),yield v.isCached({marketplaceSlug:t,pluginId:e.pluginId,version:e.version}))a=v.getCacheDir({marketplaceSlug:t,pluginId:e.pluginId,version:e.version}),c.log("info",`loadFromMarketplaceSource: Found cached plugin: ${e.pluginId} at ${a}`,{marketplaceSlug:t,pluginId:e.pluginId,gitRef:e.version,marketplaceId:null===(n=e.marketplace)||void 0===n?void 0:n.id});else{const r=v.getCacheDir({marketplaceSlug:t,pluginId:e.pluginId,version:e.version});c.log("info",`loadFromMarketplaceSource: Plugin missing from cache, installing: ${e.pluginId} at ${r}`,{marketplaceSlug:t,pluginId:e.pluginId,gitRef:e.version,marketplaceId:null===(s=e.marketplace)||void 0===s?void 0:s.id}),yield(0,fo.mkdir)(r,{recursive:!0});try{yield d.installPlugin(e,r),yield v.markCacheComplete({marketplaceSlug:t,pluginId:e.pluginId,version:e.version})}catch(e){try{yield(0,fo.rm)(r,{recursive:!0,force:!0})}catch(e){}throw e}a=r}const u=null===(i=e.marketplace)||void 0===i?void 0:i.name,p=void 0!==u&&"cursor-public"!==u&&u.length>0?"cursor-third-party":"cursor-first-party",h={name:e.name,version:e.version,pluginDbId:e.pluginDbId,configuredVariables:e.configuredVariables,marketplace:u,marketplaceDbId:e.marketplaceDbId,isTeamRequired:e.isTeamRequired},f=yield ia(a,p,h);b.push(f);try{yield v.pruneOldVersions({marketplaceSlug:t,pluginId:e.pluginId,keepVersions:[e.version]})}catch(e){}}catch(t){c.captureException(t,{error_type:"load_plugin_from_marketplace"});const r=t instanceof Error?t:new Error(String(t));g.push({pluginName:e.name,pluginId:e.pluginId,marketplaceName:null===(a=e.marketplace)||void 0===a?void 0:a.name,errorMessage:r.message,errorType:Fi(r)});const o=null===(l=e.marketplace)||void 0===l?void 0:l.name,n=void 0!==o&&"cursor-public"!==o&&o.length>0;b.push({identifier:{source:n?"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:r.message||"Plugin load failed",skills:[],rules:[],agents:[],commands:[]}),m&&m(e,r)}if(f)for(const{slug:e,pluginId:t,versions:r}of S.values())try{yield v.pruneOldVersions({marketplaceSlug:e,pluginId:t,keepVersions:r})}catch(e){}return c.log("info",`loadFromMarketplaceSource completed in ${(performance.now()-u).toFixed(1)}ms (${b.length} plugins loaded, ${g.length} failures)`),{plugins:b,failures:g}}))}(Object.assign(Object.assign({},e),{userHomeDir:null!==(r=e.userHomeDir)&&void 0!==r?r:t.userHomeDir,log:null!==(o=e.log)&&void 0!==o?o:c}))})))),p&&g.push(function(){return Mi(this,arguments,void 0,(function*(e={}){var t,r,o;const n=null!==(t=e.log)&&void 0!==t?t:un,s=performance.now(),i=null!==(r=e.userHomeDir)&&void 0!==r?r:process.env.HOME;if(!i)return n.log("info","loadUserLocalPlugins: no home directory available, skipping"),[];const l=(0,a.join)(i,".cursor","plugins","local");let c;try{c=yield(0,fo.readdir)(l,{withFileTypes:!0})}catch(e){return n.log("info",`loadUserLocalPlugins: ${l} not found or not readable (${(performance.now()-s).toFixed(1)}ms)`),[]}const u=yield(0,fo.realpath)(l).catch((()=>(0,a.resolve)(l))),d=[];for(const t of c){if(!t.isDirectory()&&!t.isSymbolicLink())continue;if(t.name.startsWith("."))continue;const r=(0,a.join)(l,t.name);try{if(t.isSymbolicLink()){let e;try{e=yield(0,fo.realpath)(r)}catch(e){n.log("warn",`loadUserLocalPlugin ${t.name} rejected: failed to resolve symlink (${e instanceof Error?e.message:String(e)})`);continue}try{$s(u,e)}catch(r){n.log("warn",`loadUserLocalPlugin ${t.name} rejected: symlink target ${e} is outside ${l}`);continue}}if(!(yield(0,fo.stat)(r)).isDirectory()){t.isSymbolicLink()&&n.log("warn",`loadUserLocalPlugin ${t.name} rejected: symlink target is not a directory`);continue}const s=performance.now(),i=yield null===(o=e.localPluginVariablesLookup)||void 0===o?void 0:o.call(e,t.name),{displayName:a,description:c,authorName:p,variablesSchema:h,skills:m,rules:f,agents:g,commands:v,mcpConfig:y,hooks:w}=yield na(r,t.name,void 0,{configuredVariables:i}),b={source:"user-local",sourceInfo:{name:t.name,localPath:r}};d.push(Object.assign(Object.assign(Object.assign(Object.assign({identifier:b,installPath:r},void 0!==a&&{displayName:a}),void 0!==c&&{description:c}),void 0!==p&&{authorName:p}),{variablesSchema:h,skills:m,rules:f,agents:g,commands:v,mcpConfig:null!=y?y:void 0,hooks:w})),n.log("info",`loadUserLocalPlugin ${t.name} loaded in ${(performance.now()-s).toFixed(1)}ms`)}catch(e){n.log("error",`loadUserLocalPlugin ${t.name} failed: ${e instanceof Error?e.message:String(e)}`)}}return n.log("info",`loadUserLocalPlugins completed in ${(performance.now()-s).toFixed(1)}ms (${d.length} plugins loaded)`),d}))}({userHomeDir:t.userHomeDir,log:c,localPluginVariablesLookup:t.localPluginVariablesLookup})),h&&g.push(function(){return Mi(this,arguments,void 0,(function*(e={}){var t,r,o;const n=null!==(t=e.log)&&void 0!==t?t:un,s=performance.now(),i=null!==(r=e.userHomeDir)&&void 0!==r?r:process.env.HOME;if(!i)return n.log("info","loadUserSettingsPlugins: no home directory available, skipping"),[];let l;try{l=yield function(e){return Pi(this,void 0,void 0,(function*(){var t;const r=null!==(t=(yield Ii(e)).enabled_plugins)&&void 0!==t?t:[];if(0===r.length)return[];const o=[],n=new Set;for(const t of r){const r=Di(t,e);if(void 0!==r)try{if(!(yield(0,fo.stat)(r)).isDirectory())continue;if(yield Ai(r)){const e=yield(0,fo.realpath)(r).catch((()=>r));n.has(e)||(n.add(e),o.push({originalPath:t,resolvedPath:e,isDiscovered:!1}));continue}const e=yield(0,fo.readdir)(r,{withFileTypes:!0}),s=yield(0,fo.realpath)(r).catch((()=>r));for(const i of e){if(!i.isDirectory()&&!i.isSymbolicLink())continue;if(i.name.startsWith("."))continue;const e=(0,a.join)(r,i.name);try{if(i.isSymbolicLink()&&$s(s,yield(0,fo.realpath)(e)),!(yield(0,fo.stat)(e)).isDirectory())continue;if(yield Ai(e)){const r=yield(0,fo.realpath)(e).catch((()=>e));n.has(r)||(n.add(r),o.push({originalPath:t,resolvedPath:r,isDiscovered:!0}))}}catch(e){}}}catch(e){}}return o}))}(i)}catch(e){return n.log("error",`loadUserSettingsPlugins: failed to resolve paths from settings: ${e instanceof Error?e.message:String(e)}`),[]}if(0===l.length)return n.log("info",`loadUserSettingsPlugins: no plugin paths found in ~/.cursor/settings.json (${(performance.now()-s).toFixed(1)}ms)`),[];const c=[];for(const{originalPath:t,resolvedPath:r,isDiscovered:s}of l)try{const i=performance.now(),l=(0,a.basename)(r),u=hn(r),d=yield null===(o=e.localPluginVariablesLookup)||void 0===o?void 0:o.call(e,u),{displayName:p,description:h,authorName:m,variablesSchema:f,skills:g,rules:v,agents:y,commands:w,mcpConfig:b,hooks:S}=yield na(r,l,void 0,{configuredVariables:d}),k={source:"user-settings",sourceInfo:{name:null!=p?p:l,localPath:r,originalSettingsPath:t,isDiscovered:s}};c.push(Object.assign(Object.assign(Object.assign(Object.assign({identifier:k,installPath:r},void 0!==p&&{displayName:p}),void 0!==h&&{description:h}),void 0!==m&&{authorName:m}),{variablesSchema:f,skills:g,rules:v,agents:y,commands:w,mcpConfig:null!=b?b:void 0,hooks:S})),n.log("info",`loadUserSettingsPlugin ${l} loaded in ${(performance.now()-i).toFixed(1)}ms`)}catch(e){const t=e instanceof Error?e.name:"Error";n.log("error",`loadUserSettingsPlugin failed for ${(0,a.basename)(r)}: ${t}`)}return n.log("info",`loadUserSettingsPlugins completed in ${(performance.now()-s).toFixed(1)}ms (${c.length} plugins loaded from ${l.length} paths)`),c}))}({userHomeDir:t.userHomeDir,log:c,localPluginVariablesLookup:t.localPluginVariablesLookup}));const[w,b]=yield Promise.all([Promise.all(g),null!=y?y:Promise.resolve([])]),S=[];for(const e of b)S.push(...e.plugins),v.push(...e.failures);S.push(...w.flat());const k=new Set,E=[];for(const e of S){const t=yield(0,fo.realpath)(e.installPath).catch((()=>e.installPath));k.has(t)||(k.add(t),E.push(e))}const x=new Map,_=[];for(const e of E){const t=ca(e);if(void 0!==t){const r=x.get(t),o=!e.loadError;if(!0===r)continue;if(!1===r&&o){const r=_.findIndex((e=>ca(e)===t&&e.loadError));-1!==r&&_.splice(r,1),x.set(t,!0),_.push(e);continue}x.set(t,o)}_.push(e)}const C=performance.now()-u;return c.log("info",`loadAllPlugins completed in ${C.toFixed(1)}ms (claude=${d}, userLocal=${p}, userSettings=${h}, marketplace=${m.length} sources, total=${_.length} plugins, failures=${v.length})`),{plugins:_,failures:v}}))}function ca(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 ua(e,t={}){return Object.assign(Object.assign({},e),{model:t.stripModel?void 0:e.model,tools:t.stripTools?void 0:e.tools})}function da(e,t){const r=[];for(const n of e){const e=gn(n.identifier),s=`plugin:${e}`,i=vn(n.identifier),l=yn(n.identifier),c=wn(n.identifier),u=bn(n.identifier);for(const d of t(n)){const t=(0,a.join)(n.installPath,d.path),{type:p,globs:h,description:m}=(o=d).alwaysApply?{type:"global"}:o.globs&&o.globs.length>0?{type:"fileGlobbed",globs:o.globs}:o.description?{type:"agentFetched",description:o.description}:{type:"manuallyAttached"};r.push({fullPath:t,content:d.content,type:p,globs:h,description:m,pluginIdentifier:e,gitRemoteOrigin:s,plugin:i,marketplace:l,pluginId:c,marketplaceId:u,environments:d.environments,disabledEnvironments:d.disabledEnvironments})}}var o;return r}(0,a.join)((0,i.homedir)(),".claude","plugins","marketplaces"),Error;var pa=function(e,t,r,o){return new(r||(r=Promise))((function(n,s){function i(e){try{l(o.next(e))}catch(e){s(e)}}function a(e){try{l(o.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(i,a)}l((o=o.apply(e,t||[])).next())}))};function ha(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(e){return!1}}class ma extends Error{constructor(e){super(e),this.name="SettingsParseError"}}function fa(e){return pa(this,void 0,void 0,(function*(){try{return yield(0,fo.readFile)(function(e){return(0,a.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}}))}function ga(e){return pa(this,void 0,void 0,(function*(){const t=yield fa(e);return void 0===t?{}:function(e){const t=[],r=(0,ts.qg)(e,t,{allowTrailingComma:!0});if(t.length>0){const e=t.slice(0,3).map((e=>`${(0,ts._n)(e.error)} at offset ${e.offset}`)).join("; ");throw new ma(`.cursor/settings.json contains syntax errors: ${e}`)}if("object"!=typeof r||null===r||Array.isArray(r))return{};const o=r;return void 0===o.plugins||"object"==typeof o.plugins&&null!==o.plugins&&!Array.isArray(o.plugins)?o:{}}(t)}))}function va(e){return pa(this,void 0,void 0,(function*(){const t=yield ga(e);return t.plugins?Object.entries(t.plugins).filter((([,e])=>!0===e.enabled)).filter((([,e])=>!e.gitUrl||ha(e.gitUrl))).map((([e,t])=>({key:e,entry:t}))):[]}))}function ya(e){const t=e.indexOf("/");return-1===t?{name:e}:{name:e.slice(t+1),marketplaceName:e.slice(0,t)}}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 o,n=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===n)return n=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var s=o.dispose.call(o.value);if(o.async)return n|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else n|=1}catch(e){r(e)}if(1===n)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var o=new Error(r);return o.name="SuppressedError",o.error=e,o.suppressed=t,o});function ba(e,{root:t,includeGlobs:r=[],excludeGlobs:o=[],caseSensitive:n=!1,cursorIgnoreFiles:s=[],sandboxPolicy:i={type:"insecure_none"},noIgnoreVcs:a=!1,followSymlinks:l=!1,source:c="ripwalk"}){const u=["--files","--hidden","--no-require-git","--no-config","--color=never"];l&&u.push("--follow"),a&&u.push("--no-ignore-vcs"),n&&u.push("--case-sensitive");for(const e of s)u.push("--cursor-ignore",e);for(const e of r)u.push("--iglob",e);for(const e of o)u.push("--iglob",`!${e}`);let d,p=!1;const h=new Promise((e=>{d=e}));return{lines:async function*(){const r={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 o,n;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");o=t[Symbol.asyncDispose]}if(void 0===o){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");o=t[Symbol.dispose],r&&(n=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");n&&(o=function(){try{n.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:o,async:r})}else r&&e.stack.push({async:!0});return t}(r,function(e,t,r,o){const n=(0,Do.spawnInSandbox)((0,Do.Ko)(),t,{cwd:r},o),s=[];n.stderr?.on("data",(e=>{s.push(e)}));const i=new Promise(((e,t)=>{n.on("error",t),n.on("close",(t=>e(t??0)))}));if(!n.stdout)throw new Error("No stdout from ripgrep process");const a=new Promise((t=>{e.signal.aborted?t("aborted"):e.signal.addEventListener("abort",(()=>t("aborted")),{once:!0})}));return{stdout:n.stdout,processExit:i,stderr:()=>Buffer.concat(s).toString(),aborted:a,[Symbol.dispose](){n.kill()}}}(e,u,t,i),!1);let n=0;const s=async function*(e){let t="";for await(const r of e){t+=r.toString();const e=t.split("\n");t=e.pop()??"",yield*e}t&&(yield t)}(o.stdout)[Symbol.asyncIterator]();for(;;){const e=await Promise.race([s.next(),o.aborted]);if("aborted"===e){p=!0,d(!0);break}if(e.done)break;n++,yield e.value}if(n>0);else if(!p){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}`:""}`)}}p||d(!1)}catch(e){r.error=e,r.hasError=!0}finally{wa(r)}}(),didTimeout:h}}function Sa({root:e,includeGlobs:t=[],excludeGlobs:r=[],caseSensitive:o=!1,cursorIgnoreFiles:n=[],sandboxPolicy:s={type:"insecure_none"},noIgnoreVcs:i=!1,followSymlinks:a=!1}){return JSON.stringify({root:e,includeGlobs:t,excludeGlobs:r,caseSensitive:o,cursorIgnoreFiles:n,sandboxPolicy:s,noIgnoreVcs:i,followSymlinks:a})}class ka{cache;constructor(e=2e4){this.cache=new h.Hc({ttlMs:e})}clear(){this.cache.clear()}delete(e){this.cache.delete(Sa(e))}walk(e,t){const r=Sa(t);let o,n=!1,s=!1;const i=new Promise((e=>{o=e})),a=e=>{s||(s=!0,o(e))},l=(c=e.signal,new Promise((e=>{c.aborted?e("aborted"):c.addEventListener("abort",(()=>e("aborted")),{once:!0})})));var c;return{lines:async function*(){const o=this.cache.get(r);if(void 0!==o){const e=await Promise.race([o.linesPromise.then((e=>({type:"lines",lines:e})),(e=>({type:"error",error:e}))),l.then((()=>({type:"aborted"})))]);if("aborted"===e.type)return n=!0,void a(!0);if("lines"===e.type)return a(!1),void(yield*e.lines);this.cache.get(r)===o&&this.cache.delete(r)}let s,i;const c={linesPromise:new Promise(((e,t)=>{s=e,i=t}))};c.linesPromise.catch((()=>{})),this.cache.set(r,c);const u=[];let d,p=!1;try{const r=ba(e,t);for await(const e of r.lines)u.push(e),yield e;if(await r.didTimeout)return n=!0,d=new Error("Ripwalk aborted before cacheable result was available"),void a(!0);p=!0}catch(e){throw d=e,e}finally{p?s?.(u):(this.cache.get(r)===c&&this.cache.delete(r),i?.(d??new Error("Ripwalk terminated before cacheable result was available"))),n||a(!1)}}.bind(this)(),didTimeout:i}}}async function Ea(e,t,r){try{return(await t.exec(e,r,["rev-parse","--show-toplevel"],{caller:"findGitRoot"})).stdout.trim()}catch{return null}}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 _a(e){const t=e.trim();if(""===t)return t;try{const e=new URL(t);return e.username="",e.password="",e.toString()}catch{return t}}function Ca(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}}const Pa=["**/node_modules/**","**/.git/**","**/.turbo/**","**/.next/**","**/.cache/**","**/.pnpm/**","**/.yarn/**","**/dist/**","**/build/**","**/out/**","**/target/**","**/.vscode/**","**/.idea/**","**/venv/**","**/__pycache__/**","**/logs/**","**/tmp/**","**/temp/**"];var Ra=r("../../node_modules/.pnpm/picomatch@4.0.3/node_modules/picomatch/index.js");async function Ta(e){if(!(0,a.isAbsolute)(e))return null;const t=await(0,h.DN)(e);return null===t?null:t}class Ia{ignoreServicePromise;constructor(e,t,r){this.ignoreServicePromise=Oa.init((0,l.q6)(),e,r??[process.cwd()],t)}isIgnoredByAny(e){return this.ignoreServicePromise.then((t=>t.isIgnoredByAny(e)))}isGitIgnored(e){return this.ignoreServicePromise.then((t=>t.isGitIgnored(e)))}isCursorIgnored(e){return this.ignoreServicePromise.then((t=>t.isCursorIgnored(e)))}isRepoBlocked(e){return this.ignoreServicePromise.then((t=>t.isRepoBlocked(e)))}listCursorIgnoreFilesByRoot(e){return this.ignoreServicePromise.then((t=>t.listCursorIgnoreFilesByRoot(e)))}getCursorIgnoreMapping(){return this.ignoreServicePromise.then((e=>e.getCursorIgnoreMapping()))}getGitIgnoreMapping(){return this.ignoreServicePromise.then((e=>e.getGitIgnoreMapping()))}getRepoBlockExcludeGlobs(e){return this.ignoreServicePromise.then((t=>t.getRepoBlockExcludeGlobs(e)))}handleCursorIgnoreCreated(e){return this.ignoreServicePromise.then((t=>t.handleCursorIgnoreCreated(e)))}handleCursorIgnoreChanged(e){return this.ignoreServicePromise.then((t=>t.handleCursorIgnoreChanged(e)))}handleCursorIgnoreDeleted(e){return this.ignoreServicePromise.then((t=>t.handleCursorIgnoreDeleted(e)))}}const Aa=Math.min(8,Math.max(1,Math.floor(i.default.availableParallelism()/2)));class Oa{gitExecutor;gitIgnoreMapping;cursorIgnoreMapping;teamSettingsService;rootDirectories;static ripwalkCache;gitIgnoreCache=new h.qK({max:2e3});cursorIgnoreCache=new h.qK({max:2e3});gitRootCache=new h.qK({max:1e3});gitRemoteUrlCache=new h.qK({max:200});hasGitDirCache=new h.qK({max:1e3});static promiseQueue=new h.TJ({max:Aa});gitParsedIgnoreCache=new Map;cursorParsedIgnoreCache=new Map;gitRepoMappingPromise;constructor(e,t,r,o,n){this.gitExecutor=e,this.gitIgnoreMapping=t,this.cursorIgnoreMapping=r,this.teamSettingsService=o,this.rootDirectories=n}static getRipwalkCache(){return Oa.ripwalkCache??=new ka,Oa.ripwalkCache}getIgnoreInstance(e,t,r){let o=r.get(e);return o||(o=an().add(t),r.set(e,o)),o}hasNoWorkspaceFolders(){return 0===Object.keys(this.gitIgnoreMapping).length&&0===Object.keys(this.cursorIgnoreMapping).length}async resolveLookupRoot(e){return await(0,h.DN)(e)??(0,h.o1)(e)}static async init(e,t,r,o){const n=await(0,h.PH)(r,(async e=>{const t=await(0,h.DN)(e);return null===t?(console.warn(`[IgnoreService] Cannot resolve workspace root, using as-is: ${e}`),e):t})),s={},i={},a=(await(0,h.PH)(n,(r=>Ea(e,t,r)))).filter((e=>null!==e));return a.length>0&&await Promise.all([o?o.getTeamRepos():Promise.resolve(void 0),Oa.initializeIgnoreMapping(a,".gitignore",s),Oa.initializeIgnoreMapping(n,".cursorignore",i)]),new Oa(t,s,i,o,n)}static async preloadHierarchy(e,t,r,o){let n=(0,h.o1)(e);const s=(0,a.parse)(n).root;for(;n!==s;){if(o?.has(n)){const e=(0,a.dirname)(n);if(e===n)break;n=e;continue}void 0===r[n]&&await Oa.handleHierarchyIgnore(n,t,r),o?.add(n);const e=(0,a.dirname)(n);if(e===n)break;n=e}}static async handleHierarchyIgnore(e,t,r){const o=(0,a.join)(e,t);try{await(0,fo.access)(o,fo.default.constants.F_OK);const t=await(0,h.yR)(o),n=Oa.parseIgnoreRules(t);r[e]=n}catch(n){"ENOENT"===n.code||console.error(`Error reading ${t} file at ${o}:`,n),r[e]=[]}}static async initializeIgnoreMapping(e,t,r){try{const o=Oa.deduplicateRootDirectories(e),n=await Oa.promiseQueue.enqueueList(o,(e=>Oa.findFilesWithRipgrep(e,t))),s=Array.from(n.values()).flat();await Promise.all(s.map((async e=>{try{const t=await(0,h.yR)(e),o=Oa.parseIgnoreRules(t),n=(0,a.dirname)(e);r[n]=o}catch(r){console.error(`Error processing ${t} file at ${e}:`,r)}})));const i=new Set;for(const e of o)await Oa.preloadHierarchy(e,t,r,i)}catch(e){console.error(`Error initializing ignore mapping for ${t}:`,e)}}static async findFilesWithRipgrep(e,t){const r=(0,l.q6)(),o=[],n={root:e,includeGlobs:[`**/${t}`],excludeGlobs:Pa,source:"ignore_scan"},s=Oa.getRipwalkCache().walk(r,n);for await(const t of s.lines)o.push((0,a.join)(e,t));return o}async handleManualLookupWhenNoWorkspaceDirs(e,t){const r={};let o=(0,a.dirname)(e);const n=(0,a.parse)(o).root;for(;;){const e=(0,a.join)(o,t);try{const t=await(0,h.yR)(e),n=Oa.parseIgnoreRules(t);n.length>0&&(r[o]=n)}catch{}if(o===n)break;o=(0,a.dirname)(o)}return this.testIgnored(e,r,((e,t)=>an().add(t)))}async isIgnoredByAny(e){const[t,r,o]=await Promise.all([this.checkGitIgnored(e),this.checkCursorIgnored(e),this.checkRepoBlocked(e)]);return t||r||o}async isGitIgnored(e){return this.checkGitIgnored(e)}async isCursorIgnored(e){return this.checkCursorIgnored(e)}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){if(this.hasNoWorkspaceFolders())return this.handleManualLookupWhenNoWorkspaceDirs(e,".cursorignore");const t=this.cursorIgnoreCache.get(e);if(void 0!==t)return t;await this.populateHierarchyIfNeeded(e,".cursorignore",this.cursorIgnoreMapping);const r=this.checkIgnored(e,this.cursorIgnoreMapping,this.cursorParsedIgnoreCache);return this.cursorIgnoreCache.set(e,r),r}async populateHierarchyIfNeeded(e,t,r){let o=(0,a.dirname)((0,h.o1)(e));const n=[],s=(0,a.parse)(o).root;for(;o!==s;){if(this.rootDirectories.some((e=>(0,h.ZU)({basePath:e,targetPath:o})))){o=(0,a.dirname)(o);continue}if(void 0!==r[o])break;n.push(o);const e=(0,a.dirname)(o);if(e===o)break;o=e}n.length>0&&(await Oa.promiseQueue.enqueueList(n,(e=>Oa.handleHierarchyIgnore(e,t,r))),".gitignore"===t?this.gitIgnoreCache.clear():this.cursorIgnoreCache.clear())}testIgnored(e,t,r){for(const[o,n]of Object.entries(t)){if(0===n.length)continue;if(!(0,h.ZU)({basePath:o,targetPath:e}))continue;const t=(0,a.relative)(o,e);if(""===t)continue;const s=r(o,n),i=(0,h.oL)(t),l=s.test(i);if(l.ignored&&!l.unignored)return!0;const c=s.test(`${i}/`);if(c.ignored&&!c.unignored)return!0}return!1}checkIgnored(e,t,r){return this.testIgnored(e,t,((e,t)=>this.getIgnoreInstance(e,t,r)))}async listCursorIgnoreFilesByRoot(e){const t=await this.resolveLookupRoot(e),r=[];for(const[e,o]of Object.entries(this.cursorIgnoreMapping)){if(0===o.length)continue;if(!(0,h.ZU)({basePath:t,targetPath:e}))continue;const n=(0,a.join)(e,".cursorignore");try{await(0,fo.access)(n),r.push(n)}catch{}}return r}async getCursorIgnoreMapping(){return{...this.cursorIgnoreMapping}}async getGitIgnoreMapping(){return{...this.gitIgnoreMapping}}static deduplicateRootDirectories(e){const t=[...e.map((e=>(0,h.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()}async handleCursorIgnoreCreated(e){const t=(0,a.dirname)(e),r=await(0,h.yR)(e),o=Oa.parseIgnoreRules(r);this.cursorIgnoreMapping[t]=o,this.cursorParsedIgnoreCache.delete(t),this.cursorIgnoreCache.clear()}async handleCursorIgnoreChanged(e){const t=(0,a.dirname)(e),r=await(0,h.yR)(e),o=Oa.parseIgnoreRules(r);this.cursorIgnoreMapping[t]=o,this.cursorParsedIgnoreCache.delete(t),this.cursorIgnoreCache.clear()}handleCursorIgnoreDeleted(e){const t=(0,a.dirname)(e);this.cursorIgnoreMapping[t]=[],this.cursorParsedIgnoreCache.delete(t),this.cursorIgnoreCache.clear()}async findGitRootsForFile(e){const t=(0,h.o1)(e),r=this.gitRootCache.get(t);if(void 0!==r)return r;const o=[],n=[],s=[];let i=t;const l=(0,a.parse)(i).root;for(;i!==l;){n.push(i),void 0===this.hasGitDirCache.get(i)&&s.push(i);const e=(0,a.dirname)(i);if(e===i)break;i=e}if(s.length>0){const e=s.map((e=>(0,fo.access)((0,a.join)(e,".git"),fo.default.constants.F_OK).then((()=>[e,!0])).catch((()=>[e,!1])))),t=await Promise.all(e);for(const[e,r]of t)this.hasGitDirCache.set(e,r)}for(const e of n)!0===this.hasGitDirCache.get(e)&&o.push(e);return this.gitRootCache.set(t,o),o}async isRepoBlocked(e){return this.checkRepoBlocked(e)}async checkRepoBlocked(e){const t=await this.findGitRootsForFile(e);if(0===t.length)return!1;const r=await(this.teamSettingsService?.getTeamRepos());if(!r||!r.repos)return!1;for(const o of t){let t;this.gitRemoteUrlCache.has(o)?t=this.gitRemoteUrlCache.get(o):(t=await xa((0,l.q6)(),this.gitExecutor,o),void 0!==t&&this.gitRemoteUrlCache.set(o,t));const n=r.repos.filter((e=>void 0!==t&&this.doesRepoUrlMatch(e.url,t)));if(0===n.length)continue;const s=(0,a.relative)(o,e)||".";for(const e of n)for(const t of e.patterns||[])if(this.matchGlob(t.pattern,s))return!0}return!1}doesRepoUrlMatch(e,t){if(e.trim().toLowerCase().replace(/\.git$/i,""),e.includes("*")){if("*"===e.trim())return!0;const r=Ca(e).toLowerCase(),o=Ca(t).toLowerCase();return this.matchRepoUrlGlob(r,o)}return Ca(e).toLowerCase()===Ca(t).toLowerCase()}matchGlob(e,t){const r=e.trim();if(!("."!==t&&""!==t||"**"!==r&&"**/*"!==r))return!0;try{return Ra(r)(t)}catch{return r===t}}matchRepoUrlGlob(e,t){const r=e.trim();return!!this.matchGlob(r,t)||!!r.startsWith("*/")&&this.matchGlob(`**/${r.slice(2)}`,t)}async getRepoBlockExcludeGlobs(e){const t=await(this.teamSettingsService?.getTeamRepos());if(!t?.repos?.length)return[];const r=await this.resolveLookupRoot(e),o=await this.getGitRepoMapping();if(0===o.size)return[];const n=[];for(const[e,s]of o){if(void 0===s)continue;const o=this.normalizePathForComparison(e),i=this.normalizePathForComparison(r);let l=!1,c="";if(i.startsWith(o)?(l=!0,c=""):o.startsWith(i)&&(l=!0,c=(0,a.relative)(r,e)),!l)continue;const u=t.repos.filter((e=>this.doesRepoUrlMatch(e.url,s)));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=c?(0,a.join)(c,e).replace(/\\/g,"/"):e,n.push(r),r.endsWith("/**")||n.push(`${r}/**`)}}return n}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(){const e=new Map,t=[],r=["**/node_modules/**","**/.turbo/**","**/.next/**","**/.cache/**","**/.pnpm/**","**/.yarn/**","**/dist/**","**/build/**","**/out/**","**/target/**","**/.vscode/**","**/.idea/**","**/venv/**","**/__pycache__/**","**/logs/**","**/tmp/**","**/temp/**"],o=(0,l.q6)();for(const e of this.rootDirectories){const n=(0,h.o1)(e);try{await(0,fo.access)((0,a.join)(n,".git"),fo.default.constants.F_OK),t.includes(n)||t.push(n)}catch{}let s=(0,a.dirname)(n);const i=(0,a.parse)(s).root;for(;s!==i&&""!==s;){try{await(0,fo.access)((0,a.join)(s,".git"),fo.default.constants.F_OK),t.includes(s)||t.push(s)}catch{}const e=(0,a.dirname)(s);if(e===s)break;s=e}try{const e={root:n,includeGlobs:["**/.git/config"],excludeGlobs:r,noIgnoreVcs:!0,source:"ignore_scan"},s=Oa.getRipwalkCache().walk(o,e);for await(const e of s.lines){const r=(0,a.join)(n,e),o=(0,a.dirname)(r),s=(0,a.dirname)(o);t.includes(s)||t.push(s)}}catch{}}return await Promise.all(t.map((async t=>{try{const r=await xa(o,this.gitExecutor,t);e.set(t,r)}catch{e.set(t,void 0)}}))),e}}var Da=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var o,n=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===n)return n=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var s=o.dispose.call(o.value);if(o.async)return n|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else n|=1}catch(e){r(e)}if(1===n)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var o=new Error(r);return o.name="SuppressedError",o.error=e,o.suppressed=t,o});const Ma=[{pattern:/[/\\]\.cursor[/\\]skills[/\\]/i,requiresThirdParty:!1},{pattern:/[/\\]\.agents[/\\]skills[/\\]/i,requiresThirdParty:!1},{pattern:/[/\\]\.claude[/\\]skills[/\\]/i,requiresThirdParty:!0},{pattern:/[/\\]\.codex[/\\]skills[/\\]/i,requiresThirdParty:!0},{pattern:/[/\\]\.cursor[/\\]skills-cursor[/\\]/i,requiresThirdParty:!1}],ja=/[/\\]\.cursor[/\\]rules[/\\]/i,Na=[{pattern:/[/\\]\.cursor[/\\]agents[/\\]/i,requiresThirdParty:!1},{pattern:/[/\\]\.claude[/\\]agents[/\\]/i,requiresThirdParty:!0}],$a=new Set(["AGENTS.md","CLAUDE.md","CLAUDE.local.md"]);function Fa(e,t){const r=e.replace(/\\/g,"/"),o=(0,a.basename)(r);if($a.has(o))return"AGENTS.md"===o||t&&("CLAUDE.md"===o||"CLAUDE.local.md"===o)?"markdown":void 0;if(ja.test(r)&&o.endsWith(".mdc"))return"rules";if("SKILL.md"===o)for(const{pattern:e,requiresThirdParty:o}of Ma)if(e.test(r)){if(o&&!t)continue;return"skills"}if(o.endsWith(".md"))for(const{pattern:e,requiresThirdParty:o}of Na)if(e.test(r)){if(o&&!t)continue;return"agents"}}class La{root;gitExecutor;userHomeDirectory;getThirdPartyExtensibilityEnabled;static ripwalkCache;constructor(e,t,r,o){this.root=e,this.gitExecutor=t,this.userHomeDirectory=r,this.getThirdPartyExtensibilityEnabled=o}static getRipwalkCache(){return La.ripwalkCache??=new ka,La.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 o,n;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");o=t[Symbol.asyncDispose]}if(void 0===o){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");o=t[Symbol.dispose],r&&(n=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");n&&(o=function(){try{n.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:o,async:r})}else r&&e.stack.push({async:!0});return t}(t,(0,l.VI)(e.withName("NestedExtensibilityService.discover")),!1),o={rules:[],skills:[],markdown:[],agents:[]};if((0,a.resolve)(this.root)===(0,a.resolve)(this.userHomeDirectory))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),o;if(!await Ea(e,this.gitExecutor,(0,a.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),o;const n=this.getThirdPartyExtensibilityEnabled(),s=this.buildIncludeGlobs(n),i={root:this.root,includeGlobs:s,excludeGlobs:Pa,followSymlinks:!0,source:"nested_extensibility"},c={rules:[],skills:[],markdown:[],agents:[]},u=La.getRipwalkCache();try{const e=u.walk(r.ctx,i);try{for await(const t of e.lines){const e=Fa(t,n);e&&c[e].push((0,a.resolve)(this.root,t))}}finally{u.delete(i)}}catch{}return r.span.setAttribute("nested_extensibility.rules",c.rules.length),r.span.setAttribute("nested_extensibility.skills",c.skills.length),r.span.setAttribute("nested_extensibility.markdown",c.markdown.length),r.span.setAttribute("nested_extensibility.agents",c.agents.length),c}catch(e){t.error=e,t.hasError=!0}finally{Da(t)}}buildIncludeGlobs(e){const t=["*/**/.cursor/**","*/**/.agents/**","*/**/AGENTS.md"];return e&&t.push("*/**/.claude/**","*/**/.codex/**","*/**/CLAUDE.md","*/**/CLAUDE.local.md"),t}}const Ua=new Set(["node_modules",".git",".svn",".hg","__pycache__",".cache","dist","build",".next",".nuxt"]);async function Ba({rootDir:e,includeFile:t,maxDepth:r=10,skipDirectories:o=Ua,containmentRootDir:n}){const s=[],i=[{dir:e,depth:0}],l=new Set,c=void 0!==n?await(0,fo.realpath)(n):null,u=e=>{if(null===c)return!0;const t=(0,a.relative)(c,e);return""===t||!t.startsWith("..")&&!(0,a.isAbsolute)(t)};for(;i.length>0;){const e=i.pop();if(void 0===e)continue;const{dir:n,depth:c}=e;if(c>r)continue;try{const e=await(0,fo.realpath)(n);if(!u(e))continue;if(l.has(e))continue;l.add(e)}catch{continue}const d=await(0,fo.readdir)(n,{withFileTypes:!0,encoding:"utf8"}).catch((()=>null));if(null!==d)for(const e of d){const r=(0,a.join)(n,e.name);let l=e.isDirectory(),u=e.isFile();if(e.isSymbolicLink())try{const e=await(0,fo.stat)(r);l=e.isDirectory(),u=e.isFile()}catch{continue}if(l){if(o.has(e.name))continue;i.push({dir:r,depth:c+1})}else u&&t(e.name)&&s.push(r)}}return s.sort(((e,t)=>e.localeCompare(t))),s}const Ha=new Set(["imagegen","openai-docs","opneai-docs","plugin-creator","skill-creator","skill-installer"]);function za(e){const t=e.replace(/\\/g,"/").split("/").filter(Boolean),r=t.lastIndexOf(".codex");if(-1===r||"skills"!==t[r+1])return!1;const o=t.at(-1),n="SKILL.md"===o?t.at(-2):o;return void 0!==n&&Ha.has(n)}function Wa(e){return{dirPath:(0,a.join)(e,".cursor","skills-cursor"),scope:"builtin",source:"builtin"}}function qa(e,t){const r=[];return t&&r.push({dirPath:(0,a.join)(e,".claude","skills"),scope:"project",source:"workspace"},{dirPath:(0,a.join)(e,".codex","skills"),scope:"project",source:"workspace"}),r.push({dirPath:(0,a.join)(e,".agents","skills"),scope:"project",source:"workspace"},{dirPath:(0,a.join)(e,".cursor","skills"),scope:"project",source:"workspace"}),r}function Ga(e,t){const r=[];return t&&r.push({dirPath:(0,a.join)(e,".claude","skills"),scope:"user",source:"user"},{dirPath:(0,a.join)(e,".codex","skills"),scope:"user",source:"user"}),r.push({dirPath:(0,a.join)(e,".agents","skills"),scope:"user",source:"user"},{dirPath:(0,a.join)(e,".cursor","skills"),scope:"user",source:"user"}),r}var Va=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var o,n;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");o=t[Symbol.asyncDispose]}if(void 0===o){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");o=t[Symbol.dispose],r&&(n=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");n&&(o=function(){try{n.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:o,async:r})}else r&&e.stack.push({async:!0});return t},Ja=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 o,n=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===n)return n=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var s=o.dispose.call(o.value);if(o.async)return n|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else n|=1}catch(e){r(e)}if(1===n)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var o=new Error(r);return o.name="SuppressedError",o.error=e,o.suppressed=t,o});const Ka=(0,l.h)("local-exec:cursor-rules");async function Za(e){return await Ba({rootDir:e,includeFile:e=>"SKILL.md"===e})}function Ya(e){return Qa(e.data?.environments??e.data?.metadata?.environments)??[]}function Xa(e){return Qa(e.data?.["disabled-environments"]??e.data?.metadata?.disabledEnvironments)??[]}function Qa(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 el(e,t){const r=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 r.length>0&&!r.includes(t)}function tl(e){return e.slice(0,1536)}async function rl(e){const t=await(0,h.yR)(e);return{skillFilePath:e,content:t,parsed:sn(t)}}function ol(e){return!0===e.data?.alwaysApply}function nl({skillFilePath:e,content:t,parsed:r}){if(ol(r))return new on.DX({fullPath:e,content:t,type:new on.f5({type:{case:"global",value:new on.i9}}),environments:Ya(r),disabledEnvironments:Xa(r)});const o="string"==typeof r.data?.description?tl(r.data.description):void 0;return o?new on.DX({fullPath:e,content:t,type:new on.f5({type:{case:"agentFetched",value:new on.Xo({description:o})}}),environments:Ya(r),disabledEnvironments:Xa(r)}):new on.DX({fullPath:e,parseError:"Description is required",type:new on.f5({type:{case:"agentFetched",value:new on.Xo}})})}function sl({skillFilePath:e,content:t,parsed:r}){const o="string"==typeof r.data?.description?tl(r.data.description):"",n=qi(r.data?.paths??r.data?.globs);return new rn.N({fullPath:e,content:t,description:o,globs:n??[],parseError:o?void 0:"Description is required",environments:Ya(r),disabledEnvironments:Xa(r),disableModelInvocation:!0===r.data?.["disable-model-invocation"]})}function il({rules:e,agentSkills:t,skillFilePath:r,errorMessage:o}){e.push(function({skillFilePath:e,errorMessage:t}){return new on.DX({fullPath:e,parseError:t,type:new on.f5({type:{case:"agentFetched",value:new on.Xo}})})}({skillFilePath:r,errorMessage:`Failed to read skill file: ${o}`})),t.push(function({skillFilePath:e,errorMessage:t}){return new rn.N({fullPath:e,parseError:t})}({skillFilePath:r,errorMessage:`Failed to read skill file: ${o}`}))}function al(e){const t=e.replace(/\\/g,"/"),r=t.toLowerCase(),o=r.indexOf("/.cursor/"),n=r.indexOf("/.claude/"),s=r.indexOf("/.codex/"),i=r.indexOf("/.agents/");return-1!==o?`${t.slice(0,o)}::${t.slice(o+9)}`:-1!==n?`${t.slice(0,n)}::${t.slice(n+9)}`:-1!==s?`${t.slice(0,s)}::${t.slice(s+8)}`:-1!==i?`${t.slice(0,i)}::${t.slice(i+9)}`:e}function ll(e){const t=e.trim();return"true"===t||"false"!==t&&(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t)}function cl(e){const t=e.trimStart();if(!t.startsWith("---"))return null;const r=t.split("---").filter(Boolean);if(r.length<2)return null;const o=r[0].trim(),n=r.slice(1).join("---").trim(),s={};let i=null,a=null;for(const e of o.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 o=t.startsWith(" ")||t.startsWith("\t");if(i&&o){const e=t.trim(),r=e.indexOf(":");if(-1===r)continue;const o=e.slice(0,r).trim(),n=e.slice(r+1).trim(),l=ll(n),c=`${i}.${o}`;""===n?(s[c]=[],a=c):"metadata.environments"===c||"metadata.disabledEnvironments"===c?(s[c]=String(l).split(",").map((e=>e.trim())).filter(Boolean),a=null):(s[c]=l,a=null);continue}i=null,a=null;const n=t.indexOf(":");if(-1===n)continue;const l=t.slice(0,n).trim(),c=t.slice(n+1).trim();""!==c||"metadata"!==l?"globs"!==l||""!==c?s[l]=ll(c):(s.globs=[],a="globs"):i=l}return{frontmatter:s,body:n}}class ul{cursorRulesServices;static CHANGE_COALESCE_MS=1e3;onChangeCallbacks=new Set;disposeChangeListeners;changeTimer;constructor(e){this.cursorRulesServices=e}async getAllCursorRules(e){const t={stack:[],error:void 0,hasError:!1};try{const r=Va(t,(0,l.VI)(e.withName("MergedCursorRulesService.getAllCursorRules")),!1),o=this.cursorRulesServices.map((e=>e.getAllCursorRules(r.ctx).catch((e=>((0,ln.debuglog)("Failed to load cursor rules from service:",e),[]))))),n=(await Promise.all(o)).flat(),s=new Set,i=[];for(const e of n){const t=al(e.fullPath);s.has(t)||(s.add(t),i.push(e))}return i}catch(e){t.error=e,t.hasError=!0}finally{Ja(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()}),ul.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()}}class dl{gitExecutor;rootDirectory;loadNestedRules;getThirdPartyExtensibilityEnabled;static ripwalkCache;_rules;loadTraceId=void 0;unsubscribeWatcher;onChangeCallbacks=new Set;ignoreService;nestedExtensibilityService;constructor(e,t,r,o,n,s,a,c){this.gitExecutor=t,this.rootDirectory=r,this.loadNestedRules=o,this.getThirdPartyExtensibilityEnabled=n,this.nestedExtensibilityService=new La(r,t,(0,i.homedir)(),n),this.ignoreService=a??new Ia(t,void 0,[this.rootDirectory]);const u=performance.now();if(this._rules=this.load(e,c).then((t=>{try{Ka.info(e,"LocalCursorRulesService load completed",{durationMs:Math.round(performance.now()-u),ruleCount:t.length})}catch{}return t})).catch((e=>((0,ln.debuglog)("Failed to load cursor rules:",e),[]))),s){const e=[".cursor/rules/**/*.mdc","AGENTS.md","CLAUDE.md","CLAUDE.local.md",".cursorrules"];this.unsubscribeWatcher=s.subscribe(this.rootDirectory,e,(e=>{const t={stack:[],error:void 0,hasError:!1};try{const r=(0,l.q6)(),o=Va(t,(0,l.VI)(r.withName("LocalCursorRulesService.fileWatcher.subscribe")),!1);this.reloadAtPath(o.ctx,e)}catch(e){t.error=e,t.hasError=!0}finally{Ja(t)}}))}}reload(e){this._rules=this.load(e).catch((e=>((0,ln.debuglog)("Failed to load cursor rules:",e),[])));for(const e of this.onChangeCallbacks)e()}static getRipwalkCache(){return dl.ripwalkCache??=new ka,dl.ripwalkCache}reloadAtPath(e,t){const r={stack:[],error:void 0,hasError:!1};try{const o=Va(r,(0,l.VI)(e.withName("LocalCursorRulesService.reloadAtPath")),!1),n=this._rules;this._rules=(async()=>[...(await n).filter((e=>e.fullPath!==t)),...(await this.readRulesAtPath(o.ctx,t)).map((e=>this.toCursorRule(e)))])().catch((e=>((0,ln.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{Ja(r)}}isRuleMarkdownFile(e){return"CLAUDE.md"===e||"CLAUDE.local.md"===e||"AGENTS.md"===e}async readRulesAtPath(e,t){const r={stack:[],error:void 0,hasError:!1};try{const o=Va(r,(0,l.VI)(e.withName("LocalCursorRulesService.readRulesAtPath")),!1),n=(0,a.basename)(t);if(".cursorrules"===n){const e=(0,a.resolve)(this.rootDirectory),t=await Ea(o.ctx,this.gitExecutor,e)||e,r=await this.loadCursorRulesRule(o.ctx,t);return r?[r]:[]}if(n.endsWith(".mdc"))try{const e=cl(await(0,h.yR)(t));if(e)return[{filename:(0,a.basename)(t,".mdc"),path:t,frontmatter:e.frontmatter,body:e.body}]}catch{}else if(this.isRuleMarkdownFile(n))try{return await this.loadRulesFromMarkdownFile(o.ctx,(0,a.dirname)(t),n)}catch{}return[]}catch(e){r.error=e,r.hasError=!0}finally{Ja(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 o=Va(r,(0,l.VI)(e.withName("LocalCursorRulesService.load")),!1);this.loadTraceId=o.span.spanContext().traceId;const n=(0,a.resolve)(this.rootDirectory),s=await Ea(o.ctx,this.gitExecutor,n)||n,i=this.loadCursorRulesRule(o.ctx,s).then((e=>e?[e]:[])),c=this.loadRulesFromDirAndAncestors(o.ctx,n);let u,d;if(this.loadNestedRules){const e=t??this.nestedExtensibilityService.discover(o.ctx);u=e.then((e=>this.parseNestedRuleFiles(o.ctx,e.rules))),d=e.then((e=>this.parseNestedMarkdownFiles(o.ctx,e.markdown)))}else u=[],d=[];const p=(await Promise.all([i,c,u,d])).flat(),h=new Map;for(const e of p)h.set(e.path,e);return[...h.values()].map((e=>this.toCursorRule(e)))}catch(e){r.error=e,r.hasError=!0}finally{Ja(r)}}async loadCursorRulesRule(e,t){const r={stack:[],error:void 0,hasError:!1};try{Va(r,(0,l.VI)(e.withName("LocalCursorRulesService.loadCursorrules")),!1);try{const e=(0,a.join)(t,".cursorrules");if((await(0,fo.stat)(e)).isFile())return{filename:".cursorrules",path:e,frontmatter:{alwaysApply:!0},body:await(0,h.yR)(e)}}catch{}return null}catch(e){r.error=e,r.hasError=!0}finally{Ja(r)}}async getAllCursorRules(e){const t={stack:[],error:void 0,hasError:!1};try{return Va(t,(0,l.VI)(e.withName("LocalCursorRulesService.getAllCursorRules")),!1).span.setAttribute("cacheTraceId",this.loadTraceId??"undefined"),await this._rules}catch(e){t.error=e,t.hasError=!0}finally{Ja(t)}}toCursorRule(e){return function(e){let t;if(!0===e.frontmatter.alwaysApply)t={case:"global",value:new on.i9};else{const r=qi(e.frontmatter.globs);t=r&&r.length>0?{case:"fileGlobbed",value:new on.uT({globs:r})}:"string"==typeof e.frontmatter.description&&e.frontmatter.description.trim().length>0?{case:"agentFetched",value:new on.Xo({description:tl(e.frontmatter.description)})}:{case:"manuallyAttached",value:new on._u}}const r=e.frontmatter["metadata.environments"],o=Array.isArray(r)?r:[],n=e.frontmatter["metadata.disabledEnvironments"],s=Array.isArray(n)?n:[];return new on.DX({fullPath:e.path,content:e.body,type:new on.f5({type:t}),environments:o,disabledEnvironments:s})}({path:e.path,body:e.body,frontmatter:e.frontmatter})}async loadRulesFromDirAndAncestors(e,t){const r={stack:[],error:void 0,hasError:!1};try{const o=Va(r,(0,l.VI)(e.withName("LocalCursorRulesService.loadRulesFromDirAndAncestors")),!1),n=[];let s=t;const i=this.getThirdPartyExtensibilityEnabled();for(;;){const e=(0,a.join)(s,".cursor","rules");n.push((async()=>await this.dirIsDirectory(o.ctx,e)?this.loadRulesFromDirectory(o.ctx,e):[])());const t=[];i&&t.push("CLAUDE.md","CLAUDE.local.md"),t.push("AGENTS.md");for(const e of t)n.push(this.loadRulesFromMarkdownFile(o.ctx,s,e));const r=(0,a.dirname)(s);if(r===s)break;s=r}const c=(await Promise.all(n)).flat();return o.span.setAttribute("rules",c.length),c}catch(e){r.error=e,r.hasError=!0}finally{Ja(r)}}async loadRulesFromMarkdownFile(e,t,r){const o={stack:[],error:void 0,hasError:!1};try{Va(o,(0,l.VI)(e.withName("LocalCursorRulesService.loadRulesFromMarkdownFile")),!1).span.setAttribute("filename",r);try{const e=(0,a.join)(t,r);if(await this.isCursorIgnored(e))return[];if((await(0,fo.stat)(e)).isFile()){const t=await(0,h.yR)(e);return[{filename:(0,a.basename)(e,".md"),path:e,frontmatter:{alwaysApply:!0},body:t}]}}catch{}return[]}catch(e){o.error=e,o.hasError=!0}finally{Ja(o)}}async isCursorIgnored(e){try{const t=await Ta((0,a.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 o=Va(r,(0,l.VI)(e.withName("LocalCursorRulesService.parseNestedRuleFiles")),!1),n=(await Promise.all(t.map((async e=>{try{const t=cl(await(0,h.yR)(e));if(t)return{filename:(0,a.basename)(e,".mdc"),path:e,frontmatter:t.frontmatter,body:t.body}}catch{}})))).filter((e=>void 0!==e));return o.span.setAttribute("ruleFiles",n.length),n}catch(e){r.error=e,r.hasError=!0}finally{Ja(r)}}async parseNestedMarkdownFiles(e,t){const r={stack:[],error:void 0,hasError:!1};try{const o=Va(r,(0,l.VI)(e.withName("LocalCursorRulesService.parseNestedMarkdownFiles")),!1),n=(await Promise.all(t.map((async e=>{try{const t=(0,a.basename)(e);if(!this.isRuleMarkdownFile(t))return[];const r=(0,a.dirname)(e);return await this.loadRulesFromMarkdownFile(o.ctx,r,t)}catch{}return[]})))).flat();return o.span.setAttribute("markdownFiles",n.length),n}catch(e){r.error=e,r.hasError=!0}finally{Ja(r)}}async loadRulesFromDirectory(e,t){const r={stack:[],error:void 0,hasError:!1};try{const o=Va(r,(0,l.VI)(e.withName("LocalCursorRulesService.loadRulesFromDirectory")),!1),n=[];try{const e={root:t,includeGlobs:["**/*.mdc"],followSymlinks:!0,source:"cursor_rules"},r=dl.getRipwalkCache().walk(o.ctx,e);for await(const e of r.lines){const r=(0,a.join)(t,e);n.push(...await this.readRulesAtPath(o.ctx,r))}}catch{}return o.span.setAttribute("rules",n.length),n}catch(e){r.error=e,r.hasError=!0}finally{Ja(r)}}async dirIsDirectory(e,t){const r={stack:[],error:void 0,hasError:!1};try{Va(r,(0,l.VI)(e.withName("LocalCursorRulesService.dirIsDirectory")),!1);try{return(await(0,fo.stat)(t)).isDirectory()}catch{return!1}}catch(e){r.error=e,r.hasError=!0}finally{Ja(r)}}}class pl{workspacePaths;userHomeDirectory;gitExecutor;initialBuiltinSkillsSyncPromise;_rules;_agentSkills;watchersByFolder=new Map;onChangeCallbacks=new Set;foldersToWatch;fileWatcher;getThirdPartyExtensibilityEnabled;surface;nestedExtensibilityEntries;constructor(e,t,r,o,n,s,i=()=>!0,a=Promise.resolve(),l="ide",c){if(this.workspacePaths=t,this.userHomeDirectory=r,this.gitExecutor=o,this.initialBuiltinSkillsSyncPromise=a,this.surface=l,this.fileWatcher=s,this.getThirdPartyExtensibilityEnabled=i,void 0!==c&&c.length!==t.length)throw new Error(`initialNestedExtensibilityResults length (${c.length}) must match workspacePaths length (${t.length})`);this.nestedExtensibilityEntries=n?t.map((e=>new La(e,o,r,i))):[],this.foldersToWatch=this.computeFoldersToWatch();const u=performance.now(),d=this.loadAll(e,c).then((t=>{try{Ka.info(e,"AgentSkillsCursorRulesService load completed",{durationMs:Math.round(performance.now()-u),ruleCount:t.rules.length,skillCount:t.agentSkills.length})}catch{}return t})).catch((e=>((0,ln.debuglog)("Failed to load Agent Skills:",e),{rules:[],agentSkills:[]})));this._rules=d.then((e=>e.rules)),this._agentSkills=d.then((e=>e.agentSkills)),this.setupWatchers(this.foldersToWatch)}computeFoldersToWatch(){const e=this.getThirdPartyExtensibilityEnabled(),t=new Set;for(const r of this.workspacePaths){t.add((0,a.join)(r,".cursor","rules"));for(const o of qa(r,e))t.add(o.dirPath)}for(const r of Ga(this.userHomeDirectory,e))t.add(r.dirPath);return t.add(Wa(this.userHomeDirectory).dirPath),Array.from(t)}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,l.q6)(),o=Va(t,(0,l.VI)(r.withName("AgentSkillsCursorRulesService.fileWatcher.subscribe")),!1);this.reloadAtPath(o.ctx,e)}catch(e){t.error=e,t.hasError=!0}finally{Ja(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){return await this._rules}reload(e){const t=this.computeFoldersToWatch(),r=new Set(this.foldersToWatch),o=new Set(t),n=this.foldersToWatch.filter((e=>!o.has(e)));this.removeWatchers(n);const s=t.filter((e=>!r.has(e)));this.setupWatchers(s),this.foldersToWatch=t;const i=this.loadAll(e).catch((e=>((0,ln.debuglog)("Failed to load Agent Skills:",e),{rules:[],agentSkills:[]})));this._rules=i.then((e=>e.rules)),this._agentSkills=i.then((e=>e.agentSkills));for(const e of this.onChangeCallbacks)e()}reloadAtPath(e,t){const r={stack:[],error:void 0,hasError:!1};try{Va(r,(0,l.VI)(e.withName("AgentSkillsCursorRulesService.reloadAtPath")),!1);const o=t.endsWith("SKILL.md")?t:(0,a.join)(t,"SKILL.md"),n=rl(o);n.catch((()=>{}));const s=async(e,t)=>{const r=(await e).filter((e=>e.fullPath!==o));if(za(o))return r;try{await(0,fo.stat)(o);const e=await n;if(el(e.parsed,this.surface))return r;const s=t(e);return void 0===s?r:[...r,s]}catch{return r}};this._rules=s(this._rules,(e=>nl(e))).catch((e=>((0,ln.debuglog)("Failed to load Agent Skills at path:",e),[]))),this._agentSkills=s(this._agentSkills,(e=>ol(e.parsed)?void 0:sl(e))).catch((e=>((0,ln.debuglog)("Failed to load Agent Skills (proto) at path:",e),[])));for(const e of this.onChangeCallbacks)e()}catch(e){r.error=e,r.hasError=!0}finally{Ja(r)}}async getAllAgentSkills(e){return await this._agentSkills}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 o=Va(r,(0,l.VI)(e.withName("AgentSkillsCursorRulesService.loadAll")),!1);await this.initialBuiltinSkillsSyncPromise;const n=[],s=[],i=new Set;for(const e of this.foldersToWatch){const t=(await Za(e)).filter((e=>!za(e))),r=await Promise.all(t.map((async e=>{try{return await rl(e)}catch(t){return{skillFilePath:e,error:t instanceof Error?t.message:String(t)}}})));for(const e of r)if(i.add(e.skillFilePath),"error"in e)il({rules:n,agentSkills:s,skillFilePath:e.skillFilePath,errorMessage:e.error});else{if(el(e.parsed,this.surface))continue;n.push(nl(e)),ol(e.parsed)||s.push(sl(e))}}const a=(await Promise.all(this.nestedExtensibilityEntries.map(((e,r)=>(t?.[r]??e.discover(o.ctx)).catch((e=>{(0,ln.debuglog)("cursor-rules-service")("Failed to discover nested agent skills: %O",e)})))))).flatMap((e=>e?.skills??[])).filter((e=>!za(e))),c=[],u=new Set;for(const e of a)i.has(e)||u.has(e)||(u.add(e),c.push(e));const d=await Promise.all(c.map((async e=>{try{return await rl(e)}catch(t){return{skillFilePath:e,error:t instanceof Error?t.message:String(t)}}})));for(const e of d)if(i.add(e.skillFilePath),"error"in e)il({rules:n,agentSkills:s,skillFilePath:e.skillFilePath,errorMessage:e.error});else{if(el(e.parsed,this.surface))continue;n.push(nl(e)),ol(e.parsed)||s.push(sl(e))}return o.span.setAttribute("agent_skills.total",n.length),o.span.setAttribute("agent_skills_proto.total",s.length),{rules:n,agentSkills:s}}catch(e){r.error=e,r.hasError=!0}finally{Ja(r)}}}function hl(e){let t;switch(e.type){case"global":t=new on.f5({type:{case:"global",value:new on.i9}});break;case"fileGlobbed":t=new on.f5({type:{case:"fileGlobbed",value:new on.uT({globs:e.globs??[]})}});break;case"agentFetched":t=new on.f5({type:{case:"agentFetched",value:new on.Xo({description:tl(e.description??"")})}});break;case"manuallyAttached":t=new on.f5({type:{case:"manuallyAttached",value:new on._u}});break;default:e.type,t=new on.f5({type:{case:"manuallyAttached",value:new on._u}})}return new on.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??[]})}class ml{getImportSettings;pluginsService;_rules;_agentSkills;onChangeCallbacks=new Set;currentImportSettings;constructor(e,t,r,o){this.getImportSettings=t,this.pluginsService=o,this.currentImportSettings=this.getImportSettings();const n=performance.now(),s=this.loadAll(e).then((t=>{try{Ka.info(e,"CursorPluginsAgentSkillsService load completed",{durationMs:Math.round(performance.now()-n),ruleCount:t.rules.length,skillCount:t.agentSkills.length})}catch{}return t})).catch((e=>((0,ln.debuglog)("cursor-plugins-agent-skills")("Failed to load Cursor Plugins Agent Skills: %s",e instanceof Error?e.message:String(e)),{rules:[],agentSkills:[]})));this._rules=s.then((e=>e.rules)),this._agentSkills=s.then((e=>e.agentSkills))}async getAllCursorRules(e){return await this._rules}async getAllAgentSkills(e){return await this._agentSkills}reload(e){const t=this.getImportSettings();this.currentImportSettings=t;const r=this.loadAll(e,!0).catch((e=>((0,ln.debuglog)("cursor-plugins-agent-skills")("Failed to load Cursor Plugins Agent Skills: %s",e instanceof Error?e.message:String(e)),{rules:[],agentSkills:[]})));this._rules=r.then((e=>e.rules)),this._agentSkills=r.then((e=>e.agentSkills));for(const e of this.onChangeCallbacks)e()}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 o=Va(r,(0,l.VI)(e.withName("CursorPluginsAgentSkillsService.loadAll")),!1),n=[],s=[];try{let e=t?await this.pluginsService.reload():await this.pluginsService.getAllEnabledPlugins();this.currentImportSettings.importThirdPartyPlugins||(e=e.filter((e=>"claude-plugin"!==e.identifier.source))),o.span.setAttribute("cursor_plugins.loaded",e.length);const r=function(e){return da(e,(e=>e.skills))}(e),i=function(e){return da(e,(e=>e.rules))}(e);for(const e of[...r,...i])n.push(hl(e));for(const t of e){const e=`plugin:${gn(t.identifier)}`,r=vn(t.identifier),o=yn(t.identifier),n=wn(t.identifier),i=bn(t.identifier);for(const l of t.skills){if(!0===l.alwaysApply)continue;let c=!1;if(l.content?.includes("disable-model-invocation"))try{c=!0===sn(l.content).data?.["disable-model-invocation"]}catch{}s.push(new rn.N({fullPath:(0,a.join)(t.installPath,l.path),content:l.content,description:tl(l.description??""),environments:l.environments??[],disabledEnvironments:l.disabledEnvironments??[],gitRemoteOrigin:e,plugin:r,marketplace:o,pluginId:n,marketplaceId:i,disableModelInvocation:c}))}}}catch(e){o.span.setAttribute("cursor_plugins.error",String(e))}return o.span.setAttribute("cursor_plugins.total",n.length),o.span.setAttribute("cursor_plugins_proto.total",s.length),{rules:n,agentSkills:s}}catch(e){r.error=e,r.hasError=!0}finally{Ja(r)}}}const fl=(0,ln.debuglog)("local-subagents");class gl{async getAllSubagents(){return[]}async reload(){return[]}}function vl(e){return"true"===(e??"").trim().toLowerCase()}function yl(e){const t=e.match(/^---\s*\n([\s\S]*?)\n---\s*\n?([\s\S]*)$/m);if(!t)return null;const r=t[1]??"",o=(t[2]??"").trim();if(0===o.length)return null;const n={};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 o=t.slice(0,r).trim().toLowerCase(),s=t.slice(r+1).trim();0!==o.length&&(n[o]=s)}const s=n.name??"",i=n.description,a=n.model,l=vl(n["force-default-model"]),c="true"===(n.readonly??"").trim().toLowerCase()?nn.b$.READONLY:nn.b$.DEFAULT,u=vl(n.background??n.is_background),d=n.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:l,prompt:o,permissionMode:c,isBackground:u}}function wl(e){const t=(0,a.extname)(e).toLowerCase();return".md"===t||".mdc"===t||".markdown"===t}function bl(e){return(0,a.basename)(e,(0,a.extname)(e)).replace(/[\s_]+/g,"-")}async function Sl(e,t){return await Ba({rootDir:e,includeFile:wl,containmentRootDir:t})}class kl{workspacePath;cursorAgentsSource;subagents;getThirdPartyExtensibilityEnabled;constructor(e,t,r="workspace"){this.workspacePath=e,this.cursorAgentsSource=r,this.getThirdPartyExtensibilityEnabled=t??(()=>!0),this.subagents=this.load().catch((e=>(fl("Failed to load subagents: %o",e),[])))}async getAllSubagents(){return this.subagents}async reload(){return this.subagents=this.load().catch((e=>(fl("Failed to load subagents: %o",e),[]))),await this.subagents}computeAgentsDirs(){const e=(0,a.resolve)(this.workspacePath),t=[{dirPath:(0,a.join)(e,".cursor","agents"),source:this.cursorAgentsSource}];return this.getThirdPartyExtensibilityEnabled()&&t.push({dirPath:(0,a.join)(e,".claude","agents"),source:"claude"}),t}async load(){const e=this.computeAgentsDirs(),t=[];for(const{dirPath:r,source:o}of e){const e=await Sl(r,this.workspacePath);for(const r of e){const e=(0,a.basename)(r);try{if(!(await(0,fo.stat)(r)).isFile())continue}catch(e){fl("Skipping subagent file %s due to stat error: %o",r,e);continue}try{const n=yl(await(0,h.yR)(r));if(!n)continue;t.push(new nn.zz({fullPath:r,name:n.name||bl(e),description:n.description??"",tools:n.tools,model:n.model??"inherit",forceDefaultModel:n.forceDefaultModel,prompt:n.prompt,permissionMode:n.permissionMode,isBackground:n.isBackground,source:o}))}catch(e){fl("Failed to parse subagent file %s: %o",r,e)}}}return t}}const El=new Set(["claude-code-tutor"]);class xl{subagentsServices;constructor(e){this.subagentsServices=e}async getAllSubagents(){const e=await Promise.all(this.subagentsServices.map((e=>e.getAllSubagents().catch((e=>(fl("Failed to load subagents from merged service: %o",e),[])))))),t=new Map;for(const r of e)for(const e of r)El.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 _l{getSettings;pluginsService;_subagentsCache=[];_loadId=0;_loadPromise=null;_loadedOnce=!1;constructor(e,t){this.getSettings=e,this.pluginsService=t,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&&(fl("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 o=function(e,t={stripModel:!0,stripTools:!0}){var r;const o=[];for(const n of e){const e=vn(n.identifier),s=yn(n.identifier),i=wn(n.identifier),l=bn(n.identifier);for(const c of n.agents){const u=ua(c,t),d=(0,a.join)(n.installPath,u.path);o.push({name:u.name,description:null!==(r=u.description)&&void 0!==r?r:"",prompt:u.prompt,fullPath:d,permissionMode:"readonly"===u.permissionMode?"readonly":"default",plugin:e,marketplace:s,pluginId:i,marketplaceId:l})}}return o}(r,{stripModel:!0,stripTools:!0});for(const e of o){const r="readonly"===e.permissionMode?nn.b$.READONLY:nn.b$.DEFAULT;t.push(new nn.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}}var Cl=r("../proto/dist/generated/agent/v1/canvas_diagnostics_exec_pb.js"),Pl=r("../proto/dist/generated/agent/v1/diagnostics_exec_pb.js"),Rl=r("../proto/dist/generated/agent/v1/utils_pb.js");class Tl{getCanvasDiagnostics;constructor(e){this.getCanvasDiagnostics=e}async execute(e,t){try{const e=await this.getCanvasDiagnostics(t.path);return void 0===e?Il(t.path,"diagnostics unavailable"):new Cl.GL({result:{case:"success",value:new Cl.uX({path:t.path,diagnostics:e.map(Al)})}})}catch(e){return Il(t.path,e instanceof Error?e.message:String(e))}}}function Il(e,t){return new Cl.GL({result:{case:"error",value:new Cl.HW({path:e,error:t})}})}function Al(e){return new Pl.oQ({severity:Ol(e.severity),range:new Rl.Q6({start:new Rl.yX({line:e.range.start.line+1,column:e.range.start.character+1}),end:new Rl.yX({line:e.range.end.line+1,column:e.range.end.character+1})}),message:e.message,source:"ts",code:e.code??""})}function Ol(e){switch(e){case 1:return Pl.h_.ERROR;case 2:return Pl.h_.WARNING;case 3:return Pl.h_.INFORMATION;case 4:return Pl.h_.HINT;default:return Pl.h_.UNSPECIFIED}}var Dl=r("../proto/dist/generated/agent/v1/computer_use_tool_pb.js");function Ml(e,t,r){return new Promise(((o,n)=>{const s={timeout:r?.timeoutMs??3e4,env:r?.env?{...process.env,...r.env}:void 0};(0,xs.execFile)(e,t.map(String),{...s,encoding:"utf8"},((e,t)=>{e?n(e):o(t)}))}))}Dl.w3.UNSPECIFIED,Dl.w3.LEFT,Dl.w3.MIDDLE,Dl.w3.RIGHT,Dl.w3.BACK,Dl.w3.FORWARD,Dl.Dh.UNSPECIFIED,Dl.Dh.UP,Dl.Dh.DOWN,Dl.Dh.LEFT,Dl.Dh.RIGHT,(0,d.v5)("computer_use.session.duration_ms",{description:"Duration of computer-use session in milliseconds"}),(0,d.v5)("computer_use.session.action_count",{description:"Number of actions executed in a computer-use session"}),(0,d.Pu)("computer_use.session.result",{description:"Result status of computer-use session",labelNames:["outcome"]}),(0,l.h)("computer-use");const jl=(0,ln.promisify)(xs.execFile);function Nl(e,t){const r=e/t;return{display:{width:e,height:t},api:{width:1280,height:Math.round(1280/r)}}}async function $l(e){const{stdout:t}=await jl("xrandr",["--display",e],{timeout:5e3}),r=function(e){let t,r,o;for(const n of e.split("\n"))if(n.includes("*")){const e=n.trim().match(/^(\d+)x(\d+)/);e&&(t=parseInt(e[1],10),r=parseInt(e[2],10));const s=n.match(/(\d+(?:\.\d+)?)\*(?:\+)?/);if(s){const e=parseFloat(s[1]);e>0&&e<=500&&(o=Math.round(e))}if(t&&r)break}if(!t||!r){const o=e.match(/current\s+(\d+)\s*x\s*(\d+)/i);o&&(t=parseInt(o[1],10),r=parseInt(o[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 o||(o=60),{width:t,height:r,refreshRate:o}}(t);return{display:r,resolution:Nl(r.width,r.height),resolutionString:`${r.width}x${r.height}`}}var Fl,Ll,Ul,Bl,Hl;!function(e){e[e.UNSPECIFIED=0]="UNSPECIFIED",e[e.ARROW=1]="ARROW",e[e.POINTER=2]="POINTER",e[e.TEXT=3]="TEXT",e[e.WAIT=4]="WAIT",e[e.CROSSHAIR=5]="CROSSHAIR",e[e.MOVE=6]="MOVE",e[e.RESIZE_NS=7]="RESIZE_NS",e[e.RESIZE_EW=8]="RESIZE_EW",e[e.RESIZE_NWSE=9]="RESIZE_NWSE",e[e.RESIZE_NESW=10]="RESIZE_NESW",e[e.NOT_ALLOWED=11]="NOT_ALLOWED",e[e.GRAB=12]="GRAB",e[e.GRABBING=13]="GRABBING"}(Fl||(Fl={})),ir.proto3.util.setEnumType(Fl,"agent.v1.CursorType",[{no:0,name:"CURSOR_TYPE_UNSPECIFIED"},{no:1,name:"CURSOR_TYPE_ARROW"},{no:2,name:"CURSOR_TYPE_POINTER"},{no:3,name:"CURSOR_TYPE_TEXT"},{no:4,name:"CURSOR_TYPE_WAIT"},{no:5,name:"CURSOR_TYPE_CROSSHAIR"},{no:6,name:"CURSOR_TYPE_MOVE"},{no:7,name:"CURSOR_TYPE_RESIZE_NS"},{no:8,name:"CURSOR_TYPE_RESIZE_EW"},{no:9,name:"CURSOR_TYPE_RESIZE_NWSE"},{no:10,name:"CURSOR_TYPE_RESIZE_NESW"},{no:11,name:"CURSOR_TYPE_NOT_ALLOWED"},{no:12,name:"CURSOR_TYPE_GRAB"},{no:13,name:"CURSOR_TYPE_GRABBING"}]),function(e){e[e.UNSPECIFIED=0]="UNSPECIFIED",e[e.SLOW=1]="SLOW",e[e.MELLOW=2]="MELLOW",e[e.QUICK=3]="QUICK",e[e.RAPID=4]="RAPID"}(Ll||(Ll={})),ir.proto3.util.setEnumType(Ll,"agent.v1.MotionStyle",[{no:0,name:"MOTION_STYLE_UNSPECIFIED"},{no:1,name:"MOTION_STYLE_SLOW"},{no:2,name:"MOTION_STYLE_MELLOW"},{no:3,name:"MOTION_STYLE_QUICK"},{no:4,name:"MOTION_STYLE_RAPID"}]),function(e){e[e.UNSPECIFIED=0]="UNSPECIFIED",e[e.LOADING_WAIT=1]="LOADING_WAIT",e[e.VIEWING_RESULT=2]="VIEWING_RESULT",e[e.THINKING_PAUSE=3]="THINKING_PAUSE",e[e.LONG_OPERATION=4]="LONG_OPERATION"}(Ul||(Ul={})),ir.proto3.util.setEnumType(Ul,"agent.v1.IdleClassification",[{no:0,name:"IDLE_CLASSIFICATION_UNSPECIFIED"},{no:1,name:"IDLE_CLASSIFICATION_LOADING_WAIT"},{no:2,name:"IDLE_CLASSIFICATION_VIEWING_RESULT"},{no:3,name:"IDLE_CLASSIFICATION_THINKING_PAUSE"},{no:4,name:"IDLE_CLASSIFICATION_LONG_OPERATION"}]),function(e){e[e.UNSPECIFIED=0]="UNSPECIFIED",e[e.SINGLE=1]="SINGLE",e[e.DOUBLE=2]="DOUBLE",e[e.TRIPLE=3]="TRIPLE",e[e.RIGHT=4]="RIGHT",e[e.MIDDLE=5]="MIDDLE"}(Bl||(Bl={})),ir.proto3.util.setEnumType(Bl,"agent.v1.ClickType",[{no:0,name:"CLICK_TYPE_UNSPECIFIED"},{no:1,name:"CLICK_TYPE_SINGLE"},{no:2,name:"CLICK_TYPE_DOUBLE"},{no:3,name:"CLICK_TYPE_TRIPLE"},{no:4,name:"CLICK_TYPE_RIGHT"},{no:5,name:"CLICK_TYPE_MIDDLE"}]),function(e){e[e.UNSPECIFIED=0]="UNSPECIFIED",e[e.KEY_COMBO=1]="KEY_COMBO",e[e.KEY_SINGLE=2]="KEY_SINGLE",e[e.TEXT_TYPED=3]="TEXT_TYPED"}(Hl||(Hl={})),ir.proto3.util.setEnumType(Hl,"agent.v1.KeystrokeEventType",[{no:0,name:"KEYSTROKE_EVENT_TYPE_UNSPECIFIED"},{no:1,name:"KEYSTROKE_EVENT_TYPE_KEY_COMBO"},{no:2,name:"KEYSTROKE_EVENT_TYPE_KEY_SINGLE"},{no:3,name:"KEYSTROKE_EVENT_TYPE_TEXT_TYPED"}]);class zl extends ir.Message{executionTimestampMs=ir.protoInt64.zero;action;commandDurationMs=ir.protoInt64.zero;positionBefore;positionAfter;cursorTypeAfter=Fl.UNSPECIFIED;constructor(e){super(),ir.proto3.util.initPartial(e,this)}static runtime=ir.proto3;static typeName="agent.v1.InputEvent";static fields=ir.proto3.util.newFieldList((()=>[{no:1,name:"execution_timestamp_ms",kind:"scalar",T:3},{no:2,name:"action",kind:"message",T:Dl.ho},{no:3,name:"command_duration_ms",kind:"scalar",T:3},{no:4,name:"position_before",kind:"message",T:Dl.xp},{no:5,name:"position_after",kind:"message",T:Dl.xp},{no:6,name:"cursor_type_after",kind:"enum",T:ir.proto3.getEnumType(Fl)}]));static fromBinary(e,t){return(new zl).fromBinary(e,t)}static fromJson(e,t){return(new zl).fromJson(e,t)}static fromJsonString(e,t){return(new zl).fromJsonString(e,t)}static equals(e,t){return ir.proto3.util.equals(zl,e,t)}}class Wl extends ir.Message{videoTimestampMs=ir.protoInt64.zero;x=0;y=0;cursorType=Fl.UNSPECIFIED;velocity=0;constructor(e){super(),ir.proto3.util.initPartial(e,this)}static runtime=ir.proto3;static typeName="agent.v1.CursorPathKeyframe";static fields=ir.proto3.util.newFieldList((()=>[{no:1,name:"video_timestamp_ms",kind:"scalar",T:3},{no:2,name:"x",kind:"scalar",T:5},{no:3,name:"y",kind:"scalar",T:5},{no:4,name:"cursor_type",kind:"enum",T:ir.proto3.getEnumType(Fl)},{no:5,name:"velocity",kind:"scalar",T:2}]));static fromBinary(e,t){return(new Wl).fromBinary(e,t)}static fromJson(e,t){return(new Wl).fromJson(e,t)}static fromJsonString(e,t){return(new Wl).fromJsonString(e,t)}static equals(e,t){return ir.proto3.util.equals(Wl,e,t)}}class ql extends ir.Message{style=Ll.UNSPECIFIED;keyframes=[];constructor(e){super(),ir.proto3.util.initPartial(e,this)}static runtime=ir.proto3;static typeName="agent.v1.CursorPath";static fields=ir.proto3.util.newFieldList((()=>[{no:1,name:"style",kind:"enum",T:ir.proto3.getEnumType(Ll)},{no:2,name:"keyframes",kind:"message",T:Wl,repeated:!0}]));static fromBinary(e,t){return(new ql).fromBinary(e,t)}static fromJson(e,t){return(new ql).fromJson(e,t)}static fromJsonString(e,t){return(new ql).fromJsonString(e,t)}static equals(e,t){return ir.proto3.util.equals(ql,e,t)}}class Gl extends ir.Message{startMs=ir.protoInt64.zero;endMs=ir.protoInt64.zero;centerX=0;centerY=0;suggestedZoom=0;actionType="";actionIndex=0;importanceScore=0;context="";constructor(e){super(),ir.proto3.util.initPartial(e,this)}static runtime=ir.proto3;static typeName="agent.v1.ZoomCandidate";static fields=ir.proto3.util.newFieldList((()=>[{no:1,name:"start_ms",kind:"scalar",T:3},{no:2,name:"end_ms",kind:"scalar",T:3},{no:3,name:"center_x",kind:"scalar",T:5},{no:4,name:"center_y",kind:"scalar",T:5},{no:5,name:"suggested_zoom",kind:"scalar",T:2},{no:6,name:"action_type",kind:"scalar",T:9},{no:7,name:"action_index",kind:"scalar",T:5},{no:8,name:"importance_score",kind:"scalar",T:5},{no:9,name:"context",kind:"scalar",T:9}]));static fromBinary(e,t){return(new Gl).fromBinary(e,t)}static fromJson(e,t){return(new Gl).fromJson(e,t)}static fromJsonString(e,t){return(new Gl).fromJsonString(e,t)}static equals(e,t){return ir.proto3.util.equals(Gl,e,t)}}class Vl extends ir.Message{startMs=ir.protoInt64.zero;endMs=ir.protoInt64.zero;durationMs=ir.protoInt64.zero;classification=Ul.UNSPECIFIED;suggestedSpeed=0;precedingActionType="";followingActionType="";constructor(e){super(),ir.proto3.util.initPartial(e,this)}static runtime=ir.proto3;static typeName="agent.v1.IdlePeriod";static fields=ir.proto3.util.newFieldList((()=>[{no:1,name:"start_ms",kind:"scalar",T:3},{no:2,name:"end_ms",kind:"scalar",T:3},{no:3,name:"duration_ms",kind:"scalar",T:3},{no:4,name:"classification",kind:"enum",T:ir.proto3.getEnumType(Ul)},{no:5,name:"suggested_speed",kind:"scalar",T:2},{no:6,name:"preceding_action_type",kind:"scalar",T:9},{no:7,name:"following_action_type",kind:"scalar",T:9}]));static fromBinary(e,t){return(new Vl).fromBinary(e,t)}static fromJson(e,t){return(new Vl).fromJson(e,t)}static fromJsonString(e,t){return(new Vl).fromJsonString(e,t)}static equals(e,t){return ir.proto3.util.equals(Vl,e,t)}}class Jl extends ir.Message{videoTimestampMs=ir.protoInt64.zero;x=0;y=0;clickType=Bl.UNSPECIFIED;actionIndex=0;hasModifiers=!1;constructor(e){super(),ir.proto3.util.initPartial(e,this)}static runtime=ir.proto3;static typeName="agent.v1.ClickEffectKeyframe";static fields=ir.proto3.util.newFieldList((()=>[{no:1,name:"video_timestamp_ms",kind:"scalar",T:3},{no:2,name:"x",kind:"scalar",T:5},{no:3,name:"y",kind:"scalar",T:5},{no:4,name:"click_type",kind:"enum",T:ir.proto3.getEnumType(Bl)},{no:5,name:"action_index",kind:"scalar",T:5},{no:6,name:"has_modifiers",kind:"scalar",T:8}]));static fromBinary(e,t){return(new Jl).fromBinary(e,t)}static fromJson(e,t){return(new Jl).fromJson(e,t)}static fromJsonString(e,t){return(new Jl).fromJsonString(e,t)}static equals(e,t){return ir.proto3.util.equals(Jl,e,t)}}class Kl extends ir.Message{videoTimestampMs=ir.protoInt64.zero;displayText="";eventType=Hl.UNSPECIFIED;displayDurationMs=ir.protoInt64.zero;actionIndex=0;constructor(e){super(),ir.proto3.util.initPartial(e,this)}static runtime=ir.proto3;static typeName="agent.v1.KeystrokeEvent";static fields=ir.proto3.util.newFieldList((()=>[{no:1,name:"video_timestamp_ms",kind:"scalar",T:3},{no:2,name:"display_text",kind:"scalar",T:9},{no:3,name:"event_type",kind:"enum",T:ir.proto3.getEnumType(Hl)},{no:4,name:"display_duration_ms",kind:"scalar",T:3},{no:5,name:"action_index",kind:"scalar",T:5}]));static fromBinary(e,t){return(new Kl).fromBinary(e,t)}static fromJson(e,t){return(new Kl).fromJson(e,t)}static fromJsonString(e,t){return(new Kl).fromJsonString(e,t)}static equals(e,t){return ir.proto3.util.equals(Kl,e,t)}}class Zl extends ir.Message{videoPath="";videoDurationMs=ir.protoInt64.zero;videoWidth=0;videoHeight=0;actionCount=0;zoomCandidates=[];idlePeriods=[];clickEffects=[];keystrokeEvents=[];cursorPaths=[];constructor(e){super(),ir.proto3.util.initPartial(e,this)}static runtime=ir.proto3;static typeName="agent.v1.DecisionInput";static fields=ir.proto3.util.newFieldList((()=>[{no:1,name:"video_path",kind:"scalar",T:9},{no:2,name:"video_duration_ms",kind:"scalar",T:3},{no:3,name:"video_width",kind:"scalar",T:5},{no:4,name:"video_height",kind:"scalar",T:5},{no:5,name:"action_count",kind:"scalar",T:5},{no:10,name:"zoom_candidates",kind:"message",T:Gl,repeated:!0},{no:11,name:"idle_periods",kind:"message",T:Vl,repeated:!0},{no:12,name:"click_effects",kind:"message",T:Jl,repeated:!0},{no:13,name:"keystroke_events",kind:"message",T:Kl,repeated:!0},{no:20,name:"cursor_paths",kind:"message",T:ql,repeated:!0}]));static fromBinary(e,t){return(new Zl).fromBinary(e,t)}static fromJson(e,t){return(new Zl).fromJson(e,t)}static fromJsonString(e,t){return(new Zl).fromJsonString(e,t)}static equals(e,t){return ir.proto3.util.equals(Zl,e,t)}}class Yl extends ir.Message{candidateIndex=0;zoomOverride;startMsOverride;endMsOverride;constructor(e){super(),ir.proto3.util.initPartial(e,this)}static runtime=ir.proto3;static typeName="agent.v1.ZoomSelection";static fields=ir.proto3.util.newFieldList((()=>[{no:1,name:"candidate_index",kind:"scalar",T:5},{no:2,name:"zoom_override",kind:"scalar",T:2,opt:!0},{no:3,name:"start_ms_override",kind:"scalar",T:3,opt:!0},{no:4,name:"end_ms_override",kind:"scalar",T:3,opt:!0}]));static fromBinary(e,t){return(new Yl).fromBinary(e,t)}static fromJson(e,t){return(new Yl).fromJson(e,t)}static fromJsonString(e,t){return(new Yl).fromJsonString(e,t)}static equals(e,t){return ir.proto3.util.equals(Yl,e,t)}}class Xl extends ir.Message{candidateIndex=0;speedOverride;constructor(e){super(),ir.proto3.util.initPartial(e,this)}static runtime=ir.proto3;static typeName="agent.v1.SpeedupSelection";static fields=ir.proto3.util.newFieldList((()=>[{no:1,name:"candidate_index",kind:"scalar",T:5},{no:2,name:"speed_override",kind:"scalar",T:2,opt:!0}]));static fromBinary(e,t){return(new Xl).fromBinary(e,t)}static fromJson(e,t){return(new Xl).fromJson(e,t)}static fromJsonString(e,t){return(new Xl).fromJsonString(e,t)}static equals(e,t){return ir.proto3.util.equals(Xl,e,t)}}class Ql extends ir.Message{cursorStyle=Ll.UNSPECIFIED;selectedZooms=[];selectedSpeedups=[];showClickEffects=!1;selectedClickEffects=[];showKeystrokes=!1;cuts=[];constructor(e){super(),ir.proto3.util.initPartial(e,this)}static runtime=ir.proto3;static typeName="agent.v1.DecisionOutput";static fields=ir.proto3.util.newFieldList((()=>[{no:1,name:"cursor_style",kind:"enum",T:ir.proto3.getEnumType(Ll)},{no:2,name:"selected_zooms",kind:"message",T:Yl,repeated:!0},{no:3,name:"selected_speedups",kind:"message",T:Xl,repeated:!0},{no:4,name:"show_click_effects",kind:"scalar",T:8},{no:5,name:"selected_click_effects",kind:"scalar",T:5,repeated:!0},{no:6,name:"show_keystrokes",kind:"scalar",T:8},{no:7,name:"cuts",kind:"message",T:ec,repeated:!0}]));static fromBinary(e,t){return(new Ql).fromBinary(e,t)}static fromJson(e,t){return(new Ql).fromJson(e,t)}static fromJsonString(e,t){return(new Ql).fromJsonString(e,t)}static equals(e,t){return ir.proto3.util.equals(Ql,e,t)}}class ec extends ir.Message{startMs=ir.protoInt64.zero;endMs=ir.protoInt64.zero;reason="";constructor(e){super(),ir.proto3.util.initPartial(e,this)}static runtime=ir.proto3;static typeName="agent.v1.VideoCut";static fields=ir.proto3.util.newFieldList((()=>[{no:1,name:"start_ms",kind:"scalar",T:3},{no:2,name:"end_ms",kind:"scalar",T:3},{no:3,name:"reason",kind:"scalar",T:9}]));static fromBinary(e,t){return(new ec).fromBinary(e,t)}static fromJson(e,t){return(new ec).fromJson(e,t)}static fromJsonString(e,t){return(new ec).fromJsonString(e,t)}static equals(e,t){return ir.proto3.util.equals(ec,e,t)}}ir.Message,ir.proto3,ir.proto3.util.newFieldList((()=>[{no:1,name:"raw_video_path",kind:"scalar",T:9},{no:2,name:"duration_ms",kind:"scalar",T:3},{no:3,name:"display_width",kind:"scalar",T:5},{no:4,name:"display_height",kind:"scalar",T:5},{no:5,name:"api_width",kind:"scalar",T:5},{no:6,name:"api_height",kind:"scalar",T:5},{no:7,name:"recording_start_epoch_ms",kind:"scalar",T:3},{no:10,name:"input_events",kind:"message",T:zl,repeated:!0},{no:20,name:"cursor_paths",kind:"message",T:ql,repeated:!0},{no:30,name:"zoom_candidates",kind:"message",T:Gl,repeated:!0},{no:31,name:"idle_periods",kind:"message",T:Vl,repeated:!0},{no:32,name:"click_effects",kind:"message",T:Jl,repeated:!0},{no:33,name:"keystroke_events",kind:"message",T:Kl,repeated:!0},{no:40,name:"decision_input",kind:"message",T:Zl},{no:41,name:"decision_output",kind:"message",T:Ql},{no:50,name:"polished_video_path",kind:"scalar",T:9}]));class tc{config;xScaleUp;yScaleUp;xScaleDown;yScaleDown;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 rc={left_ptr:Fl.ARROW,arrow:Fl.ARROW,default:Fl.ARROW,top_left_arrow:Fl.ARROW,hand:Fl.POINTER,hand1:Fl.POINTER,hand2:Fl.POINTER,pointer:Fl.POINTER,pointing_hand:Fl.POINTER,xterm:Fl.TEXT,ibeam:Fl.TEXT,text:Fl.TEXT,watch:Fl.WAIT,wait:Fl.WAIT,progress:Fl.WAIT,left_ptr_watch:Fl.WAIT,crosshair:Fl.CROSSHAIR,cross:Fl.CROSSHAIR,tcross:Fl.CROSSHAIR,move:Fl.MOVE,fleur:Fl.MOVE,size_all:Fl.MOVE,sb_v_double_arrow:Fl.RESIZE_NS,v_double_arrow:Fl.RESIZE_NS,ns_resize:Fl.RESIZE_NS,row_resize:Fl.RESIZE_NS,top_side:Fl.RESIZE_NS,bottom_side:Fl.RESIZE_NS,sb_h_double_arrow:Fl.RESIZE_EW,h_double_arrow:Fl.RESIZE_EW,ew_resize:Fl.RESIZE_EW,col_resize:Fl.RESIZE_EW,left_side:Fl.RESIZE_EW,right_side:Fl.RESIZE_EW,top_left_corner:Fl.RESIZE_NWSE,bottom_right_corner:Fl.RESIZE_NWSE,nwse_resize:Fl.RESIZE_NWSE,size_fdiag:Fl.RESIZE_NWSE,top_right_corner:Fl.RESIZE_NESW,bottom_left_corner:Fl.RESIZE_NESW,nesw_resize:Fl.RESIZE_NESW,size_bdiag:Fl.RESIZE_NESW,not_allowed:Fl.NOT_ALLOWED,no_drop:Fl.NOT_ALLOWED,forbidden:Fl.NOT_ALLOWED,circle:Fl.NOT_ALLOWED,grab:Fl.GRAB,openhand:Fl.GRAB,grabbing:Fl.GRABBING,closedhand:Fl.GRABBING};class oc{events=[];recordingStartTime=0;lastKnownPosition={x:0,y:0};isRunning=!1;pending=Promise.resolve();env;scaler;constructor(e){const t=e.displayNum??1;this.env={DISPLAY:`:${t}`},this.scaler=new tc(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 o={...this.lastKnownPosition},n=this.getExpectedPositionAfterAction(e,o);this.lastKnownPosition=n;const s=async()=>{let s,i;try{[s,i]=await Promise.all([this.captureCurrentPosition(),this.detectCursorType()]),this.lastKnownPosition=s}catch{s=n,i=Fl.ARROW}const a={executionTimestampMs:r-this.recordingStartTime,action:e,commandDurationMs:r-t,positionBefore:o,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 Ml("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 o=parseInt(t[1],10),n=parseInt(r[1],10);return this.scaler.displayToApi(o,n)}async detectCursorType(){try{const e=(await Ml("xdotool",["getmouselocation","--shell"],{env:this.env})).match(/CURSOR=(\S+)/i);if(e){const t=e[1].toLowerCase();return rc[t]??Fl.ARROW}try{const e=await Ml("xprop",["-root","_XSERVER_CURSOR"],{env:this.env,timeoutMs:500});for(const[t,r]of Object.entries(rc))if(e.toLowerCase().includes(t))return r}catch{}return Fl.ARROW}catch{return Fl.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}}const nc=1048576,sc=52428800;var ic;!function(e){e.Write="write",e.Shell="shell",e.Delete="delete",e.Mcp="mcp"}(ic||(ic={}));var ac=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 o,n=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===n)return n=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var s=o.dispose.call(o.value);if(o.async)return n|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else n|=1}catch(e){r(e)}if(1===n)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var o=new Error(r);return o.name="SuppressedError",o.error=e,o.suppressed=t,o});class lc{pendingDecisionProvider;fileChangeTracker;permissionsService;workspacePath;onDeleteForAiTracking;constructor(e,t,r,o,n){this.pendingDecisionProvider=e,this.fileChangeTracker=t,this.permissionsService=r,this.workspacePath=o,this.onDeleteForAiTracking=n}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 o,n;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");o=t[Symbol.asyncDispose]}if(void 0===o){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");o=t[Symbol.dispose],r&&(n=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");n&&(o=function(){try{n.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:o,async:r})}else r&&e.stack.push({async:!0})}(r,(0,l.VI)(e.withName("LocalDeleteExecutor.execute")),!1);const o=t.path,n=(0,h.o1)(o,this.workspacePath),s=await this.permissionsService.shouldBlockWrite(e,n,"");if(s){const e=await Fo(s,{onNeedsApproval:async(e,t)=>null,onUserRejected:e=>new qe.Pi({result:{case:"rejected",value:new qe.iq({path:n,reason:e||""})}}),onPermissionDenied:(e,t)=>new qe.Pi({result:{case:"permissionDenied",value:new qe.QG({path:n,clientVisibleError:e,isReadonly:t?.isReadonly??!1})}})});if(null!==e)return e}const i=await this.pendingDecisionProvider.requestApproval({type:ic.Delete,details:{path:n},toolCallId:t.toolCallId});if(!i.approved)return new qe.Pi({result:{case:"rejected",value:new qe.iq({path:n,reason:i.reason||""})}});let a;try{a=await(0,fo.stat)(n)}catch(e){return"ENOENT"===e.code?new qe.Pi({result:{case:"fileNotFound",value:new qe.n0({path:n})}}):new qe.Pi({result:{case:"error",value:new qe.GU({path:n,error:e.message})}})}if(!a.isFile()){const e=a.isDirectory()?"directory":"other";return new qe.Pi({result:{case:"notFile",value:new qe.LX({path:n,actualType:e})}})}const c=a.size;let u;if(c<=sc)try{u=await(0,h.yR)(n)}catch{}const d=u??"";try{await(0,fo.unlink)(n)}catch(e){return"EACCES"===e.code?new qe.Pi({result:{case:"permissionDenied",value:new qe.QG({path:n,clientVisibleError:"Permission denied"})}}):"EBUSY"===e.code?new qe.Pi({result:{case:"fileBusy",value:new qe.vX({path:n})}}):new qe.Pi({result:{case:"error",value:new qe.GU({path:n,error:e.message})}})}if(this.fileChangeTracker&&void 0!==u){const e=t.toolCallId?{toolCallId:t.toolCallId}:void 0;await this.fileChangeTracker.trackChange(n,u,void 0,e)}return this.onDeleteForAiTracking&&this.onDeleteForAiTracking({path:n}).catch((()=>{})),new qe.Pi({result:{case:"success",value:new qe.fl({path:n,deletedFile:n,fileSize:BigInt(c),prevContent:d})}})}catch(e){r.error=e,r.hasError=!0}finally{ac(r)}}}class cc{inner;extraTools;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((()=>[])),o=new Set(t);return[...r,...this.extraTools.filter((e=>o.has(e.clientKey)||o.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===Me));if(0===r.length)return t;const o=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 sr.I0({serverIdentifier:Me,serverName:Me,instructions:`User-defined tools for this session (server "${Me}"). Discover schemas via MCP meta-tool discovery for that server, then invoke via the MCP invocation meta-tool.\n\nAvailable tools:\n${o}`})]}async getToolSet(e){return this.inner.getToolSet(e)}}class uc extends cc{observableInner;constructor(e,t){super(e,t),this.observableInner=e}onDidChange(e){return this.observableInner.onDidChange(e)}}var dc=r("../proto/dist/generated/agent/v1/fetch_exec_pb.js"),pc=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 o,n=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===n)return n=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var s=o.dispose.call(o.value);if(o.async)return n|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else n|=1}catch(e){r(e)}if(1===n)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var o=new Error(r);return o.name="SuppressedError",o.error=e,o.suppressed=t,o});class hc{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 o,n;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");o=t[Symbol.asyncDispose]}if(void 0===o){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");o=t[Symbol.dispose],r&&(n=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");n&&(o=function(){try{n.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:o,async:r})}else r&&e.stack.push({async:!0})}(r,(0,l.VI)(e.withName("LocalFetchExecutor.execute")),!1);const o=t.url;try{const e=await fetch(o),t=await e.text(),r=e.headers.get("content-type")||"text/plain";return new dc.uN({result:{case:"success",value:new dc.Uk({url:o,content:t,statusCode:e.status,contentType:r})}})}catch(e){return new dc.uN({result:{case:"error",value:new dc.fk({url:o,error:e.message})}})}}catch(e){r.error=e,r.hasError=!0}finally{pc(r)}}}class mc{workspacePath;changes=new Map;listeners=new Set;constructor(e){this.workspacePath=e}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,o){const n=this.changes.get(e);if(n){const t=n.before,s=o||n.metadata;if(t===r||void 0===t&&void 0===r)this.changes.delete(e),this.notify();else{const o={path:e,before:t,after:r,metadata:s};this.changes.set(e,o),this.notify(o)}}else{const n={path:e,before:t,after:r,metadata:o};this.changes.set(e,n),this.notify(n)}}getChanges(){return Array.from(this.changes.values())}getChange(e){return this.changes.get(e)}hasChange(e){return this.changes.has(e)}accept(e){const t=this.changes.get(e);this.changes.delete(e),this.notify(t)}acceptAll(){this.changes.clear(),this.notify()}async reject(e){const t=this.changes.get(e);if(t)try{void 0===t.before&&void 0!==t.after?await(0,fo.unlink)(e):(void 0!==t.before&&void 0===t.after||void 0!==t.before&&void 0!==t.after)&&await(0,h.x3)(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}}var fc=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 o,n=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===n)return n=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var s=o.dispose.call(o.value);if(o.async)return n|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else n|=1}catch(e){r(e)}if(1===n)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var o=new Error(r);return o.name="SuppressedError",o.error=e,o.suppressed=t,o});const gc=(0,ln.promisify)(xs.execFile);class vc{async exec(e,t,r,o){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 o,n;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");o=t[Symbol.asyncDispose]}if(void 0===o){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");o=t[Symbol.dispose],r&&(n=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");n&&(o=function(){try{n.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:o,async:r})}else r&&e.stack.push({async:!0})}(n,(0,l.VI)(e.withName("LocalGitExecutor.exec"),{attributes:{"git.cwd":t,"git.args":r,"git.caller":o?.caller}}),!1);const{stdout:s,stderr:i}=await gc("git",r,{cwd:t,timeout:o?.timeout});return{exitCode:0,stdout:s.toString(),stderr:i.toString()}}catch(e){n.error=e,n.hasError=!0}finally{fc(n)}}}const yc=-(2**31),wc=2**31-1;function bc(e){return Number.isNaN(e)?0:e<yc?yc:e>wc?wc:e}function Sc(e){if("number"==typeof e&&Number.isFinite(e)&&!(e<0))return bc(Math.trunc(e))}const kc="agent-tools",Ec=52428800;var xc=r("../mcp-core/dist/index.js"),_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 o,n=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===n)return n=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var s=o.dispose.call(o.value);if(o.async)return n|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else n|=1}catch(e){r(e)}if(1===n)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var o=new Error(r);return o.name="SuppressedError",o.error=e,o.suppressed=t,o});class Cc extends Error{constructor(e){super(`MCP server "${e}" is disabled`),this.name="McpServerDisabledError"}}class Pc extends Error{serverName;constructor(e){super(`MCP server "${e}" has not been approved`),this.serverName=e,this.name="McpServerNotApprovedError"}}class Rc{disabledService;constructor(e){this.disabledService=e}async load(e,t,r,o,n){if(await this.disabledService.isServerDisabled(t))throw new Cc(t);return await n(e,r)}}class Tc{approvalService;constructor(e){this.approvalService=e}async load(e,t,r,o,n){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 o,n;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");o=t[Symbol.asyncDispose]}if(void 0===o){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");o=t[Symbol.dispose],r&&(n=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");n&&(o=function(){try{n.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:o,async:r})}else r&&e.stack.push({async:!0})}(s,(0,l.VI)(e.withName("ServerApprovalMiddleware.load")),!1),!await this.approvalService.isServerApproved(t,r,o))throw new Pc(t);return await n(e,r)}catch(e){s.error=e,s.hasError=!0}finally{_c(s)}}}class Ic{approvalsPath;cwd;approvalsPromise;constructor(e,t){this.approvalsPath=e,this.cwd=t,this.approvalsPromise=this.loadApprovals()}async isServerApproved(e,t,r){const o=function(e,t,r){const o={path:r,server:t};return`${e}-${(0,n.createHash)("sha256").update(JSON.stringify(o)).digest("hex").substring(0,16)}`}(e,t,this.cwd);return(await this.getApprovals()).includes(o)}async loadApprovals(){try{const e=await(0,fo.readFile)(this.approvalsPath,"utf8"),t=JSON.parse(e);return Array.isArray(t)?t:(await this.saveApprovalsToFile([]),[])}catch(e){if(e instanceof Error&&e.message.includes("ENOENT"))return[];throw e}}async getApprovals(){return this.approvalsPromise}async addApproval(e){const t=await this.approvalsPromise;t.includes(e)||(t.push(e),await this.saveApprovals(t))}async addApprovals(e){const t=await this.approvalsPromise,r=e.filter((e=>!t.includes(e)));r.length>0&&(t.push(...r),await this.saveApprovals(t))}async removeApproval(e){const t=await this.approvalsPromise,r=t.filter((t=>t!==e));r.length!==t.length&&await this.saveApprovals(r)}async clearApprovals(e){const t=await this.approvalsPromise,r=e?t.filter((t=>!e(t))):[];r.length!==t.length&&await this.saveApprovals(r)}async saveApprovalsToFile(e){await(0,fo.mkdir)(a.default.dirname(this.approvalsPath),{recursive:!0}),await(0,fo.writeFile)(this.approvalsPath,JSON.stringify(e,null,2))}async saveApprovals(e){await this.saveApprovalsToFile(e),this.approvalsPromise=Promise.resolve(e)}}var Ac=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var o,n;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");o=t[Symbol.asyncDispose]}if(void 0===o){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");o=t[Symbol.dispose],r&&(n=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");n&&(o=function(){try{n.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:o,async:r})}else r&&e.stack.push({async:!0});return t},Oc=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 o,n=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===n)return n=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var s=o.dispose.call(o.value);if(o.async)return n|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else n|=1}catch(e){r(e)}if(1===n)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var o=new Error(r);return o.name="SuppressedError",o.error=e,o.suppressed=t,o});class Dc{async load(e,t,r,o,n){const s=n(e,r);return new jc(e,t,s,r)}}function Mc(e){let t;return e.then((e=>{t=e})).catch((()=>{})),t}class jc{serverName;clientPromise;config;toolsPromise;resourcesPromise;promptsPromise;clientPromiseTraceId;constructor(e,t,r,o){var n,s;this.serverName=t,this.clientPromise=r,this.config=o,this.clientPromiseTraceId=null===(s=null===(n=(0,l.fU)(e))||void 0===n?void 0:n.spanContext())||void 0===s?void 0:s.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){var t;const r={stack:[],error:void 0,hasError:!1};try{const o=Ac(r,(0,l.VI)(e.withName("CachedMcpClient.getTools")),!1);o.span.setAttribute("serverName",this.serverName),o.span.setAttribute("cacheTraceId",null!==(t=this.clientPromiseTraceId)&&void 0!==t?t:"undefined");const n=Mc(this.toolsPromise);return void 0!==n?n:await this.toolsPromise}catch(e){r.error=e,r.hasError=!0}finally{Oc(r)}}async callTool(e,t,r,o,n){const s={stack:[],error:void 0,hasError:!1};try{const i=Ac(s,(0,l.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,o,n)}catch(e){s.error=e,s.hasError=!0}finally{Oc(s)}}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{const r=Ac(t,(0,l.VI)(e.withName("CachedMcpClient.getInstructions")),!1),o=await this.getClient(r.ctx);if(null===o)return;return await o.getInstructions(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{Oc(t)}}async getClient(e){var t;const r={stack:[],error:void 0,hasError:!1};try{const o=Ac(r,(0,l.VI)(e.withName("CachedMcpClient.getClient")),!1);return o.span.setAttribute("serverName",this.serverName),o.span.setAttribute("cacheTraceId",null!==(t=this.clientPromiseTraceId)&&void 0!==t?t:"undefined"),await this.clientPromise}catch(e){r.error=e,r.hasError=!0}finally{Oc(r)}}async listResources(e){var t;const r={stack:[],error:void 0,hasError:!1};try{const o=Ac(r,(0,l.VI)(e.withName("CachedMcpClient.listResources")),!1);o.span.setAttribute("serverName",this.serverName),o.span.setAttribute("cacheTraceId",null!==(t=this.clientPromiseTraceId)&&void 0!==t?t:"undefined");const n=Mc(this.resourcesPromise);return void 0!==n?{resources:n}:{resources:await this.resourcesPromise}}catch(e){r.error=e,r.hasError=!0}finally{Oc(r)}}async readResource(e,t){const r={stack:[],error:void 0,hasError:!1};try{const o=Ac(r,(0,l.VI)(e.withName("CachedMcpClient.readResource")),!1),n=await this.getClient(o.ctx);return null===n?{contents:[]}:n.readResource(o.ctx,t)}catch(e){r.error=e,r.hasError=!0}finally{Oc(r)}}async listPrompts(e){var t;const r={stack:[],error:void 0,hasError:!1};try{const o=Ac(r,(0,l.VI)(e.withName("CachedMcpClient.listPrompts")),!1);o.span.setAttribute("serverName",this.serverName),o.span.setAttribute("cacheTraceId",null!==(t=this.clientPromiseTraceId)&&void 0!==t?t:"undefined");const n=Mc(this.promptsPromise);return void 0!==n?n:await this.promptsPromise}catch(e){r.error=e,r.hasError=!0}finally{Oc(r)}}async getPrompt(e,t,r){const o={stack:[],error:void 0,hasError:!1};try{const n=Ac(o,(0,l.VI)(e.withName("CachedMcpClient.getPrompt")),!1),s=await this.getClient(n.ctx);return null===s?{messages:[]}:s.getPrompt(n.ctx,t,r)}catch(e){o.error=e,o.hasError=!0}finally{Oc(o)}}async getState(e){const t={stack:[],error:void 0,hasError:!1};try{const r=Ac(t,(0,l.VI)(e.withName("CachedMcpClient.getState")),!1);r.span.setAttribute("serverName",this.serverName);const o=await this.getClient(r.ctx);if(null===o)throw new Error("Client is not ready");return await o.getState(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{Oc(t)}}async close(){var e;try{const t=await this.clientPromise;await(null===(e=null==t?void 0:t.close)||void 0===e?void 0:e.call(t))}catch(e){}}}function Nc(e){var t,r;const o=e;if(!o.resource||"object"!=typeof o.resource)return o.uri?`Resource: ${o.uri}${o.name?` (${o.name})`:""}`:`Unsupported content type "${e.type}": ${JSON.stringify(e)}`;{const e=o.resource;if("string"==typeof e.text)return e.text;if("string"!=typeof e.blob)return`Resource: ${null!==(r=e.uri)&&void 0!==r?r:"unknown"}${e.name?` (${e.name})`:""}`;try{return Buffer.from(e.blob,"base64").toString("utf8")}catch(r){return`[Binary resource: ${null!==(t=e.uri)&&void 0!==t?t:"unknown"}]`}}}const $c=/\$\{(?:env:([A-Za-z_][A-Za-z0-9_]*)|([^:}]+)(?::-([^}]*))?)\}/g;function Fc(e,t){if("string"==typeof e)return function(e,t){return e.replace($c,((e,r,o,n)=>{if(void 0!==r){const o=t(r);return void 0!==o?o:e}const s=t(o);return void 0!==s?s:void 0!==n?n:e}))}(e,t);if(Array.isArray(e))return e.map((e=>Fc(e,t)));if(null!==e&&"object"==typeof e){const r={};for(const[o,n]of Object.entries(e))r[o]=Fc(n,t);return r}return e}const Lc=cn.z.object({type:cn.z.literal("stdio").optional(),command:cn.z.string(),args:cn.z.array(cn.z.string()).optional(),env:cn.z.record(cn.z.string(),cn.z.string()).optional(),cwd:cn.z.string().optional()}),Uc=cn.z.object({CLIENT_ID:cn.z.string(),CLIENT_SECRET:cn.z.string().optional(),scopes:cn.z.array(cn.z.string()).optional()}),Bc=cn.z.object({type:cn.z.enum(["http","sse"]).optional(),url:cn.z.string(),headers:cn.z.record(cn.z.string(),cn.z.string()).optional(),auth:Uc.optional()}),Hc=cn.z.union([Lc,Bc]),zc=cn.z.object({mcpServers:cn.z.record(cn.z.string(),Hc)});async function Wc(e,t=e=>process.env[e]){try{const r=await(0,fo.readFile)(e,"utf8"),o=Fc((0,ts.qg)(r),t);return zc.parse(o)}catch(e){return{mcpServers:{}}}}var qc=r("../../node_modules/.pnpm/string-argv@0.3.2/node_modules/string-argv/index.js"),Gc=r("../constants/dist/index.js"),Vc=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=09ddafc9053ad92a2da409aa9fafaaf83fd21f6a2f2_d6dcb3bf6d4dcedd25e081dcae0620fe/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js"),Jc=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=09ddafc9053ad92a2da409aa9fafaaf83fd21f6a2f2_d6dcb3bf6d4dcedd25e081dcae0620fe/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js"),Kc=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=09ddafc9053ad92a2da409aa9fafaaf83fd21f6a2f2_d6dcb3bf6d4dcedd25e081dcae0620fe/node_modules/@modelcontextprotocol/sdk/dist/esm/client/sse.js"),Zc=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=09ddafc9053ad92a2da409aa9fafaaf83fd21f6a2f2_d6dcb3bf6d4dcedd25e081dcae0620fe/node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.js"),Yc=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=09ddafc9053ad92a2da409aa9fafaaf83fd21f6a2f2_d6dcb3bf6d4dcedd25e081dcae0620fe/node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js"),Xc=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=09ddafc9053ad92a2da409aa9fafaaf83fd21f6a2f2_d6dcb3bf6d4dcedd25e081dcae0620fe/node_modules/@modelcontextprotocol/sdk/dist/esm/types.js");class Qc extends Error{url;constructor(e,t="MCP network request blocked by policy"){super(t),this.url=e,this.name="McpNetworkRequestBlockedError"}}const eu=["accept","accept-language","content-language","content-type"];function tu(e){return 301===e.status||302===e.status||303===e.status||307===e.status||308===e.status}function ru(e,t){try{return new URL(t,e).toString()}catch(e){return}}function ou(e,t){try{return new URL(e).origin!==new URL(t).origin}catch(e){return!0}}function nu(e){if(void 0===(null==e?void 0:e.headers))return e;const t=new Headers(e.headers),r=new Headers;for(const e of eu){const o=t.get(e);null!==o&&r.set(e,o)}return Object.assign(Object.assign({},e),{headers:r})}function su(e,t){return void 0===e||void 0===t?e:async(r,o)=>{var n,s;if(!1===await(null===(n=t.isEnabled)||void 0===n?void 0:n.call(t)))return e(r,o);let i=r,a=function(e){return"string"==typeof e?e:e instanceof URL?e.toString():"undefined"!=typeof Request&&e instanceof Request?e.url:void 0}(i),l=o;if(void 0===a)throw new Qc("<unknown>","Cannot extract URL from fetch input for policy check");for(let r=0;;r++){const o=await t.checkUrl(a);if(!o.allowed)throw new Qc(a,o.message);const n=await e(i,Object.assign(Object.assign({},l),{redirect:"manual"}));if(!tu(n))return n;const c=n.headers.get("location");if(null===c)return n;if(r>=10)throw new Error("Too many MCP network request redirects");const u=ru(a,c);if(void 0===u)return n;const d=a;i=u,a=u;const p=ou(d,u)?nu(l):l;l=Object.assign(Object.assign({},p),{redirect:"manual"}),303!==n.status&&(301!==n.status&&302!==n.status||"POST"!==(null===(s=l.method)||void 0===s?void 0:s.toUpperCase()))||(l=Object.assign(Object.assign({},l),{body:void 0,method:"GET"}))}}}var iu=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var o,n;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");o=t[Symbol.asyncDispose]}if(void 0===o){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");o=t[Symbol.dispose],r&&(n=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");n&&(o=function(){try{n.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:o,async:r})}else r&&e.stack.push({async:!0});return t},au=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 o,n=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===n)return n=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var s=o.dispose.call(o.value);if(o.async)return n|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else n|=1}catch(e){r(e)}if(1===n)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var o=new Error(r);return o.name="SuppressedError",o.error=e,o.suppressed=t,o});const lu=["authorization_code","refresh_token"],cu=["code"];class uu{_codeVerifier;_lastRedirectUrl;_oauthState;_oauthAttemptId;_identifier;_redirectUrl;_clientMetadata;_scopes;_tokens;_clientInformation;_saveTokens;_prepareForRefresh;_releaseRefreshLeaseOnError;_invalidateCredentials;_saveClientInformation;constructor(e){this._identifier=e.identifier,this._redirectUrl=e.redirectUrl,this._clientMetadata=e.clientMetadata,this._scopes=e.scopes,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}get redirectUrl(){return this._redirectUrl}get clientMetadata(){return this._clientMetadata}state(){return this._oauthAttemptId=(0,n.randomUUID)(),this._oauthState=function(e,t,r){const o=Object.assign({id:e,owner:t},r?{attemptId:r}:{});return Buffer.from(JSON.stringify(o),"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._tokens}async saveTokens(e){this._tokens=e,await this._saveTokens(e)}async prepareForRefresh(){var e;await(null===(e=this._prepareForRefresh)||void 0===e?void 0:e.call(this))}async releaseRefreshLeaseOnError(e){var t;await(null===(t=this._releaseRefreshLeaseOnError)||void 0===t?void 0:t.call(this,e))}async invalidateCredentials(e){var t;switch(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;break;default:return e}await(null===(t=this._invalidateCredentials)||void 0===t?void 0:t.call(this,e))}redirectToAuthorization(e){var t;(null===(t=this._scopes)||void 0===t?void 0:t.length)&&!e.searchParams.has("scope")&&e.searchParams.set("scope",this._scopes.join(" ")),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 du(e){var t;const{serverName:r,config:o,tokenStorage:n,authRedirectUrl:s}=e,i=function(e,t){if(e)return Object.assign(Object.assign({client_id:e.CLIENT_ID},e.CLIENT_SECRET?{client_secret:e.CLIENT_SECRET}:{}),{redirect_uris:(0,Gc.RJ)(t),grant_types:[...lu],response_types:[...cu],token_endpoint_auth_method:"none"})}(o.auth,s),a=function({storedClientInformation:e,staticClientInformation:t}){var r,o,n,s;return t?e&&e.client_id===t.client_id?Object.assign(Object.assign(Object.assign({},t),e),{client_secret:null!==(r=t.client_secret)&&void 0!==r?r:e.client_secret,redirect_uris:t.redirect_uris,grant_types:null!==(o=e.grant_types)&&void 0!==o?o:t.grant_types,response_types:null!==(n=e.response_types)&&void 0!==n?n:t.response_types,token_endpoint_auth_method:null!==(s=e.token_endpoint_auth_method)&&void 0!==s?s:t.token_endpoint_auth_method}):t:e}({storedClientInformation:await n.loadClientInformation(),staticClientInformation:i});return new uu({identifier:r,redirectUrl:s,clientMetadata:{redirect_uris:(0,Gc.RJ)(s),token_endpoint_auth_method:"none",grant_types:[...lu],response_types:[...cu],client_name:"Cursor",logo_uri:Gc.G$},scopes:null===(t=o.auth)||void 0===t?void 0:t.scopes,tokens:await n.loadTokens(),clientInformation:a,saveTokens:e=>n.saveTokens(e),prepareForRefresh:()=>{var e,t;return null!==(t=null===(e=n.prepareForRefresh)||void 0===e?void 0:e.call(n))&&void 0!==t?t:Promise.resolve()},releaseRefreshLeaseOnError:e=>{var t,r;return null!==(r=null===(t=n.releaseRefreshLeaseOnError)||void 0===t?void 0:t.call(n,e))&&void 0!==r?r:Promise.resolve()},invalidateCredentials:n.invalidateCredentials?e=>n.invalidateCredentials(e):void 0,saveClientInformation:e=>n.saveClientInformation(e)})}class pu{serverName;config;client;tools;stateValue;_authProvider;_sessionId;_currentElicitationProvider;_currentToolCallId;_currentToolName;_callToolLock=Promise.resolve();_oauthLifecycleLogger;_stateEnteredAtMs=Date.now();constructor(e,t,r){this.serverName=e,this.client=t,this.tools=new xc.B1,this.stateValue=r.initialState,this._authProvider=r.authProvider,this._sessionId=r.sessionId,this.config=r.config,this._oauthLifecycleLogger=r.oauthLifecycleLogger,this.setupElicitationHandler()}_stateKindLabel(e){return"requires_authentication"===e.kind?"needsAuth":e.kind}_logStateTransition(e,t,r,o){if(!this._oauthLifecycleLogger)return;const n=this._stateKindLabel(e),s=this._stateKindLabel(t);if(n===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(e){return}})();(0,xc.VD)({logger:this._oauthLifecycleLogger,event:"mcp_oauth_state_transition",metadata:Object.assign({identifier:this.serverName,from:n,to:s,cause:r,serverUrlHost:a,previousStateDurationMs:i},o)})}static createClient(){return new Jc.K({name:"Cursor",version:"1.0.0"},{capabilities:{elicitation:{form:{}}}})}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=await this._currentElicitationProvider.elicit({message:e.params.message,requestedSchema:e.params.requestedSchema});return{action:t.action,content:t.content}}catch(e){return{action:"decline"}}}))}static async fromStreamableHttp(e,t,r,o,n,s,i,a,l){const c=new URL(t.url);n=null!=n?n:Gc.tl;const u=await r.loadTokens(),d=await du({serverName:e,config:t,tokenStorage:r,authRedirectUrl:n}),p=su(null!=s?s:globalThis.fetch?globalThis.fetch.bind(globalThis):void 0,l),h=e=>void 0===p||void 0===i?p:(0,xc.jI)({fetch:p,logger:i.logger,metadata:Object.assign(Object.assign({},i.metadata),{transportType:e})}),m=pu.createClient(),f=r=>{var o,n,s;const i=null!==(s=null===(n=null===(o=d.lastRedirectUrl)||void 0===o?void 0:o.toString)||void 0===n?void 0:n.call(o))&&void 0!==s?s:"",l=new pu(e,m,{oauthLifecycleLogger:a,initialState:{kind:"requires_authentication",url:i,callback:async t=>{try{if(!d.hasClientInformation())throw new Error("OAuth client registration has not completed. The MCP server may not support dynamic client registration or the registration failed.");await(0,Vc.j2)(d,Object.assign({serverUrl:c.toString(),authorizationCode:t},void 0!==p?{fetchFn:p}:{})),a&&(0,xc.VD)({logger:a,event:"mcp_oauth_callback_completion",metadata:Object.assign(Object.assign({identifier:e},(0,xc.q2)(c.toString())),(0,xc.tB)(d.tokens(),{expiresInIsFresh:!0}))}),l.updateState({kind:"ready"})}catch(e){const t=e instanceof Error?e.message:"Authentication failed";throw new Error(`Authentication callback failed: ${t}`)}}},authProvider:d,sessionId:r,config:t});return l},g=async()=>{const r=new Kc.A(c,{authProvider:d,requestInit:{headers:Object.assign({"User-Agent":"Cursor/1.0.0"},null!=o?o:{})},fetch:h("sse")});try{return await m.connect(r),new pu(e,m,{initialState:{kind:"ready"},authProvider:d,config:t,oauthLifecycleLogger:a})}catch(t){if(t instanceof Vc.D_)return a&&(0,xc.VD)({logger:a,event:"mcp_oauth_state_transition",metadata:Object.assign(Object.assign({identifier:e,from:"connecting",to:"needsAuth",cause:"connect_auth_error",transport:"sse",refreshTokenPresent:Boolean(null==u?void 0:u.refresh_token)},(0,xc.q2)(c.toString())),(0,xc.X5)(t))}),f();throw t}};if("sse"===t.type)return g();const v=new Yc.j(c,{authProvider:d,requestInit:{headers:Object.assign({"User-Agent":"Cursor/1.0.0"},null!=o?o:{})},fetch:h("streamableHttp")});try{return await m.connect(v),new pu(e,m,{initialState:{kind:"ready"},authProvider:d,sessionId:v.sessionId,config:t,oauthLifecycleLogger:a})}catch(t){if(t instanceof Vc.D_)return a&&(0,xc.VD)({logger:a,event:"mcp_oauth_state_transition",metadata:Object.assign(Object.assign({identifier:e,from:"connecting",to:"needsAuth",cause:"connect_auth_error",transport:"streamableHttp",refreshTokenPresent:Boolean(null==u?void 0:u.refresh_token)},(0,xc.q2)(c.toString())),(0,xc.X5)(t))}),f(v.sessionId);if((0,xc.PK)(t))return g();throw t}}static async fromNetworkControlledStreamableHttp(e,t,r,o,n,s,i,a,l){return pu.fromStreamableHttp(e,t,r,n,s,i,a,l,o)}static async fromCachedSession(e,t,r,o,n,s=Gc.tl,i,a,l,c){const u=new URL(t.url),d=await du({serverName:e,config:t,tokenStorage:o,authRedirectUrl:s}),p=su(null!=i?i:globalThis.fetch?globalThis.fetch.bind(globalThis):void 0,c),h=new Yc.j(u,{authProvider:d,sessionId:r.sessionId,requestInit:{headers:Object.assign({"User-Agent":"Cursor/1.0.0"},null!=n?n:{})},fetch:void 0!==p&&void 0!==a?(0,xc.jI)({fetch:p,logger:a.logger,metadata:Object.assign(Object.assign({},a.metadata),{transportType:"streamableHttp"})}):p}),m=pu.createClient();return await m.connect(h),new pu(e,m,{initialState:{kind:"ready"},authProvider:d,sessionId:h.sessionId,config:t,oauthLifecycleLogger:l})}get sessionId(){return this._sessionId}static async fromCommand(e,t,r,o,n){var s;const i={stack:[],error:void 0,hasError:!1};try{iu(i,(0,l.VI)(e.withName("McpSdkClient.fromCommand")),!1);const a=new Zc.oQ(Object.assign({command:r.command,args:null!==(s=r.args)&&void 0!==s?s:[],env:o,cwd:r.cwd,stderr:"ignore"},(null==n?void 0:n.spawn)&&{spawn:n.spawn})),c=pu.createClient();return await c.connect(a),new pu(t,c,{initialState:{kind:"ready"},config:r})}catch(e){i.error=e,i.hasError=!0}finally{au(i)}}async close(){await this.client.close()}async getTools(e){var t,r,o;const n={stack:[],error:void 0,hasError:!1};try{if(iu(n,(0,l.VI)(e.withName("McpSdkClient.getTools")),!1),"requires_authentication"===this.stateValue.kind)return[];try{return await this.tools.get((async()=>{let e;const t=[];for(;;){const r=await this.client.listTools({cursor:e});if(t.push(...r.tools.map((e=>Object.assign(Object.assign({},e),{inputSchema:e.inputSchema,outputSchema:e.outputSchema})))),e=r.nextCursor,void 0===e)break}return t}))}catch(e){if(e instanceof Vc.D_&&"ready"===this.stateValue.kind){const n=this.stateValue,s=null!==(o=null===(r=null===(t=this._authProvider)||void 0===t?void 0:t.lastRedirectUrl)||void 0===r?void 0:r.toString())&&void 0!==o?o:"";this.stateValue={kind:"requires_authentication",url:s,callback:async e=>{}},this._logStateTransition(n,this.stateValue,"runtime_unauthorized",Object.assign({},(0,xc.X5)(e))),this._stateEnteredAtMs=Date.now()}throw e}}catch(e){n.error=e,n.hasError=!0}finally{au(n)}}async callTool(e,t,r,o,n){var s,i,a;const c={stack:[],error:void 0,hasError:!1};try{iu(c,(0,l.VI)(e.withName("McpSdkClient.callTool")),!1).span.setAttribute("toolName",t);const u=this._callToolLock;let d;this._callToolLock=new Promise((e=>{d=e}));try{await u,this._currentToolCallId=o,this._currentToolName=t,this._currentElicitationProvider=n;try{const e=await this.client.callTool({name:t,arguments:r});return{content:e.content,isError:void 0!==e.error}}catch(e){if(e instanceof Vc.D_&&"ready"===this.stateValue.kind){const t=this.stateValue,r=null!==(a=null===(i=null===(s=this._authProvider)||void 0===s?void 0:s.lastRedirectUrl)||void 0===i?void 0:i.toString())&&void 0!==a?a:"";this.stateValue={kind:"requires_authentication",url:r,callback:async e=>{}},this._logStateTransition(t,this.stateValue,"runtime_unauthorized",Object.assign({},(0,xc.X5)(e))),this._stateEnteredAtMs=Date.now()}throw e}finally{this._currentElicitationProvider=void 0,this._currentToolCallId=void 0,this._currentToolName=void 0}}finally{d()}}catch(e){c.error=e,c.hasError=!0}finally{au(c)}}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{if(iu(t,(0,l.VI)(e.withName("McpSdkClient.getInstructions")),!1),"requires_authentication"===this.stateValue.kind)return;return await this.client.getInstructions()}catch(e){t.error=e,t.hasError=!0}finally{au(t)}}async listResources(e){const t={stack:[],error:void 0,hasError:!1};try{if(iu(t,(0,l.VI)(e.withName("McpSdkClient.listResources")),!1),"requires_authentication"===this.stateValue.kind)return{resources:[]};const r=this.client.getServerCapabilities();if(!(null==r?void 0:r.resources))return{resources:[]};let o;const n=[];for(;;){const e=await this.client.listResources({cursor:o});if(n.push(...e.resources),o=e.nextCursor,void 0===o)break}return{resources:n}}catch(e){t.error=e,t.hasError=!0}finally{au(t)}}async readResource(e,t){const r={stack:[],error:void 0,hasError:!1};try{return iu(r,(0,l.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{au(r)}}async listPrompts(e){var t;const r={stack:[],error:void 0,hasError:!1};try{if(iu(r,(0,l.VI)(e.withName("McpSdkClient.listPrompts")),!1),"requires_authentication"===this.stateValue.kind)return[];if(!(null!==(t=this.client.getServerCapabilities())&&void 0!==t?t:{prompts:!1}).prompts)return[];const o=await this.client.listPrompts();return(null==o?void 0:o.prompts)?o.prompts.map((e=>{var t;return{name:e.name,description:e.description,arguments:null===(t=e.arguments)||void 0===t?void 0:t.map((e=>({name:e.name,description:e.description,required:e.required})))}})):[]}catch(e){r.error=e,r.hasError=!0}finally{au(r)}}async getPrompt(e,t,r){const o={stack:[],error:void 0,hasError:!1};try{return iu(o,(0,l.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){o.error=e,o.hasError=!0}finally{au(o)}}getCurrentToolCallContext(){if(this._currentToolName)return{toolName:this._currentToolName,toolCallId:this._currentToolCallId}}async getState(e){return this.stateValue}updateState(e,t){const r=this.stateValue;this.stateValue=e,this._logStateTransition(r,e,null!=t?t:"explicit_update"),this._stateEnteredAtMs=Date.now()}}class hu extends Error{toolName;availableTools;constructor(e,t){super(`Tool ${e} not found, available tools: ${t.join(", ")}`),this.toolName=e,this.availableTools=t,this.name="McpToolNotFoundError"}}class mu extends Error{serverName;availableServers;constructor(e,t){super(`MCP server ${e} not found, available servers: ${t.join(", ")}`),this.serverName=e,this.availableServers=t,this.name="McpServerNotFoundError"}}Error;class fu{tools;constructor(e){this.tools=e}async execute(e,t,r,o){const n=this.tools[e];if(!n)throw new hu(e,Object.keys(this.tools));return n.execute(t,r,o)}getTools(){return Object.entries(this.tools).map((([e,t])=>Object.assign(Object.assign({},t.definition),{name:e})))}}class gu{async getClients(e){return{}}async getClient(e,t){}async getInstructions(e){return[]}async getToolSet(e){return new fu({})}async getTools(e){return[]}async getToolsForServers(e,t){return[]}}class vu{manager;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=iu(t,(0,l.VI)(e.withName("ManagerMcpLease.getInstructions")),!1);return await this.manager.getInstructions(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{au(t)}}async getToolSet(e){const t={stack:[],error:void 0,hasError:!1};try{const r=iu(t,(0,l.VI)(e.withName("ManagerMcpLease.getToolSet")),!1);return await this.manager.getToolSet(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{au(t)}}async getTools(e){const t={stack:[],error:void 0,hasError:!1};try{const r=iu(t,(0,l.VI)(e.withName("ManagerMcpLease.getTools")),!1);return(await this.getToolSet(r.ctx)).getTools()}catch(e){t.error=e,t.hasError=!0}finally{au(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){var o;for(const e of t.removed){const t=this.manager.getClient(e);this.manager.deleteClient(e);try{await(null===(o=null==t?void 0:t.close)||void 0===o?void 0:o.call(t))}catch(e){}}for(const o of t.added){if(this.manager.getClient(o))continue;const t=await r(e,o);this.manager.setClient(o,t)}}}class yu{clients;elicitationFactory;changeListeners=new Set;constructor(e,t){this.clients=e,this.elicitationFactory=t}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()}async closeAllClients(){const e=Object.values(this.clients);await Promise.all(e.map((async e=>{var t;try{await(null===(t=e.close)||void 0===t?void 0:t.call(e))}catch(e){}})))}async getToolSet(e){const t={stack:[],error:void 0,hasError:!1};try{const r=iu(t,(0,l.VI)(e.withName("McpManager.getToolSet")),!1),o=await(0,h.PH)(Object.entries(this.clients),(([e,t])=>t.getTools(r.ctx).then((r=>r.map((r=>Object.assign(Object.assign({},r),{clientKey:e,clientName:t.serverName,client:t}))))).catch((()=>[]))),{max:4}),n=Array.from(o.values()).flat(),s={};for(const e of n)s[`${e.clientName}-${e.name}`]={definition:Object.assign(Object.assign({},e),{clientKey:e.clientKey,providerIdentifier:e.clientName,toolName:e.name}),execute:async(t,o,n)=>{const s=null==n?void 0:n.createProvider(e.clientName,e.name,o);return await e.client.callTool(r.ctx,e.name,t,o,s)}};return new fu(s)}catch(e){t.error=e,t.hasError=!0}finally{au(t)}}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{const r=iu(t,(0,l.VI)(e.withName("McpManager.getInstructions")),!1),o=await(0,h.PH)(Object.entries(this.clients),(([e,t])=>t.getInstructions(r.ctx).then((e=>e&&0!==e.trim().length?new sr.I0({serverName:t.serverName,instructions:e.trim()}):null)).catch((()=>null))),{max:4});return Array.from(o.values()).filter((e=>null!==e))}catch(e){t.error=e,t.hasError=!0}finally{au(t)}}}class wu{server;networkControlsService;static legacy(e){return new wu(e)}static fromTeamSettings(e){return new wu(e.server,e.networkControlsService)}constructor(e,t){this.server=e,this.networkControlsService=t}kind(){return"command"in this.server?"local":"remote"}async usesNetworkControlledRemoteFlow(){return"remote"===this.kind()&&!0===(await this.getMcpNetworkControlsConfig()).enabled}async checkRemoteUrl(e){const t=(0,xc.T4)(e,await this.getMcpNetworkControlsConfig());return void 0===t?{allowed:!0}:{allowed:!1,message:t}}async checkUrl(e){return this.checkRemoteUrl(e)}async getMcpNetworkControlsConfig(){var e,t,r;return null!==(r=await(null===(t=null===(e=this.networkControlsService)||void 0===e?void 0:e.getMcpNetworkControlsConfig)||void 0===t?void 0:t.call(e)))&&void 0!==r?r:{}}}function bu(e,t){return function(e){const{logger:t,ctx:r}=e;return{debug:(e,o)=>t.debug(r,e,o),info:(e,o)=>t.info(r,e,o),warn:(e,o)=>t.warn(r,e,o),error:(e,o,n)=>t.error(r,e,o,n)}}({ctx:e,logger:t})}class Su{options;constructor(e){this.options=e,(0,xc.VD)({logger:e.logger,event:"mcp_oauth_provider_initialized",metadata:this.baseMetadata})}get baseMetadata(){return Object.assign({identifier:this.options.identifier},this.options.serverUrl?{serverUrl:(0,xc.q2)(this.options.serverUrl)}:{})}async loadTokens(){const e=await this.options.inner.loadTokens();return(0,xc.VD)({logger:this.options.logger,event:"mcp_oauth_tokens_loaded",level:"debug",metadata:Object.assign(Object.assign({},this.baseMetadata),(0,xc.tB)(e))}),e}async saveTokens(e){await this.options.inner.saveTokens(e),(0,xc.VD)({logger:this.options.logger,event:"mcp_oauth_tokens_saved",metadata:Object.assign(Object.assign({},this.baseMetadata),(0,xc.tB)(e,{expiresInIsFresh:!0}))})}async prepareForRefresh(){var e,t;(0,xc.VD)({logger:this.options.logger,event:"mcp_oauth_refresh_prepare",metadata:this.baseMetadata}),await(null===(t=(e=this.options.inner).prepareForRefresh)||void 0===t?void 0:t.call(e))}async releaseRefreshLeaseOnError(e){var t,r;(0,xc.VD)({logger:this.options.logger,event:"mcp_oauth_refresh_error_release",level:"warn",error:e,metadata:Object.assign(Object.assign({},this.baseMetadata),(0,xc.X5)(e))}),await(null===(r=(t=this.options.inner).releaseRefreshLeaseOnError)||void 0===r?void 0:r.call(t,e))}async loadClientInformation(){const e=await this.options.inner.loadClientInformation();return(0,xc.VD)({logger:this.options.logger,event:"mcp_oauth_client_info_loaded",level:"debug",metadata:Object.assign(Object.assign({},this.baseMetadata),(0,xc.O3)(e))}),e}async saveClientInformation(e){await this.options.inner.saveClientInformation(e),(0,xc.VD)({logger:this.options.logger,event:"mcp_oauth_client_info_saved",metadata:Object.assign(Object.assign({},this.baseMetadata),(0,xc.O3)(e))})}async invalidateCredentials(e){void 0!==this.options.inner.invalidateCredentials&&((0,xc.VD)({logger:this.options.logger,event:"mcp_oauth_credentials_invalidated",level:"warn",metadata:Object.assign(Object.assign({},this.baseMetadata),{scope:e})}),await this.options.inner.invalidateCredentials(e))}}class ku{storage;identifier;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)}}class Eu{inner;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){var t,r;await(null===(r=(t=this.inner).invalidateCredentials)||void 0===r?void 0:r.call(t,e))}}var xu=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var o,n;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");o=t[Symbol.asyncDispose]}if(void 0===o){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");o=t[Symbol.dispose],r&&(n=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");n&&(o=function(){try{n.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:o,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 o,n=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===n)return n=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var s=o.dispose.call(o.value);if(o.async)return n|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else n|=1}catch(e){r(e)}if(1===n)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var o=new Error(r);return o.name="SuppressedError",o.error=e,o.suppressed=t,o});const Cu=(0,l.h)("DefinitionMcpLoader");function Pu(e){const{filePath:t,baseDir:r}=e;return"~"===t||t.startsWith("~/")?a.default.join(i.default.homedir(),t.slice(1)):t.startsWith("./")||"."===t?a.default.resolve(null!=r?r:process.cwd(),t):t}function Ru(e){return"function"==typeof e.getMcpNetworkControlsConfig}function Tu(e,t){return{logger:{debug:(t,r)=>Cu.debug(e,t,r),info:(t,r)=>Cu.info(e,t,r),warn:(t,r)=>Cu.warn(e,t,r),error:(t,r,o)=>Cu.error(e,t,r,o)},metadata:{identifier:t,source:"mcp-agent-exec"}}}class Iu{configPath;configPromise;constructor(e){this.configPath=e,this.configPromise=Wc(e)}clearCache(){this.configPromise=Wc(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 Au{source;tokenStorage;middlewares;options;clientCache=new Map;sandboxPolicyFingerprint;constructor(e,t,r=[],o={}){this.source=e,this.tokenStorage=t,this.middlewares=r,this.options=o}async load(e,t=!0){var r,o,n;const s={stack:[],error:void 0,hasError:!1};try{xu(s,(0,l.VI)(e.withName("DefinitionMcpLoader.load")),!1),await this.evictClientsOnSandboxPolicyChange(e),t||(await this.closeAllCachedClients(),null===(o=(r=this.source).clearCache)||void 0===o||o.call(r));const i=await this.source.getDefinitions(e,t),a={};return await(0,h.PH)([...i],(async r=>{try{const o=t?this.clientCache.get(r.identifier):void 0,n=null!=o?o:await this.loadDefinitionClient(e,r);o||this.clientCache.set(r.identifier,n),a[r.identifier]=n}catch(t){if(this.handleDefinitionLoadError(e,r,t))return;!function(e,t,r){Cu.warn(e,"Failed to load MCP server",{identifier:t.identifier,source:t.source,configPath:t.configPath,metadata:t.metadata,errorMessage:r instanceof Error?r.message:String(r)})}(e,r,t)}}),{max:null!==(n=this.options.maxConcurrency)&&void 0!==n?n:Math.max(i.length,1)}),new yu(a,this.options.elicitationFactory)}catch(e){s.error=e,s.hasError=!0}finally{_u(s)}}clearClient(e){this.clientCache.delete(e)}clearAllMcpCaches(){this.clientCache.clear()}async evictClientsOnSandboxPolicyChange(e){var t,r;const o=this.middlewares.find(Ru);if(!o)return;let n;try{const e=null!==(r=await(null===(t=o.getMcpNetworkControlsConfig)||void 0===t?void 0:t.call(o)))&&void 0!==r?r:{};n=(0,xc.Fm)(e)}catch(e){return}const s=this.sandboxPolicyFingerprint;this.sandboxPolicyFingerprint=n,void 0!==s&&s!==n&&(Cu.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,h.PH)(e,(async e=>{var t;try{await(null===(t=e.close)||void 0===t?void 0:t.call(e))}catch(e){}}),{max:Math.max(e.length,1)})}async loadClient(e,t,r){const o={stack:[],error:void 0,hasError:!1};try{if(xu(o,(0,l.VI)(e.withName("DefinitionMcpLoader.loadClient")),!1),await this.evictClientsOnSandboxPolicyChange(e),!r){const e=this.clientCache.get(t);if(e)return e}const n=(await this.source.getDefinitions(e)).find((e=>e.identifier===t));if(!n)throw new Error(`MCP server "${t}" not found in config`);let s;try{s=await this.loadDefinitionClient(e,n,r)}catch(t){throw this.handleDefinitionLoadError(e,n,t),t}return r||this.clientCache.set(t,s),s}catch(e){o.error=e,o.hasError=!0}finally{_u(o)}}async loadDefinitionClient(e,t,o){var n,s;const i=null!==(n=t.authStorageKey)&&void 0!==n?n:t.identifier,a=new ku(this.tokenStorage,i),c=bu(e,Cu),u=new Su({inner:a,logger:c,identifier:i,serverUrl:"url"in t.serverConfig?t.serverConfig.url:void 0}),d=o?new Eu(u):u;return async function(e,t,o,n,s={middlewares:[],configPath:""},i){const a={stack:[],error:void 0,hasError:!1};try{const{middlewares:c,configPath:u}=s,d=xu(a,(0,l.VI)(e.withName("mcp-agent-exec.loadServer")),!1);d.span.setAttribute("serverName",t);let p=async(e,o)=>{const s={stack:[],error:void 0,hasError:!1};try{const a=xu(s,(0,l.VI)(e.withName("loadServer.next")),!1);a.span.setAttribute("serverName",t);const u=a.ctx;if("command"in o){a.span.setAttribute("kind","command");const e=c.find(Ru);return await async function(e,t,o,n){var s,i;const a=o.cwd?Pu({filePath:o.cwd}):void 0;let l,c;if(o.args&&o.args.length>0)l=Pu({filePath:o.command,baseDir:a}),c=o.args.map((e=>Pu({filePath:e,baseDir:a})));else{const e=(0,qc.A)(o.command);l=Pu({filePath:e[0],baseDir:a}),c=e.slice(1).map((e=>Pu({filePath:e,baseDir:a})))}const u=null!==(i=o.env)&&void 0!==i?i:{},d=await(null===(s=null==n?void 0:n.getMcpNetworkControlsConfig)||void 0===s?void 0:s.call(n));if(!0===(null==d?void 0:d.enabled)){const{buildMcpSandboxPolicy:o}=await Promise.resolve().then(r.bind(r,"../mcp-agent-exec/dist/mcp-sandbox-policy.js")),{SandboxUnsupportedError:n,spawnInSandbox:s}=await Promise.resolve().then(r.bind(r,"../shell-exec/dist/index.js")),i=null!=a?a:process.cwd(),p=await o(d,i);Cu.info(e,`Sandboxing local MCP server "${t}" with network controls`);try{return await pu.fromCommand(e,t,{command:l,args:c,cwd:a},u,{spawn:(e,t,r)=>s(e,t,r,p)})}catch(e){if(e instanceof n)throw new xc.c8(t,e);throw e}}return pu.fromCommand(e,t,{command:l,args:c,cwd:a},u)}(u,t,o,e)}if("url"in o){a.span.setAttribute("kind","url");const e=null==i?void 0:i(t),r=function(e,t){return wu.fromTeamSettings({server:e,networkControlsService:t.find(Ru)})}(o,c);return await r.usesNetworkControlledRemoteFlow()?await async function(e,t,r,o,n,s){const i=bu(e,Cu),a=Tu(e,t);return pu.fromNetworkControlledStreamableHttp(t,r,o,n,r.headers,s,void 0,a,i)}(u,t,o,n,r,e):await async function(e,t,r,o,n){const s=bu(e,Cu),i=Tu(e,t);return pu.fromStreamableHttp(t,r,o,r.headers,n,void 0,i,s)}(u,t,o,n,e)}throw new Error(`Invalid server: ${JSON.stringify(o)}`)}catch(e){s.error=e,s.hasError=!0}finally{_u(s)}};for(const e of c){const r=p;p=async(o,n)=>await e.load(o,t,n,u,r)}return await p(d.ctx,o)}catch(e){a.error=e,a.hasError=!0}finally{_u(a)}}(e,t.identifier,t.serverConfig,d,{middlewares:this.middlewares,configPath:null!==(s=t.configPath)&&void 0!==s?s:""},this.options.authRedirectUrlGenerator)}handleDefinitionLoadError(e,t,r){var o,n;let s=!1;try{s="handled"===(null===(n=(o=this.options).onDefinitionLoadError)||void 0===n?void 0:n.call(o,e,t,r))}catch(r){Cu.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 s||function(e){return e instanceof Cc||e instanceof Pc||e instanceof Ou}(r)}}class Ou extends Error{serverName;reason;constructor(e,t,r){super(null!=r?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"}}class Du{blockingService;constructor(e){this.blockingService=e}async getMcpNetworkControlsConfig(){var e,t,r;return null!==(r=await(null===(t=(e=this.blockingService).getMcpNetworkControlsConfig)||void 0===t?void 0:t.call(e)))&&void 0!==r?r:{}}async load(e,t,r,o,n){var s,i,a,l,c;const u={command:"command"in r?[r.command,...null!==(a=r.args)&&void 0!==a?a:[]].join(" "):void 0,url:"url"in r?r.url:void 0},d=null!==(l=await(null===(i=(s=this.blockingService).getMcpServerBlockInfo)||void 0===i?void 0:i.call(s,u)))&&void 0!==l?l:{blocked:await this.blockingService.isServerBlocked(u)};if(d.blocked)throw new Ou(t,null!==(c=d.reason)&&void 0!==c?c:"teamPolicy",d.message);return n(e,r)}}class Mu extends Au{configPath;elicitationFactory;constructor(e,t,r=[],o,n){super(new Iu(e),t,r,{authRedirectUrlGenerator:o,elicitationFactory:n}),this.configPath=e,this.elicitationFactory=n}static init(e,t,r=[]){return new Mu(t,e,r)}}function ju(e){var t;return"stdio"===e.type&&e.command?{command:e.command,args:null!==(t=e.args)&&void 0!==t?t:[],env:e.env,cwd:e.cwd}:"streamableHttp"===e.type&&e.url?{url:e.url,headers:e.headers,auth:e.auth}:void 0}r("../mcp-agent-exec/dist/mcp-sandbox-policy.js");class Nu{mcpAuthPath;static mcpAuthPromises=new Map;static saveLocks=new Map;mcpAuthPromise;constructor(e){this.mcpAuthPath=e;const t=Nu.mcpAuthPromises.get(e);if(t)this.mcpAuthPromise=t;else{const t=this.loadMcpAuth();this.mcpAuthPromise=t,Nu.mcpAuthPromises.set(e,t),t.catch((()=>{Nu.mcpAuthPromises.get(e)===t&&Nu.mcpAuthPromises.delete(e)}))}Nu.saveLocks.has(e)||Nu.saveLocks.set(e,Promise.resolve())}async loadMcpAuth(){try{const e=await(0,fo.readFile)(this.mcpAuthPath,"utf8"),t=JSON.parse(e);if(t&&"object"==typeof t){if(Object.values(t).some((e=>e&&"object"==typeof e&&null!==e&&("access_token"in e||"refresh_token"in e)&&!("tokens"in e)&&!("clientInfo"in e)))){const e={};for(const[r,o]of Object.entries(t))e[r]={tokens:o};return e}const e={};for(const[r,o]of Object.entries(t))o&&"object"==typeof o&&null!==o&&(e[r]={tokens:"tokens"in o?o.tokens:void 0,clientInfo:"clientInfo"in o?o.clientInfo:void 0});return e}return{}}catch(e){if(e instanceof Error&&e.message.includes("ENOENT"))return{};throw e}}async loadTokens(e){var t;return null===(t=(await this.mcpAuthPromise)[e])||void 0===t?void 0:t.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){var t;return null===(t=(await this.mcpAuthPromise)[e])||void 0===t?void 0:t.clientInfo}async withSaveLock(e){var t;const r=null!==(t=Nu.saveLocks.get(this.mcpAuthPath))&&void 0!==t?t:Promise.resolve();let o;Nu.saveLocks.set(this.mcpAuthPath,new Promise((e=>{o=e})));try{return await r,await e()}finally{o()}}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 deleteCredentials(e){await this.withSaveLock((async()=>{const t=await this.mcpAuthPromise;e in t&&(delete t[e],await this.saveMcpAuth(t))}))}async saveMcpAuth(e){await(0,fo.mkdir)(a.dirname(this.mcpAuthPath),{recursive:!0}),await(0,fo.writeFile)(this.mcpAuthPath,JSON.stringify(e,null,2))}}"function"==typeof SuppressedError&&SuppressedError,(0,d.Pu)("mcp.filesystem.divergence",{description:"Divergence detected between MCP lease state and filesystem state",labelNames:["divergence_type","mcp_source","configured_servers","mcp_version"]}),(0,d.Pu)("mcp.filesystem.sync_check",{description:"MCP filesystem sync check executed",labelNames:["synced","mcp_source","configured_servers","mcp_version"]}),(0,d.wt)("mcp.filesystem.sync_check.expected_servers",{description:"Number of expected MCP servers at last sync check",labelNames:["mcp_source","mcp_version"]}),(0,d.wt)("mcp.filesystem.sync_check.actual_servers",{description:"Number of actual MCP servers on disk at last sync check",labelNames:["mcp_source","mcp_version"]}),(0,d.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"]}),(0,d.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"]}),(0,l.h)("McpFileSystemWriter");const $u="mcp_auth";["# 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");var Fu=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var o,n;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");o=t[Symbol.asyncDispose]}if(void 0===o){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");o=t[Symbol.dispose],r&&(n=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");n&&(o=function(){try{n.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:o,async:r})}else r&&e.stack.push({async:!0});return t},Lu=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 o,n=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===n)return n=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var s=o.dispose.call(o.value);if(o.async)return n|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else n|=1}catch(e){r(e)}if(1===n)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var o=new Error(r);return o.name="SuppressedError",o.error=e,o.suppressed=t,o});const Uu=(0,l.h)("local-exec:mcp");async function Bu(e,t,r){if(r>0&&e.length>r){const r=a.default.join(t,kc),o=a.default.join(r,`${(0,n.randomUUID)()}.txt`);await(0,fo.mkdir)(a.default.dirname(o),{recursive:!0});const s=e.slice(0,Ec),i=s.split("\n").length,l=Buffer.byteLength(s,"utf8");return await(0,fo.writeFile)(o,s,"utf8"),new Ge._Z({content:{case:"text",value:new Ge.zN({text:"",outputLocation:new Rl.pV({filePath:o,sizeBytes:BigInt(l),lineCount:BigInt(i)})})}})}return new Ge._Z({content:{case:"text",value:new Ge.zN({text:e})}})}function Hu(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 zu(e,t,r){const o=!t.skipApproval&&await r.permissionsService.shouldBlockMcp(e,t);if(o)return await Fo(o,{onNeedsApproval:async(e,o)=>{if("mcp"!==o.type)return new Ge.iz({result:{case:"error",value:new Ge.Nh({error:"Invalid approval details type for MCP execution"})}});const n=await r.pendingDecisionProvider.requestApproval({type:ic.Mcp,details:{name:o.name,toolName:o.toolName,providerIdentifier:o.providerIdentifier,source:r.toolDef?.source,args:o.args,reason:o.reason??e,canAllowlist:o.canAllowlist,smartModeApprovalReason:o.smartModeApprovalReason,smartModeApprovalRequestId:o.smartModeApprovalRequestId},toolCallId:t.toolCallId});return n.approved?t.smartModeApprovalOnly?new Ge.iz({result:{case:"approved",value:new Ge.Ke}}):null:new Ge.iz({result:{case:"rejected",value:new Ge.xo({reason:`User rejected MCP: ${t.name}${n.reason?` - ${n.reason}`:""}`})}})},onUserRejected:e=>new Ge.iz({result:{case:"error",value:new Ge.Nh({error:`User rejected MCP: ${t.name}${e?` - ${e}`:""}`})}}),onPermissionDenied:(e,r)=>{const o=`MCP tool execution blocked: ${t.name} - ${e}`;return new Ge.iz({result:{case:"permissionDenied",value:new Ge.HQ({error:o,isReadonly:r?.isReadonly??!1})}})}})??void 0}class Wu{toolSet;permissionsService;pendingDecisionProvider;projectDir;fileOutputThresholdBytes;elicitationFactory;constructor(e,t,r,o,n=4e4,s){this.toolSet=e,this.permissionsService=t,this.pendingDecisionProvider=r,this.projectDir=o,this.fileOutputThresholdBytes=n,this.elicitationFactory=s}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const o=Fu(r,(0,l.VI)(e.withName("LocalMcpToolExecutor.execute")),!1).ctx,n=await this.toolSet.getTools(o),s=Array.from(new Set(n.map((e=>e.clientKey)))).sort(),i=n.find((e=>e.providerIdentifier===t.providerIdentifier&&e.toolName===t.toolName)),a=await zu(o,t,{permissionsService:this.permissionsService,pendingDecisionProvider:this.pendingDecisionProvider,toolDef:i});if(void 0!==a)return a;const c=await this.toolSet.getToolSet(o);let u;try{u=await c.execute(t.name,Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t.toJson()]))),t.toolCallId,this.elicitationFactory)}catch(e){let r=e;if(r instanceof hu&&t.providerIdentifier.length>0&&!n.some((e=>e.clientKey===t.providerIdentifier||e.providerIdentifier===t.providerIdentifier))&&(r=new mu(t.providerIdentifier,s)),r instanceof mu)return new Ge.iz({result:{case:"serverNotFound",value:new Ge.JL({name:r.serverName,availableServers:r.availableServers})}});if(r instanceof hu)return new Ge.iz({result:{case:"toolNotFound",value:new Ge.WV({name:r.toolName,availableTools:r.availableTools})}});throw r}const d=[];for(const e of u.content){const t=e.type;if("text"===t){const t=e;d.push(await Bu(t.text,this.projectDir,this.fileOutputThresholdBytes))}else if("resource"===t){const t=e;t.resource?.text&&d.push(await Bu(t.resource.text,this.projectDir,this.fileOutputThresholdBytes))}else if("image"===t){const t=e,r=Buffer.from(t.data,"base64"),o=await(0,h.O5)(r);d.push(new Ge._Z({content:{case:"image",value:new Ge.do({data:o.data,mimeType:o.mimeType})}}))}else if("image"!==t){const t=Nc(e);d.push(await Bu(t,this.projectDir,this.fileOutputThresholdBytes))}}const p=u.structuredContent&&"object"==typeof u.structuredContent&&!Array.isArray(u.structuredContent)?ir.Struct.fromJson(u.structuredContent):void 0,m=new Ge.QW({content:d,isError:u.isError,structuredContent:p});return new Ge.iz({result:{case:"success",value:m}})}catch(e){r.error=e,r.hasError=!0}finally{Lu(r)}}}class qu{mcpLease;constructor(e){this.mcpLease=e}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const o=Fu(r,(0,l.VI)(e.withName("LocalListMcpResourcesExecutor.execute")),!1).ctx;try{const e=new Set,r=await this.mcpLease.getTools(o);for(const t of r)e.add(t.providerIdentifier),e.add(`user-${t.providerIdentifier}`);const n=await this.mcpLease.getClients(o),s=[];if(t.server){const e=n[t.server];if(!e)return new Ge.kP({result:{case:"error",value:new Ge.w2({error:`Server "${t.server}" not found`})}});const r=await this.listResourcesFromClient(o,e,t.server);s.push(...r)}else for(const[t,r]of Object.entries(n)){if(e.size>0&&!e.has(t))continue;const n=await this.listResourcesFromClient(o,r,t);s.push(...n)}return new Ge.kP({result:{case:"success",value:new Ge.T2({resources:s})}})}catch(e){const t=e instanceof Error?e.message:String(e);return new Ge.kP({result:{case:"error",value:new Ge.w2({error:`Failed to list MCP resources: ${t}`})}})}}catch(e){r.error=e,r.hasError=!0}finally{Lu(r)}}async listResourcesFromClient(e,t,r){if("ready"!==(await t.getState(e)).kind)return[];const o=await t.listResources(e);return o&&o.resources?o.resources.map((e=>new Ge.X2({uri:e.uri,name:e.name,description:e.description,mimeType:e.mimeType,server:r,annotations:e.annotations}))):[]}}class Gu{mcpLease;projectDir;permissionsService;pendingDecisionProvider;workspacePaths;constructor(e,t=".",r,o=[],n){this.mcpLease=e,this.projectDir=t,this.permissionsService=r,this.pendingDecisionProvider=n,this.workspacePaths=o.filter((e=>e.length>0))}resolveProjectDir(e){const t=e.get(Oe),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 o=Fu(r,(0,l.VI)(e.withName("LocalReadMcpResourceExecutor.execute")),!1).ctx,n=t.smartModeApproval?.reason;if(void 0!==n){if(void 0===this.pendingDecisionProvider)return new Ge.ZD({result:{case:"error",value:new Ge.Jx({uri:t.uri,error:"Auto-review approval provider is not configured"})}});const e=await this.pendingDecisionProvider.requestApproval({type:ic.Mcp,details:{name:"FetchMcpResource",toolName:"FetchMcpResource",providerIdentifier:t.server,args:{server:ir.Value.fromJson(t.server),uri:ir.Value.fromJson(t.uri),...void 0!==t.downloadPath?{downloadPath:ir.Value.fromJson(t.downloadPath)}:{}},reason:"smartMode",canAllowlist:!1,smartModeApprovalReason:n,smartModeApprovalRequestId:t.smartModeApproval?.requestId},toolCallId:t.toolCallId});if(!e.approved)return new Ge.ZD({result:{case:"rejected",value:new Ge.Dh({reason:"User rejected MCP resource fetch"+(e.reason?` - ${e.reason}`:"")})}})}const s=(await this.mcpLease.getClients(o))[t.server];if(!s)return new Ge.ZD({result:{case:"error",value:new Ge.Jx({uri:t.uri,error:`Server "${t.server}" not found`})}});try{if("ready"!==(await s.getState(o)).kind)return new Ge.ZD({result:{case:"error",value:new Ge.Jx({uri:t.uri,error:`Server "${t.server}" is not ready`})}});const e=await s.readResource(o,{uri:t.uri});if(!e||!e.contents||0===e.contents.length)return new Ge.ZD({result:{case:"notFound",value:new Ge.ov({uri:t.uri})}});const r=e.contents[0];if(t.downloadPath){const e=t.downloadPath.replace(/^\/+/,""),n=a.default.join(this.resolveProjectDir(o),e);if(await(0,fo.mkdir)(a.default.dirname(n),{recursive:!0}),r.text)await(0,fo.writeFile)(n,r.text,"utf8");else if(r.blob){const e=Buffer.from(r.blob,"base64");await(0,fo.writeFile)(n,e)}return new Ge.ZD({result:{case:"success",value:new Ge.KZ({uri:t.uri,name:r.name,description:r.description,mimeType:r.mimeType})}})}if(r.text)return new Ge.ZD({result:{case:"success",value:new Ge.KZ({uri:t.uri,name:r.name,description:r.description,mimeType:r.mimeType,annotations:r.annotations,content:{case:"text",value:r.text}})}});if(r.blob){const e=Buffer.from(r.blob,"base64");return new Ge.ZD({result:{case:"success",value:new Ge.KZ({uri:t.uri,name:r.name,description:r.description,mimeType:r.mimeType,annotations:r.annotations,content:{case:"blob",value:e}})}})}return new Ge.ZD({result:{case:"error",value:new Ge.Jx({uri:t.uri,error:"Failed to read resource"})}})}catch(e){const r=e instanceof Error?e.message:String(e);return Uu.warn(o,"LocalReadMcpResourceExecutor.execute failed",{server:t.server,hasDownloadPath:Boolean(t.downloadPath),errorName:e instanceof Error?e.name:typeof e,errorMessage:r}),new Ge.ZD({result:{case:"error",value:new Ge.Jx({uri:t.uri,error:`Failed to read MCP resource: ${r}`})}})}}catch(e){r.error=e,r.hasError=!0}finally{Lu(r)}}}async function Vu(e,t){const r=Hu(t),o=(0,a.join)(e,"mcps",r,"tools");let n;try{n=await(0,fo.readdir)(o)}catch(e){if("ENOENT"===e?.code)return{toolNames:[],toolsDirExists:!1};throw e}const s=await Promise.all(n.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(e){return}}(await(0,fo.readFile)((0,a.join)(o,e),"utf8"))}catch{return}}))),i=new Set;for(const e of s)e&&i.add(e);return{toolNames:Array.from(i).sort(((e,t)=>e.localeCompare(t))),toolsDirExists:!0}}const Ju=(0,l.h)("local-exec:mcp-disk-freshness-on-access"),Ku="/mcps/",Zu=(0,d.Pu)("mcp.discovery_freshness.check",{description:"MCP discovery surface freshness comparison outcome against canonical live tools",labelNames:["surface","outcome"]}),Yu=(0,d.v5)("mcp.discovery_freshness.missing_tools",{description:"Number of tools present in canonical live state but missing from the observed discovery surface",labelNames:["surface"]}),Xu=(0,d.v5)("mcp.discovery_freshness.extra_tools",{description:"Number of tools present on the observed discovery surface but absent from canonical live state",labelNames:["surface"]}),Qu=(0,d.v5)("mcp.discovery_freshness.symmetric_difference",{description:"Total symmetric difference between canonical live tools and the observed discovery surface",labelNames:["surface"]}),ed=new Map;function td(e){const t=e.replace(/\\/g,"/");return t.endsWith("/mcps")?`${t}/`:t}async function rd({ctx:e,mcpStateAccessor:t,projectDir:r,sanitizedServerFolder:o,readDiskCatalog:n,state:s}){let i=s;if(void 0===i)try{i=await t.getState(e)}catch(t){return void Ju.warn(e,"mcp_disk_state_read_failed",{error_type:t instanceof Error?t.name:typeof t})}const a=i.servers.find((e=>Hu(e.serverIdentifier)===o));if(void 0===a)return;let l;try{l=await n(r,a.serverIdentifier)}catch(t){return void Ju.warn(e,"mcp_disk_catalog_read_failed",{error_type:t instanceof Error?t.name:typeof t})}if(!l.toolsDirExists)return;const c=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:o}){const n=new Set(o),s=new Set(r),i=r.filter((e=>!n.has(e))),a=o.filter((e=>!s.has(e))),l=0===i.length&&0===a.length?"match":"mismatch",c={surface:"disk"};Zu.increment(e,1,{...c,outcome:l}),Yu.histogram(e,i.length,c),Xu.histogram(e,a.length,c),Qu.histogram(e,i.length+a.length,c),"mismatch"===l&&Ju.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:c,observedToolNames:l.toolNames})}function od(e,t,r,o=Vu){if(void 0===r||(void 0===(n=r)||!td(n).includes(Ku)))return;var n;const s=function(e){const t=td(e),r=t.indexOf(Ku);if(-1===r)return;const o=t.slice(0,r),n=t.slice(r+6).split("/").filter(Boolean);return 0!==o.length?0===n.length?{projectDir:o,kind:"mcps_root"}:{projectDir:o,kind:"server",sanitizedServerFolder:n[0]}:void 0}(r);if(void 0===s)return;let i,a;const l="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 c=ed.get(i);void 0!==c&&clearTimeout(c);const u=e,d=setTimeout((()=>{ed.delete(i),(async()=>{if(l){const e=await t.getState(u);for(const r of e.servers){const n=Hu(r.serverIdentifier);await rd({ctx:u,mcpStateAccessor:t,projectDir:s.projectDir,sanitizedServerFolder:n,readDiskCatalog:o,state:e})}}else void 0!==a&&await rd({ctx:u,mcpStateAccessor:t,projectDir:s.projectDir,sanitizedServerFolder:a,readDiskCatalog:o})})().catch((e=>{Ju.warn(u,"mcp_disk_discovery_freshness_schedule_failed",{error_type:e instanceof Error?e.name:typeof e})}))}),2e3);ed.set(i,d)}var nd=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var o,n;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");o=t[Symbol.asyncDispose]}if(void 0===o){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");o=t[Symbol.dispose],r&&(n=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");n&&(o=function(){try{n.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:o,async:r})}else r&&e.stack.push({async:!0});return t},sd=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 o,n=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===n)return n=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var s=o.dispose.call(o.value);if(o.async)return n|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else n|=1}catch(e){r(e)}if(1===n)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var o=new Error(r);return o.name="SuppressedError",o.error=e,o.suppressed=t,o});function id(e){return e.replace(/\r\n/g,"\n").replace(/\r/g,"\n").split("\n")}function ad(e,t,r){const o=function(e,t){let r;for(const o of t)(0,h.ZU)({basePath:o,targetPath:e})&&(void 0===r||o.length>r.length)&&(r=o);return r}((0,a.resolve)(e,t),r);return void 0===o||o===e}const ld=(0,l.h)("local-exec/grep");function cd(e){return e instanceof Error&&e.message.includes("ENOENT")&&e.message.includes("spawn")}function ud(e){try{return(0,s.existsSync)(e)}catch{return"check_failed"}}function dd(e,t,r,o){return{...hd(e),...o,cwd:t,cwdExists:ud(t),errorMessage:r.message,errorCode:r.code,errno:r.errno,syscall:r.syscall,errorPath:r.path}}function pd(e){return new Error(`Path does not exist: ${e}`)}function hd(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,s.existsSync)(e)}catch(e){t.rgPathExists=!1,t.rgPathExistsError=e instanceof Error?e.message:String(e)}try{const r=(0,s.lstatSync)(e);t.rgIsSymlink=r.isSymbolicLink(),r.isSymbolicLink()&&!t.rgPathExists&&(t.rgBrokenSymlink=!0)}catch{t.rgLstatFailed=!0}const r=(0,a.dirname)(e);try{t.parentDirExists=(0,s.existsSync)(r),t.parentDirExists&&(t.parentDirContents=(0,s.readdirSync)(r).slice(0,50))}catch(e){t.parentDirError=e instanceof Error?e.message:String(e)}const o=(0,a.dirname)(r);try{t.grandparentDirExists=(0,s.existsSync)(o),t.grandparentDirExists&&(t.grandparentDirContents=(0,s.readdirSync)(o).slice(0,50))}catch(e){t.grandparentDirError=e instanceof Error?e.message:String(e)}if(t.rgPathExists)try{const r=(0,s.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 n="node_modules.asar.unpacked";if(e.includes(n)){const r=e.split(n)[0];if(r){const e=r.concat("node_modules.asar");try{t.asarExists=(0,s.existsSync)(e)}catch{t.asarExists="check_failed"}const o=r.concat(n);try{if(t.asarUnpackedDirExists=(0,s.existsSync)(o),t.asarUnpackedDirExists){const e=(0,a.join)(o,"@vscode","ripgrep");t.ripgrepPkgDirExists=(0,s.existsSync)(e)}}catch{t.asarUnpackedDirExists="check_failed"}}}return t}class md{ignoreService;grepProvider;workspacePath;static MAIN_TIMEOUT_MS=25e3;static INDEXED_GREP_TIMEOUT_MS=25e3;static INDEXED_GREP_CONTEXT_TIMEOUT_MS=md.INDEXED_GREP_TIMEOUT_MS+100;static HARD_MAX_OUTPUT_LINES=1e4;static CLIENT_LIMIT_LINES=2e3;singleWorkspacePath;mcpStateAccessor;constructor(e,t,r,o){this.ignoreService=e,this.grepProvider=t,this.workspacePath=r;const n=Array.isArray(this.workspacePath)?this.workspacePath[0]:this.workspacePath;this.singleWorkspacePath=Array.isArray(this.workspacePath)&&this.workspacePath.length>1?void 0:n,this.mcpStateAccessor=o?.mcpStateAccessor}computeRelativeTarget(e,t){const r=(0,h.o1)(e,this.singleWorkspacePath);return r===t?".":(0,a.relative)(t,r)}async buildArgs(e,t,r){const o=[],n=await this.ignoreService.listCursorIgnoreFilesByRoot(e);for(const e of n)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("-l");else{if("count"!==r)throw new Error(`Unknown output mode: ${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),t.multiline&&o.push("--multiline","--multiline-dotall");const s=t.sort??"modified";if("none"!==s){const e=!0===t.sortAscending?"--sort":"--sortr";o.push(e,s)}return o.push("--no-config","--color=never"),o.push("--hidden"),o.push("--regexp",t.pattern),o.push("--"),o.push(t.path?this.computeRelativeTarget(t.path,e):"."),o}async filterBlockedFiles(e,t){const r=[];for(const o of e){const e=await Ta((0,h.o1)(o.file,t));null===e||await this.ignoreService.isRepoBlocked(e)||r.push(o)}return r}async runFilesMode(e,t,r,o,n){const s={stack:[],error:void 0,hasError:!1};try{const i=nd(s,(0,l.VI)(e.withName("LocalGrepExecutor.runFilesMode")),!1),a=await this.buildArgs(t,r,"files_with_matches"),c=await this.executeRg(i.ctx,t,a,void 0,o,n);if((""!==c.stderr||2===c.exitCode)&&""===c.stdout.trim())throw new Error(c.stderr||`ripgrep exited with code ${c.exitCode}`);const{files:u,totalFiles:d,clientTruncated:p,ripgrepTruncated:m}=function(e,t,r){const o=e.trim(),n=""!==o?id(o):[],s=n.length,i=n.slice(0,t),a=n.length>t;return{files:i,totalFiles:bc(s),clientTruncated:a,ripgrepTruncated:s>=r}}(c.stdout,md.CLIENT_LIMIT_LINES,md.HARD_MAX_OUTPUT_LINES),f=[];for(const e of u){const r=await Ta((0,h.o1)(e,t));null===r||await this.ignoreService.isRepoBlocked(r)||f.push(e)}const g=u.length-f.length,v=new ro.T7({files:f,totalFiles:bc(d-g),clientTruncated:p,ripgrepTruncated:m});return new ro.vD({result:{case:"files",value:v}})}catch(e){s.error=e,s.hasError=!0}finally{sd(s)}}async runCountMode(e,t,r,o,n){const s={stack:[],error:void 0,hasError:!1};try{const i=nd(s,(0,l.VI)(e.withName("LocalGrepExecutor.runCountMode")),!1),a=await this.buildArgs(t,r,"count"),c=await this.executeRg(i.ctx,t,a,void 0,o,n);if((""!==c.stderr||2===c.exitCode)&&""===c.stdout.trim())throw new Error(c.stderr||`ripgrep exited with code ${c.exitCode}`);const{counts:u,totalFiles:d,totalMatches:p,clientTruncated:h,ripgrepTruncated:m}=function(e,t,r){const o=e.trim(),n=""!==o?id(o):[],s=[];for(const e of n){if(""===e||void 0===e)continue;const t=e.lastIndexOf(":");if(t<=0)continue;const r=e.substring(t+1).trim(),o=parseInt(r,10);if(!Number.isFinite(o))continue;const n=e.substring(0,t);s.push({file:n,count:o})}const i=s.length,a=s.reduce(((e,t)=>e+t.count),0),l=s.slice(0,t),c=s.length>t;return{counts:l,totalFiles:bc(i),totalMatches:bc(a),clientTruncated:c,ripgrepTruncated:i>=r}}(c.stdout,md.CLIENT_LIMIT_LINES,md.HARD_MAX_OUTPUT_LINES),f=await this.filterBlockedFiles(u,t),g=f.reduce(((e,t)=>e+t.count),0),v=u.length-f.length,y=u.reduce(((e,t)=>e+t.count),0)-g,w=new ro.xA({counts:f.map((e=>new ro.sS({file:e.file,count:bc(e.count)}))),totalFiles:bc(d-v),totalMatches:bc(p-y),clientTruncated:h,ripgrepTruncated:m});return new ro.vD({result:{case:"count",value:w}})}catch(e){s.error=e,s.hasError=!0}finally{sd(s)}}async runContentMode(e,t,r,o,n){const s={stack:[],error:void 0,hasError:!1};try{const i=nd(s,(0,l.VI)(e.withName("LocalGrepExecutor.runContentMode")),!1),a=await this.buildArgs(t,r,"content"),c=await this.executeRg(i.ctx,t,a,void 0,o,n);if((""!==c.stderr||2===c.exitCode)&&""===c.stdout.trim())throw new Error(c.stderr||`ripgrep exited with code ${c.exitCode}`);const{byFile:u,totalLines:d,totalMatchedLines:p,clientTruncated:h,ripgrepTruncated:m}=function(e,t,r,o){const n={stack:[],error:void 0,hasError:!1};try{nd(n,(0,l.VI)(o.withName("parseContentOutput")),!1);const s=""===e.trim()?[]:id(e);s.length>0&&""===s[s.length-1]&&s.pop();const i=new Map,a=new Set;let c=0,u=0;for(const e of s){if(void 0===e)continue;if("--"===e)continue;const[r,o]=e.split("\0",2);if(void 0===r||void 0===o)continue;const n=/^(\d+)([:-])(.*)$/.exec(o);if(!n)continue;const s=n[1],l=n[2],d=n[3]??"",p=parseInt(s,10);if(!Number.isFinite(p))continue;const h="-"===l;if(!1===h&&c++,a.has(r)||a.add(r),u>=t)continue;const m=i.get(r)??{file:r,matches:[]};m.matches.push({lineNumber:p,content:d,isContextLine:h}),i.set(r,m),u++}const d=a.size;return{byFile:i,totalLines:bc(s.length),totalMatchedLines:bc(c),totalFiles:bc(d),clientTruncated:u>=t,ripgrepTruncated:s.length>=r}}catch(e){n.error=e,n.hasError=!0}finally{sd(n)}}(c.stdout,md.CLIENT_LIMIT_LINES,md.HARD_MAX_OUTPUT_LINES,i.ctx),f=Array.from(u.values()),g=await this.filterBlockedFiles(f,t),v=f.filter((e=>!g.includes(e))),y=v.reduce(((e,t)=>e+t.matches.length),0),w=v.reduce(((e,t)=>e+t.matches.filter((e=>!e.isContextLine)).length),0),b=new ro.Zp({matches:g.map((e=>new ro.uI({file:e.file,matches:e.matches.map((e=>new ro.dx({lineNumber:e.lineNumber,content:e.content,isContextLine:e.isContextLine})))}))),totalLines:bc(d-y),totalMatchedLines:bc(p-w),clientTruncated:h,ripgrepTruncated:m});return new ro.vD({result:{case:"content",value:b}})}catch(e){s.error=e,s.hasError=!0}finally{sd(s)}}async executeIndexedGrepWithTimeout(e,t,r,o){if(void 0===this.grepProvider.executeIndexedGrep)return;const[n,s]=e.withTimeoutAndCancel(md.INDEXED_GREP_CONTEXT_TIMEOUT_MS);try{return await(0,h.wj)(this.grepProvider.executeIndexedGrep(n,t,r),md.INDEXED_GREP_TIMEOUT_MS,`Indexed grep timed out after ${md.INDEXED_GREP_TIMEOUT_MS/1e3}s`)}catch(t){if(t instanceof h.MU)return void ld.warn(e,"indexed_grep.timeout_fallback",o);throw t}finally{s()}}async executeRg(e,t,r,o,n,s){const i=(0,l.VI)(e.withName("LocalGrepExecutor.executeRg")),a="utf8",c=8388608;return o=o??md.HARD_MAX_OUTPUT_LINES,new Promise(((l,u)=>{let d=!1,p=!1;const h=()=>{p||(p=!0,i.span.end())};let m,f;try{const e=n;m=(0,Do.spawnInSandbox)((0,Do.Ko)(),r,{cwd:t},e),0}catch(r){if(h(),cd(r)){const o=r,n=(0,Do.Ko)();if(ld.error(e,"rg_diagnostics.spawn_throw",void 0,dd(n,t,o,s)),!1===ud(t))return u(pd(t))}return u(r)}const g=[],v=[];let y=0,w=0,b=0,S=!1;f=setTimeout((()=>{if(!d)try{h(),u(new Error(`Timed out after ${md.MAIN_TIMEOUT_MS/1e3}s`)),m.kill()}catch{}}),md.MAIN_TIMEOUT_MS),m.stdout?.on("data",(e=>{if(y+=e.length,void 0!==o&&!0!==S){let t=-1,r=0;for(let n=0;n<e.length;n++)if(10===e[n]&&(r++,b+r>=o)){t=n+1,S=!0;try{m.kill()}catch{}break}b+=r;const n=t>=0?e.subarray(0,t):e;y<=c&&g.push(n)}else!0!==S&&y<=c&&g.push(e)})),m.stderr?.on("data",(e=>{w+=e.length,w<=c&&v.push(e)})),m.on("error",(r=>{if(clearTimeout(f),h(),cd(r)){const o=(0,Do.Ko)(),n=r;if(ld.error(e,"rg_diagnostics.spawn_enoent",void 0,dd(o,t,n,s)),!1===ud(t))return void u(pd(t))}u(r)})),m.on("close",(e=>{d=!0,clearTimeout(f);const t=Buffer.concat(g).toString(a),r=Buffer.concat(v).toString(a);h(),l({stdout:t,stderr:r,exitCode:e??0})}))}))}async execute(e,t,r){const o={stack:[],error:void 0,hasError:!1};try{const s=nd(o,(0,l.VI)(e.withName("LocalGrepExecutor.execute")),!1),i=Array.isArray(this.workspacePath)?this.workspacePath:[this.workspacePath??process.cwd()],c=t.outputMode??"content",u={toolCallId:t.toolCallId,execId:r?.execId,outputMode:c,targetPath:t.path,workspacePaths:i},d=No(t.sandboxPolicy);try{const r=this.grepProvider.getWorktreeGuardInfo?.(i);if((0,h.fl)({targetPath:t.path,workspacePaths:i,mainWorktreePath:r?.mainWorktreePath}))return new ro.Ud({result:{case:"error",value:new ro.ts({error:h.PS})}});if(t.path){const r=await Ta((0,h.o1)(t.path,this.singleWorkspacePath));if(null===r)return new ro.Ud({result:{case:"error",value:new ro.ts({error:(n=t.path,`Path '${n}' could not be verified while resolving symlinks. This can happen when access is denied or the path contains a symlink loop.`)})}});if(await this.ignoreService.isCursorIgnored(r))return new ro.Ud({result:{case:"error",value:new ro.ts({error:`Path '${t.path}' is filtered out by .cursorignore`})}});void 0!==this.mcpStateAccessor&&od(e,this.mcpStateAccessor,r)}let o={};const l=await this.executeIndexedGrepWithTimeout(s.ctx,i,t,u);if(void 0!==l)o=l;else for(const e of i){if(!1===ud(e))return new ro.Ud({result:{case:"error",value:new ro.ts({error:`Path does not exist: ${e}`})}});let r;if("content"===c)r=await this.runContentMode(s.ctx,e,t,d,u);else if("files_with_matches"===c)r=await this.runFilesMode(s.ctx,e,t,d,u);else{if("count"!==c)throw new Error(`Unknown output mode: ${c}`);r=await this.runCountMode(s.ctx,e,t,d,u)}o[e]=r}const p=function(e,t){if(t.length<=1)return e;const r=[...new Set(t.map((e=>(0,a.resolve)(e))))],o={};for(const[t,n]of Object.entries(e)){const e=(0,a.resolve)(t),s=t=>ad(e,t,r),i=n.result;switch(i.case){case"content":{const e=i.value,r=[];let n=0,a=0;for(const t of e.matches)s(t.file)?r.push(t):(n+=t.matches.length,a+=t.matches.filter((e=>!e.isContextLine)).length);o[t]=new ro.vD({result:{case:"content",value:new ro.Zp({...e,matches:r,totalLines:Math.max(0,e.totalLines-n),totalMatchedLines:Math.max(0,e.totalMatchedLines-a)})}});break}case"files":{const e=i.value,r=e.files.filter((e=>s(e)));o[t]=new ro.vD({result:{case:"files",value:new ro.T7({...e,files:r,totalFiles:Math.max(0,e.totalFiles-(e.files.length-r.length))})}});break}case"count":{const e=i.value,r=[];let n=0;for(const t of e.counts)s(t.file)?r.push(t):n+=t.count;o[t]=new ro.vD({result:{case:"count",value:new ro.xA({...e,counts:r,totalFiles:Math.max(0,e.totalFiles-(e.counts.length-r.length)),totalMatches:Math.max(0,e.totalMatches-n)})}});break}default:o[t]=n}}return o}(o,i),m=new ro._0({pattern:t.pattern,path:t.path,outputMode:c,workspaceResults:p});return new ro.Ud({result:{case:"success",value:m}})}catch(e){if(t.path){const e=(0,h.o1)(t.path,this.singleWorkspacePath);try{await(0,fo.stat)(e)}catch(t){return new ro.Ud({result:{case:"error",value:new ro.ts({error:`Path does not exist: ${e}`})}})}}return new ro.Ud({result:{case:"error",value:new ro.ts({error:e instanceof Error?e.message:String(e)})}})}}catch(e){o.error=e,o.hasError=!0}finally{sd(o)}var n}}var fd=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var o,n;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");o=t[Symbol.asyncDispose]}if(void 0===o){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");o=t[Symbol.dispose],r&&(n=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");n&&(o=function(){try{n.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:o,async:r})}else r&&e.stack.push({async:!0});return t},gd=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 o,n=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===n)return n=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var s=o.dispose.call(o.value);if(o.async)return n|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else n|=1}catch(e){r(e)}if(1===n)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var o=new Error(r);return o.name="SuppressedError",o.error=e,o.suppressed=t,o});class vd{permissionsService;ignoreService;workspacePath;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{fd(r,(0,l.VI)(e.withName("LocalLsExecutor.execute")),!1).ctx;const o=(0,h.o1)(t.path,this.workspacePath);try{let r;try{r=await(0,fo.stat)(o)}catch(e){return"ENOENT"===e.code?(0,h.jq)(o)?new oo.fv({result:{case:"error",value:new oo.uj({path:o,error:"No active terminals."})}}):new oo.fv({result:{case:"error",value:new oo.uj({path:o,error:`Path does not exist: ${o}`})}}):new oo.fv({result:{case:"error",value:new oo.uj({path:o,error:e.message})}})}if(!r.isDirectory())return new oo.fv({result:{case:"error",value:new oo.uj({path:o,error:`Path is not a directory: ${o}`})}});const n=No(t.sandboxPolicy),s=t.timeoutMs??5e3,i=e.withTimeout(s),{tree:a,didTimeout:l}=await this.getDirectoryTree(i,o,t.ignore,n);return l?new oo.fv({result:{case:"timeout",value:new oo.ze({directoryTreeRoot:a})}}):new oo.fv({result:{case:"success",value:new oo.PC({directoryTreeRoot:a})}})}catch(e){return new oo.fv({result:{case:"error",value:new oo.uj({path:o,error:e instanceof Error?e.message:"Unknown error occurred"})}})}}catch(e){r.error=e,r.hasError=!0}finally{gd(r)}}async getDirectoryTree(e,t,r,o){const n={stack:[],error:void 0,hasError:!1};try{return fd(n,(0,l.VI)(e.withName("LocalLsExecutor.getDirectoryTree")),!1),await this.buildTreeFromRipgrepStream(e,t,r,o,2500)}catch(e){n.error=e,n.hasError=!0}finally{gd(n)}}async buildTreeFromRipgrepStream(e,t,r,o,n){const s={stack:[],error:void 0,hasError:!1};try{fd(s,(0,l.VI)(e.withName("LocalLsExecutor.buildTreeFromRipgrepStream")),!1);const i=(0,a.resolve)(t),c=new oo.vq({absPath:i,childrenDirs:[],childrenFiles:[],childrenWereProcessed:!0,fullSubtreeExtensionCounts:{}}),u=new Map;u.set(i,c);const d={charactersUsed:i.length,budgetExceeded:!1},[p,h]=await Promise.all([this.ignoreService.listCursorIgnoreFilesByRoot(t),this.ignoreService.getRepoBlockExcludeGlobs(t)]),m=[...r,...h],{lines:f,didTimeout:g}=ba(e,{root:t,excludeGlobs:m,caseSensitive:!0,cursorIgnoreFiles:p,sandboxPolicy:o,source:"ls"});for await(const e of f){if(!e)continue;const r=(0,a.resolve)(t,e),o=await Ta(r);null===o||await this.ignoreService.isRepoBlocked(o)||this.addPathToTree(r,i,u,d,n)}return this.sortTreeChildren(c),{tree:c,didTimeout:await g}}catch(e){s.error=e,s.hasError=!0}finally{gd(s)}}addPathToTree(e,t,r,o,n){const s=(0,a.basename)(e),i=(0,a.dirname)(e);this.ensureDirectoryPath(i,t,r,o.budgetExceeded);const l=r.get(i);if(!l)return;const c=s.length;if(!o.budgetExceeded&&o.charactersUsed+c<=n){const e=new oo.ur({name:s});l.childrenFiles.push(e),o.charactersUsed+=c}else{if(!o.budgetExceeded){o.budgetExceeded=!0;let e=i;for(;e.startsWith(t);){const t=r.get(e);t&&(t.childrenWereProcessed=!1);const o=(0,a.dirname)(e);if(o===e)break;e=o}}const n=(0,a.extname)(e);let s=i;for(;s.startsWith(t);){const e=r.get(s);e&&(e.fullSubtreeExtensionCounts[n]??=0,e.fullSubtreeExtensionCounts[n]=bc(e.fullSubtreeExtensionCounts[n]+1),e.numFiles??=0,e.numFiles=bc(e.numFiles+1));const t=(0,a.dirname)(s);if(t===s)break;s=t}}}ensureDirectoryPath(e,t,r,o){if(r.has(e)||e===t)return;const n=(0,a.dirname)(e);n!==e&&n.startsWith(t)&&this.ensureDirectoryPath(n,t,r,o);const s=new oo.vq({absPath:e,childrenDirs:[],childrenFiles:[],childrenWereProcessed:!o,fullSubtreeExtensionCounts:{}});r.set(e,s);const i=r.get(n);i&&i.childrenDirs.push(s)}sortTreeChildren(e){e.childrenDirs.sort(((e,t)=>(0,a.basename)(e.absPath).localeCompare((0,a.basename)(t.absPath)))),e.childrenFiles.sort(((e,t)=>e.name.localeCompare(t.name)));for(const t of e.childrenDirs)this.sortTreeChildren(t)}}class yd{shellStdinWriter;constructor(e){this.shellStdinWriter=e}async execute(e,t){const r=t.shellId;try{await this.shellStdinWriter(r,t.chars)}catch(e){return new We.nt({result:{case:"error",value:new We.Gv({error:`Failed to write to shell ${r} stdin: ${e instanceof Error?e.message:"Unknown error"}`})}})}return new We.nt({result:{case:"success",value:new We.tR({shellId:r,terminalFileLengthBeforeInputWritten:0})}})}}var wd=r("../../node_modules/.pnpm/lru-cache@11.2.5/node_modules/lru-cache/dist/esm/index.js");function bd(e,t){const r=new wd.q({max:t?.max??10,ttl:t?.ttl});return{async execute(t,o,n){if(!n?.execId)return e.execute(t,o,n);const s=n.execId,i=r.get(s);if(void 0!==i)return i;const a=await e.execute(t,o,n);return r.set(s,a),a}}}var Sd=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 o,n=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===n)return n=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var s=o.dispose.call(o.value);if(o.async)return n|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else n|=1}catch(e){r(e)}if(1===n)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var o=new Error(r);return o.name="SuppressedError",o.error=e,o.suppressed=t,o});class kd{workspacePath;diagnosticsProvider;constructor(e,t){this.workspacePath=e,this.diagnosticsProvider=t}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{let o;!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var o,n;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");o=t[Symbol.asyncDispose]}if(void 0===o){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");o=t[Symbol.dispose],r&&(n=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");n&&(o=function(){try{n.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:o,async:r})}else r&&e.stack.push({async:!0})}(r,(0,l.VI)(e.withName("LocalDiagnosticsExecutor.execute")),!1),[e,o]=e.withTimeoutAndCancel(1e4);try{const r=(0,h.o1)(t.path,this.workspacePath);try{const e=await(0,fo.stat)(r);if(!e.isFile()&&!e.isDirectory())return new Pl.Ek({result:{case:"fileNotFound",value:new Pl.Mu({path:t.path})}})}catch(e){if("ENOENT"===e.code)return new Pl.Ek({result:{case:"fileNotFound",value:new Pl.Mu({path:t.path})}});if("EACCES"===e.code)return new Pl.Ek({result:{case:"permissionDenied",value:new Pl.RP({path:t.path})}});throw e}const o=(0,h.o1)(r,this.workspacePath),n=new h.qA(o);await this.diagnosticsProvider.open(e,n);const s=(await this.diagnosticsProvider.getDiagnostics(e,n)).map((e=>this.convertDiagnostic(e)));return new Pl.Ek({result:{case:"success",value:new Pl.a1({path:t.path,diagnostics:s,totalDiagnostics:s.length})}})}catch(r){return e.canceled?new Pl.Ek({result:{case:"error",value:new Pl.Ho({path:t.path,error:"Request timed out after 10 seconds"})}}):new Pl.Ek({result:{case:"error",value:new Pl.Ho({path:t.path,error:r instanceof Error?r.message:String(r)})}})}finally{o()}}catch(e){r.error=e,r.hasError=!0}finally{Sd(r)}}convertDiagnostic(e){return new Pl.oQ({severity:this.convertSeverity(e.severity),range:e.range?new Rl.Q6({start:new Rl.yX({line:e.range.start.line,column:e.range.start.character}),end:new Rl.yX({line:e.range.end.line,column:e.range.end.character})}):void 0,message:e.message,source:e.source,code:e.code?String(e.code):void 0})}convertSeverity(e){switch(e){case 1:return Pl.h_.ERROR;case 2:return Pl.h_.WARNING;case 3:return Pl.h_.INFORMATION;case 4:return Pl.h_.HINT;default:return Pl.h_.UNSPECIFIED}}}class Ed{permissionsService;constructor(e){this.permissionsService=e}async execute(e,t){const r=await this.permissionsService.isMcpFullyAllowlisted(e,{providerIdentifier:t.providerIdentifier,toolName:t.toolName});return new Ue.M({allowlisted:r})}}var xd=r("../proto/dist/generated/agent/v1/read_exec_pb.js"),_d=r("../../node_modules/.pnpm/iconv-lite@0.7.0/node_modules/iconv-lite/lib/index.js"),Cd=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 o,n=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===n)return n=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var s=o.dispose.call(o.value);if(o.async)return n|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else n|=1}catch(e){r(e)}if(1===n)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var o=new Error(r);return o.name="SuppressedError",o.error=e,o.suppressed=t,o});const Pd=(0,l.h)("LocalReadExecutor"),Rd=async(e,t,r,o)=>{const n=setTimeout((()=>{Pd.warn(e,`[watchdog, LocalReadExecutor] ${t} still not completed after ${r}ms`)}),r);try{return await o()}finally{clearTimeout(n)}};function Td(e){return e>=32&&e<=126||9===e||10===e||13===e}const Id=Buffer.from("\n---\n");const Ad=[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 Od(e){const t=(0,a.extname)(e).toLowerCase(),r=""===t?"Binary files without an extension are not supported by the read executor":`Binary files of type ${t} are not supported by the read executor`;return new xd.sV({result:{case:"invalidFile",value:new xd.cW({path:e,reason:r})}})}function Dd(e,t,r){if(void 0===r.offset&&void 0===r.limit)return{content:e,rangeApplied:!1};if(""===e)return{content:e,rangeApplied:!1};const o=r.offset??1,n=r.limit??(o<0?Math.abs(o):t),s=o<0?Math.max(0,t+o):Math.max(0,o-1);if(s>=t)return{content:e,rangeApplied:!1};const i=Math.min(t,s+n);return{content:e.split("\n").slice(s,i).join("\n"),rangeApplied:!0}}function Md(e,t,r=Gc.pZ){if(0===t.length)return e;const o=r-e.text.length;return o<=0?{text:e.text,truncated:!0}:t.length>o?{text:e.text+t.slice(0,o),truncated:!0}:{text:e.text+t,truncated:e.truncated}}function jd(e,t){const r=Md(e,t);return{text:r.text,truncated:r.truncated}}function Nd(e,t,r){let o=e;return t.forEach(((e,t)=>{const n=function(e,t){const{line:r,hasNewline:o}=e;return t&&o&&r.text.endsWith("\r")?{...r,text:r.text.slice(0,-1)}:r}(e,r);t>0&&(o=Md(o,"\n")),o=Md(o,n.text),n.truncated&&(o={text:o.text,truncated:!0})})),o}function $d(e){const t=e.toLowerCase();return"utf-8"===t?"utf8":"utf-8-bom"===t||"utf-8 bom"===t?"utf8bom":"latin-1"===t?"latin1":t}class Fd extends Error{constructor(){super("Invalid UTF-8 while streaming read"),this.name="InvalidUtf8Error"}}async function Ld(e,t,r,o){const n=void 0!==r.offset||void 0!==r.limit,i=(r.offset??1)<0,a=r.offset??1,l=Math.max(0,a-1),c=void 0===r.limit?void 0:l+r.limit,u=i?Math.abs(a):0,d=[];let p=0,m=!1;const f=[];let g=0,v=!1;const y=[];let w=0,b=!1,S={text:"",truncated:!1},k=0,E=0,x=0,_=!1,C=!1;const P=e=>{let t=e;return!_&&t.length>0&&(_=!0,65279===t.charCodeAt(0)&&(C=!0,t=t.slice(1))),t},R=(e,t)=>{const r=k;if(t&&(e.text.endsWith("\r")?E++:x++),((e,t)=>{if(m&&p>=Gc.pZ)return;const r=d.length>0?1:0;let o=Gc.pZ-p;if(r>0){if(o<=0)return void(m=!0);o--}const n=e.text.length>o?{line:{text:e.text.slice(0,o),truncated:!0},hasNewline:t}:{line:e,hasNewline:t};d.push(n),p+=r+n.line.text.length,(e.truncated||n.line.truncated)&&(m=!0)})(e,t),i){if(u>0){for(y.push({line:e,hasNewline:t}),w+=e.text.length+1;y.length>u;){const e=y.shift();void 0!==e&&(w-=e.line.text.length+1)}for(;y.length>1&&w>Gc.pZ;){const e=y.shift();void 0!==e&&(w-=e.line.text.length+1,b=!0)}}}else n&&r>=l&&(void 0===c||r<c)&&((e,t)=>{if(v&&g>=Gc.pZ)return;const r=f.length>0?1:0;let o=Gc.pZ-g;if(r>0){if(o<=0)return void(v=!0);o--}const n=e.text.length>o?{line:{text:e.text.slice(0,o),truncated:!0},hasNewline:t}:{line:e,hasNewline:t};f.push(n),g+=r+n.line.text.length,e.truncated&&(v=!0),n.line.truncated&&(v=!0)})(e,t);k++};for await(const r of async function*(e,t,r){if("strictUtf8"===r.kind){const r=new ln.TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}),o=(0,s.createReadStream)(t,{highWaterMark:65536,signal:e.signal});try{for await(const e of o){const t=r.decode(e,{stream:!0});t.length>0&&(yield t)}const e=r.decode();e.length>0&&(yield e)}catch(e){if(e instanceof TypeError)throw new Fd;throw e}return}const o=(0,s.createReadStream)(t,{highWaterMark:65536,signal:e.signal}).pipe(_d.decodeStream(r.decoderEncoding));for await(const e of o)yield"string"==typeof e?e:String(e)}(e,t,o)){const e=P(r).split("\n");for(let t=0;t<e.length;t++)S=jd(S,e[t]),t<e.length-1&&(R(S,!0),S={text:"",truncated:!1})}R(S,!1);const T=E+x,I=T>0&&E/T*100>=5;!function(e,t){if(h.Yd.has(e)&&h.Yd.delete(e),h.Yd.set(e,t),h.Yd.size<=100)return;const r=h.Yd.keys().next().value;void 0!==r&&h.Yd.delete(r)}(t,"utf8"===o.cacheEncoding&&C?"utf8bom":o.cacheEncoding);let A={text:"",truncated:m};if(A=Nd(A,d,I),!n)return{content:A.text,totalLines:k,truncated:A.truncated,rangeApplied:!1};if(""===A.text)return{content:"",totalLines:k,truncated:!1,rangeApplied:!1};if(i){const e=r.limit??u;let t={text:"",truncated:b};return t=Nd(t,y.slice(0,e),I),{content:t.text,totalLines:k,truncated:t.truncated,rangeApplied:!0}}if(l>=k)return{content:A.text,totalLines:k,truncated:A.truncated,rangeApplied:!1};let O={text:"",truncated:v};return O=Nd(O,f,I),{content:O.text,totalLines:k,truncated:O.truncated,rangeApplied:!0}}class Ud{permissionsService;workspacePath;mcpStateAccessor;useStreamingRead;constructor(e,t,r){this.permissionsService=e,this.workspacePath=t,this.mcpStateAccessor=r?.mcpStateAccessor,this.useStreamingRead=r?.useStreamingRead}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 o,n;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");o=t[Symbol.asyncDispose]}if(void 0===o){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");o=t[Symbol.dispose],r&&(n=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");n&&(o=function(){try{n.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:o,async:r})}else r&&e.stack.push({async:!0})}(r,(0,l.VI)(e.withName("LocalReadExecutor.execute")),!1);const o=t.path,n=(0,h.o1)(o,this.workspacePath);if(await Rd(e,"permissionsService.shouldBlockRead",3e3,(()=>this.permissionsService.shouldBlockRead(n))))return new xd.sV({result:{case:"permissionDenied",value:new xd.lW({path:n})}});void 0!==this.mcpStateAccessor&&od(e,this.mcpStateAccessor,n);try{const r=await Rd(e,"stat",3e3,(()=>(0,fo.stat)(n)));if(r.isDirectory())return new xd.sV({result:{case:"invalidFile",value:new xd.cW({path:n,reason:"Path is a directory, not a file"})}});if(!r.isFile())return new xd.sV({result:{case:"invalidFile",value:new xd.cW({path:n,reason:"Path is neither a file nor a directory"})}});const o=(0,h.CM)(n),s=(0,h.JD)(n);if(o||s)return await this.readTerminalFile(e,n,r,t,s&&!o);const i=await Rd(e,"getFormatForFile",3e3,(()=>(0,h.zV)(n))),l=i.isImageFile,c=function(e){return".pdf"===(0,a.extname)(e).toLowerCase()}(n),u=(0,h.d8)(n);if(l){const t=await Rd(e,"resizeImageIfNeeded",3e3,(async()=>{const e=await(0,fo.readFile)(n);return(0,h.O5)(e)}));return new xd.sV({result:{case:"success",value:new xd.mE({path:n,output:{case:"data",value:t.data},totalLines:0,fileSize:BigInt(r.size),truncated:!1})}})}if(c){const t=await Rd(e,"readPdfBinary",3e3,(()=>(0,fo.readFile)(n)));return new xd.sV({result:{case:"success",value:new xd.mE({path:n,output:{case:"data",value:t},totalLines:0,fileSize:BigInt(r.size),truncated:!1})}})}if(i.isBinaryFile&&u){const t=await Rd(e,"readBinaryFile",3e3,(()=>(0,fo.readFile)(n)));return new xd.sV({result:{case:"success",value:new xd.mE({path:n,output:{case:"data",value:t},totalLines:0,fileSize:BigInt(r.size),truncated:!1})}})}if(i.isBinaryFile)return Od(n);{const o=this.useStreamingRead;if(o&&await Rd(e,"useStreamingRead",3e3,(()=>o()))){const o=await Rd(e,"readTextStreaming",7e3,(()=>async function(e,t,r,o){const n=function(e,t,r){const o=function(e,t,r){return $d(r??h.Yd.get(e)??t.encoding)}(e,t,r),n=function(e){const t=$d(e);return"utf8bom"===t?"utf8":t}(o);return"utf8"===n?{kind:"strictUtf8",cacheEncoding:"utf8"}:_d.encodingExists(n)?{kind:"iconv",decoderEncoding:n,cacheEncoding:o}:{kind:"strictUtf8",cacheEncoding:"utf8"}}(t,r,o.encodingHint);try{return await Ld(e,t,o,n)}catch(r){if(r instanceof Fd)return await Ld(e,t,o,{kind:"iconv",decoderEncoding:"latin1",cacheEncoding:"latin1"});throw r}}(e,n,i,t)));return new xd.sV({result:{case:"success",value:new xd.mE({path:n,output:{case:"content",value:o.content},totalLines:o.totalLines,fileSize:BigInt(r.size),truncated:o.truncated,rangeApplied:o.rangeApplied})}})}const s=await Rd(e,"readText",3e3,(()=>(0,h.yR)(n,t.encodingHint))),a=await Rd(e,"countLines",3e3,(()=>(0,h.lt)(s))),l=Dd(s,a,t);let c=l.content,u=!1;return c.length>Gc.pZ&&(c=c.substring(0,Gc.pZ),u=!0),new xd.sV({result:{case:"success",value:new xd.mE({path:n,output:{case:"content",value:c},totalLines:a,fileSize:BigInt(r.size),truncated:u,rangeApplied:l.rangeApplied})}})}}catch(e){const t=e;return"ENOENT"===t.code?new xd.sV({result:{case:"fileNotFound",value:new xd.Ko({path:n})}}):"EACCES"===t.code||"EPERM"===t.code?new xd.sV({result:{case:"permissionDenied",value:new xd.lW({path:n})}}):new xd.sV({result:{case:"error",value:new xd.F_({path:n,error:t instanceof Error?t.message:"Unknown error occurred"})}})}}catch(e){r.error=e,r.hasError=!0}finally{Cd(r)}}async readTerminalFile(e,t,r,o,n){const s=await Rd(e,"readTerminalFile",3e3,(()=>(0,fo.readFile)(t)));if(n&&(i=s,Ad.some((e=>function(e,t){return e.length>=t.length&&e.subarray(0,t.length).equals(t)}(i,e)))))return Od(t);var i;let a=function(e){const t=function(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}(e),r=t>0?e.subarray(0,t).toString("utf-8"):"",o=function(e,t){const r=e.length;if(r<2*Id.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 o=Math.max(t,r-4096),n=e.lastIndexOf(Id,r-Id.length-1);return-1===n||n<o?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],o=t[t.length-1];return!(!/^(exit_code: (?:-?\d+|unknown)|error: .+)$/.test(r)||!o.startsWith("ended_at: ")||3===t.length&&!/^elapsed_ms: \d+$/.test(t[1]))}(e.subarray(n+Id.length,r-4).toString("utf-8"))?n:r}(e,t),n=o<e.length?e.subarray(o).toString("utf-8"):"",s=e.subarray(t,o),i=function(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,o=0;for(let n=0;n+1<t;n+=2){const t=e[n],s=e[n+1];0===s&&Td(t)&&r++,0===t&&Td(s)&&o++}return r>=8&&r>=4*Math.max(1,o)?"utf-16le":o>=8&&o>=4*Math.max(1,r)?"utf-16be":"utf-8"}(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+n}(s).replaceAll("\r\n","\n");const l=(0,h.lt)(a),c=Dd(a,l,o);a=c.content;let u=!1;return a.length>Gc.pZ&&(a=a.substring(0,Gc.pZ),u=!0),new xd.sV({result:{case:"success",value:new xd.mE({path:t,output:{case:"content",value:a},totalLines:l,fileSize:BigInt(r.size),truncated:u,rangeApplied:c.rangeApplied})}})}}var Bd=r("../proto/dist/generated/agent/v1/record_screen_exec_pb.js"),Hd=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 o,n=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===n)return n=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var s=o.dispose.call(o.value);if(o.async)return n|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else n|=1}catch(e){r(e)}if(1===n)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var o=new Error(r);return o.name="SuppressedError",o.error=e,o.suppressed=t,o});const zd=(0,ln.promisify)(xs.execFile);class Wd{activeRecording=null;artifactsDir;stagingDir;display;disablePolishedRendering;polishedRenderer;onRecordingStartedCallback=null;onRecordingStoppedCallback=null;recordingStoppedCallbackInvoked=!1;constructor(e){if(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(!e.childProcess.killed&&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(){if(this.activeRecording){await this.cleanupRecording(this.activeRecording),this.invokeStoppedCallbackOnce();try{await fo.rm(this.activeRecording.sessionDir,{force:!0,recursive:!0})}catch{}this.activeRecording=null}}sanitizeToolCallId(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_")}async ensureRecordingDirectoryExists(){await fo.mkdir(this.stagingDir,{recursive:!0}),await fo.mkdir(this.artifactsDir,{recursive:!0})}buildSessionDir(e){const t=this.sanitizeToolCallId(e),r=`session-${(new Date).toISOString().replace(/[:.]/g,"-")}-${t}`;return a.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:Bd.y.UNSPECIFIED}:t.includes("/")||t.includes("\\")?{success:!1,reason:Bd.y.SLASHES_NOT_ALLOWED}:(t=t.replace(/[^a-zA-Z0-9 ._-]/g,"_"),t=t.trim(),0===t.length?{success:!1,reason:Bd.y.UNSPECIFIED}:(t.length>128&&(t=t.slice(0,128).trim()),t.toLowerCase().endsWith(".mp4")||(t=`${t}.mp4`),{success:!0,filename:t}))}async pathExists(e){try{return await fo.access(e),!0}catch{return!1}}async getUniqueArtifactVideoPath(e){const t=a.parse(e),r=t.name||"recording",o=t.ext||".mp4";let n=`${r}${o}`,s=2;for(;await this.pathExists(a.join(this.artifactsDir,n));)n=`${r}-${s}${o}`,s++;return a.join(this.artifactsDir,n)}async resolveArtifactVideoPath(e){const{saveAsFilename:t,stagingSessionDir:r}=e;let o,n;if(t){const e=this.validateAndNormalizeSaveAsFilename(t);e.success?n=e.filename:(o=e.reason,n=`${a.basename(r)}.mp4`)}else n=`${a.basename(r)}.mp4`;return{finalVideoPath:await this.getUniqueArtifactVideoPath(n),requestedFilePathRejectedReason:o}}static PROXY_TARGET_WIDTH=1920;static PROXY_TARGET_FPS=60;static PROXY_CRF=17;static PROXY_PRESET="veryfast";static PROXY_PROFILE_VERSION="render-proxy-h264-all-i-v1";async getVideoDurationMs(e){const{stdout:t}=await zd("ffprobe",["-v","error","-show_entries","format=duration","-of","default=noprint_wrappers=1:nokey=1",e]),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 zd("ffprobe",["-v","error","-select_streams","v:0","-show_entries","stream=width,height","-of","csv=p=0:s=x",e]),[r,o]=t.trim().split("x"),n=Number.parseInt(r,10),s=Number.parseInt(o,10);if(!Number.isFinite(n)||!Number.isFinite(s))throw new Error(`Invalid video dimensions from ffprobe: ${t.trim()}`);if(n<=0||s<=0)throw new Error(`Invalid non-positive video dimensions from ffprobe: ${t.trim()}`);return{width:n,height:s}}async renderPolished(e){const t=a.join(e,"recording"),r=a.join(t,"recording_full.mp4");return await this.polishedRenderer.renderRecordingSession({stagingSessionDir:e,outputVideoPath:r,fps:Wd.PROXY_TARGET_FPS,includeBrandTag:!0}),await fo.access(r,fo.constants.R_OK),r}async getVideoFramerate(e){try{const{stdout:t}=await zd("ffprobe",["-v","error","-select_streams","v:0","-show_entries","stream=r_frame_rate","-of","default=noprint_wrappers=1:nokey=1",e]),r=t.trim();if(r.includes("/")){const[e,t]=r.split("/"),o=Number.parseFloat(e),n=Number.parseFloat(t);if(Number.isFinite(o)&&Number.isFinite(n)&&0!==n){const e=o/n;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 ${Wd.PROXY_TARGET_FPS}fps`)}catch(e){console.warn(`[record-screen] Failed to read video framerate: ${e instanceof Error?e.message:String(e)}, defaulting to ${Wd.PROXY_TARGET_FPS}fps`)}return Wd.PROXY_TARGET_FPS}static DEFAULT_REFRESH_RATE=60;async startFfmpegRecording(e,t){const r=a.join(t,"recording");await fo.mkdir(r,{recursive:!0});const o=a.join(r,"recording_render_proxy_1080p.mp4");let n;try{n=(await $l(this.display)).display.refreshRate}catch(e){console.warn(`[record-screen] Failed to detect refresh rate: ${e instanceof Error?e.message:String(e)}, using default ${Wd.DEFAULT_REFRESH_RATE}Hz`),n=Wd.DEFAULT_REFRESH_RATE}const s=["-video_size",e,"-framerate",String(n),"-draw_mouse","0","-f","x11grab","-i",this.display,"-vf",`scale=${Wd.PROXY_TARGET_WIDTH}:-2:flags=lanczos,fps=${Wd.PROXY_TARGET_FPS}`,"-c:v","libx264","-preset",Wd.PROXY_PRESET,"-crf",String(Wd.PROXY_CRF),"-pix_fmt","yuv420p","-profile:v","high","-x264-params","keyint=1:min-keyint=1:scenecut=0:bframes=0","-movflags","+faststart","-tune","fastdecode","-y",o],i=(0,xs.spawn)("ffmpeg",s,{stdio:["ignore","pipe","pipe"],detached:!0}),l=new Promise(((e,t)=>{let r="",o=!1;i.stderr?.on("data",(t=>{r+=t.toString(),!o&&r.includes("frame=")&&(o=!0,e(Date.now()))}));const n=setTimeout((()=>{o||t(new Error("ffmpeg did not start encoding within 5 seconds"))}),5e3);i.once("exit",((e,r)=>{clearTimeout(n),o||t(new Error(`ffmpeg exited before starting: code=${e} signal=${r}`))})),i.once("error",(e=>{clearTimeout(n),o||t(new Error(`ffmpeg failed to start: ${e.message}`))}))}));return await new Promise(((e,t)=>{const r=setTimeout(e,300);i.once("error",(e=>{clearTimeout(r),t(new Error(`Failed to start ffmpeg: ${e.message}`))})),i.once("exit",((e,o)=>{clearTimeout(r),t(null!==e&&0!==e?new Error(`ffmpeg exited with code ${e}`):null!==o?new Error(`ffmpeg killed by signal ${o}`):new Error("ffmpeg exited unexpectedly during startup"))}))})),{process:i,videoStartedPromise:l}}async runFfmpegCommand(e,t){return await new Promise(((r,o)=>{const n=(0,xs.spawn)("ffmpeg",t,{stdio:["ignore","ignore","pipe"]});let s="";n.stderr?.on("data",(e=>{s.length<2e4&&(s+=e.toString())})),n.once("error",(t=>{o(new Error(`ffmpeg ${e} failed to start: ${t instanceof Error?t.message:String(t)}`))})),n.once("close",(t=>{0===t?r():o(new Error(`ffmpeg ${e} exited with code ${t}: ${s.trim()}`))}))}))}async saveRecordingDataPackage(e){const{sessionDir:t,durationMs:r,recordingStartEpochMs:o,ffmpegStartedEpochMs:n,inputEvents:s,resolution:i,renderProxies:l}=e,c=a.join(t,"recording"),u=a.join(c,"recording-data.json"),d=n-o,p=s.map((e=>({executionTimestampMs:e.executionTimestampMs,commandDurationMs:e.commandDurationMs,positionBefore:e.positionBefore,positionAfter:e.positionAfter,cursorTypeAfter:e.cursorTypeAfter,action:{action:this.serializeAction(e.action)}}))),h={version:3,durationMs:r,recordingStartEpochMs:o,ffmpegStartedEpochMs:n,eventToVideoOffsetMs:d,displayWidth:i.display.width,displayHeight:i.display.height,apiWidth:i.api.width,apiHeight:i.api.height,inputEvents:p,renderProxies:l??null};await fo.writeFile(u,JSON.stringify(h,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(t.killed||!t.pid)return;const r=t.pid;return new Promise(((e,o)=>{const n=setTimeout((()=>{try{try{process.kill(-r,"SIGKILL")}catch{process.kill(r,"SIGKILL")}}catch{}o(new Error("Timeout waiting for ffmpeg to stop"))}),2e4);t.once("exit",(()=>{clearTimeout(n),e()})),t.once("error",(e=>{clearTimeout(n),o(new Error(`Error stopping ffmpeg: ${e.message}`))}));try{try{process.kill(-r,"SIGTERM")}catch{process.kill(r,"SIGTERM")}}catch(e){clearTimeout(n),o(new Error(`Failed to send SIGTERM: ${e instanceof Error?e.message:String(e)}`))}}))}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 o,n;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");o=t[Symbol.asyncDispose]}if(void 0===o){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");o=t[Symbol.dispose],r&&(n=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");n&&(o=function(){try{n.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:o,async:r})}else r&&e.stack.push({async:!0})}(r,(0,l.VI)(e.withName("LocalRecordScreenExecutor.execute")),!1);try{await this.ensureRecordingDirectoryExists()}catch(e){return new Bd.Tj({result:{case:"failure",value:new Bd.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===Bd.$u.UNSPECIFIED)return new Bd.Tj({result:{case:"failure",value:new Bd.yH({error:"Mode must be one of START_RECORDING, SAVE_RECORDING, DISCARD_RECORDING"})}});switch(t.mode){case Bd.$u.START_RECORDING:{this.recordingStoppedCallbackInvoked=!1;let e=!1;if(this.activeRecording){e=!0;try{await this.cleanupRecording(this.activeRecording),await fo.rm(this.activeRecording.sessionDir,{force:!0,recursive:!0}).catch((()=>{}))}catch{}this.activeRecording=null}let r=null,o=null,n=null;try{n=this.buildSessionDir(t.toolCallId||"recording"),await fo.mkdir(n,{recursive:!0});const{resolutionString:s,resolution:i}=await $l(this.display),{process:a,videoStartedPromise:l}=await this.startFfmpegRecording(s,n);r=a;const c=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],o=parseInt(r,10);if(!Number.isFinite(o)||o<0)throw new Error(`Invalid X11 display number in: ${e} (parsed: ${r})`);return o}(this.display);o=new oc({displayNum:c,resolution:i}),await o.start();const u=o.getRecordingStartTime();let d;try{d=await l}catch(e){throw new Error(`ffmpeg failed to start encoding: ${e instanceof Error?e.message:String(e)}`)}this.activeRecording={childProcess:r,sessionDir:n,startTime:u,inputEventLogger:o,resolution:i,ffmpegStartedEpochMs:d,ffmpegDiedEarly:!1,ffmpegDiedTime:null,ffmpegExitCode:null,ffmpegExitSignal:null},this.onRecordingStartedCallback&&this.onRecordingStartedCallback(o),r.once("exit",((e,t)=>{this.activeRecording&&(this.activeRecording.ffmpegDiedEarly=!0,this.activeRecording.ffmpegDiedTime=Date.now(),this.activeRecording.ffmpegExitCode=e,this.activeRecording.ffmpegExitSignal=t)}));const p=!!t.saveAsFilename;return new Bd.Tj({result:{case:"startSuccess",value:new Bd.T4({wasPriorRecordingCancelled:e,wasSaveAsFilenameIgnored:p})}})}catch(e){if(o)try{await o.stop()}catch{}if(r&&!r.killed&&r.pid)try{process.kill(r.pid,"SIGKILL")}catch{}return n&&await fo.rm(n,{force:!0,recursive:!0}).catch((()=>{})),this.activeRecording=null,new Bd.Tj({result:{case:"failure",value:new Bd.yH({error:e instanceof Error?e.message:String(e)})}})}}case Bd.$u.SAVE_RECORDING:{if(!this.activeRecording)return new Bd.Tj({result:{case:"failure",value:new Bd.yH({error:"No active recording to save"})}});const e=this.activeRecording;try{const r=await e.inputEventLogger.stop(),o=e.inputEventLogger.getRecordingStartTime();this.invokeStoppedCallbackOnce(),!e.childProcess.killed&&e.childProcess.pid&&await this.stopFfmpegRecording(e);const n=e.ffmpegStartedEpochMs??o,s=e.sessionDir,{finalVideoPath:i,requestedFilePathRejectedReason:l}=await this.resolveArtifactVideoPath({saveAsFilename:t.saveAsFilename,stagingSessionDir:s}),c=a.join(s,"recording"),u=a.join(c,"recording_render_proxy_1080p.mp4");try{await fo.access(u,fo.constants.R_OK)}catch{return this.activeRecording=null,new Bd.Tj({result:{case:"failure",value:new Bd.yH({error:`Recording proxy not found at ${u}`})}})}const[d,p,h]=await Promise.all([this.getVideoDurationMs(u),this.getVideoDimensions(u),this.getVideoFramerate(u)]),m={profileVersion:Wd.PROXY_PROFILE_VERSION,generatedAtEpochMs:Date.now(),source:{width:p.width,height:p.height,durationMs:d,fps:h},artifacts:[{name:"render_proxy_1080p",path:"recording_render_proxy_1080p.mp4",width:p.width,height:p.height,fps:Wd.PROXY_TARGET_FPS,codec:"h264",profile:Wd.PROXY_PROFILE_VERSION,keyint:1,status:"success",elapsedMs:0}]};if(await this.saveRecordingDataPackage({sessionDir:s,durationMs:d,recordingStartEpochMs:o,ffmpegStartedEpochMs:n,inputEvents:r,resolution:e.resolution,renderProxies:m}),this.disablePolishedRendering)await fo.copyFile(u,i);else{const e=await this.renderPolished(s);await fo.rename(e,i)}return this.activeRecording=null,new Bd.Tj({result:{case:"saveSuccess",value:new Bd.ol({path:i,recordingDurationMs:ir.protoInt64.parse(d.toString()),requestedFilePathRejectedReason:l})}})}catch(t){return await this.cleanupRecording(e),this.invokeStoppedCallbackOnce(),this.activeRecording=null,new Bd.Tj({result:{case:"failure",value:new Bd.yH({error:t instanceof Error?t.message:String(t)})}})}}case Bd.$u.DISCARD_RECORDING:{if(!this.activeRecording)return new Bd.Tj({result:{case:"failure",value:new Bd.yH({error:"No active recording to discard"})}});const e=this.activeRecording;try{return await e.inputEventLogger.stop(),this.invokeStoppedCallbackOnce(),!e.childProcess.killed&&e.childProcess.pid&&await this.stopFfmpegRecording(e),await fo.rm(e.sessionDir,{force:!0,recursive:!0}),this.activeRecording=null,new Bd.Tj({result:{case:"discardSuccess",value:new Bd.N8}})}catch(t){await this.cleanupRecording(e),this.invokeStoppedCallbackOnce();const r=e.sessionDir;return this.activeRecording=null,new Bd.Tj({result:{case:"failure",value:new Bd.yH({error:`Failed to discard recording: ${t instanceof Error?t.message:String(t)}. Session may remain at: ${r}`})}})}}default:{const e=t.mode;return new Bd.Tj({result:{case:"failure",value:new Bd.yH({error:`Unhandled recording mode: ${e}`})}})}}}catch(e){r.error=e,r.hasError=!0}finally{Hd(r)}}}async function qd(e){const t=await(0,fo.readdir)(e,{withFileTypes:!0}).catch((()=>[])),r=[];for(const o of t){const t=a.join(e,o.name),n={name:o.name,path:t,isDirectory:o.isDirectory()};o.isDirectory()&&(n.children=await qd(t)),r.push(n)}return r.sort(((e,t)=>e.isDirectory&&!t.isDirectory?-1:!e.isDirectory&&t.isDirectory?1:e.name.localeCompare(t.name)))}function Gd(e,t="",r=!0){const o=[`${t}${r?"└── ":"├── "}${e.isDirectory?`${e.name}/`:e.name}`],n=e.children;if(n?.length){const e=t+(r?" ":"│ ");n.forEach(((t,r)=>{const s=r===n.length-1;o.push(...Gd(t,e,s))}))}return o}async function Vd(e){if(!await(0,fo.access)(e,fo.constants.R_OK).then((()=>!0),(()=>!1)))return"(No notes directory yet - will be created when you write your first note)";const t=await qd(e);return 0===t.length?"(Notes directory is empty)":t.flatMap(((e,r)=>Gd(e,"",r===t.length-1))).join("\n")}async function Jd(e,t){return Vd(a.join(e,"agent-notes",t))}async function Kd(e){return Vd(a.join(e,"agent-notes","shared"))}var Zd=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var o,n;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");o=t[Symbol.asyncDispose]}if(void 0===o){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");o=t[Symbol.dispose],r&&(n=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");n&&(o=function(){try{n.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:o,async:r})}else r&&e.stack.push({async:!0});return t},Yd=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 o,n=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===n)return n=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var s=o.dispose.call(o.value);if(o.async)return n|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else n|=1}catch(e){r(e)}if(1===n)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var o=new Error(r);return o.name="SuppressedError",o.error=e,o.suppressed=t,o});const Xd=(0,l.h)("local-exec:request-context");async function Qd(e,t,r,o){const n={stack:[],error:void 0,hasError:!1};try{Zd(n,(0,l.VI)(e.withName("LocalRequestContextExecutor.getGitStatusForRepoPath")),!1);try{return(await t.exec(e,r,["--no-optional-locks","status","--short","--branch"],{timeout:o,caller:"getGitStatusForRepoPath"})).stdout}catch{return}}catch(e){n.error=e,n.hasError=!0}finally{Yd(n)}}async function ep(e,t,r,o){try{const n=(await t.exec(e,r,["rev-parse","--abbrev-ref","HEAD"],{timeout:o,caller:"getGitBranchForRepoPath"})).stdout.trim();if("HEAD"===n||0===n.length)return;return n}catch{return}}async function tp(e,t,r={}){const{projectDir:o,notesSessionId:n,metaAgentNotesEnabled:s,smartModeClassifierAutoModeEnabled:a,devForceNextSmartModeClassifierBlockToken:l,isWorkingDirHomeDir:c,getSandboxEnabled:u,getSandboxSupported:d,getNetworkAllowlistInfo:p,userTerminalHint:h,artifactsFolder:m,secretRedactionEnabled:f,getComputerUseSupported:g}=r,v=`${i.default.platform()} ${i.default.release()}`,y=(0,Do.G6)(h),w=(()=>{try{return(new Intl.DateTimeFormat).resolvedOptions().timeZone??void 0}catch{return}})(),b=o,S=o?`${o}/terminals`:void 0,k=o&&!0!==s?`${o}/agent-notes/shared`:void 0,E=o&&n?`${o}/agent-notes/${n}`:void 0,x=o?`${o}/agent-transcripts`:void 0,_=!!u&&u(),C=d?.();let P;if(p)try{P=await p()}catch{P=void 0}return new bt.GE({osVersion:v,workspacePaths:t,shell:y,sandboxEnabled:_,projectFolder:b,terminalsFolder:S,agentSharedNotesFolder:k,agentConversationNotesFolder:E,agentTranscriptsFolder:x,timeZone:w,processWorkingDirectory:process.cwd(),artifactsFolder:m,...void 0!==a&&{smartModeClassifierAutoModeEnabled:a},...void 0!==l&&{devForceNextSmartModeClassifierBlockToken:l},...void 0!==f&&{secretRedactionEnabled:f},...void 0!==C&&{sandboxSupported:C},...void 0!==P?.hasDefaults&&{sandboxNetworkHasDefaults:P.hasDefaults},...P?.explicitEntries&&P.explicitEntries.length>0&&{sandboxNetworkExplicitAllowlist:P.explicitEntries},...void 0!==g&&{computerUseSupported:g()},...void 0!==c&&{isWorkingDirHomeDir:c}})}const rp={type:"object",properties:{},additionalProperties:!1};function op(e){const t=e?.trim();return t||void 0}function np(e,t){const r=function(e){return op(e.serverIdentifier)}(e);if(r)return r;const o=op(e.serverName);return o?t.get(o)??o:void 0}function sp(e){switch(e.kind){case"ready":return"connected";case"requires_authentication":return"needsAuth";case"error":return"error";default:return"loading"}}class ip{mcpLease;constructor(e){this.mcpLease=e}async getState(e){const[t,r]=await Promise.all([this.mcpLease.getTools(e).catch((t=>(Xd.warn(e,"Error fetching MCP tools",{error:t}),[]))),this.mcpLease.getInstructions(e).catch((t=>(Xd.warn(e,"Error fetching MCP instructions",{error:t}),[])))]);return function(e,t,r){const o=new Map;for(const t of e)o.has(t.providerIdentifier)||o.set(t.providerIdentifier,t.clientKey);const n=t.map((e=>np(e,o))).filter((e=>Boolean(e)));return{servers:[...new Set([...e.map((e=>e.clientKey)),...n,...Array.from(r?.entries()??[]).filter((([,e])=>"connected"!==e)).map((([e])=>e))])].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=>np(e,o)===n)),status:r?.get(n)}}))}}(t,r,await async function(e,t){const r=await t.getClients(e).catch((t=>(Xd.warn(e,"Error fetching MCP clients",{error:t}),{}))),o=await Promise.all(Object.entries(r).map((async([t,r])=>[t,sp(await r.getState(e).catch((()=>({kind:"error",message:"Failed to fetch MCP client state"}))))])));return new Map(o)}(e,this.mcpLease))}}class ap{mcpStateAccessor;constructor(e){this.mcpStateAccessor=e}async execute(e,t){return r=await this.mcpStateAccessor.getState(e),new Ge._W({result:{case:"success",value:new Ge.pv({servers:r.servers.map((e=>new Ge.XE({serverName:e.serverName,serverIdentifier:e.serverIdentifier,plugin:e.plugin,marketplace:e.marketplace,tools:e.tools.map((e=>new sr.gd({name:e.name,providerIdentifier:e.providerIdentifier,toolName:e.toolName,description:e.description,inputSchema:e.inputSchema?ir.Value.fromJson(e.inputSchema):void 0}))),instructions:e.instructions,status:e.status})))})}});var r}}class lp{cursorRulesService;cloudRulesService;subagentsService;repositoryProvider;grepProvider;lsExecutor;mcpStateAccessor;gitExecutor;workspacePaths;getSandboxEnabled;getSandboxSupported;getNetworkAllowlistInfo;smartModeClassifierAutoModeEnabled;devForceNextSmartModeClassifierBlockToken;projectDir;isWorkingDirHomeDir;userTerminalHint;getMcpFileSystemOptions;mcpMetaToolEnabled;alwaysExposeVirtualMcpAuthTool;artifactsFolder;secretRedactionEnabled;attributionConfigProvider;isAttributionDisabledByAdmin;getAgentSkills;additionalRules;getComputerUseSupported;cachedWorkspaces=new Map;inFlightWorkspaceWarms=new Map;globalCache;globalCacheTraceId;cacheDebounceTimeout;fileWatcher;constructor(e,t,r,o,n,s,i,a,l,c={}){this.cursorRulesService=e,this.cloudRulesService=t,this.subagentsService=r,this.repositoryProvider=o,this.grepProvider=n,this.lsExecutor=s,this.mcpStateAccessor=i,this.gitExecutor=a,this.workspacePaths=l;const{projectDir:u,smartModeClassifierAutoModeEnabled:d,devForceNextSmartModeClassifierBlockToken:p,isWorkingDirHomeDir:h,createFileWatcher:m,getSandboxEnabled:f,getSandboxSupported:g,getNetworkAllowlistInfo:v,userTerminalHint:y,getMcpFileSystemOptions:w,mcpMetaToolEnabled:b,alwaysExposeVirtualMcpAuthTool:S,artifactsFolder:k,secretRedactionEnabled:E,attributionConfigProvider:x,isAttributionDisabledByAdmin:_,getAgentSkills:C,additionalRules:P,getComputerUseSupported:R}=c;this.projectDir=u,this.isWorkingDirHomeDir=h,this.getSandboxEnabled=f,this.getSandboxSupported=g,this.getNetworkAllowlistInfo=v,this.smartModeClassifierAutoModeEnabled=d,this.devForceNextSmartModeClassifierBlockToken=p,this.userTerminalHint=y,this.getMcpFileSystemOptions=w,this.mcpMetaToolEnabled=b??!1,this.alwaysExposeVirtualMcpAuthTool=S??!1,this.artifactsFolder=k,this.secretRedactionEnabled=E,this.attributionConfigProvider=x,this.isAttributionDisabledByAdmin=_,this.getAgentSkills=C,this.additionalRules=P??[],this.getComputerUseSupported=R,this.warmWorkspaceCaches(),void 0!==m&&(this.rebuildAllCaches(),this.fileWatcher=m(),this.fileWatcher.onDidChange((e=>{this.onWorkspacePathChanged(e)})),this.fileWatcher.onDidCreate((e=>{this.onWorkspacePathChanged(e)})),this.fileWatcher.onDidDelete((e=>{this.onWorkspacePathChanged(e)})))}onWorkspacePathChanged(e){this.rebuildAllCaches()}getWorkspaceCache(e){return this.cachedWorkspaces.get(e)}warmWorkspaceCaches(){const e=(0,l.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 o=this.warmWorkspaceCache(e,t).finally((()=>{this.inFlightWorkspaceWarms.delete(t)}));return this.inFlightWorkspaceWarms.set(t,o),o}async warmWorkspaceCache(e,t){const r={stack:[],error:void 0,hasError:!1};try{const o=Zd(r,(0,l.VI)(e.withName("LocalRequestContextExecutor.warmWorkspaceCache")),!1),n=await async function(e,t,r){try{return(await t.exec(e,r,["rev-parse","--show-toplevel"],{caller:"getGitRepoPathForWorkspacePath"})).stdout.trim()}catch{return null}}(o.ctx,this.gitExecutor,t),s=n?await xa(o.ctx,this.gitExecutor,n):void 0,i={repoPath:n??void 0,remoteUrl:void 0!==s?_a(s):void 0};this.cachedWorkspaces.set(t,i)}catch(e){r.error=e,r.hasError=!0}finally{Yd(r)}}rebuildAllCaches(){this.cacheDebounceTimeout&&clearTimeout(this.cacheDebounceTimeout),this.cacheDebounceTimeout=setTimeout((()=>{this.cacheDebounceTimeout=void 0,this.rebuildGlobalCache()}),5e3)}rebuildGlobalCache(){const e={stack:[],error:void 0,hasError:!1};try{const t=(0,l.q6)(),r=Zd(e,(0,l.VI)(t.withName("LocalRequestContextExecutor.rebuildGlobalCache")),!1);this.globalCacheTraceId=r.span.spanContext().traceId,this.globalCache=this.computeGlobalCache(r.ctx)}catch(t){e.error=t,e.hasError=!0}finally{Yd(e)}}async computeGlobalCache(e){const t={stack:[],error:void 0,hasError:!1};try{const r=Zd(t,(0,l.VI)(e.withName("LocalRequestContextExecutor.computeGlobalCache")),!1),o=AbortSignal.timeout(1e3),n=performance.now(),s={},i=(e,t)=>{const r=performance.now();return t.finally((()=>{s[e]=Math.round(performance.now()-r)}))},[a,c,u,d]=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,o).catch((()=>{}))),i("subagents",this.subagentsService?this.subagentsService.getAllSubagents().catch((()=>[])):Promise.resolve([]))]),p=Math.round(performance.now()-n);return p>1e3&&Xd.warn(r.ctx,"computeGlobalCache: slow",{totalMs:p,...s,ruleCount:a.length}),{rules:[...this.additionalRules,...a],cloudRule:c,codebaseReference:u,customSubagents:d}}catch(e){t.error=e,t.hasError=!0}finally{Yd(t)}}dispose(){this.cacheDebounceTimeout&&(clearTimeout(this.cacheDebounceTimeout),this.cacheDebounceTimeout=void 0),this.fileWatcher&&(this.fileWatcher.dispose(),this.fileWatcher=void 0),this.globalCache=void 0}async collectWorkspaceCaches(e){const t={stack:[],error:void 0,hasError:!1};try{const r=Zd(t,(0,l.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 n=!0;const s=(await Promise.all(this.workspacePaths.map((async e=>{const t=this.getWorkspaceCache(e);if(void 0===t)return n=!1,void this.ensureWorkspaceCacheWarm(r.ctx,e);const s=o?.[e];if(void 0!==s)return new bt.DS({path:t.repoPath,status:s.gitStatus,branchName:s.gitBranchName,remoteUrl:t.remoteUrl});if(void 0===t.repoPath)return;const{status:i,branchName:a}=await async function(e,t,r,o){const n=e=>{let t;const r=new Promise((e=>{t=setTimeout((()=>{e(void 0)}),o)}));return Promise.race([e.catch((()=>{})),r]).finally((()=>{void 0!==t&&clearTimeout(t)}))},[s,i]=await Promise.all([n(Qd(e,t,r,o)),n(ep(e,t,r,o))]);return{status:s,branchName:i}}(r.ctx,this.gitExecutor,t.repoPath,3e3);return new bt.DS({path:t.repoPath,status:i,branchName:a,remoteUrl:t.remoteUrl})})))).filter((e=>void 0!==e));return{gitRepos:s,gitRepoInfoComplete:n}}catch(e){t.error=e,t.hasError=!0}finally{Yd(t)}}async computeCachedRequestContext(e,t){const r={stack:[],error:void 0,hasError:!1};try{const o=Zd(r,(0,l.VI)(e.withName("LocalRequestContextExecutor.computeCachedRequestContext")),!1),n=this.projectDir,s=async()=>{const e={stack:[],error:void 0,hasError:!1};try{const t=Zd(e,(0,l.VI)(o.ctx.withName("LocalRequestContextExecutor.computeCachedRequestContext.getGlobalData")),!1);return this.globalCacheTraceId&&t.span.setAttribute("cacheTraceId",this.globalCacheTraceId),this.globalCache??this.computeGlobalCache(o.ctx)}catch(t){e.error=t,e.hasError=!0}finally{Yd(e)}},i=performance.now(),[a,c,u,{gitRepos:d,gitRepoInfoComplete:p},h,m]=await Promise.all([s(),this.mcpStateAccessor.getState(o.ctx),tp(o.ctx,this.workspacePaths,{projectDir:n,notesSessionId:t.notesSessionId,metaAgentNotesEnabled:!1,smartModeClassifierAutoModeEnabled:this.smartModeClassifierAutoModeEnabled,devForceNextSmartModeClassifierBlockToken:this.devForceNextSmartModeClassifierBlockToken,isWorkingDirHomeDir:this.isWorkingDirHomeDir,getSandboxEnabled:this.getSandboxEnabled,getSandboxSupported:this.getSandboxSupported,getNetworkAllowlistInfo:this.getNetworkAllowlistInfo,userTerminalHint:this.userTerminalHint,artifactsFolder:this.artifactsFolder,secretRedactionEnabled:this.secretRedactionEnabled,getComputerUseSupported:this.getComputerUseSupported}),this.collectWorkspaceCaches(o.ctx),n&&t.notesSessionId?Jd(n,t.notesSessionId):Promise.resolve(void 0),n?Kd(n):Promise.resolve(void 0)]),f=performance.now()-i;f>1e3&&Xd.warn(o.ctx,"computeCachedRequestContext: slow parallel data collection",{durationMs:Math.round(f)});const g=this.getMcpFileSystemOptions?await this.getMcpFileSystemOptions(o.ctx,{timeoutMs:3e3}):void 0,v=this.mcpMetaToolEnabled?function(e,t){const r=e.servers.map((e=>{const r=e.instructions.map((e=>e.instructions)).filter(Boolean).join("\n"),o=e.tools.map((e=>new sr.E$({toolName:e.toolName,description:e.description,inputSchema:void 0!==e.inputSchema?ir.Value.fromJson(e.inputSchema):void 0})));return!0!==t?.alwaysExposeVirtualMcpAuthTool&&"needsAuth"!==e.status||o.some((e=>e.toolName===$u))||o.push(new sr.E$({toolName:$u,description:"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.",inputSchema:ir.Value.fromJson(rp)})),new sr.UC({serverIdentifier:e.serverIdentifier,serverName:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginDbId:e.pluginId,marketplaceId:e.marketplaceId,serverUseInstructions:r||void 0,tools:o})}));return new sr.U_({enabled:!0,mcpDescriptors:r})}(c,{alwaysExposeVirtualMcpAuthTool:this.alwaysExposeVirtualMcpAuthTool}):void 0;let y=!1;if(void 0!==this.isAttributionDisabledByAdmin)try{y=await this.isAttributionDisabledByAdmin()}catch{y=!0}const w=this.attributionConfigProvider?.get(),b=!y&&(w?.attribution?.attributeCommitsToAgent??!0),S=!y&&(w?.attribution?.attributePRsToAgent??!0),k=new bt.bb({rules:a.rules,env:u,gitRepos:d,gitRepoInfoComplete:p,repositoryInfo:a.codebaseReference?[{relativeWorkspacePath:a.codebaseReference.relativeWorkspacePath,repoName:a.codebaseReference.repoName,repoOwner:a.codebaseReference.repoOwner,isTracked:a.codebaseReference.isTracked,isLocal:a.codebaseReference.isLocal,orthogonalTransformSeed:a.codebaseReference.orthogonalTransformSeed,pathEncryptionKey:a.codebaseReference.pathEncryptionKey}]:[],tools:c.servers.flatMap((e=>e.tools)).map((e=>new sr.gd({name:e.name,providerIdentifier:e.providerIdentifier,toolName:e.toolName,description:e.description,inputSchema:e.inputSchema?ir.Value.fromJson(e.inputSchema):void 0}))),conversationNotesListing:h,sharedNotesListing:m,mcpInstructions:c.servers.flatMap((e=>e.instructions)),customSubagents:a.customSubagents,mcpFileSystemOptions:g,mcpMetaToolOptions:v,supportsMcpAuth:!0,commitAttributionMessage:b?"enabled":void 0,prAttributionMessage:S?"enabled":void 0,agentSkills:this.getAgentSkills?await this.getAgentSkills(o.ctx):[]});return null!==a.cloudRule&&void 0!==a.cloudRule&&(k.cloudRule=a.cloudRule),k}catch(e){r.error=e,r.hasError=!0}finally{Yd(r)}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const o=Zd(r,(0,l.VI)(e.withName("LocalRequestContextExecutor.execute")),!1);o.span.setAttribute("enableCaching",void 0!==this.fileWatcher),o.span.setAttribute("hasGlobalCache",!!this.globalCache);try{const e=await this.computeCachedRequestContext(o.ctx,t);return new bt._G({result:{case:"success",value:new bt.yW({requestContext:e})}})}catch(e){return o.span.recordException(e),new bt._G({result:{case:"error",value:new bt.nf({error:e instanceof Error?e.message:String(e)})}})}}catch(e){r.error=e,r.hasError=!0}finally{Yd(r)}}}function cp(e){return 0!==e.timeout?e.timeout:e.isBackground||e.timeoutBehavior===Ve._d.BACKGROUND||void 0!==e.hardTimeout&&e.hardTimeout>0?0:3e4}var up=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 o,n=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===n)return n=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var s=o.dispose.call(o.value);if(o.async)return n|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else n|=1}catch(e){r(e)}if(1===n)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var o=new Error(r);return o.name="SuppressedError",o.error=e,o.suppressed=t,o});class dp{permissionsService;coreExecutor;ignoreService;constructor(e,t,r,o){this.permissionsService=e,this.coreExecutor=t,this.ignoreService=r}buildResultFromExit(e){return 0===(e.exitCode??-1)?new Ve.W4({result:{case:"success",value:new Ve.QR({...e,stdout:e.outputLocation?"":e.stdout,stderr:e.outputLocation?"":e.stderr})},sandboxPolicy:$o(e.sandboxPolicy)}):new Ve.W4({result:{case:"failure",value:new Ve.xC({...e,stdout:e.outputLocation?"":e.stdout,stderr:e.outputLocation?"":e.stderr})},sandboxPolicy:$o(e.sandboxPolicy)})}async executeWithPolicy(e,t,r,o,n){const s=Date.now(),i=new AbortController,a=e.signal?AbortSignal.any([e.signal,i.signal]):i.signal,l=setTimeout((()=>{i.abort()}),o);try{let o,i,c="",u="",d=null,p=!1;const h=n?{perRepo:n}:void 0;for await(const n of this.coreExecutor.execute(e,{command:t.command,workingDirectory:r,signal:a,toolCallId:t.toolCallId,conversationId:t.conversationId,sandboxPolicy:h,fileOutputThresholdBytes:t.fileOutputThresholdBytes,pipeStdin:!1}))"stdout"===n.type?c+=n.data:"stderr"===n.type?u+=n.data:"exit"===n.type&&(d=null!=n.code?0|n.code:null,o=n.outputLocation,p=n.aborted,i=Sc(n.localExecutionTimeMs));clearTimeout(l);const m=Date.now()-s,f={command:t.command,workingDirectory:r,exitCode:p?-1:d??-1,signal:p?"SIGTERM":"",stdout:c,stderr:u,executionTime:m,localExecutionTimeMs:i,sandboxPolicy:n,outputLocation:o};return this.buildResultFromExit(f)}catch(s){return clearTimeout(l),i.signal.aborted&&!e.signal.aborted?new Ve.W4({result:{case:"timeout",value:new Ve.eG({command:t.command,workingDirectory:r,timeoutMs:o})},sandboxPolicy:$o(n)}):e.signal.aborted?new Ve.W4({result:{case:"rejected",value:new Ve.pZ({command:t.command,workingDirectory:r,reason:"Command aborted"})},sandboxPolicy:$o(n)}):new Ve.W4({result:{case:"spawnError",value:new Ve.mJ({command:t.command,workingDirectory:r,error:s instanceof Error?s.message:"Unknown error"})},sandboxPolicy:$o(n)})}}async execute(e,t){const r={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 o,n;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");o=t[Symbol.asyncDispose]}if(void 0===o){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");o=t[Symbol.dispose],r&&(n=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");n&&(o=function(){try{n.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:o,async:r})}else r&&e.stack.push({async:!0});return t}(r,(0,l.VI)(e.withName("LocalShellExecutor.execute")),!1).ctx;(0,l.HF)(o,"LocalShellExecutor.execute");const n=t.command,s=t.requestedSandboxPolicy?No(t.requestedSandboxPolicy):void 0,i=t.workingDirectory||await this.coreExecutor.getCwd(),a=cp(t),c=(0,h.o1)(i);if(!t.parsingResult)return new Ve.W4({result:{case:"spawnError",value:new Ve.mJ({command:n,workingDirectory:c,error:"Parsing result is required"})}});let u;if(t.skipApproval)u=s;else{const e=await this.permissionsService.shouldBlockShellCommand(o,n,{workingDirectory:c,timeout:a,parsingResult:t.parsingResult,toolCallId:t.toolCallId,smartModeApprovalReason:t.smartModeApproval?.reason,smartModeApprovalRequestId:t.smartModeApproval?.requestId,hookApprovalRequirement:dt(t)},s);if("block"===e.kind)return"permissionsConfig"===e.reason.type&&e.reason.isReadonly?new Ve.W4({result:{case:"permissionDenied",value:new Ve.jn({command:n,workingDirectory:c,error:"Command blocked by permissions configuration",isReadonly:!0})}}):new Ve.W4({result:{case:"rejected",value:new Ve.pZ({command:n,workingDirectory:c,reason:Lo(e.reason)})}});u=e.policy}if(_o()&&(u=Ao(n,t.parsingResult)),u&&"insecure_none"!==u.type){const e=await this.ignoreService.getCursorIgnoreMapping();u={...u,ignoreMapping:e}}return this.executeWithPolicy(o,t,i,a,u)}catch(e){r.error=e,r.hasError=!0}finally{up(r)}}}class pp{permissionsService;constructor(e){this.permissionsService=e}async execute(e,t){const r=t.parsingResult??new Ve.HO,o=await this.permissionsService.isShellCommandFullyAllowlisted(e,t.command,{workingDirectory:t.workingDirectory,parsingResult:r,classifierResult:t.classifierResult,toolCallId:t.toolCallId});return new at.e({allowlisted:o})}}class hp{shellStreamExecutor;constructor(e){this.shellStreamExecutor=e}async execute(e,t,r){return""===t.toolCallId.trim()?new Ve.jK({status:Ve.iA.NOT_FOUND}):this.shellStreamExecutor.forceBackgroundByToolCallId(t.toolCallId)}}var mp=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var o,n;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");o=t[Symbol.asyncDispose]}if(void 0===o){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");o=t[Symbol.dispose],r&&(n=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");n&&(o=function(){try{n.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:o,async:r})}else r&&e.stack.push({async:!0});return t},fp=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 o,n=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===n)return n=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var s=o.dispose.call(o.value);if(o.async)return n|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else n|=1}catch(e){r(e)}if(1===n)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var o=new Error(r);return o.name="SuppressedError",o.error=e,o.suppressed=t,o});const gp=(0,l.h)("local-exec:shell-core"),vp="win32"===process.platform;class yp{executor;workspacePath;projectDir;shellOutputBackpressureOptions;constructor(e,t,r,o){this.executor=e,this.workspacePath=t,this.projectDir=r,this.shellOutputBackpressureOptions=o}async*execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{mp(r,(0,l.VI)(e.withName("ShellCoreExecutor.execute")),!1);const o=performance.now(),i=t.workingDirectory||await this.executor.getCwd(),c=(0,h.o1)(i,this.workspacePath);let u,d=0,p=0,m=!1,f=!1,g=!1;t.fileOutputThresholdBytes&&this.projectDir&&(u={buffer:"",lineCount:0,size:0,threshold:Number(t.fileOutputThresholdBytes)});const v=t.signal,y=(0,Do.CG)(t.sandboxPolicy??Do.BM);t.sandboxPolicy&&(yield{type:"start",sandboxed:"workspace_readonly"===y||"workspace_readwrite"===y});const w={CURSOR_AGENT:"1"};t.conversationId&&(w.CURSOR_CONVERSATION_ID=(0,h.sh)(t.conversationId)),this.projectDir&&(w.AGENT_TRANSCRIPTS=a.default.join(this.projectDir,h.O2)),t.askpassConfig&&!vp&&(w.SUDO_ASKPASS=t.askpassConfig.helperPath,w.CURSOR_ASKPASS_SOCKET=t.askpassConfig.socketPath,w.CURSOR_ASKPASS_SECRET=t.askpassConfig.secret);let b=0,S="";for await(const r of this.executor.execute(e,t.command,{signal:v,workingDirectory:c,env:w,sandboxPolicy:t.sandboxPolicy,sandboxWorkspaceRoot:this.workspacePath,pipeStdin:t.pipeStdin??!1,bufferOutputEvents:this.shellOutputBackpressureOptions?.bufferOutputEvents,outputLimiterOptions:this.shellOutputBackpressureOptions?.outputLimiterOptions})){if(b=0,S="",("stdout"===r.type||"stderr"===r.type)&&(S=r.data.toString(),b=r.data.length,u))if(u.size+=b,u.lineCount+=S.split("\n").length-1,u.size>Ec);else if(u.file)u.file.write(S);else if(u.buffer+=S,u.size>u.threshold){const e=a.default.join(this.projectDir,kc);u.path=a.default.join(e,`${(0,n.randomUUID)()}.txt`),await(0,fo.mkdir)(a.default.dirname(u.path),{recursive:!0}),u.file=(0,s.createWriteStream)(u.path),u.file.write(u.buffer),u.buffer=""}switch(r.type){case"stdout":m||(d+b>nc?(m=!0,yield{type:"stdout_trimmed"}):(d+=b,yield{type:"stdout",data:S}));break;case"suppressed_output":g||(g=!0,yield{type:"stdout",data:Do.Ls});break;case"stderr":f||(p+b>nc?(f=!0,yield{type:"stderr_trimmed"}):(p+=b,yield{type:"stderr",data:S}));break;case"exit":{const e=Math.max(0,Math.round(performance.now()-o));let t;u?.file&&(await new Promise((e=>u.file.end(e))),t=new Rl.pV({filePath:u.path,sizeBytes:BigInt(u.size),lineCount:BigInt(u.lineCount)})),yield{type:"exit",code:r.code,aborted:r.aborted,outputLocation:t,localExecutionTimeMs:e};break}case"stdin_ready":yield{type:"stdin_ready",stdin:r.stdin,pid:r.pid};break;case"sandbox_denies":yield{type:"sandbox_denies",events:r.events}}}}catch(e){r.error=e,r.hasError=!0}finally{fp(r)}}async getCwd(){return this.executor.getCwd()}getWorkspacePath(){if(!this.workspacePath)throw new Error("Workspace path is not configured");return this.workspacePath}}class wp{innerExecutor;shellManager;constructor(e,t){this.innerExecutor=e,this.shellManager=t}async*execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{mp(r,(0,l.VI)(e.withName("ManagedShellCoreExecutor.execute")),!1),gp.info(e,"Executing shell command",{command:t.command,workingDirectory:t.workingDirectory,toolCallId:t.toolCallId});let o=null;t.toolCallId&&(o=this.shellManager.getOrCreateShellEmitter(t.toolCallId));for await(const r of this.innerExecutor.execute(e,t)){if(o)switch(r.type){case"stdin_ready":o.emit({type:"stdin_ready",stdin:r.stdin,pid:r.pid});break;case"start":o.emit({type:"start",sandboxed:r.sandboxed});break;case"stdout":o.emit({type:"stdout",data:r.data});break;case"stderr":o.emit({type:"stderr",data:r.data});break;case"exit":o.emit({type:"exit",code:r.code??-1,aborted:r.aborted})}yield r}}catch(e){r.error=e,r.hasError=!0}finally{fp(r)}}async getCwd(){return this.innerExecutor.getCwd()}getWorkspacePath(){return this.innerExecutor.getWorkspacePath()}}class bp{innerExecutor;askpassConfig;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(){return this.innerExecutor.getCwd()}getWorkspacePath(){return this.innerExecutor.getWorkspacePath()}}var Sp=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 o,n=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===n)return n=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var s=o.dispose.call(o.value);if(o.async)return n|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else n|=1}catch(e){r(e)}if(1===n)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var o=new Error(r);return o.name="SuppressedError",o.error=e,o.suppressed=t,o});const kp=(0,l.h)("local-exec:shell-stream");class Ep{iterator;timeoutMs;pendingPromise=null;stopReason;timer;stopResolve;stopPromise;constructor(e,t){this.iterator=e,this.timeoutMs=t,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===Ve.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:Ve.Jg.TIMEOUT})}),this.timeoutMs);try{for(;;){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:Ve.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}}class xp{permissionsService;coreExecutor;ignoreService;backgroundShellManager;activeForegroundExecutions=new Map;constructor(e,t,r,o){this.permissionsService=e,this.coreExecutor=t,this.ignoreService=r,this.backgroundShellManager=o}async forceBackgroundByToolCallId(e){const t=this.activeForegroundExecutions.get(e),r=t?.requestBackground();return r?new Ve.jK({status:Ve.iA.ACCEPTED,shellResult:r}):new Ve.jK({status:Ve.iA.NOT_FOUND})}async*execute(e,t){const r={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 o,n;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");o=t[Symbol.asyncDispose]}if(void 0===o){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");o=t[Symbol.dispose],r&&(n=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");n&&(o=function(){try{n.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:o,async:r})}else r&&e.stack.push({async:!0})}(r,(0,l.VI)(e.withName("LocalShellStreamExecutor.execute")),!1);const o=t.command;let n=t.requestedSandboxPolicy?No(t.requestedSandboxPolicy):void 0;if(n&&"insecure_none"!==n.type){const e=await this.ignoreService.getCursorIgnoreMapping();n={...n,ignoreMapping:e}}const s=t.workingDirectory||await this.coreExecutor.getCwd(),i=cp(t),a=(0,h.o1)(s),c=Date.now();if(!t.parsingResult)throw new Error("Parsing result is required");const u=await this.permissionsService.shouldEnforceShellInvariantBlocks(e,{workingDirectory:a,skipUnsafeWorkingDirectoryBlock:!0},n);if("block"===u.kind)return"permissionsConfig"===u.reason.type?void(yield new Ve.FI({event:{case:"permissionDenied",value:new Ve.jn({command:o,workingDirectory:a,error:"Command blocked by permissions configuration",isReadonly:u.reason.isReadonly??!1})}})):void(yield new Ve.FI({event:{case:"rejected",value:new Ve.pZ({command:o,workingDirectory:a,reason:Lo(u.reason)})}}));if(kp.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:n?.type??"undefined",parserCommandCount:t.parsingResult?.executableCommands.length??0,classifierCommandCount:t.classifierResult?.commands.length??0,commandLength:o.length}),t.skipApproval)kp.info(e,"Shell stream: skipped local approval",{toolCallId:t.toolCallId,requestedPolicyType:n?.type??"undefined"});else{const r=await this.permissionsService.shouldBlockShellCommand(e,o,{workingDirectory:a,timeout:i,parsingResult:t.parsingResult,toolCallId:t.toolCallId,classifierResult:t.classifierResult,smartModeApprovalReason:t.smartModeApproval?.reason,smartModeApprovalRequestId:t.smartModeApproval?.requestId,hookApprovalRequirement:dt(t)},n);if("block"===r.kind){if(kp.info(e,"Shell stream: approval gate blocked command",{toolCallId:t.toolCallId,blockReasonType:r.reason.type,hasSmartModeApproval:void 0!==t.smartModeApproval,skipApproval:t.skipApproval}),"permissionsConfig"===r.reason.type)return void(yield new Ve.FI({event:{case:"permissionDenied",value:new Ve.jn({command:o,workingDirectory:a,error:"Command blocked by permissions configuration",isReadonly:r.reason.isReadonly??!1})}}));const n=Lo(r.reason);return void(yield new Ve.FI({event:{case:"rejected",value:new Ve.pZ({command:o,workingDirectory:a,reason:n})}}))}n=r.policy,kp.info(e,"Shell stream: approval gate allowed command",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,effectivePolicyType:n.type})}if(_o()&&(n=Ao(o,t.parsingResult),"insecure_none"!==n.type)){const e=await this.ignoreService.getCursorIgnoreMapping();n={...n,ignoreMapping:e}}yield new Ve.FI({event:{case:"start",value:new Ve.tD({sandboxPolicy:$o(n)})}});const d=t.timeoutBehavior===Ve._d.BACKGROUND,p=d&&!t.closeStdin&&void 0===t.smartModeApproval,m=new AbortController,f=d?m.signal:e.signal?AbortSignal.any([e.signal,m.signal]):m.signal,g=!0,v=n?{perRepo:n}:void 0,y=this.coreExecutor.execute(e,{command:o,workingDirectory:s,signal:f,toolCallId:t.toolCallId,conversationId:t.conversationId,sandboxPolicy:v,fileOutputThresholdBytes:t.fileOutputThresholdBytes,pipeStdin:p,showElapsedTime:g});let w;d||(w=setTimeout((()=>m.abort()),i));const b=d?new Ep(y[Symbol.asyncIterator](),i):null;let S,k,E,x="",_=!1;const C=t.toolCallId&&b?{requestBackground:()=>{if(b.requestBackground())return E=E??this.backgroundShellManager.generateShellId(),new Ve.W4({result:{case:"success",value:new Ve.QR({shellId:E,pid:k,command:o,workingDirectory:a,msToWait:Sc(Date.now()-c),backgroundReason:Ve.Jg.USER_REQUEST,interleavedOutput:x})}})}}:void 0;t.toolCallId&&C&&this.activeForegroundExecutions.set(t.toolCallId,C);const P=()=>{t.toolCallId&&this.activeForegroundExecutions.get(t.toolCallId)===C&&this.activeForegroundExecutions.delete(t.toolCallId)};let R;b&&e.signal&&e.signal.addEventListener("abort",(()=>{b.backgroundRequested||(m.abort(),b.abort())}),{once:!0});const T=t.hardTimeout;void 0!==T&&T>0&&(R=setTimeout((()=>{void 0!==E?this.backgroundShellManager.abort(E)||m.abort():(_=!0,m.abort(),b?.abort())}),T));const I=b?.iterate()??y;try{for await(const t of I)if("stdout"===t.type)x+=t.data,yield new Ve.FI({event:{case:"stdout",value:new Ve.o0({data:t.data})}});else if("stderr"===t.type)x+=t.data,yield new Ve.FI({event:{case:"stderr",value:new Ve.Db({data:t.data})}});else if("stdin_ready"===t.type)S=t.stdin,k=t.pid;else if("exit"===t.type){let r;t.aborted&&(r=e.signal?.aborted?Ve.Lv.USER_ABORT:b?.timedOut||m.signal.aborted?Ve.Lv.TIMEOUT:Ve.Lv.USER_ABORT),yield new Ve.FI({event:{case:"exit",value:new Ve.vb({code:(t.code??0)>>>0,cwd:await this.coreExecutor.getCwd(),outputLocation:t.outputLocation,aborted:t.aborted,abortReason:r,localExecutionTimeMs:Sc(t.localExecutionTimeMs)})}})}}finally{clearTimeout(w),b?.backgroundRequested||clearTimeout(R),P()}if(b?.backgroundRequested&&!_){const r=E??this.backgroundShellManager.generateShellId();E=r;const n=b.backgroundReasonValue===Ve.Jg.USER_REQUEST?Ve.Jg.USER_REQUEST:Ve.Jg.TIMEOUT,s=n===Ve.Jg.USER_REQUEST?Date.now()-c:i;await this.backgroundShellManager.adopt({ctx:e,shellId:r,command:o,workingDirectory:a,toolCallId:t.toolCallId,sandboxPolicy:v,initialOutput:x,stdin:S,pid:k,abortController:m,eventIterator:b.getHandoffIterator(),startTime:c,showElapsedTime:g,description:t.description,outputNotification:t.outputNotification}),yield new Ve.FI({event:{case:"backgrounded",value:new Ve.Y9({shellId:r,command:o,workingDirectory:a,pid:k,msToWait:g?s:void 0,reason:n})}})}else e.signal?.aborted&&void 0!==b?.stopReasonValue?(clearTimeout(R),yield new Ve.FI({event:{case:"exit",value:new Ve.vb({code:4294967295,cwd:await this.coreExecutor.getCwd(),aborted:!0,abortReason:Ve.Lv.USER_ABORT})}})):clearTimeout(R)}catch(e){r.error=e,r.hasError=!0}finally{Sp(r)}}}class _p{permissionsService;constructor(e){this.permissionsService=e}async execute(e,t){const r=await this.permissionsService.isWebFetchFullyAllowlisted(e,{url:t.url});return new yt.M({allowlisted:r})}}var Cp=r("node:constants");Error,r("../../node_modules/.pnpm/which@4.0.0/node_modules/which/lib/index.js");const Pp="win32"===process.platform;function Rp(e,t){return Pp&&(e=e.toLowerCase(),t=t.toLowerCase()),e===t||(e.charAt(e.length-1)!==a.sep&&(e+=a.sep),t.startsWith(e))}process.platform,r("node:events?d66f"),r("node:url?7874"),Error;const Tp=(0,a.join)((0,i.homedir)(),".cursor","projects"),Ip=(0,a.join)((0,i.homedir)(),".cursor","worktrees");function Ap(e){return Rp(Tp,e)&&e!==Tp}function Op(e){return Rp(Ip,e)&&e!==Ip}function Dp(e,t){const r=function(e){if(!Rp(Tp,e))return;if(e===Tp)return;const t=(0,a.relative)(Tp,e).split(a.sep).filter(Boolean);return t.length>=2?t[1]:void 0}(e);return void 0!==r&&t.includes(r)}var Mp=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 o,n=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===n)return n=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var s=o.dispose.call(o.value);if(o.async)return n|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else n|=1}catch(e){r(e)}if(1===n)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var o=new Error(r);return o.name="SuppressedError",o.error=e,o.suppressed=t,o});const jp=(0,l.h)("LocalWriteExecutor"),Np=async(e,t,r,o)=>{const n=setTimeout((()=>{jp.warn(e,`[watchdog, LocalWriteExecutor] ${t} still not completed after ${r}ms`)}),r);try{return await o()}finally{clearTimeout(n)}};class $p{fileChangeTracker;permissionsService;pendingDecisionProvider;workspacePaths;workspacePath;worktreeMainPath;onWriteForAiTracking;constructor(e,t,r,{workspacePaths:o,workspacePath:n,worktreeMainPath:s,onWriteForAiTracking:i}){this.fileChangeTracker=e,this.permissionsService=t,this.pendingDecisionProvider=r,this.workspacePaths=o,this.workspacePath=n,this.worktreeMainPath=s,this.onWriteForAiTracking=i}async execute(e,t){const r={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 o,n;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");o=t[Symbol.asyncDispose]}if(void 0===o){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");o=t[Symbol.dispose],r&&(n=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");n&&(o=function(){try{n.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:o,async:r})}else r&&e.stack.push({async:!0});return t}(r,(0,l.VI)(e.withName("LocalWriteExecutor.execute")),!1).ctx,n=t.path,s=t.fileText,i=t.fileBytes.length>0?t.fileBytes:void 0,c=(0,h.o1)(n,this.workspacePath),u=Dp(c,["assets","agent-tools","swarm-agents"]);if((0,h.fl)({targetPath:c,workspacePaths:this.workspacePaths,mainWorktreePath:this.worktreeMainPath}))return new Je.v3({result:{case:"error",value:new Je.QM({path:c,error:h.PS})}});let d,p=!1;try{(await(0,fo.stat)(c)).size<=sc?d=await Np(o,"readText before write",3e3,(()=>(0,h.yR)(c,t.encodingHint))):p=!0}catch{}const m=await Np(o,"permissionsService.shouldBlockWrite",3e3,(()=>this.permissionsService.shouldBlockWrite(o,c,s)));if(m){const e=await Np(o,"handleBlockReason",3e3,(()=>Fo(m,{onNeedsApproval:async(e,r)=>{const o="fileEdit"!==r?.type||r.isNewFile,n="fileEdit"===r?.type?r.diffString:s,i="fileEdit"===r?.type?r.blockReason:void 0,a=await this.pendingDecisionProvider.requestApproval({type:ic.Write,details:{path:c,reason:e,isNewFile:o,diffString:n,before:d,after:s,blockReason:i},toolCallId:t.toolCallId});return a.approved?null:new Je.v3({result:{case:"rejected",value:new Je.en({path:c,reason:a.reason||""})}})},onUserRejected:e=>new Je.v3({result:{case:"rejected",value:new Je.en({path:c,reason:e||""})}}),onPermissionDenied:(e,t)=>new Je.v3({result:{case:"permissionDenied",value:new Je.U7({path:c,error:e,isReadonly:t?.isReadonly??!1})}})})));if(null!==e)return e}const f=(0,a.dirname)(c);try{await Np(o,"mkdir",3e3,(()=>(0,fo.mkdir)(f,{recursive:!0})))}catch(e){const t=e.code;return"EACCES"===t||"EPERM"===t?new Je.v3({result:{case:"permissionDenied",value:new Je.U7({path:c,directory:f,operation:"create_directory",error:"Permission denied"})}}):new Je.v3({result:{case:"error",value:new Je.QM({path:c,error:e.message})}})}let g,v;if(void 0!==i)g=i,v=0;else{const e=await Np(o,"getBufferForWrite",3e3,(()=>(0,h.Bh)(c,s,this.workspacePath,t.encodingHint)));g=e.buffer,v=e.lines}try{await Np(o,"writeFile",3e3,(async()=>{let e;await(0,fo.writeFile)(c,g,{flush:!0});try{e=await(0,fo.open)((0,a.dirname)(c),Cp.default.O_RDONLY),await e.sync()}catch{}finally{await(e?.close())}}))}catch(e){const t=e.code;return"EACCES"===t||"EPERM"===t?new Je.v3({result:{case:"permissionDenied",value:new Je.U7({path:c,directory:"",operation:"create_file",error:"Permission denied"})}}):"ENOSPC"===e.code?new Je.v3({result:{case:"noSpace",value:new Je.bM({path:c})}}):new Je.v3({result:{case:"error",value:new Je.QM({path:c,error:e.message})}})}if(this.fileChangeTracker&&void 0===i&&!u&&!p){const e=t.toolCallId?{toolCallId:t.toolCallId}:void 0;await this.fileChangeTracker.trackChange(c,d,s,e)}if(this.onWriteForAiTracking&&void 0===i&&!u){const e=t.toolCallId?{toolCallId:t.toolCallId}:{};try{await this.onWriteForAiTracking({path:c,beforeContent:d,afterContent:s,metadata:e})}catch(e){jp.warn(o,"onWriteForAiTracking failed (write succeeded)",{path:c,error:e instanceof Error?e.message:String(e)})}}const y=g.byteLength;let w;if(t.returnFileContentAfterWrite)try{w=await Np(o,"readText after write",3e3,(()=>(0,h.yR)(c,t.encodingHint)))}catch{}return new Je.v3({result:{case:"success",value:new Je.j6({path:c,linesCreated:v,fileSize:y,...void 0!==w&&{fileContentAfterWrite:w}})}})}catch(e){r.error=e,r.hasError=!0}finally{Mp(r)}}}class Fp extends I{getMcpExecutionPolicyDeps(){return{permissionsService:this.permissionsService,pendingDecisionProvider:this.pendingDecisionStore}}backgroundShellExecutor;computerUseExecutor;pendingDecisionStore;fileChangeTracker;gitExecutor;ignoreService;grepProvider;permissionsService;workspacePaths;worktreeMainPath;diagnosticsProvider;mcpLease;mcpStateAccessor;cursorRulesService;cloudRulesService;subagentsService;repositoryProvider;projectDir;shellManager;_sandboxPolicyResolver;_defaultSandboxPolicy;_defaultSandboxPolicySources;mcpFileOutputThresholdBytes;backgroundShellFactory;backgroundWorkRegistry;mcpElicitationFactory;createFileWatcher;sharedRequestContextExecutor;terminalExecutor;userTerminalHint;enableRecordScreen;recordScreenArtifactsDir;recordScreenDisplay;disableRecordScreenRendering;attributionConfigProvider;isAttributionDisabledByAdmin;getAgentSkills;smartModeClassifierAutoModeEnabled;devForceNextSmartModeClassifierBlockToken;mcpMetaToolEnabled;additionalRules;askpassConfig;recordScreenExecutor;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,a.join)(e,".cursor/sandbox.json");try{const r=(0,s.readFileSync)(t,"utf-8"),o=JSON.parse(r),n=(0,Do.$6)(o);return(0,Do.l7)(n,e)}catch{return}}(t):void 0,o=e._defaultSandboxPolicySources;this._defaultSandboxPolicySources=r||o?{perUser:o?.perUser,perRepo:r??o?.perRepo,teamAdmin:o?.teamAdmin}:void 0,this.mcpFileOutputThresholdBytes=e.mcpFileOutputThresholdBytes,this.backgroundShellFactory=e.backgroundShellFactory,this.backgroundWorkRegistry=e.backgroundWorkRegistry,this.mcpElicitationFactory=e.mcpElicitationFactory,this.createFileWatcher=e.createFileWatcher,this.sharedRequestContextExecutor=e.sharedRequestContextExecutor,this.terminalExecutor=e.terminalExecutor,this.mcpMetaToolEnabled=e.mcpMetaToolEnabled??!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.smartModeClassifierAutoModeEnabled=e.smartModeClassifierAutoModeEnabled,this.devForceNextSmartModeClassifierBlockToken=e.devForceNextSmartModeClassifierBlockToken,this.additionalRules=e.additionalRules??[],this.askpassConfig=e.askpassConfig;const n=this.terminalExecutor??(0,Do.Fn)({env:{CURSOR_AGENT:"1"},userTerminalHint:this.userTerminalHint});let l;if(this.workspacePaths.length>1){const e=this.workspacePaths.map((e=>(0,a.dirname)(e)));l=e.every((t=>t===e[0]))?e[0]:void 0}else l=t;let c=new yp(n,t??(0,i.homedir)(),this.projectDir,e.shellOutputBackpressureOptions);e.shellCoreWrapper&&(c=e.shellCoreWrapper(c)),this.askpassConfig&&(c=new bp(c,this.askpassConfig)),this.shellManager&&(c=new wp(c,this.shellManager));const u=e.overrideShellExecutor??new dp(this.permissionsService,c,this.ignoreService,this.pendingDecisionStore);this.register(Ke,bd(u));const d=e.overrideWriteExecutor??new $p(this.fileChangeTracker,this.permissionsService,this.pendingDecisionStore,{workspacePaths:this.workspacePaths,workspacePath:l,worktreeMainPath:this.worktreeMainPath,onWriteForAiTracking:e.onWriteForAiTracking});this.register(Ye,bd(d)),this.register(H,bd(new lc(this.pendingDecisionStore,this.fileChangeTracker,this.permissionsService,l,e.onDeleteForAiTracking))),this.register(W,bd(new hc));const p=this.mcpStateAccessor??new ip(this.mcpLease);this.register(q,bd(new md(this.ignoreService,this.grepProvider,this.workspacePaths,{mcpStateAccessor:p})));const m=bd(e.overrideReadExecutor??new Ud(this.permissionsService,l,{mcpStateAccessor:p,useStreamingRead:e.useStreamingRead}));this.register(He,m),e.registerRedactedReadExecutor&&this.register(ze,m);const f=new vd(this.permissionsService,this.ignoreService,l);this.register(De,bd(f)),this.register(z,bd(new kd(l,this.diagnosticsProvider))),e.getCanvasDiagnostics&&this.register(U,bd(new Tl(e.getCanvasDiagnostics))),this.register(Ne,bd(new Wu(this.mcpLease,this.permissionsService,this.pendingDecisionStore,this.projectDir,this.mcpFileOutputThresholdBytes,this.mcpElicitationFactory))),this.register($e,bd(new qu(this.mcpLease))),this.register(Fe,bd(new Gu(this.mcpLease,l||this.projectDir,this.permissionsService,this.workspacePaths,this.pendingDecisionStore))),this.register(Le,bd(new ap(p))),this.register(it,bd(this.sharedRequestContextExecutor??new lp(this.cursorRulesService,this.cloudRulesService,this.subagentsService,this.repositoryProvider,this.grepProvider,f,p,this.gitExecutor,this.workspacePaths,{projectDir:this.projectDir,isWorkingDirHomeDir:(0,h.yn)(t,(0,i.homedir)()),createFileWatcher:this.createFileWatcher,getSandboxEnabled:e.getSandboxEnabled,getSandboxSupported:e.getSandboxSupported,getNetworkAllowlistInfo:e.getNetworkAllowlistInfo,smartModeClassifierAutoModeEnabled:this.smartModeClassifierAutoModeEnabled,devForceNextSmartModeClassifierBlockToken:this.devForceNextSmartModeClassifierBlockToken,userTerminalHint:this.userTerminalHint,getMcpFileSystemOptions:e.getMcpFileSystemOptions,mcpMetaToolEnabled:this.mcpMetaToolEnabled,artifactsFolder:e.artifactsFolder,secretRedactionEnabled:e.secretRedactionEnabled,attributionConfigProvider:this.attributionConfigProvider,isAttributionDisabledByAdmin:this.isAttributionDisabledByAdmin,getAgentSkills:this.getAgentSkills,additionalRules:this.additionalRules,getComputerUseSupported:()=>void 0!==this.computerUseExecutor}))),this.backgroundShellExecutor=new en(this.permissionsService,c,this.ignoreService,this.projectDir,this.backgroundShellFactory,this.backgroundWorkRegistry),this.register(N,bd(this.backgroundShellExecutor));const g=new xp(this.permissionsService,c,this.ignoreService,this.backgroundShellExecutor.getManager());this.register(Ze,function(e,t){const r=new wd.q({max:10,ttl:t?.ttl});return{async*execute(t,o,n){if(!n?.execId)return void(yield*e.execute(t,o,n));const s=n.execId,i=r.get(s);if(i)return void(yield*i.fork());const a=e.execute(t,o,n),l=new h.dV(a);r.set(s,l),yield*l.fork()}}}(g)),this.register(lt,new pp(this.permissionsService)),this.register(Be,new Ed(this.permissionsService)),this.register(wt,new _p(this.permissionsService));const v=new hp(g);this.register(ct,bd(v));const y=!1===e.enableWriteBackgroundShellStdin?new yd((async()=>{throw new Error(e.writeBackgroundShellStdinDisabledReason??"write_shell_stdin is disabled for this session")})):new yd(((e,t)=>this.backgroundShellExecutor.writeStdin(e,t)));if(this.register($,bd(y)),e.computerUseExecutor&&(this.computerUseExecutor=e.computerUseExecutor,this.register(B,bd(this.computerUseExecutor))),this.enableRecordScreen){if(!this.recordScreenArtifactsDir||!this.recordScreenDisplay)throw new Error("recordScreenArtifactsDir and recordScreenDisplay are required when enableRecordScreen is true");this.recordScreenExecutor=new Wd({artifactsDir:this.recordScreenArtifactsDir,display:this.recordScreenDisplay,disablePolishedRendering:this.disableRecordScreenRendering,polishedRenderer:e.polishedRecordingRenderer}),this.register(st,bd(this.recordScreenExecutor))}}getRecordScreenExecutor(){return this.recordScreenExecutor}async dispose(){this.backgroundShellExecutor.dispose(),this.recordScreenExecutor&&await this.recordScreenExecutor.dispose()}}function Lp(e){return e.replace(/\\/g,"/")}function Up(e,t){for(const r of t){const t=Lp(r);if(e===t||e.startsWith(`${t}/`))return!0}return!1}var Bp;function Hp(e,t){if(function(e){return Boolean(e.plugin?.trim()||e.pluginId?.trim()||e.marketplaceId?.trim())}(e))return Bp.Plugin;const r=Lp(e.fullPath);return Up(r,t.builtinDirs)?Bp.Builtin:Up(r,t.userDirs)?Bp.UserHome:(Up(r,t.workspaceDirs),Bp.Workspace)}"function"==typeof SuppressedError&&SuppressedError,function(e){e[e.Builtin=0]="Builtin",e[e.UserHome=1]="UserHome",e[e.Workspace=2]="Workspace",e[e.Plugin=3]="Plugin"}(Bp||(Bp={}));var zp=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var o,n=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===n)return n=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var s=o.dispose.call(o.value);if(o.async)return n|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else n|=1}catch(e){r(e)}if(1===n)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var o=new Error(r);return o.name="SuppressedError",o.error=e,o.suppressed=t,o});const Wp=(0,ln.debuglog)("merged-agent-skills");class qp{services;getDisabledManagedSkillPaths;getPromptSortContext;static CHANGE_COALESCE_MS=1500;onChangeCallbacks=new Set;disposeChangeListeners;changeTimer;constructor(e,t=()=>[],r){this.services=e,this.getDisabledManagedSkillPaths=t,this.getPromptSortContext=r}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 o,n;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");o=t[Symbol.asyncDispose]}if(void 0===o){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");o=t[Symbol.dispose],r&&(n=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");n&&(o=function(){try{n.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:o,async:r})}else r&&e.stack.push({async:!0});return t}(t,(0,l.VI)(e.withName("MergedAgentSkillsService.getAllAgentSkills")),!1),o=this.services.map((e=>e.getAllAgentSkills(r.ctx).catch((e=>(Wp("Failed to load agent skills from service: %s",e instanceof Error?e.message:String(e)),[]))))),[n,s]=await Promise.all([Promise.all(o),Promise.resolve(this.getDisabledManagedSkillPaths()).catch((e=>(Wp("getDisabledManagedSkillPaths rejected; fail-open: %s",e instanceof Error?e.message:String(e)),[])))]),i=n.flat(),c=new Set,u=[];for(const e of i){const t=al(e.fullPath);c.has(t)||(c.add(t),u.push(e))}let d=u;s.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,s))));const p=this.getPromptSortContext;return void 0!==p?function(e,t){if(e.length<=1)return e;const r=function(e){const t=[Wa(e.userHomeDirectory).dirPath],r=Ga(e.userHomeDirectory,!0).map((e=>e.dirPath)),o=[];for(const t of e.workspacePaths){o.push((0,a.join)(t,".cursor","rules"));for(const e of qa(t,!0))o.push(e.dirPath)}return{builtinDirs:t,userDirs:r,workspaceDirs:o}}(t),o=e.map(((e,t)=>({skill:e,index:t,tier:Hp(e,r)})));return o.sort(((e,t)=>e.tier-t.tier||e.index-t.index)),o.map((e=>e.skill))}(d,p()):d}catch(e){t.error=e,t.hasError=!0}finally{zp(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()}),qp.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()}}const Gp=(0,l.h)("skill-sync-manifest"),Vp=".sync-manifest.json";async function Jp(e,t){try{const r=await(0,fo.readFile)((0,a.join)(e,Vp),"utf-8"),o=JSON.parse(r);return function(e){if("object"!=typeof e||null===e||Array.isArray(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)}(o)?o:(Gp.warn(t,"Manifest failed schema validation, resetting",{skillDir:e}),{version:1,skills:{}})}catch(r){return r instanceof Error&&"ENOENT"===r.code||Gp.warn(t,"Failed to read sync manifest, resetting",{skillDir:e,error:String(r)}),{version:1,skills:{}}}}function Kp(e,t,r){e.skills[t]={lastSyncedAt:r}}function Zp(e,t){delete e.skills[t]}var Yp=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 o,n=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===n)return n=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var s=o.dispose.call(o.value);if(o.async)return n|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else n|=1}catch(e){r(e)}if(1===n)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var o=new Error(r);return o.name="SuppressedError",o.error=e,o.suppressed=t,o});const Xp=(0,l.h)("builtin-skills-sync");function Qp(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function eh(e){const t=sn(e.content),r=Qp(t.data)?t.data:{};return sn.stringify(`${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 o={...Qp(r.metadata)?r.metadata:{}};return delete o.environments,delete o.disabledEnvironments,delete o["disabled-environments"],Object.keys(o).length>0?r.metadata=o:delete r.metadata,r}(e,r))}async function th(e,t,r){const o=(0,a.join)(t,r.id),n=(0,a.join)(o,"SKILL.md"),s=r.fileContent;try{if(await(0,fo.readFile)(n,"utf-8")===s)return!1}catch(t){t instanceof Error&&"ENOENT"===t.code||Xp.warn(e,"Unexpected error reading skill file",{skillId:r.id,error:String(t)})}return await(0,fo.mkdir)(o,{recursive:!0}),await(0,fo.writeFile)(n,s,"utf-8"),!0}async function rh(e,t){try{return(await(0,fo.readdir)(t,{withFileTypes:!0})).filter((e=>e.isDirectory())).map((e=>e.name))}catch(r){return r instanceof Error&&"ENOENT"===r.code||Xp.warn(e,"Failed to list skills directory, skipping cleanup",{skillDir:t,error:String(r)}),[]}}async function oh(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 o,n;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");o=t[Symbol.asyncDispose]}if(void 0===o){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");o=t[Symbol.dispose],r&&(n=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");n&&(o=function(){try{n.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:o,async:r})}else r&&e.stack.push({async:!0});return t}(r,(0,l.VI)(e.withName("syncBuiltinSkills")),!1).ctx,s=Date.now(),c=(0,a.join)((0,i.homedir)(),".cursor","skills-cursor");await(0,fo.mkdir)(c,{recursive:!0});const[u,d]=await Promise.all([Jp(c,n),rh(n,c)]),p=u.lastInventoryAt;(void 0===p||s-p>=864e5)&&(await async function(e,t,r,o){try{const n=await Promise.all(r.map((async e=>{const r=(0,a.join)(t,e),[n,s]=await Promise.all([nh((0,a.join)(r,"SKILL.md")),"canvas"===e?nh((0,a.join)(r,"sdk")):Promise.resolve(!1)]);return{skill_id:e,has_skill_md:n,has_sdk_dir:s,last_synced_at:o.skills[e]?.lastSyncedAt??null}})));Xp.info(e,"managed_skills.startup_inventory",{skills_on_disk:n,manifest_present:Object.keys(o.skills).length>0})}catch(t){Xp.warn(e,"Failed to emit managed skills startup inventory",{error:String(t)})}}(n,c,d,u),u.lastInventoryAt=s);const h=new Map;for(const e of t.managedSkills??[])(o=e.id)&&o===o.trim()&&!(o.includes("..")||o.includes("/")||o.includes("\\"))?h.set(e.id,e):Xp.warn(n,"Skipping managed skill with unsafe id",{skillId:e.id});const m=new Set([...h.keys(),...d]);let f=0,g=0;const v=[];for(const e of m)try{const t=h.get(e),r=u.skills[e],o=r?s-r.lastSyncedAt:0,i=void 0!==r&&o>2592e5;if(t&&!1!==t.enabled)await th(n,c,{id:e,fileContent:eh(t)})?f++:g++,Kp(u,e,s);else if(!1===t?.enabled||i){const o=!1===t?.enabled?"enabled_false":"grace_expired";await(0,fo.rm)((0,a.join)(c,e),{recursive:!0,force:!0}),Zp(u,e),v.push(e),Xp.info(n,"managed_skills.removed",{skill_id:e,reason:o,server_enabled:t?.enabled??null,had_manifest_entry:void 0!==r,last_synced_ms_ago:r?s-r.lastSyncedAt:null})}else r||Kp(u,e,s)}catch(t){Xp.warn(n,"Failed to apply skill, will retry next sync",{skillId:e,error:String(t)})}try{await async function(e,t){const r=(0,a.join)(e,".sync-manifest.json.tmp"),o=(0,a.join)(e,Vp);await(0,fo.writeFile)(r,JSON.stringify(t,null,2),"utf-8"),await(0,fo.rename)(r,o)}(c,u)}catch(e){Xp.warn(n,"Failed to persist sync manifest",{skillDir:c,error:String(e)})}return{synced:f,upToDate:g,removed:v}}catch(e){r.error=e,r.hasError=!0}finally{Yp(r)}var o}async function nh(e){try{return await(0,fo.stat)(e),!0}catch(e){const t=e.code;if("ENOENT"===t||"ENOTDIR"===t)return!1;throw e}}const sh=(0,l.h)("managed-skills-sync");function ih(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 ah{pluginsService;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,o="marketplaceDbId"in r.identifier.sourceInfo?r.identifier.sourceInfo.marketplaceDbId:void 0,n=r.identifier.sourceInfo.name,s="pluginDbId"in r.identifier.sourceInfo?r.identifier.sourceInfo.pluginDbId:void 0,i=r.mcpConfig;i&&t.push(...ps(i,e,o,n,s,r.identifier.source))}return function(e){const t=[],r=new Set;for(const o of e){if("streamableHttp"!==o.type||!o.url){t.push(o);continue}const e=ih(o.url);r.has(e)||(r.add(e),t.push(o))}return t}(t)}}var lh=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 o,n=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===n)return n=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var s=o.dispose.call(o.value);if(o.async)return n|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else n|=1}catch(e){r(e)}if(1===n)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var o=new Error(r);return o.name="SuppressedError",o.error=e,o.suppressed=t,o});class ch{workspacePaths;userHomeDirectory;getSettings;marketplaceOptions;localPluginVariablesLookup;plugins=[];_loadFailures=[];loadPromise;loadedOnce=!1;pluginLogger;_extensionPlugins=new Map;_extensionPluginOriginalPaths=new Map;constructor(e,t,r,o,n,s){this.workspacePaths=e,this.userHomeDirectory=t,this.getSettings=r,this.marketplaceOptions=o,this.localPluginVariablesLookup=s,this.pluginLogger=n??un,this.reload()}async getAllEnabledPlugins(){return await this.ensureLoaded(),[...this.plugins]}getLoadFailures(){return[...this._loadFailures]}async reload(){return this.loadPromise||(this.loadPromise=this.load().then((async e=>{let t=[];try{t=await this._reloadExtensionPlugins()}catch(e){this.pluginLogger.log("error",`Failed to reload extension plugins after base load success: ${e}`)}const r=new Set(e.plugins.map((e=>e.installPath))),o=t.filter((e=>!r.has(e.installPath)));return this.plugins=[...e.plugins,...o],this._loadFailures=e.failures,this.loadedOnce=!0,this.pluginLogger.log("info",`Plugins reload completed: ${this.plugins.length} plugins loaded (${o.length} extension), ${e.failures.length} failures`),this.plugins})).catch((async e=>{this.pluginLogger.log("error",`Failed to load plugins: ${e}`);try{const e=await this._reloadExtensionPlugins();this.plugins=[...e]}catch(e){this.pluginLogger.log("error",`Failed to reload extension plugins after base load failure: ${e}`),this.plugins=[]}return this._loadFailures=[],this.loadedOnce=!0,this.plugins})).finally((()=>{this.loadPromise=void 0}))),this.loadPromise}async registerExtensionPlugin({path:e,extensionId:t}){const r=(0,a.resolve)(e),o=await(0,fo.realpath)(r);if(!(await(0,fo.stat)(o)).isDirectory())throw new Error(`Extension plugin path is not a directory: ${o}`);const n=i.homedir();if(o.split(a.sep).filter(Boolean).length<3||o===n||"/"===o)throw new Error(`Extension plugin path is too broad (must be a specific subdirectory, not root or home): ${o}`);for(const[e,r]of this._extensionPlugins)if(e!==t&&r.has(o))throw new Error(`Plugin path ${o} is already registered by extension ${e}`);let s=this._extensionPlugins.get(t);if(s||(s=new Map,this._extensionPlugins.set(t,s)),s.has(o))return void this._rememberExtensionPluginOriginalPath({extensionId:t,originalPath:r,canonicalPath:o});const l=(0,a.basename)(o),c=await this._loadExtensionPluginContent(o,t);s.set(o,c),this._rememberExtensionPluginOriginalPath({extensionId:t,originalPath:r,canonicalPath:o}),this.pluginLogger.log("info",`Registered extension plugin: ${l} from ${o} (extension: ${t})`)}async unregisterExtensionPlugin({path:e,extensionId:t}){const r=this._extensionPlugins.get(t);if(!r)return!1;const o=(0,a.resolve)(e);let n;try{n=await(0,fo.realpath)(o)}catch{const e=this._extensionPluginOriginalPaths.get(t);n=e?.get(o)??o}const s=r.delete(n);return 0===r.size?(this._extensionPlugins.delete(t),this._extensionPluginOriginalPaths.delete(t)):s&&this._forgetExtensionPluginOriginalPath(t,n),s&&this.pluginLogger.log("info",`Unregistered extension plugin: ${n} (extension: ${t})`),s}async _loadExtensionPluginContent(e,t){const r=(0,a.basename)(e),o={name:r,localPath:e,extensionId:t},n=await na(e,r,{name:r,version:"0.0.0"});return n.displayName&&(o.name=n.displayName),{identifier:{source:"extension",sourceInfo:o},installPath:e,...void 0!==n.displayName&&{displayName:n.displayName},...void 0!==n.description&&{description:n.description},...void 0!==n.authorName&&{authorName:n.authorName},skills:n.skills,rules:n.rules,agents:n.agents,commands:n.commands,mcpConfig:n.mcpConfig??void 0,hooks:n.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,o]of r)o===t&&r.delete(e);0===r.size&&this._extensionPluginOriginalPaths.delete(e)}}_getExtensionPluginPaths(){const e=[];for(const[t,r]of this._extensionPlugins)for(const o of r.keys())e.push({canonicalPath:o,extensionId:t});return e}async _reloadExtensionPlugins(){const e=this._getExtensionPluginPaths(),t=[];for(const{canonicalPath:r,extensionId:o}of e)try{const e=await this._loadExtensionPluginContent(r,o),n=this._extensionPlugins.get(o);n&&n.set(r,e),t.push(e)}catch(e){this.pluginLogger.log("error",`Failed to reload extension plugin ${r}: ${e}`);const n=this._extensionPlugins.get(o),s=n?.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 o=(0,l.q6)().withName("LocalPluginsService.load"),n=(function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var o,n;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");o=t[Symbol.asyncDispose]}if(void 0===o){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");o=t[Symbol.dispose],r&&(n=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");n&&(o=function(){try{n.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:o,async:r})}else r&&e.stack.push({async:!0})}(e,(0,l.VI)(o),!1),performance.now()),s=e=>{this.pluginLogger.increment(`local_plugins_service.load.${e}`,1),this.pluginLogger.distribution("local_plugins_service.load.duration",performance.now()-n,{outcome:e})},i=this.getSettings(),a=(t=this.marketplaceOptions,r=this.userHomeDirectory,void 0===t?[]:(Array.isArray(t)?t:[t]).map((e=>({...e,userHomeDir:r})))),c=i.importThirdPartyPlugins,u=i.loadUserLocalPlugins??!0,d=i.loadUserSettingsPlugins??!1,p=i.loadCursorFirstParty??a.length>0;if(!(c||p||u||d))return this.pluginLogger.log("info","Skipping plugin loading, cursor 1p, 3p, user-local, and user-settings plugins are disabled"),{plugins:[],failures:[]};this.pluginLogger.increment("local_plugins_service.load.start",1);const h=this.workspacePaths[0]??void 0,m=(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 la(h,{userHomeDir:this.userHomeDirectory,loadClaude:c,loadUserLocal:u,loadUserSettings:d,loadCursorFirstParty:p&&a.length>0,marketplaceSources:a.length>0?a.map((e=>({...e,onCursorError:m}))):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 s("success"),this.pluginLogger.log("info",`Plugins loaded in ${(performance.now()-n).toFixed(1)}ms`),e}catch(e){return s("error"),this.pluginLogger.log("error",`Failed to load all plugins: ${e}`),{plugins:[],failures:[]}}}catch(t){e.error=t,e.hasError=!0}finally{lh(e)}var t,r}}var uh=r("../../node_modules/.pnpm/diff@8.0.3/node_modules/diff/libesm/patch/create.js");function dh(e,t,r){return{resolvedPath:e,originalPath:t,resolution:r}}function ph(e){switch(e.code){case"ENOENT":return{status:"newFile"};case"EACCES":case"EPERM":return{status:"permissionDenied",errno:e.code};case"ELOOP":return{status:"symlinkLoop",errno:e.code};default:return{status:"unknownError",errno:e.code??"UNKNOWN",message:e.message}}}async function hh(e,t){const r=(0,h.o1)(e,t);try{return dh(await(0,fo.realpath)(r),r,{status:"resolved"})}catch(e){const t=e;if("ENOENT"!==t.code)return dh(r,r,ph(t));try{if((await(0,fo.lstat)(r)).isSymbolicLink()){let e=null;try{e=await(0,fo.readlink)(r)}catch{}return dh(r,r,{status:"danglingSymlink",symlinkTarget:e})}return dh(r,r,{status:"unknownError",errno:"ENOENT",message:"realpath returned ENOENT but lstat found a non-symlink entry"})}catch(e){const t=e;return"ENOENT"===t.code?async function(e){let t=(0,a.dirname)(e);const r=[(0,a.basename)(e)];for(;(0,a.dirname)(t)!==t;){try{const o=await(0,fo.realpath)(t);return dh((0,a.join)(o,...r),e,{status:"newFile"})}catch(t){const r=t;if("ENOENT"!==r.code)return dh(e,e,ph(r))}r.unshift((0,a.basename)(t)),t=(0,a.dirname)(t)}return dh(e,e,{status:"newFile"})}(r):dh(r,r,ph(t))}}}function mh(e){return"resolved"===e.status||"newFile"===e.status}function fh(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}\`.`}}var gh=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var o,n;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");o=t[Symbol.asyncDispose]}if(void 0===o){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");o=t[Symbol.dispose],r&&(n=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");n&&(o=function(){try{n.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:o,async:r})}else r&&e.stack.push({async:!0});return t},vh=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 o,n=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===n)return n=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var s=o.dispose.call(o.value);if(o.async)return n|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else n|=1}catch(e){r(e)}if(1===n)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var o=new Error(r);return o.name="SuppressedError",o.error=e,o.suppressed=t,o});const yh=(0,l.h)("permissions-service"),wh=(0,d.Pu)("local_exec.permissions.mcp_allowlist_check.result",{description:"Result of MCP allowlist checks at user and team levels per tool call.",labelNames:["allowlist_scope","outcome"]});function bh(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 Sh(e){return[...new Set(e)]}function kh(){return{fdTargets:new Map([[0,"original-stdin"],[1,"original-stdout"],[2,"original-stderr"]])}}function Eh({basePath:e,targetPath:t,pathModule:r}){const o=r.resolve(e),n=r.resolve(t),s=r.relative(o,n);return""===s||".."!==s&&!s.startsWith(`..${r.sep}`)&&!r.isAbsolute(s)}function xh(e){return">"===e||">>"===e||">|"===e||"&>"===e||"&>>"===e}function _h(e){if(void 0===e||e.trim()!==e)return;const t=Number(e);return Number.isInteger(t)&&t>=0?t:void 0}function Ch(e){return"<<"===e.operator&&"heredoc_redirect"===e.targetNodeType&&1===e.destinationFds.length&&0===Number(e.destinationFds[0])&&void 0!==e.targetText&&(0,Do.Nl)(e.targetText)}async function Ph({targetText:e,workingDirectory:t,rootDirectories:r,resolvePathForPermissions:o,pathModule:n,tempPathOptions:s}){if(""!==n.parse(e).root&&!n.isAbsolute(e))return;const i=await o(e,t);if(mh(i.resolution)){for(const e of r){const t=await o(e);if(mh(t.resolution)&&Eh({basePath:t.resolvedPath,targetPath:i.resolvedPath,pathModule:n}))return"workspace-file"}return Mh(i.resolvedPath,s)?"tmp-file":void 0}}function Rh(e){return Sh(e.map((e=>e.trim())).filter(Boolean))}function Th(e){const t=e.name.trim();if(!t)return[];const r=e.arguments.map((e=>e.trim())).filter(Boolean),o=r.length>0?`${t} ${r.join(" ")}`:t,n=e.subcommandTokens.map((e=>e.trim())).filter(Boolean);if(0===n.length)return[o];const s=`${t} ${n.join(" ")}`;return s===o?[o]:[o,s]}function Ih(e,t){const r=t.trim();return!!r&&e.some((e=>e===r||e.startsWith(`${r} `)))}function Ah(e){const t=e.name.trim(),r=e.arguments.map((e=>e.trim())).filter(Boolean).map((e=>new Ve.r6({type:"word",value:e})));return new Ve.Pv({name:t,args:r,fullText:[t,...r.map((e=>e.value))].join(" ").trim()})}function Oh(e,t={}){return{type:e,...t}}function Dh(e){const t=e.match(/^\s*(Shell|Bash)\s*\((.*)\)\s*$/);if(!t)return null;const r=t[1],o=t[2]?.trim()??"",n=o.indexOf(":");return-1!==n?{shellType:r,fullPattern:o,commandPattern:o.slice(0,n).trim(),argsPattern:o.slice(n+1).trim()}:{shellType:r,fullPattern:o,commandPattern:o,argsPattern:null}}function Mh(e,{platform:t,env:r,pathModule:o}){if("win32"===t){const t=r.TEMP??r.TMP;if(t){const r=o.normalize(t).toLowerCase(),n=o.normalize(e).toLowerCase(),s=r.endsWith(o.sep)?r:r+o.sep;return n===r||n.startsWith(s)}return!1}return"darwin"===t?["/tmp/","/private/tmp/","/var/folders/","/private/var/folders/"].some((t=>e.startsWith(t))):["/tmp/","/private/tmp/","/var/folders/","/private/var/folders/","/var/tmp/"].some((t=>e.startsWith(t)))}function jh(e,t){if("insecure_none"===t.type)return!0;if("insecure_none"===e.type)return!1;const r=(0,Do.$b)(e.networkPolicy),o=(0,Do.$b)(t.networkPolicy);if(r&&!o)return!1;const n=(0,Do._B)(e.networkPolicy),s=(0,Do._B)(t.networkPolicy);return!(n&&o&&!s)&&("workspace_readonly"===e.type&&"workspace_readwrite"===t.type||e.type===t.type)}class Nh{command;requestedPolicy;state;matchForms;constructor(e,t,r,o){this.command=e,this.requestedPolicy=t;const n=void 0!==r&&jh(t,r);this.state=n?"preapproved":"approvable";const s=[e.fullText.trim()].filter(Boolean);this.matchForms=o&&o.length>0?[...o]:s}approveWithPolicy(e){"approvable"!==this.state&&"preapproved"!==this.state||!jh(this.requestedPolicy,e)||(this.state="allowlisted")}deny(){this.state="denied"}isRunnable(){return"preapproved"===this.state||"allowlisted"===this.state}}function $h(e){return e?.type??"undefined"}class Fh{ignoreService;pendingDecisionStore;permissionsProvider;teamSettingsService;adminNetworkControlsEnabled;rootDirectories;perUserSandboxConfigPath;mcpAllowlistLog;constructor(e,t,r,o,n,s=!1,l){this.ignoreService=e,this.pendingDecisionStore=t,this.permissionsProvider=r,this.teamSettingsService=o,this.adminNetworkControlsEnabled=s,this.rootDirectories=Array.isArray(n)?n:[n??process.cwd()],this.perUserSandboxConfigPath=l?.perUserSandboxConfigPath??(0,a.join)((0,i.homedir)(),".cursor","sandbox.json"),this.mcpAllowlistLog=l?.mcpAllowlistLog}async shouldBlockRead(e,{cursorIgnoreChecked:t=!1}={}){const r=(0,h.o1)(e),o=await Ta(r);return null===o?{type:"unsafeResolution",message:bh("Read","path",r)}:await this.ignoreService.isRepoBlocked(o)?{type:"adminBlock",source:"Team repo blocklist"}:await this.isPathExplicitlyDenied("Read",r)?{type:"permissionsConfig"}:!Ap(o)&&!Op(o)&&(!t&&await this.ignoreService.isCursorIgnored(o)?{type:"cursorIgnore"}:(await this.isPathExplicitlyAllowed("Read",r),!1))}async shouldBlockWrite(e,t,r){const o={stack:[],error:void 0,hasError:!1};try{gh(o,(0,l.VI)(e.withName("InteractivePermissionsService.shouldBlockWrite")),!1).ctx;const n=await hh(t);if(!mh(n.resolution))return{type:"unsafeResolution",message:fh(n.originalPath,n.resolution)};const s=n.resolvedPath,c=s;if(await this.ignoreService.isRepoBlocked(c))return{type:"adminBlock",source:"Team repo blocklist"};if(await this.isPathExplicitlyDenied("Write",s))return{type:"permissionsConfig"};const u=n.originalPath.split(a.sep).pop()?.toLowerCase()??"",d=s.split(a.sep).pop()?.toLowerCase()??"";if(".cursorignore"===u||".cursorignore"===d)return{type:"permissionsConfig"};const p=Ap(c),m=Op(c),f=!p&&!m&&await this.ignoreService.isCursorIgnored(c);if(p||m);else if(f)return{type:"cursorIgnore"};if(await this.isPathExplicitlyAllowed("Write",s))return!1;if(function(e){const t=e.replace(/\\/g,"/");return/(^|\/)\.cursor\/debug(?:-[a-zA-Z0-9-]+)?\.log$/i.test(t)}(s))return!1;const g=await this.getPermissions();if("workspace_readonly"===g.userConfiguredPolicy.type)return{type:"permissionsConfig",isReadonly:!0};if("unrestricted"===g.approvalMode)return!1;const v="win32"===process.platform||"darwin"===process.platform;for(const e of this.rootDirectories){const t=await hh(e);if(!mh(t.resolution))continue;const r=t.resolvedPath;if(v?s.toLowerCase()===r.toLowerCase()||s.toLowerCase().startsWith(r.toLowerCase()+a.sep):s===r||s.startsWith(r+a.sep)){const e=(0,a.relative)(r,s).split(a.sep).map((e=>"win32"===process.platform&&e.includes(":")?e.split(":")[0]:e)),t=await this.checkCursorFileProtection(e);if(t)return t;break}}const y=async()=>{let e=!1,t="";try{t=await(0,h.yR)(s),e=!1}catch{e=!0}let o="";if(e)o=r;else{const e=e=>e.endsWith("\n")?e:`${e}\n`,{hunks:n}=(0,uh.YB)("a","b",e(t),e(r),"","",{context:2});o=n.map((e=>e.lines.map((e=>e.length>0?`${e[0]} ${e.slice(1)}`:e)).join("\n"))).join("\n...\n")}return{isNewFile:e,diffString:o}};let w,b=!1;for(const e of this.rootDirectories){const t=await hh(e);if(!mh(t.resolution))continue;const r=t.resolvedPath;if(s.toLowerCase().startsWith(r.toLowerCase())){b=!0,w=r;break}}const S=b?void 0:function(e){if(!Op(e))return;const t=(0,a.relative)(Ip,e).split(a.sep).filter(Boolean);return 0!==t.length?(0,a.join)(Ip,t[0]):void 0}(s);if(!b&&void 0===S){if(function(e){return Mh(e,{platform:process.platform,env:process.env,pathModule:a})}(s))return!1;if(Dp(s,["assets","agent-notes","agent-tools","swarm-agents"]))return!1;const e=`${(0,i.homedir)()}${a.sep}.cursor${a.sep}`;if(s.startsWith(e)){const e=s.split(a.sep).pop()?.toLowerCase()??"";if(e.endsWith(".md")||e.endsWith(".mdc")||".cursorrules"===e)return!1}const{isNewFile:t,diffString:r}=await y();return{type:"needsApproval",approvalReason:"Out of workspace",approvalDetails:{type:"fileEdit",isNewFile:t,diffString:r,blockReason:"outOfWorkspace"}}}const k=w??S,E=s;let x=(0,a.relative)(k,E).split(a.sep);if(x=x.map((e=>"win32"===process.platform&&e.includes(":")?e.split(":")[0]:e)),"win32"===process.platform&&x.some((e=>e.includes("~")))){const{isNewFile:e,diffString:t}=await y();return{type:"needsApproval",approvalReason:`Protected config file: ${x[x.length-1]??""}`,approvalDetails:{type:"fileEdit",isNewFile:e,diffString:t,blockReason:"protectedConfig"}}}if(await(0,Do.OK)(s,k)){const e=x[x.length-1]?.toLowerCase()??"",{isNewFile:t,diffString:r}=await y();return{type:"needsApproval",approvalReason:`Protected config file: ${e}`,approvalDetails:{type:"fileEdit",isNewFile:t,diffString:r,blockReason:"protectedConfig"}}}return await this.checkCursorFileProtection(x)||!1}catch(e){o.error=e,o.hasError=!0}finally{vh(o)}}async shouldEnforceShellInvariantBlocks(e,t,r){const o=await Ta(t.workingDirectory);if(null===o){if(!0!==t.skipUnsafeWorkingDirectoryBlock)return{kind:"block",reason:{type:"unsafeResolution",message:bh("Command","working directory",t.workingDirectory)}}}else if(await this.ignoreService.isRepoBlocked(o))return{kind:"block",reason:{type:"adminBlock",source:"Team repo blocklist"}};const n=(await this.getPermissions()).userConfiguredPolicy,s=r??n;return"workspace_readonly"===n.type&&"workspace_readonly"!==s.type?{kind:"block",reason:{type:"permissionsConfig",isReadonly:!0}}:{kind:"allow"}}async shouldBlockShellCommand(e,t,r,o){const n=await this.shouldEnforceShellInvariantBlocks(e,{workingDirectory:r.workingDirectory},o);if("block"===n.kind)return n;const s=await this.getPermissions(),i=s.approvalMode,l="unrestricted"===i,c=s.userConfiguredPolicy,u=!s.dashboardTerminalAllowlistOverriddenByPermissionsFile;if(yh.info(e,"Shell permissions: evaluating shell command",{toolCallId:r.toolCallId,approvalMode:i,userConfiguredPolicyType:$h(c),requestedPolicyType:$h(o),effectiveRequestedPolicyType:$h(o??c),smartAllowlistEnabled:!0===s.smartAllowlistEnabled,hasSmartModeApprovalReason:void 0!==r.smartModeApprovalReason,hasSmartModeApprovalRequestId:void 0!==r.smartModeApprovalRequestId,hookForcesPrompt:pt(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,s))return yh.info(e,"Shell permissions: prompting for empty allowlist",{toolCallId:r.toolCallId,approvalMode:i,userConfiguredPolicyType:$h(c),requestedPolicyType:$h(o),hasSmartModeApprovalReason:void 0!==r.smartModeApprovalReason,hasSmartModeApprovalRequestId:void 0!==r.smartModeApprovalRequestId}),await this.requestApprovalForEmptyShellAllowlist(t,r,o??c);const d=r.parsingResult.executableCommands,p=r.parsingResult.hasRedirects,m=!0===r.parsingResult.allRedirectsAreDevNull,f=r.parsingResult.parsingFailed,g=r.classifierResult,v=r.smartModeApprovalReason,y=r.smartModeApprovalRequestId,w=void 0!==g&&!g.classificationFailed&&g.commands.length>0?g:void 0,b="allowlist"===i&&s.smartAllowlistEnabled?w?.commands:void 0,S=void 0!==b,k=b?b.map(Ah):d,E=void 0!==b?b.map(Th):k.map((e=>[e.fullText.trim()].filter(Boolean))),x=void 0!==w?w.commands.map(Th):E;if(o||(o=s.userConfiguredPolicy),"insecure_none"!==o.type&&void 0===o.skipStatsigDefaults&&"insecure_none"!==c.type&&(o={...o,skipStatsigDefaults:c.skipStatsigDefaults??!0}),"insecure_none"!==c.type&&(0,Do.$b)(c.networkPolicy)&&"insecure_none"!==o.type&&!(0,Do._B)(o.networkPolicy)){const e=c.networkPolicy,t=o.networkPolicy?.allow;if(void 0!==t&&t.length>0&&e){const r=[...new Set([...e.allow??[],...t])];o={...o,networkPolicy:{...e,allow:r}}}else o={...o,networkPolicy:e}}g&&yh.info(e,"Smart allowlist: classifier result received",{classificationFailed:g.classificationFailed,suggestedSandboxMode:g.suggestedSandboxMode,commandCount:g.commands.length,suggestedAllowlistEntryCount:g.commands.filter((e=>e.suggestedAllowlistEntry)).length});let _=!1;const C=[],P=[];let R=[],T=[],I=[];const A=Rh(s.smartAllowlistDenylist??[]);if(A.length>0){T=[];const t=x.map((e=>e[0]??""));for(let e=0;e<x.length;e++){const r=x[e];if(r&&0!==r.length&&A.some((e=>Ih(r,e)))){const r=t[e];r&&T.push(r)}}T.length>0&&(yh.info(e,"Command blocklist: commands require approval",{count:T.length}),C.push(`In blocklist: ${T.join(", ")}`))}if(S&&g){const t=E.map((e=>e[0]??"")),r=s.allow.filter((e=>this.isShellEntry(e)));yh.info(e,"Smart allowlist: checking commands against lists",{commandCount:t.length,allowlistCount:r.length,commandBlocklistCount:A.length});const o=E.map((e=>r.some((t=>e.some((e=>this.matchesShell(t,e))))))),n=o.every(Boolean),i=[];for(let e=0;e<g.commands.length;e++){if(o[e])continue;const t=g.commands[e];t&&i.push(t)}if(R=Rh(i.flatMap((e=>function(e){const t=e.name.trim();if(!t)return[];const r=e.subcommandTokens.map((e=>e.trim())).filter(Boolean),o=e.arguments.map((e=>e.trim())).filter(Boolean),n=[t],s=[t];for(const e of r)s.push(e),n.push(s.join(" "));const i=[t,...o].join(" ");return n.includes(i)||n.push(i),Rh(n)}(e)))),I=i.map((e=>e.suggestedAllowlistEntry)).filter((e=>"string"==typeof e)).filter((e=>R.includes(e))),R.length>0){const e=(0,h.To)(R,I),t=e.length>0?e.join(", "):R.join(", ");P.push(`Not in allowlist: ${t}`)}_=n&&0===T.length,_&&yh.info(e,"Smart allowlist: all commands in allowlist, will check security",{commandCount:t.length})}const O="ask-every-time"===i||"insecure_none"===o.type&&"allowlist"===i?void 0:c,D=k.map(((e,t)=>new Nh(e,o,O,E[t])));if((0===k.length||f&&!S)&&!l){yh.info(e,"Shell permissions: prompting after parser miss",{toolCallId:r.toolCallId,approvalMode:i,requestedPolicyType:$h(o),userConfiguredPolicyType:$h(c),isSmartAllowlistActive:S,parsingFailed:f,parserCommandCount:k.length,hasSmartModeApprovalReason:void 0!==v,hasSmartModeApprovalRequestId:void 0!==y});const n={type:ic.Shell,toolCallId:r.toolCallId,details:{command:t,workingDirectory:r.workingDirectory,timeout:r.timeout,reason:v??(f?"Parser failed to parse command (possible bypass)":"Parser found no commands (possible bypass)"),isSandboxAvailable:!1,isSandboxEnabled:!1,canAllowlist:!1,notAllowedCommands:[],smartModeApprovalReason:v,smartModeApprovalRequestId:y}},s=await this.pendingDecisionStore.requestApproval(n);return s.approved?{kind:"allow",policy:await this.applyServerAndAdminPolicies(o)}:{kind:"block",reason:{type:"userRejected",reason:s.reason}}}if(await this.hasHardDeny(e,D))return{kind:"block",reason:{type:"permissionsConfig"}};const M=await this.teamSettingsService.getAutoRunControls(),j={type:"insecure_none"};for(const e of D)await this.isInShellAllowlist(e)&&e.approveWithPolicy(j),u&&M&&this.isInTeamAllowlist(M,e)&&e.approveWithPolicy(j);for(const e of D)M&&this.isInTeamBlocklist(M,e)&&e.deny();const N=await this.teamSettingsService.getDeleteFileProtection();if(N)for(const e of D)"rm"===e.command.name&&e.deny();const $=this.buildShellApprovalDecisionFacts({commands:D,autoRunControls:M,shouldApplyTeamShellAllowlist:u,deleteProtectionEnabled:N,softDenylistedCommands:T});if("workspace_readonly"===c.type&&"workspace_readonly"!==o.type)return yh.info(e,"Shell permissions: blocked by readonly mode"),{kind:"block",reason:{type:"permissionsConfig",isReadonly:!0}};const F=pt(r.hookApprovalRequirement),L=r.hookApprovalRequirement?.reason,U=F?void 0:this.getShellAutoApprovalPolicy({approvalMode:i,isUnrestricted:l,requestedPolicy:o,facts:$,preserveRequestedPolicyForAllowlistedCommands:S}),B=void 0!==U&&$.allCommandsAllowlisted&&"insecure_none"===U.type&&"allowlistEscalated"in U&&!0===U.allowlistEscalated;if(U&&(void 0===v||B)){S&&$.allCommandsPreapproved&&!$.allCommandsAllowlisted&&yh.info(e,"Shell permissions: all commands allowed by sandbox policy");const t=await this.applyServerAndAdminPolicies(U);return yh.info(e,"Shell permissions: auto-approved shell command",{toolCallId:r.toolCallId,approvalMode:i,requestedPolicyType:$h(o),userConfiguredPolicyType:$h(c),autoApprovalPolicyType:$h(U),mergedPolicyType:$h(t),isSmartAllowlistActive:S,smartModeApprovalBypassedByAllowlist:B,allCommandsRunnable:$.allCommandsRunnable,allCommandsAllowlisted:$.allCommandsAllowlisted,allCommandsPreapproved:$.allCommandsPreapproved,hasSmartModeApprovalReason:void 0!==v,commandCount:D.length}),{kind:"allow",policy:t}}const H=!(!p||m||f)&&await async function({parsingResult:e,workingDirectory:t,rootDirectories:r,resolvePathForPermissions:o=hh,pathModule:n=a,tempPathOptions:s={platform:process.platform,env:process.env,pathModule:n}}){if(!e.hasRedirects)return!0;const i=e.redirects;if(0===i.length)return!1;const l=e.executableCommands.length>1,c=kh();for(const e of i){if(Ch(e))continue;const i=l?kh():c,{operator:a,targetText:d}=e,p=e.destinationFds.map((e=>Number(e)));if(">&"===a){const e=_h(d),t=void 0===e?void 0:i.fdTargets.get(e);if("original-stdout"!==(u=t)&&"original-stderr"!==u&&"dev-null"!==u&&"workspace-file"!==u&&"tmp-file"!==u){for(const e of p)i.fdTargets.set(e,"unsafe");return!1}for(const e of p)i.fdTargets.set(e,t);continue}if("<&"===a){const e=_h(d),t=void 0===e?void 0:i.fdTargets.get(e);if("dev-null"!==t){for(const e of p)i.fdTargets.set(e,"unsafe");return!1}for(const e of p)i.fdTargets.set(e,t);continue}if("/dev/null"===d){for(const e of p)i.fdTargets.set(e,"dev-null");continue}if(!xh(a)||void 0===d){for(const e of p)i.fdTargets.set(e,"unsafe");return!1}const h=await Ph({targetText:d,workingDirectory:t,rootDirectories:r,resolvePathForPermissions:o,pathModule:n,tempPathOptions:s});if(!h){for(const e of p)i.fdTargets.set(e,"unsafe");return!1}for(const e of p)i.fdTargets.set(e,h)}var u;return!0}({parsingResult:r.parsingResult,workingDirectory:r.workingDirectory,rootDirectories:this.rootDirectories});let z=(S||(!p||m||H)&&!f)&&("allowlist"===i||"ask-every-time"===i)&&$.canAllowlistInPrompt;const W=[],q=void 0!==v,G=$.notInTeamAllowlist.length>0&&($.hasSecurityDenies||$.hasSoftDenies||!$.allCommandsRunnable);if(void 0!==v&&W.push(v),F&&(q||W.push(L?`Hook requested approval: ${L}`:"Hook requested approval"),z=!1),C.length>0&&(q||W.push(...C),z=!1),!q)if(S&&P.length>0)W.push(...P);else if($.unapprovedCommands.length>0){const e=this.generateAllowlistPatterns($.unapprovedCommands.map((e=>e.command))),t=(0,h.To)(e),r=t.length>0?t.join(", "):$.unapprovedCommands.map((e=>e.command.fullText)).join(", ");W.push(`Not in allowlist: ${r}`)}if($.hasSecurityDenies&&(q||($.rmDeniedByDeleteProtection.length>0&&W.push("Delete protection is enabled"),$.teamBlocklistedCommands.length>0&&W.push(`In team blocklist: ${$.teamBlocklistedCommands.map((e=>e.command.name)).join(", ")}`)),z=!1),G){const t=$.notInTeamAllowlist.map((e=>e.command.fullText)).join(", ");yh.info(e,"Shell permissions: commands not in team allowlist",{commandCount:$.notInTeamAllowlist.length}),q||W.push(`Not in team allowlist: ${t}`),z=!1}const V=W.join(" • "),J=[];z&&J.push(...this.generateAllowlistPatterns($.unapprovedCommands.map((e=>e.command))));const K=S&&P.length>0,Z=K?R:J,Y=K&&I.length>0?I:void 0,X="insecure_none"!==o.type&&"insecure_none"!==c.type,Q="insecure_none"!==o.type,ee=[void 0!==v?"smart_mode_approval":void 0,F?"hook_forces_prompt":void 0,C.length>0?"command_blocklist":void 0,S&&P.length>0?"smart_allowlist_miss":void 0,$.unapprovedCommands.length>0?"unapproved_commands":void 0,$.hasSecurityDenies?"security_denies":void 0,G?"team_allowlist_miss":void 0].filter((e=>void 0!==e));yh.info(e,"Shell permissions: requesting shell approval",{toolCallId:r.toolCallId,approvalMode:i,requestedPolicyType:$h(o),userConfiguredPolicyType:$h(c),isSandboxAvailable:X,isSandboxEnabled:Q,canAllowlist:z,isSmartAllowlistActive:S,hasSmartModeApprovalReason:void 0!==v,hasSmartModeApprovalRequestId:void 0!==y,hookForcesPrompt:F,approvalReasonTypes:ee,commandCount:D.length,unapprovedCommandCount:$.unapprovedCommands.length,deniedCommandCount:$.deniedCommands.length,notInTeamAllowlistCount:$.notInTeamAllowlist.length,notAllowedCommandCount:Z.length,suggestedAllowlistEntryCount:Y?.length??0,allCommandsRunnable:$.allCommandsRunnable,allCommandsAllowlisted:$.allCommandsAllowlisted,allCommandsPreapproved:$.allCommandsPreapproved,hasSecurityDenies:$.hasSecurityDenies,hasSoftDenies:$.hasSoftDenies});const te={type:ic.Shell,toolCallId:r.toolCallId,details:{command:t,workingDirectory:r.workingDirectory,timeout:r.timeout,reason:V,isSandboxAvailable:"allowlist"===i&&X,isSandboxEnabled:"allowlist"===i&&Q,canAllowlist:z,notAllowedCommands:Z,suggestedAllowlistEntries:Y,smartModeApprovalReason:v,smartModeApprovalRequestId:y}},re=await this.pendingDecisionStore.requestApproval(te);if(re.approved){const e="unrestricted"===i?{type:"insecure_none"}:o;return{kind:"allow",policy:await this.applyServerAndAdminPolicies(e)}}return{kind:"block",reason:{type:"userRejected",reason:re.reason}}}async isShellCommandFullyAllowlisted(e,t,r){const o=e.withName("InteractivePermissionsService.isShellCommandFullyAllowlisted"),n=await this.getPermissions(),s=!n.dashboardTerminalAllowlistOverriddenByPermissionsFile;if("allowlist"!==n.approvalMode)return!1;if("workspace_readonly"===n.userConfiguredPolicy.type)return!1;const i=r.classifierResult,a=void 0!==i&&!i.classificationFailed&&i.commands.length>0?i:void 0,l=(n.smartAllowlistEnabled??!1)&&void 0!==a;if(r.parsingResult.parsingFailed&&!l)return!1;const c=r.parsingResult.executableCommands,u=l?a.commands.map(Ah):c;if(0===u.length)return!1;const d=l?a.commands.map(Th):u.map((e=>[e.fullText.trim()].filter(Boolean))),p=void 0!==a?a.commands.map(Th):d,h={type:"insecure_none"},m=u.map(((e,t)=>new Nh(e,h,void 0,d[t])));if(await this.hasHardDeny(o,m))return!1;const f=Rh(n.smartAllowlistDenylist??[]);if(f.length>0)for(const e of p)if(e&&0!==e.length&&f.some((t=>Ih(e,t))))return!1;if(await this.teamSettingsService.getDeleteFileProtection()&&m.some((e=>"rm"===e.command.name)))return!1;const g=await this.teamSettingsService.getAutoRunControls();if(void 0!==g&&m.some((e=>this.isInTeamBlocklist(g,e))))return!1;for(const e of m){const t=await this.isInShellAllowlist(e),r=s&&void 0!==g&&this.isInTeamAllowlist(g,e);if(!t&&!r)return!1}return!0}async applyServerAndAdminPolicies(e){if("insecure_none"===e.type)return e;const t=await this.foldPerUserFilePolicy(e),r=t.skipStatsigDefaults?t:await this.applyStatsigDefaults(t),o=await this.loadPerRepoFilePolicy(r.type),n=await this.buildTeamAdminPolicy(r.type),s=(0,Do._B)(e.networkPolicy),{policy:i}=await(0,Do.resolveSandboxPolicyForWorkspace)(this.rootDirectories[0],{perUser:r,perRepo:o,teamAdmin:n});return s?{...i,networkPolicy:(0,Do.T6)()}:i}async foldPerUserFilePolicy(e){const t=await(0,Do.tv)(this.perUserSandboxConfigPath,(0,i.homedir)());if(!t||"insecure_none"===t.type)return e;let r=(0,Do.fZ)(t.networkPolicy,e.networkPolicy);r&&void 0!==e.networkPolicy?.default&&(r={...r,default:e.networkPolicy.default});const o=(0,Do.s9)(t.additionalReadonlyPaths,e.additionalReadonlyPaths),n={...e,networkPolicy:r,additionalReadonlyPaths:o.length>0?o:void 0};if("workspace_readwrite"===e.type&&"workspace_readwrite"===t.type){const r=(0,Do.s9)(t.additionalReadwritePaths,e.additionalReadwritePaths);return{...n,additionalReadwritePaths:r.length>0?r:void 0}}return n}async applyStatsigDefaults(e){const t=await this.teamSettingsService.getDefaultNetworkAllowlist();if(!t.available||0===t.allowlist.length)return e;if((0,Do._B)(e.networkPolicy))return e;const r={default:"deny",allow:Sh(t.allowlist)};return{...e,networkPolicy:(0,Do.fZ)(e.networkPolicy,r)}}async loadPerRepoFilePolicy(e){const t=this.rootDirectories[0];if(!t)return;const r=await(0,Do.tv)((0,a.join)(t,".cursor","sandbox.json"),t);return r&&"insecure_none"!==r.type?r.type!==e?Oh(e,{networkPolicy:r.networkPolicy,additionalReadonlyPaths:r.additionalReadonlyPaths,..."additionalReadwritePaths"in r?{additionalReadwritePaths:r.additionalReadwritePaths}:{},disableTmpWrite:r.disableTmpWrite,networkPolicyStrict:r.networkPolicyStrict}):r:void 0}async buildTeamAdminPolicy(e){if(!this.adminNetworkControlsEnabled)return;const t=await this.teamSettingsService.getNetworkAccessControls();if(!t.available)return Oh(e,{networkPolicy:(0,Do.Po)()});if(0===t.allowlist.length&&0===t.denylist.length)return;const r={};return t.allowlist.length>0&&(r.default="deny",r.allow=Sh(t.allowlist)),t.denylist.length>0&&(r.deny=Sh(t.denylist)),Oh(e,{networkPolicy:r})}async isInShellAllowlist(e){return(await this.getPermissions()).allow.some((t=>this.isShellEntry(t)&&e.matchForms.some((e=>this.matchesShell(t,e)))))}isInTeamBlocklist(e,t){return e.blocked.some((e=>this.matchesAutoRunCommand(t.command.fullText,e)))}isInTeamAllowlist(e,t){return e.allowed.some((e=>this.matchesAutoRunCommand(t.command.fullText,e)))}buildShellApprovalDecisionFacts({commands:e,softDenylistedCommands:t,autoRunControls:r,shouldApplyTeamShellAllowlist:o,deleteProtectionEnabled:n}){const s=e.filter((e=>"denied"===e.state)),i=e.filter((e=>"approvable"===e.state)),a=o&&r?.enabled?e.filter((e=>!this.isInTeamAllowlist(r,e))):[],l=s.filter((e=>void 0!==r&&this.isInTeamBlocklist(r,e))),c=n?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:l,rmDeniedByDeleteProtection:c}}getShellAutoApprovalPolicy({approvalMode:e,isUnrestricted:t,requestedPolicy:r,facts:o,preserveRequestedPolicyForAllowlistedCommands:n}){if(!o.hasSecurityDenies&&!o.hasSoftDenies&&o.allCommandsRunnable){if(t)return"workspace_readonly"===r.type?r:{type:"insecure_none"};if("allowlist"===e)return o.allCommandsAllowlisted&&!n?{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,o]=await Promise.all([this.teamSettingsService.getAutoRunControls(),this.teamSettingsService.getDeleteFileProtection()]);return!this.hasTeamShellControls(r,!t.dashboardTerminalAllowlistOverriddenByPermissionsFile)&&!o}async requestApprovalForEmptyShellAllowlist(e,t,r){const o=this.getEmptyShellAllowlistCandidates(t),n=await this.pendingDecisionStore.requestApproval({type:ic.Shell,toolCallId:t.toolCallId,details:{command:e,workingDirectory:t.workingDirectory,timeout:t.timeout,reason:t.smartModeApprovalReason??"Shell allowlist is empty",isSandboxAvailable:!1,isSandboxEnabled:!1,canAllowlist:o.length>0,notAllowedCommands:o,smartModeApprovalReason:t.smartModeApprovalReason,smartModeApprovalRequestId:t.smartModeApprovalRequestId}});return n.approved?{kind:"allow",policy:await this.applyServerAndAdminPolicies(r)}:{kind:"block",reason:{type:"userRejected",reason:n.reason}}}getEmptyShellAllowlistCandidates(e){const t=e.parsingResult;return t.parsingFailed||0===t.executableCommands.length||t.hasRedirects&&!0!==t.allRedirectsAreDevNull?[]:this.generateAllowlistPatterns(t.executableCommands)}async hasHardDeny(e,t){const r=await this.getPermissions();return t.some((e=>r.deny.some((t=>this.isShellEntry(t)&&e.matchForms.some((e=>this.matchesShell(t,e)))))))}isShellEntry(e){return null!==Dh(e)}isPathEntry(e,t){return new RegExp(`^\\s*${e}\\s*\\(`).test(t)}matchesShell(e,t){const r=Dh(e);if(!r)return!1;const o=t.trim(),n=this.extractBaseCommand(o);if(null!==r.argsPattern){const e=o.includes(" ")?o.slice(o.indexOf(" ")+1).trim():"",t=this.matchGlob(r.commandPattern,n)||this.matchGlob(r.commandPattern,o),s=this.matchGlob(r.argsPattern,e);if(t&&s)return!0}return!!this.matchGlob(r.fullPattern,o)||!!o.startsWith(`${r.fullPattern} `)||!!this.matchGlob(r.fullPattern,n)||n===r.fullPattern}async checkCursorFileProtection(e){const t=await this.teamSettingsService.getDotCursorProtection();if(e.some((e=>".cursor"===e.toLowerCase()||".vscode"===e.toLowerCase()))&&t){const t=e[e.length-1]?.toLowerCase()??"";return t.endsWith(".md")||t.endsWith(".mdc")||".cursorrules"===t?null:{type:"permissionsConfig"}}return 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","bash","npx"];for(const o of e)r.includes(o.name)&&o.args.length>0&&"word"===o.args[0].type?t.push(`${o.name} ${o.args[0].value}`):t.push(o.name);return[...new Set(t)]}matchesPathEntry(e,t,r){const o=new RegExp(`^\\s*${e}\\s*\\((.*)\\)\\s*$`),n=t.match(o);if(!n)return!1;const s=(n[1]??"").trim(),i=this.expandTilde(s);return this.matchGlob(i,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)))}expandTilde(e){return"~"===e?(0,i.homedir)():e.startsWith("~/")?(0,i.homedir)()+e.slice(1):e}escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}matchGlob(e,t){const r=`^${this.escapeRegExp(e.trim()).replace(/\\\*/g,".*")}$`;try{return new RegExp(r).test(t)}catch{return e.trim()===t}}async addToAllowList(e,t,r){const o=`${t}(${r})`;await this.permissionsProvider.updatePermissions((e=>{const t=e.allow.includes(o)?e.allow:[...e.allow,o];return{...e,allow:t}}))}async addToDenyList(e,t,r){const o=`${t}(${r})`;await this.permissionsProvider.updatePermissions((e=>{const t=e.deny.includes(o)?e.deny:[...e.deny,o];return{...e,deny:t}}))}async shouldBlockMcp(e,t){const r={stack:[],error:void 0,hasError:!1};try{gh(r,(0,l.VI)(e.withName("InteractivePermissionsService.shouldBlockMcp")),!1);const{name:o,toolName:n,providerIdentifier:s,args:i}=t,a=e=>{this.mcpAllowlistLog?.(e)};a(`[permissions-service] shouldBlockMcp: toolName="${n}", providerIdentifier="${s}"`);const c=await this.getPermissions(),u=await this.teamSettingsService.getMcpToolControls(),d=!0===u?.enabled;if(await this.isMcpExplicitlyDenied(e,s,n))return a(`[permissions-service] shouldBlockMcp: BLOCKED (explicitly denied) toolName="${n}", providerIdentifier="${s}"`),{type:"permissionsConfig"};const p=t.smartModeApproval?.reason;if(void 0!==p)return"workspace_readonly"===c.userConfiguredPolicy.type&&"unrestricted"!==c.approvalMode?(a(`[permissions-service] shouldBlockMcp: BLOCKED (readonly mode, Smart Mode forced approval) toolName="${n}", providerIdentifier="${s}"`),{type:"permissionsConfig",isReadonly:!0}):(a(`[permissions-service] shouldBlockMcp: needsApproval (Smart Mode) toolName="${n}", providerIdentifier="${s}"`),!(d?this.isMcpInTeamAllowlist(u,{providerIdentifier:s,toolName:n}):await this.isMcpExplicitlyAllowed(e,s,n))&&{type:"needsApproval",approvalReason:p,approvalDetails:{type:"mcp",name:o,toolName:n,providerIdentifier:s,args:i,reason:"smartMode",canAllowlist:!1,smartModeApprovalReason:p,smartModeApprovalRequestId:t.smartModeApproval?.requestId}});if(d){const t=this.isMcpInTeamAllowlist(u,{providerIdentifier:s,toolName:n});if(this.recordMcpAllowlistCheckResult(e,{allowlistScope:"team",outcome:t?"pass":"fail"}),t)return a(`[permissions-service] shouldBlockMcp: ALLOWED (in admin MCP allowlist) toolName="${n}", providerIdentifier="${s}"`),!1;if(u.allowUserOverride){const t=await this.isMcpExplicitlyAllowed(e,s,n);if(this.recordMcpAllowlistCheckResult(e,{allowlistScope:"user",outcome:t?"pass":"fail"}),t)return a(`[permissions-service] shouldBlockMcp: ALLOWED (user override, in user allowlist) toolName="${n}", providerIdentifier="${s}"`),!1}}else{const t=await this.isMcpExplicitlyAllowed(e,s,n);if(this.recordMcpAllowlistCheckResult(e,{allowlistScope:"user",outcome:t?"pass":"fail"}),t)return a(`[permissions-service] shouldBlockMcp: ALLOWED (explicitly in allowlist) toolName="${n}", providerIdentifier="${s}"`),!1}if("workspace_readonly"===c.userConfiguredPolicy.type&&"unrestricted"!==c.approvalMode)return a(`[permissions-service] shouldBlockMcp: BLOCKED (readonly mode) toolName="${n}", providerIdentifier="${s}"`),{type:"permissionsConfig",isReadonly:!0};if("unrestricted"===c.approvalMode){if(!await this.teamSettingsService.getShouldBlockMcp())return a(`[permissions-service] shouldBlockMcp: ALLOWED (auto-run, no team block) toolName="${n}", providerIdentifier="${s}"`),!1;a(`[permissions-service] shouldBlockMcp: needsApproval (auto-run but team blocks MCP) toolName="${n}", providerIdentifier="${s}"`)}return a(`[permissions-service] shouldBlockMcp: needsApproval (not in allowlist) toolName="${n}", providerIdentifier="${s}", approvalMode="${c.approvalMode}"`),{type:"needsApproval",approvalReason:`MCP tool: ${n}`,approvalDetails:{type:"mcp",name:o,toolName:n,providerIdentifier:s,args:i,canAllowlist:!0}}}catch(e){r.error=e,r.hasError=!0}finally{vh(r)}}async isMcpFullyAllowlisted(e,t){const r=e.withName("InteractivePermissionsService.isMcpFullyAllowlisted"),{providerIdentifier:o,toolName:n}=t;if(await this.isMcpExplicitlyDenied(r,o,n))return!1;const s=await this.teamSettingsService.getMcpToolControls();return!0===s?.enabled?!!this.isMcpInTeamAllowlist(s,{providerIdentifier:o,toolName:n})||!!s.allowUserOverride&&await this.isMcpExplicitlyAllowed(r,o,n):await this.isMcpExplicitlyAllowed(r,o,n)}async isWebFetchFullyAllowlisted(e,t){const r=await this.getPermissions();if("allowlist"!==r.approvalMode)return!1;let o;try{o=new URL(t.url)}catch{return!1}const n=o.hostname;return!r.deny.some((e=>this.matchesWebFetchEntry(e,n)))&&r.allow.some((e=>this.matchesWebFetchEntry(e,n)))}matchesAutoRunCommand(e,t){const r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`^${r}(\\s|$)`).test(e.trim())}matchesMcpPattern({pattern:e,providerIdentifier:t,toolName:r,logLabel:o}){const n=e.indexOf(":");if(-1===n)return!1;const s=e.slice(0,n).trim().toLowerCase(),i=e.slice(n+1).trim().toLowerCase(),a=t.toLowerCase().trim(),l=r.toLowerCase().trim(),c="*"===s||this.matchGlob(s,a),u="*"===i||this.matchGlob(i,l),d=c&&u,p=`[permissions-service] ${o}: serverPattern="${s}", toolPattern="${i}", normalizedProviderIdentifier="${a}", normalizedToolName="${l}", serverMatches=${c}, toolMatches=${u}, result=${d}`;return this.mcpAllowlistLog?.(p),d}recordMcpAllowlistCheckResult(e,{allowlistScope:t,outcome:r}){wh.increment(e,1,{allowlist_scope:t,outcome:r})}matchesMcpEntry(e,t,r){const o=e.match(/^\s*Mcp\s*\((.*)\)\s*$/);if(!o)return!1;const n=o[1]?.trim()??"";return this.matchesMcpPattern({pattern:n,providerIdentifier:t,toolName:r,logLabel:"matchesMcpEntry"})}matchesWebFetchEntry(e,t){const r=e.match(/^\s*WebFetch\s*\((.*)\)\s*$/);return!!r&&function(e,t){const r=Tt(e),o=Tt(t);if("*"===o)return!0;if(o.includes("/"))return function(e,t){const r=t.lastIndexOf("/");if(r<=0||r===t.length-1)return!1;const o=Ot(t.slice(0,r)),n=Ot(e);if(!o||!n||o.version!==n.version)return!1;const s=Number(t.slice(r+1)),i=4===o.version?32:128;if(!Number.isInteger(s)||s<0||s>i)return!1;const a=BigInt(i-s);return n.value>>a==o.value>>a}(r,o);if(o.startsWith("*.")){const e=o.slice(2);return r===e||r.endsWith(`.${e}`)}return r===o}(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}){return e.mcpToolAllowlist.some((e=>this.matchesMcpEntryBare({pattern:e,providerIdentifier:t,toolName:r})))}async isMcpExplicitlyDenied(e,t,r){return(await this.getPermissions()).deny.some((e=>this.matchesMcpEntry(e,t,r)))}async isMcpExplicitlyAllowed(e,t,r){return(await this.getPermissions()).allow.some((e=>this.matchesMcpEntry(e,t,r)))}}var Lh=r("../proto/dist/generated/aiserver/v1/dashboard_pb.js");const Uh=3e5,Bh=BigInt(0),Hh=BigInt(8),zh=BigInt(16),Wh=BigInt(65535);function qh(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 Gh(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(":");[...t.slice(e+1)].every((e=>/\d/.test(e)))&&(t=t.slice(0,e))}return t}function Vh(e){const t=e.split(".");if(4!==t.length)return;let r=Bh;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<<Hh|BigInt(t)}return{version:4,value:r}}function Jh(e){if(0===e.length)return[];const t=[],r=e.split(":");for(let e=0;e<r.length;e++){const o=r[e];if(0===o.length)return;if(o.includes(".")){if(e!==r.length-1)return;const n=Vh(o);if(!n)return;t.push(Number(n.value>>zh&Wh)),t.push(Number(n.value&Wh))}else{if(!/^[0-9a-f]{1,4}$/i.test(o))return;t.push(Number.parseInt(o,16))}}return t}function Kh(e){return Vh(e)??function(e){const t=Gh(e);if(0===t.length||t.includes(":::"))return;const r=t.indexOf("::");if(-1===r){const e=Jh(t);if(!e||8!==e.length)return;return{version:6,value:e.reduce(((e,t)=>e<<zh|BigInt(t)),Bh)}}if(-1!==t.indexOf("::",r+1))return;const o=Jh(t.slice(0,r)),n=Jh(t.slice(r+2));if(!o||!n)return;const s=o.length+n.length;return s>7?void 0:{version:6,value:[...o,...new Array(8-s).fill(0),...n].reduce(((e,t)=>e<<zh|BigInt(t)),Bh)}}(e)}function Zh(e,t){if(function(e,t){if(!e.includes("*"))return e===t;const r=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${r}$`).test(t)}(e,t))return!0;const r=function(e){const t=function(e){const t=e.trim(),r=t.indexOf("["),o=t.indexOf("]");if(-1!==r&&o>r){const e=t.slice(r+1,o);if(t.slice(o+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=Gh(t.slice(0,r));if(e.length>0)return`${e}/${t.slice(r+1).trim()}`}const o=qh(t);if(o)return Gh(o.hostname);let n=t;const s=n.indexOf("://");-1!==s&&(n=n.slice(s+3));const i=n.indexOf("/");-1!==i&&(n=n.slice(0,i));const a=Gh(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&&[...t[1]].every((e=>/\d/.test(e)))?t[0]:e}(n));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),o=function(e){const t=qh(e);if(t)return Gh(t.hostname);const r=Gh(e);return r.length>0?r:void 0}(t);return!(!r||!o)&&function(e,t){const r=Gh(e),o=Gh(t);if("*"===o)return!0;if(o.includes("/"))return function(e,t){const r=t.lastIndexOf("/");if(r<=0||r===t.length-1)return!1;const o=Kh(t.slice(0,r)),n=Kh(e);if(!o||!n||o.version!==n.version)return!1;const s=Number(t.slice(r+1)),i=4===o.version?32:128;if(!Number.isInteger(s)||s<0||s>i)return!1;const a=BigInt(i-s);return n.value>>a==o.value>>a}(r,o);if(o.startsWith("*.")){const e=o.slice(2);return r===e||r.endsWith(`.${e}`)}return r===o}(o,r)}class Yh{dashboardClient;constructor(e){this.dashboardClient=e}getTeamAdminSettings(){return this.dashboardClient.getTeamAdminSettingsOrEmptyIfNotInTeam(new Lh.Byz({}))}getTeamRepos(){return this.dashboardClient.getTeamReposOrEmptyIfNotInTeam(new Lh.aYW({}))}}class Xh{teamAdminSettingsProvider;defaultAllowlistProvider;options;settingsPromise;teamReposPromise;defaultAllowlistPromise;lastFetchTime=0;lastReposFetchTime=0;lastDefaultAllowlistFetchTime=0;lastFetchSucceeded=!0;constructor(e,t,r={}){this.teamAdminSettingsProvider=e,this.defaultAllowlistProvider=t,this.options=r,this.settingsPromise=this.fetchSettings()}invalidateCache(){this.lastFetchTime=0,this.lastDefaultAllowlistFetchTime=0,this.defaultAllowlistPromise=void 0}async fetchSettings(){this.lastFetchTime=Date.now();try{const e=await this.teamAdminSettingsProvider.getTeamAdminSettings();return this.lastFetchSucceeded=!0,e}catch(e){return void(this.lastFetchSucceeded=!1)}}async getTeamAdminSettings(){return(Date.now()-this.lastFetchTime>Uh||void 0===await this.settingsPromise)&&(this.settingsPromise=this.fetchSettings()),this.settingsPromise}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;if(!0===r?.disableAll)return{blocked:!0,reason:"teamPolicy",message:"Blocked by team policy"};const o=r?.allowedMcpServers,n=!0===r?.allowUserOverrideMcpServers&&await this.isMcpSettingsOverhaulEnabled({disableExposureLog:!0});if(o&&o.length>0&&!n){const t=(e,t)=>{if(!e.includes("*"))return e===t;const r=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${r}$`).test(t)},r=o.map((e=>e.command)).filter((e=>void 0!==e)),n=o.map((e=>e.serverUrl)).filter((e=>void 0!==e)),s=r.length>0,i=n.length>0,a=!s||(void 0!==e.command?r.some((r=>t(r,e.command))):void 0!==e.url&&i),l=!i||(void 0!==e.url?n.some((t=>Zh(t,e.url))):void 0!==e.command&&s);if(!a||!l)return{blocked:!0,reason:"teamPolicy",message:"Blocked by team policy"}}if(!0===r?.enableMcpNetworkControls){const t=await this.getMcpNetworkControlsConfig(),r=void 0===e.url?{allowed:!0}:(0,xc.ME)(e.url,t);if(!r.allowed)return{blocked:!0,reason:"teamNetworkAllowlist",message:r.message}}const s=function({isMcpAccessNetworkAllowlistEnabled:e,server:t,settings:r}){if(!e||!0!==r?.allowedMcpConfiguration?.requireMcpServersInTeamNetworkAllowlist)return{blocked:!1};const o=(r.networkAllowlist??[]).map((e=>e.trim())).filter((e=>e.length>0));if(void 0===t.url||0===o.length)return{blocked:!1};const n=(0,xc.ME)(t.url,{enabled:!0,localAgentNetworkAllowlist:o,blockMessage:"Not on the team network allowlist"});return n.allowed?{blocked:!1}:{blocked:!0,reason:"teamNetworkAllowlist",message:n.message}}({isMcpAccessNetworkAllowlistEnabled:!0===r?.enableMcpNetworkControls||await this.isMcpAccessNetworkAllowlistEnabled(),server:e,settings:t});return s.blocked?s:{blocked:!1}}async getMcpNetworkControlsConfig(){const e=await this.getTeamAdminSettings(),t=e?.allowedMcpConfiguration,r=t?.enableMcpNetworkControls;return{enabled:r,sandboxStdioServers:!0===r,mcpNetworkAllowlist:t?.mcpNetworkAllowlist,localAgentNetworkAllowlist:e?.networkAllowlist,blockMessage:"Not on the team network allowlist"}}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 isMcpSettingsOverhaulEnabled(e){const t=this.options.isMcpSettingsOverhaulEnabled?.(e);return void 0!==t&&await t}async getMcpToolControls(){const e=await this.getTeamAdminSettings(),t=await this.isMcpSettingsOverhaulEnabled(),r=function(e,t){const r=e?.allowedMcpConfiguration?.enableMcpToolControls;return!0===r||!1!==r&&(t?!0===e?.autoRunControls?.enabled:e?.autoRunControls?.enabled??!1)}(e,t);if(!r)return;const o=t&&!0===e?.allowedMcpConfiguration?.allowUserOverrideMcpTools;return{enabled:!0,mcpToolAllowlist:e?.autoRunControls?.mcpToolAllowlist??[],allowUserOverride:o}}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;return{sandboxingDisabled:t?.sandboxing===Lh.faf.DISABLED,networkingDisabled:t?.sandboxNetworking===Lh._mX.ALWAYS_DISABLED,gitDisabled:t?.sandboxGit===Lh.i24.ALWAYS_DISABLED}}async isAttributionDisabledByAdmin(){const e=await this.getTeamAdminSettings();return void 0===e&&!this.lastFetchSucceeded||(e?.attributionControls?.disableAttribution??!1)}async getDefaultNetworkAllowlist(){const e=Date.now();return(!this.defaultAllowlistPromise||e-this.lastDefaultAllowlistFetchTime>Uh)&&(this.lastDefaultAllowlistFetchTime=e,this.defaultAllowlistPromise=this.fetchDefaultAllowlist()),this.defaultAllowlistPromise}async fetchDefaultAllowlist(){if(!this.defaultAllowlistProvider)return{allowlist:[],available:!0};try{return{allowlist:await this.defaultAllowlistProvider.getDefaultNetworkAllowlist(),available:!0}}catch{return{allowlist:[],available:!1}}}async getTeamRepos(){const e=Date.now();return(!this.teamReposPromise||e-this.lastReposFetchTime>Uh)&&(this.teamReposPromise=this.fetchTeamRepos(),this.lastReposFetchTime=e),this.teamReposPromise}async fetchTeamRepos(){return this.teamAdminSettingsProvider.getTeamRepos()}async isMcpAccessNetworkAllowlistEnabled(){return await(this.options.isMcpAccessNetworkAllowlistEnabled?.())??!1}}function Qh(){return(0,a.join)(function(){const e=process.env.CURSOR_DATA_DIR;return(null==e?void 0:e.trim())?e:(0,a.join)((0,i.homedir)(),".cursor")}(),"projects")}function em(e){return(0,a.join)(Qh(),(0,h.r_)(e))}const tm=cn.z.any().transform(((e,t)=>{if(e instanceof L.Gm)return e;try{return L.Gm.fromJson(e,{ignoreUnknownFields:!1})}catch(r){return t.addIssue({code:cn.z.ZodIssueCode.custom,message:r instanceof Error?r.message:String(r)}),e}})),rm=cn.z.object({type:cn.z.literal("command"),command:cn.z.string().min(1),padding:cn.z.number().int().min(0).optional(),updateIntervalMs:cn.z.number().int().positive().optional(),timeoutMs:cn.z.number().int().positive().optional()}),om=cn.z.object({permissions:cn.z.object({allow:cn.z.array(cn.z.string()),deny:cn.z.array(cn.z.string())})}),nm=om.extend({version:cn.z.number(),editor:cn.z.object({vimMode:cn.z.boolean(),defaultBehavior:cn.z.enum(["ide","agent"]).optional()}),display:cn.z.object({showLineNumbers:cn.z.boolean().default(!1),showThinkingBlocks:cn.z.boolean().default(!1),showStatusIndicators:cn.z.boolean().default(!1),showStatusLineRunningTime:cn.z.boolean().default(!1)}).default({showLineNumbers:!1,showThinkingBlocks:!1,showStatusIndicators:!1,showStatusLineRunningTime:!1}),notifications:cn.z.boolean().default(!0),hints:cn.z.boolean().default(!0),rewind:cn.z.boolean().default(!1),suggestNextPrompt:cn.z.boolean().default(!1),statusLine:rm.optional(),channel:cn.z.literal("static").or(cn.z.literal("prod")).or(cn.z.literal("lab")).or(cn.z.literal("staging")).or(cn.z.literal("prod-stable-internal")).or(cn.z.literal("asb")).optional(),model:tm.optional(),bedrock:cn.z.object({enabled:cn.z.boolean().default(!1),mode:cn.z.enum(["access-key","team-role"]).default("access-key"),region:cn.z.string().optional(),testModel:cn.z.string().optional(),teamRoleArn:cn.z.string().optional(),teamExternalId:cn.z.string().optional()}).optional(),hasChangedDefaultModel:cn.z.boolean().default(!1).optional(),maxMode:cn.z.boolean().default(!1).optional(),modelParameters:cn.z.record(cn.z.string(),cn.z.array(cn.z.object({id:cn.z.string(),value:cn.z.string()}))).optional(),selectedModel:cn.z.object({modelId:cn.z.string(),parameters:cn.z.array(cn.z.object({id:cn.z.string(),value:cn.z.string()}))}).optional(),privacyCache:cn.z.object({ghostMode:cn.z.boolean(),privacyMode:cn.z.number().optional(),updatedAt:cn.z.number()}).optional(),serverConfigCache:cn.z.object({backendUrl:cn.z.string(),authCacheKey:cn.z.string().optional(),teamId:cn.z.number().optional(),agentUrlConfig:cn.z.object({agentUrl:cn.z.string(),agentnUrl:cn.z.string()}).optional(),cliSandboxDefaultEnabled:cn.z.boolean().optional(),serverHttp2Config:cn.z.number().optional(),updatedAt:cn.z.number()}).optional(),authInfo:cn.z.object({email:cn.z.string().optional(),displayName:cn.z.string().optional(),teamId:cn.z.number().optional(),teamName:cn.z.string().optional(),userId:cn.z.number().optional(),authId:cn.z.string().optional(),organizationId:cn.z.string().optional()}).optional(),network:cn.z.object({useHttp1ForAgent:cn.z.boolean().default(!1)}).default({useHttp1ForAgent:!1}),approvalMode:cn.z.enum(["allowlist","unrestricted"]).default("allowlist").optional(),sandbox:cn.z.object({mode:cn.z.enum(["disabled","enabled"]).default("disabled"),networkAccess:cn.z.preprocess((e=>"allowlist"===e?"user_config_with_defaults":"enabled"===e?"allow_all":e),cn.z.enum(["user_config_only","user_config_with_defaults","allow_all"])).optional(),networkAllowlist:cn.z.array(cn.z.string()).default([]).optional()}).optional(),showSandboxIntro:cn.z.boolean().default(!1).optional(),runEverythingSettingsPromptStreak:cn.z.number().int().nonnegative().optional(),runEverythingSettingsPromptCooldownUntilMs:cn.z.number().int().nonnegative().optional(),attribution:cn.z.object({attributeCommitsToAgent:cn.z.boolean().default(!0),attributePRsToAgent:cn.z.boolean().default(!0)}).optional(),webFetchDomainAllowlist:cn.z.array(cn.z.string()).default([]).optional(),conversationClassificationScoredConversations:cn.z.array(cn.z.object({conversationId:cn.z.string(),lastUpdatedAt:cn.z.number()})).optional()}),sm=om.strict().extend({});nm.merge(sm);class im{storage;prefix;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 am{storage;prefix;constructor(e,t){this.storage=e,this.prefix=t}async isServerApproved(e,t,r){return this.storage.isServerApproved(this.prefix+e,t,r)}}class lm{loaders;constructor(e){this.loaders=e}async load(e,t=!0){const r=await Promise.allSettled(this.loaders.map((({loader:r})=>r.load(e,t)))),o=r.find((e=>"rejected"===e.status));if(o)throw await Promise.allSettled(r.flatMap((e=>"fulfilled"===e.status?[e.value.closeAllClients()]:[]))),o.reason;const n=r.filter((e=>"fulfilled"===e.status)).map((e=>e.value)),s={};for(let e=0;e<n.length;e++){const t=n[e],r=this.loaders[e].prefix,o=t.getClients();for(const[e,t]of Object.entries(o)){const o=r+e;o in s||(s[o]=t)}}return new yu(s)}async loadClient(e,t,r=!1){for(const{loader:o,prefix:n}of this.loaders)if(t.startsWith(n)){t=t.slice(n.length);try{return await o.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){var t;for(const{loader:r,prefix:o}of this.loaders){if(!e.startsWith(o))continue;const n=e.slice(o.length);null===(t=r.clearClient)||void 0===t||t.call(r,n)}}clearAllMcpCaches(){var e;for(const{loader:t}of this.loaders)null===(e=t.clearAllMcpCaches)||void 0===e||e.call(t)}}class cm{loader;constructor(e,t,r,o,n=!1,s,l,c=a.join((0,i.homedir)(),".cursor","mcp.json")){const u=Array.isArray(e)?e:[e],d=[];for(let e=0;e<u.length;e++){const t=u[e],r=a.join(t,".cursor","mcp.json"),o=`project-${e}-${a.basename(t)}-`;d.push({path:r,prefix:o})}d.push({path:c,prefix:"user-"});const p=new Map;for(const{path:e,prefix:t}of d)p.has(e)&&"user-"!==t||p.set(e,t);const h=[];for(const[e,i]of p){const a=n?"":i,u=new im(t,a),d=new am(o,a),p=e===c,m=[new Dc,...p?[]:[new Tc(d)],new Du(r),...l?[new Rc(l)]:[]];h.push({prefix:a,loader:new Mu(e,u,m,s)})}this.loader=new lm(h)}static init(e,t,r,o=!1,n){const s=new Nu(a.join(r,"mcp-auth.json"));(async function(e){await(0,fo.rm)(a.join(e,"mcp-cache.json"),{force:!0})})(r).catch((()=>{}));const i=o?{isServerApproved:()=>Promise.resolve(!0)}:new Ic(a.join(r,"mcp-approvals.json"),t);return new cm(t,s,e,i,!0,void 0,n)}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 um=new vc,dm={async resolveWorkspaceState(e){var t,r,o,n,s,i,a;const c=null!==(o=null!==(r=e.workingDirectory)&&void 0!==r?r:e.projectRoot)&&void 0!==o?o:null===(t=e.workspaceRoots)||void 0===t?void 0:t[0],u=null!==(n=e.projectRoot)&&void 0!==n?n:void 0!==c?null!==(s=await Ea((0,l.q6)(),um,c))&&void 0!==s?s:c:void 0,d=null!==(i=e.workspaceRoots)&&void 0!==i?i:void 0!==u?[u]:void 0!==c?[c]:[];return{workingDirectory:c,projectRoot:u,projectDirectory:null!==(a=e.projectDirectory)&&void 0!==a?a:void 0!==u?em(u):void 0,workspaceRoots:d,createdAt:new Date}}};let pm={warn:console.warn.bind(console),error:console.error.bind(console)};const hm=new tn.AsyncLocalStorage;function mm(){var e;return null!==(e=hm.getStore())&&void 0!==e?e:pm}const fm={warn(...e){mm().warn(...e)},error(...e){mm().error(...e)}};function gm(e){var t;if("userMessageAction"===e.action.case)return null===(t=e.action.value.userMessage)||void 0===t?void 0:t.text}function vm(e,t,r){var o,n;const s=null===(o=e.runOptions)||void 0===o?void 0:o.requestedModel;return{conversationId:e.conversationId,generationId:e.conversationId,model:null!==(n=null==s?void 0:s.modelId)&&void 0!==n?n:"unknown",modelId:null==s?void 0:s.modelId,modelParams:null==s?void 0:s.parameters.map((e=>({id:e.id,value:e.value}))),loopCount:t,promptText:r}}function ym(e){return e instanceof DOMException&&"AbortError"===e.name||e instanceof Error&&("AbortError"===e.name||"The operation was aborted"===e.message)}const wm="cursor-plugins/local";function bm(e){var t;if(e)for(const r of e)if("object"==typeof(t=r)&&null!==t&&t.kind===wm)return r}class Sm extends vu{runtimeManager;disposed=!1;constructor(e){super(e),this.runtimeManager=e}async dispose(){this.disposed||(this.disposed=!0,await this.runtimeManager.closeAllClients())}}class km{storagePath;constructor(e){this.storagePath=e}async isServerDisabled(e){try{const t=await(0,fo.readFile)(this.storagePath,"utf8"),r=JSON.parse(t);return Array.isArray(r)?r.includes(e):(await this.writeDisabledServers([]),!1)}catch(e){if("ENOENT"===e.code)return!1;throw e}}async writeDisabledServers(e){await(0,fo.mkdir)((0,a.dirname)(this.storagePath),{recursive:!0}),await(0,fo.writeFile)(this.storagePath,JSON.stringify(e,null,2))}}class Em{pluginMcpService;importThirdPartyPlugins;constructor(e,t){this.pluginMcpService=e,this.importThirdPartyPlugins=t}async getDefinitions(){let e;try{e=await this.pluginMcpService.getPluginMcpServers()}catch(e){return fm.warn("[cursor-config-mcp] Failed to enumerate plugin MCP servers:",e),[]}const t=[];for(const r of e){if(!this.importThirdPartyPlugins&&Rm(r))continue;const e=ju(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}}):fm.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 xm{servers;constructor(e){this.servers=e}async getDefinitions(){return Object.entries(this.servers).map((([e,t])=>({identifier:e,authStorageKey:`inline:${e}`,serverConfig:Pm(e,t),source:"inline",metadata:{source:"cursor-sdk"}})))}}function _m(e={}){var t,r,o;const n=null!==(t=e.teamSettingsService)&&void 0!==t?t:{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:[]}),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:()=>{}},s=null!==(r=e.ignoreApprovals)&&void 0!==r&&r,c=null!==(o=e.importThirdPartyPlugins)&&void 0!==o&&o;return{async createLease(t){var r,o,u,d,p,h;const m=t.workspaceState,f=null!==(r=m.projectRoot)&&void 0!==r?r:m.workingDirectory,g=m.projectDirectory;if(!f||!g)return new gu;const v=new km((0,a.join)(g,"mcp-disabled.json")),y=function(e){const{teamSettingsService:t,projectRoot:r,projectDirectory:o,ignoreApprovals:n,disabledStore:s,includeProjectMcp:l,includeUserMcp:c}=e;if(l&&c)return cm.init(t,r,o,n,s);if(!l&&!c)return;const u=new Nu((0,a.join)(o,"mcp-auth.json")),d=n?{isServerApproved:()=>Promise.resolve(!0)}:new Ic((0,a.join)(o,"mcp-approvals.json"),r),p=[new Dc,new Tc(d),new Du(t),new Rc(s)],h=[];return l&&h.push({prefix:"",loader:new Mu((0,a.join)(r,".cursor","mcp.json"),u,p)}),c&&h.push({prefix:"",loader:new Mu((0,a.join)((0,i.homedir)(),".cursor","mcp.json"),u,p)}),Cm(h)}({teamSettingsService:n,projectRoot:f,projectDirectory:g,ignoreApprovals:s,disabledStore:v,includeProjectMcp:null===(o=e.includeProjectMcp)||void 0===o||o,includeUserMcp:null===(u=e.includeUserMcp)||void 0===u||u}),w=[],b=null!==(d=e.inlineMcpServers)&&void 0!==d?d:{};if(Object.keys(b).length>0){const e=new Nu((0,a.join)(g,"mcp-auth.json")),t=[new Dc,new Du(n)];w.push({prefix:"",loader:new Au(new xm(b),e,t)})}const S=bm(t.services.pluginBootstrapOutputs);if(S&&(null===(p=e.includePluginMcp)||void 0===p||p)){const e=new Ic((0,a.join)(g,"mcp-approvals.json"),f),t=new Nu((0,a.join)(g,"mcp-auth.json")),r=[new Dc];s||r.push(new Tc(e)),r.push(new Du(n),new Rc(v));const o=new ah(S.pluginsService),i=new Au(new Em(o,c),t,r);w.push({prefix:"",loader:i})}if(y&&w.push({prefix:"",loader:y}),0===w.length)return new gu;const k=Cm(w),E=await k.load(null!==(h=e.initializationCtx)&&void 0!==h?h:(0,l.q6)(),e.cache);return new Sm(E)}}}function Cm(e){return 1===e.length?e[0].loader:new lm(e)}function Pm(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}}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?Object.assign(Object.assign({},r),{type:"sse"}):r}throw new Error(`Invalid inline MCP server config for "${e}"`)}function Rm(e){return"claude-plugin"===e.pluginSource}const Tm=["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","mcp_instructions","mcp_file_system","mcp_file_system_servers","git_status","agent_transcripts","cursor_rules_context","attached_files","system_notification","task_notification","agent_notification"];function Im(e){return function(e,t){let r=e;for(const e of t){const t=new RegExp(`<${e}(?:\\s[^>]*)?>[\\s\\S]*?</${e}>`,"gi");r=r.replace(t,"")}return r.replace(/\n{3,}/g,"\n\n").trim()}(e,Tm)}function Am(e){const t=(0,h.sh)(e.conversationId);if("subagent"===e.kind&&e.parentConversationId){const r=(0,h.sh)(e.parentConversationId);return`${h.O2}/${r}/subagents/${t}.${e.ext}`}return`${h.O2}/${t}/${t}.${e.ext}`}function Om(e){const t=(0,h.sh)(e.conversationId);return`${h.O2}/${t}.${e.ext}`}function Dm(e){var t,r;const o=null!==(t=e.exts)&&void 0!==t?t:["jsonl","txt"],n=null===(r=e.includeLegacy)||void 0===r||r,s=[],i=e=>{s.includes(e)||s.push(e)};for(const t of o)i(Am({conversationId:e.conversationId,ext:t,kind:e.kind,parentConversationId:e.parentConversationId})),"subagent"===e.kind&&e.parentConversationId&&i(Am({conversationId:e.conversationId,ext:t,kind:"primary"})),n&&i(Om({conversationId:e.conversationId,ext:t}));return s}var Mm;r("../proto/dist/generated/aiserver/v1/chat_pb.js"),function(e){e.INTERNAL="INTERNAL",e.EXTERNAL="EXTERNAL",e.NO_PREAMBLE="NO_PREAMBLE"}(Mm||(Mm={}));var jm=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var o,n;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");o=t[Symbol.asyncDispose]}if(void 0===o){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");o=t[Symbol.dispose],r&&(n=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");n&&(o=function(){try{n.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:o,async:r})}else r&&e.stack.push({async:!0});return t},Nm=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 o,n=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===n)return n=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var s=o.dispose.call(o.value);if(o.async)return n|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else n|=1}catch(e){r(e)}if(1===n)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var o=new Error(r);return o.name="SuppressedError",o.error=e,o.suppressed=t,o});function $m(e){switch(e){case L.xy.AGENT:return"agent";case L.xy.ASK:return"ask";case L.xy.PLAN:return"plan";case L.xy.DEBUG:return"debug";case L.xy.TRIAGE:return"triage";case L.xy.PROJECT:return"project";case L.xy.MULTITASK:return"multitask";case L.xy.UNSPECIFIED:default:return"agent"}}function Fm(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 Lm(e,t){return t&&"object"==typeof t&&"Uint8Array"===t.__type&&"string"==typeof t.hex?`[Binary data omitted from transcript: ${t.hex.length/2} bytes]`:t}const Um=new TextEncoder,Bm=new TextDecoder,Hm=new class{serialize(e){const t=JSON.stringify(e,Fm);return Um.encode(t)}deserialize(e){const t=Bm.decode(e);return t.includes('"__type":"Uint8Array"')?JSON.parse(t,Lm):JSON.parse(t)}};function zm(e){var t;const r=e.providerOptions;return!0===(null===(t=null==r?void 0:r.cursor)||void 0===t?void 0:t.isSummary)}async function Wm(e,t,r){const o=[];let n=0,s=0,i=0,a=0,l=0,c=0,u=0;for(const p of r){const r=await t.getBlob(e,p);if(r){if(r.length>5e6){o.push((void 0,{role:"assistant",content:`[Oversize transcript blob omitted: ${d=r.length,`${(d/1e6).toFixed(1)} MB`}]`})),l++,c+=r.length,u=Math.max(u,r.length);continue}try{const e=performance.now(),t=Hm.deserialize(r),l=performance.now()-e;o.push(t),n++,s+=r.length,i=Math.max(i,r.length),a+=l}catch(e){}}}var d;return{messages:o,hydratedBlobCount:n,hydratedBlobBytes:s,largestHydratedBlobBytes:i,totalDeserializeDurationMs:a,omittedOversizeBlobCount:l,omittedOversizeBlobBytes:c,largestOmittedOversizeBlobBytes:u}}function qm(e,t){switch(e.type){case"text":return t?Gm(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"";if("object"!=typeof e)return String(e);const t=e,r=Object.entries(t);return 0===r.length?"":`\n${r.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 Gm(e){return Im(e)}function Vm(e){return e.replace(/<think>[\s\S]*?<\/think>/gi,"").replace(/<thinking>[\s\S]*?<\/thinking>/gi,"").replace(/\n{3,}/g,"\n\n").trim()}function Jm(e,t,r){if(void 0===e)return"";if("string"==typeof e){const o=t?Gm(e):e;return r?Vm(o):o}return e.map((e=>{if(r&&"text"===e.type){const r=Vm(t?Gm(e.text):e.text);return qm(Object.assign(Object.assign({},e),{text:r}),!1)}return qm(e,t)})).filter(Boolean).join("\n")}function Km(e,t){const r={role:e.role},o=e.content;if("string"==typeof o){const n=t?Gm(o):o,s="assistant"===e.role?Vm(n):n;s.trim()&&(r.text=s)}else if(Array.isArray(o)){const n=[],s=[],i=[];let a;for(const r of o)switch(r.type){case"text":{const o=t?Gm(r.text):r.text,s="assistant"===e.role?Vm(o):o;s.trim()&&n.push(s);break}case"reasoning":r.text.trim()&&s.push(r.text);break;case"redacted-reasoning":s.push("[REDACTED]");break;case"image":n.push("[Image]");break;case"file":n.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}}n.length>0&&(r.text=n.join("\n")),s.length>0&&(r.thinking=s.join("\n")),i.length>0&&(r.toolCalls=i),a&&(r.toolResult=a)}return r}function Zm(e){return e.endsWith("\n")?e:`${e}\n`}function Ym(e){const{turnEnded:t}=e,r=[],o={},n=[];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)),o.turnEnded=t,n.push(JSON.stringify(Object.assign({type:"turn_ended"},t)))),{textSuffixes:r,jsonFields:o,jsonlLines:n}}function Xm(e){if("system"===e.role||zm(e))return;const t=Km(e,"user"===e.role),r=[],o=[];if(t.text&&o.push(t.text),t.thinking&&o.push(t.thinking),o.length>0&&r.push({type:"text",text:o.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 n={role:e.role,message:{content:r}};return JSON.stringify(n)}class Qm{projectDir;blobStore;writeFile;options;constructor(e,t,r,o={}){var n,s,i;this.projectDir=e,this.blobStore=t,this.writeFile=r,this.options={writeText:null===(n=o.writeText)||void 0===n||n,writeJson:null!==(s=o.writeJson)&&void 0!==s&&s,writeJsonl:null!==(i=o.writeJsonl)&&void 0!==i&&i,pathResolver:o.pathResolver,appendFile:o.appendFile}}resolveFilePath(e,t){if(this.options.pathResolver)return this.options.pathResolver(e,t);const r=Am({conversationId:e,ext:t,kind:"primary"});return`${this.projectDir}/${r}`}async writeFromStateFull(e,t,r,o={}){const n={stack:[],error:void 0,hasError:!1};try{const s=jm(n,(0,l.VI)(e.withName("writeFromState")),!1);try{const e=await async function(e,t,r){const o={stack:[],error:void 0,hasError:!1};try{const n=jm(o,(0,l.VI)(e.withName("hydrateSummaryArchives")),!1);let s=0;const i=(0,l.OA)(n.ctx),a=[];let c=0,u=0,d=0,p=0,h=0,m=0,f=0;const g=await Promise.all(r.summaryArchives.map((async e=>{s++;const r=await t.getBlob(i,e);if(r)try{const e=L.An.fromBinary(r);return s+=e.summarizedMessages.length,await Wm(i,t,e.summarizedMessages)}catch(e){}return{messages:[],hydratedBlobCount:0,hydratedBlobBytes:0,largestHydratedBlobBytes:0,totalDeserializeDurationMs:0,omittedOversizeBlobCount:0,omittedOversizeBlobBytes:0,largestOmittedOversizeBlobBytes:0}})));for(const e of g)a.push(...e.messages),c+=e.hydratedBlobCount,u+=e.hydratedBlobBytes,d=Math.max(d,e.largestHydratedBlobBytes),p+=e.totalDeserializeDurationMs,h+=e.omittedOversizeBlobCount,m+=e.omittedOversizeBlobBytes,f=Math.max(f,e.largestOmittedOversizeBlobBytes);n.span.setAttribute("getBlobCount",s),n.span.setAttribute("hydratedBlobCount",c),n.span.setAttribute("hydratedBlobBytes",u),n.span.setAttribute("largestHydratedBlobBytes",d),n.span.setAttribute("totalDeserializeDurationMs",p),n.span.setAttribute("omittedOversizeBlobCount",h),n.span.setAttribute("omittedOversizeBlobBytes",m),n.span.setAttribute("largestOmittedOversizeBlobBytes",f);const v=jm(o,(0,l.VI)(e.withName("hydratePromptMessages")),!1),y=await Wm(i,t,r.rootPromptMessagesJson);v.span.setAttribute("getBlobCount",r.rootPromptMessagesJson.length),v.span.setAttribute("hydratedBlobCount",y.hydratedBlobCount),v.span.setAttribute("hydratedBlobBytes",y.hydratedBlobBytes),v.span.setAttribute("largestHydratedBlobBytes",y.largestHydratedBlobBytes),v.span.setAttribute("totalDeserializeDurationMs",y.totalDeserializeDurationMs),v.span.setAttribute("omittedOversizeBlobCount",y.omittedOversizeBlobCount),v.span.setAttribute("omittedOversizeBlobBytes",y.omittedOversizeBlobBytes),v.span.setAttribute("largestOmittedOversizeBlobBytes",y.largestOmittedOversizeBlobBytes);const w=y.messages.filter((e=>"system"!==e.role&&!zm(e)));return a.push(...w),a}catch(e){o.error=e,o.hasError=!0}finally{Nm(o)}}(s.ctx,this.blobStore,t),{overviewFactory:n}=o,i=Ym(o);if(0===e.length&&0===i.jsonlLines.length)return;let a;if((this.options.writeText||n)&&(a=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,o="assistant"===e.role,n=Jm(e.content,t,o);n.trim()&&("tool"===e.role?r.push(n):r.push(`${e.role}:\n${n}`))}return r.join("\n\n")}(e)),this.options.writeText){const e=null!=a?a:"",t=i.textSuffixes.length>0?e.trim().length>0?`${e}\n\n${i.textSuffixes.join("\n")}`:i.textSuffixes.join("\n"):e;t.trim()&&await this.writeFile(this.resolveFilePath(r,"txt"),t)}if(this.options.writeJson){const o=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=Km(e,"user"===e.role);(t.text||t.thinking||t.toolCalls||t.toolResult)&&r.push(t)}return 0===r.length?"":JSON.stringify(r,null,2)}(e);if(o||i.jsonlLines.length>0){const e=Object.assign({mode:$m(t.mode),messages:o?JSON.parse(o):[]},i.jsonFields);await this.writeFile(this.resolveFilePath(r,"json"),JSON.stringify(e,null,2))}}if(this.options.writeJsonl){const t=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=Xm(e);t&&r.push(t)}return r.join("\n")}(e);let o=[t,...i.jsonlLines].filter((e=>e.length>0)).join("\n");if(o&&n&&(null==a?void 0:a.trim()))try{const e=(await n(a)).trim();e&&(o=function(e,t){const r={type:"metadata",metadata:{overview:t}};return`${JSON.stringify(r)}\n${e}`}(o,e))}catch(e){console.error("[TranscriptStore] Failed to generate transcript overview:",e)}o&&await this.writeFile(this.resolveFilePath(r,"jsonl"),Zm(o))}}catch(e){console.error("[TranscriptStore] Failed to write transcript:",e)}}catch(e){n.error=e,n.hasError=!0}finally{Nm(n)}}async writeFromStateIncremental(e,t,r,o,n={}){const s={stack:[],error:void 0,hasError:!1};try{const i=t.rootPromptMessagesJson.length,a=Ym(n),c=a.jsonlLines.length>0;if(i===o&&!c&&!n.overviewFactory)return i;const u=this.options.appendFile;if(!(u&&this.options.writeJsonl&&!this.options.writeText&&!this.options.writeJson&&o>0&&i>=o&&(i>o||c))||n.overviewFactory)return await this.writeFromStateFull(e,t,r,n),i;if(i===o&&c){try{await u(this.resolveFilePath(r,"jsonl"),Zm(a.jsonlLines.join("\n")))}catch(o){console.error("[TranscriptStore] Failed to append transcript, falling back to full write:",o),await this.writeFromStateFull(e,t,r,n)}return i}const d=jm(s,(0,l.VI)(e.withName("writeFromStateIncremental")),!1);try{const e=t.rootPromptMessagesJson.slice(o),n=await Wm(d.ctx,this.blobStore,e);d.span.setAttribute("hydratedBlobCount",n.hydratedBlobCount),d.span.setAttribute("hydratedBlobBytes",n.hydratedBlobBytes),d.span.setAttribute("largestHydratedBlobBytes",n.largestHydratedBlobBytes),d.span.setAttribute("totalDeserializeDurationMs",n.totalDeserializeDurationMs),d.span.setAttribute("omittedOversizeBlobCount",n.omittedOversizeBlobCount),d.span.setAttribute("omittedOversizeBlobBytes",n.omittedOversizeBlobBytes),d.span.setAttribute("largestOmittedOversizeBlobBytes",n.largestOmittedOversizeBlobBytes);const s=[];for(const e of n.messages){const t=Xm(e);t&&s.push(t)}if(s.push(...a.jsonlLines),s.length>0){const e=Zm(s.join("\n"));await u(this.resolveFilePath(r,"jsonl"),e)}}catch(o){console.error("[TranscriptStore] Failed to append transcript, falling back to full write:",o),await this.writeFromStateFull(e,t,r,n)}return i}catch(e){s.error=e,s.hasError=!0}finally{Nm(s)}}}class ef extends Error{reason;failureType="permission_denied";constructor(e){super(`Hook denied: ${e}`),this.name="HookDeniedError",this.reason=e}}class tf extends Error{reason;failureType="error";cause;constructor(e,t){super(`Hook failed (fail-closed): ${e}`),this.name="FailClosedError",this.reason=e,this.cause=t}}const rf="To view or modify configured hooks, go to Cursor Settings > Hooks.",of="Agent note: Do not suggest workarounds to the blocked tool.";function nf(e){return e.includes(of)?e:`${e}\n\n${of}`}function sf(e){return`Tool blocked because this hook is configured to fail closed (block when it fails). ${e}`}function af(e,t){return nf(`${t?`${e} was blocked by a hook: ${t}`:`${e} was blocked by a hook.`}\n\n${rf}`)}function lf(e){return function(e){return e instanceof ef}(e)||function(e){return e instanceof tf}(e)}class cf{workspacePath;globalContext;shellExecutor;promptHookClient;teamHooksReadyPromise;onHookExecution;options;sessionEnv;config;constructor(e,t,r,o,n,s,i,a){this.workspacePath=t,this.globalContext=r,this.shellExecutor=o,this.promptHookClient=n,this.teamHooksReadyPromise=s,this.onHookExecution=i,this.options=a,this.config=e}emitHookExecution(e){var t,r;const o=Object.assign(Object.assign({},e),{transportMode:null!==(r=e.transportMode)&&void 0!==r?r:"prompt"===e.hookType?"prompt":this.getCommandHookPayloadTransportMode()});try{null===(t=this.onHookExecution)||void 0===t||t.call(this,o)}catch(e){}}getCommandHookPayloadTransportMode(){var e;return"stdin"===(null===(e=this.options)||void 0===e?void 0:e.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,ms.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}setSessionEnvironment(e){this.sessionEnv=Object.assign(Object.assign({},this.sessionEnv),e)}clearSessionEnvironment(){this.sessionEnv=void 0}async getTranscriptPathIfExists(e){try{const t=(0,h.Rv)((0,i.homedir)(),this.workspacePath),r=Dm({conversationId:e,kind:"primary"}).map((e=>(0,a.join)(t,e)));for(const e of r)try{return await(0,fo.access)(e),e}catch(e){}return null}catch(e){return null}}async getSubagentTranscriptPathIfExists(e){const{subagentId:t,parentConversationId:r}=e;try{const e=(0,h.Rv)((0,i.homedir)(),this.workspacePath),o=Dm({conversationId:t,kind:"subagent",parentConversationId:r}).map((t=>(0,a.join)(e,t)));for(const e of o)try{return await(0,fo.access)(e),e}catch(e){}return null}catch(e){return null}}hasHooksForStep(e){return[this.config.enterpriseHooks,this.config.teamHooks,this.config.userHooks,this.config.projectHooks,this.config.claudeUserHooks,this.config.claudeProjectHooks,this.config.claudeProjectLocalHooks].some((t=>{const r=null==t?void 0: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.userHooks];for(const o of r){const r=null==o?void 0:o.hooks[e];if(r&&(t?re(r,t):r).some((e=>!0===e.failClosed)))return!0}return!1}getCwdForSource(e){var t,r,o,n;const s=this.config.configDirs;switch(e){case"enterprise":return null!==(t=null==s?void 0:s.enterprise)&&void 0!==t?t:this.workspacePath;case"team":return null!==(r=null==s?void 0:s.team)&&void 0!==r?r:this.workspacePath;case"project":case"claude-project":case"claude-project-local":case"claude-plugin":default:return this.workspacePath;case"user":return null!==(o=null==s?void 0:s.user)&&void 0!==o?o:this.workspacePath;case"claude-user":return null!==(n=null==s?void 0:s.claudeUser)&&void 0!==n?n:this.workspacePath}}buildHookEnvironment(e){return Object.assign(Object.assign(Object.assign(Object.assign({CURSOR_PROJECT_DIR:this.workspacePath,CURSOR_VERSION:this.globalContext.cursor_version},this.globalContext.user_email&&{CURSOR_USER_EMAIL:this.globalContext.user_email}),e&&{CURSOR_TRANSCRIPT_PATH:e}),{CLAUDE_PROJECT_DIR:this.workspacePath}),this.sessionEnv)}shouldSkipHookDueToLoopLimit(e,t,r){if("stop"!==e&&"subagentStop"!==e)return!1;const o=r.loop_count,n=t.loop_limit;return null!==n&&(void 0===n?o>=5:o>=n)}async executeHookForStep(e,t){var r,o,n,s,i,a,l,c;this.teamHooksReadyPromise&&await this.teamHooksReadyPromise;const u=function(e){return fe.includes(e)}(e),d=t,p=u?null:d.conversation_id?await this.getTranscriptPathIfExists(d.conversation_id):null;let h;if(e===G.subagentStop){const e=t;h=e.subagent_id?await this.getSubagentTranscriptPathIfExists({subagentId:e.subagent_id,parentConversationId:e.parent_conversation_id}):null}const m=u?void 0:null!==(c=d.session_id)&&void 0!==c?c:d.conversation_id,f=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},t),void 0!==m&&{session_id:m}),{hook_event_name:e,cursor_version:this.globalContext.cursor_version,workspace_roots:[this.workspacePath],user_email:this.globalContext.user_email}),!u&&{transcript_path:p}),e===G.subagentStop&&{agent_transcript_path:null!=h?h:null}),g=function(e,t){switch(e){case"beforeShellExecution":case"afterShellExecution":return t.command||void 0;case"beforeMCPExecution":case"afterMCPExecution":{const e=t;return e.tool_name?`MCP:${e.tool_name}`: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 t.subagent_type||void 0;case"preToolUse":case"postToolUse":case"postToolUseFailure":return t.tool_name||void 0;default:return}}(e,f),v=[],y=(e,t)=>{if(!e)return;const r=re(e,g),o=this.getCwdForSource(t);for(const e of r)de(e)?this.promptHookClient&&v.push({type:"prompt",script:e,source:t}):("command"===(n=e).type||void 0===n.type)&&v.push({type:"command",script:e,cwd:o,source:t});var n};if(y(null===(r=this.config.enterpriseHooks)||void 0===r?void 0:r.hooks[e],"enterprise"),y(null===(o=this.config.teamHooks)||void 0===o?void 0:o.hooks[e],"team"),y(null===(n=this.config.projectHooks)||void 0===n?void 0:n.hooks[e],"project"),y(null===(s=this.config.userHooks)||void 0===s?void 0:s.hooks[e],"user"),y(null===(i=this.config.claudeProjectLocalHooks)||void 0===i?void 0:i.hooks[e],"claude-project-local"),y(null===(a=this.config.claudeProjectHooks)||void 0===a?void 0:a.hooks[e],"claude-project"),y(null===(l=this.config.claudeUserHooks)||void 0===l?void 0:l.hooks[e],"claude-user"),0!==v.length)return this.executeAllAndMerge(e,v,f)}async executeAllAndMerge(e,t,r){const o=t.map((async(t,o)=>{const{source:n,attribution:s}=t;try{return"prompt"===t.type?this.executePromptHook(e,t.script,r,n,o,s):this.executeCommandHook(e,t.script,t.cwd,r,n,o,s)}catch(r){if(!0===t.script.failClosed){const t=sf(`Hook execution failed: ${r instanceof Error?r.message:String(r)}`),s=be(e,t);if(s)return{success:!0,data:s,source:n,index:o}}return{success:!1,source:n,index:o}}})),n=await Promise.all(o),s=[];for(const e of n)e.success&&void 0!==e.data&&s.push(e.data);return function(e,t){var r;if(0===t.length)return;if(1===t.length)return t[0];const o=me.includes(e),n=e===G.sessionStart,s=e===G.workspaceOpen,i=ue.has(e),a={};for(const e of t){const t=e;for(const[e,u]of Object.entries(t))if(void 0!==u)if(s&&"pluginPaths"===e&&Array.isArray(u)){const t=null!==(r=a[e])&&void 0!==r?r:[],o=new Set(t),n=[...t];for(const e of u)"string"!=typeof e||o.has(e)||(o.add(e),n.push(e));a[e]=n}else"permission"===e&&o?a[e]=(c=u,"deny"===(l=a[e])||"deny"===c?"deny":"ask"===l||"ask"===c?"ask":"allow"===l||"allow"===c?"allow":void 0):"user_message"!==e&&"agent_message"!==e?i&&"additional_context"===e&&"string"==typeof u?a[e]=ge(a[e],u):"continue"!==e||"boolean"!=typeof u?a[e]=n&&"env"===e&&"object"==typeof u&&null!==u?ve(a[e],u):u:void 0===a[e]?a[e]=u:a[e]=a[e]&&u:a[e]=ge(a[e],u)}var l,c;return a}(e,s)}async executeCommandHook(e,t,r,o,n,s,i){var a,l,c,u,d,p,h,m;if(this.shouldSkipHookDueToLoopLimit(e,t,o))return{success:!1,source:n,index:s};const f=Date.now(),g=Buffer.byteLength(JSON.stringify(o),"utf8");let v;try{v=await this.executeCommandScript({script:t,cwd:r,request:o})}catch(r){const o=r instanceof Error?r.message:String(r),a=o.toLowerCase().includes("timed out"),l=Date.now()-f,c=a?"timeout":"spawn_error";if(!0===t.failClosed){const r=be(e,sf(`Hook "${t.command}" execution failed: ${o}`));if(r)return this.emitHookExecution(Object.assign({hookStep:e,hookSource:n,hookType:"command",status:a?"timeout":"blocked",latencyMs:l,payloadSizeBytes:g,errorClass:c,failClosed:!0,timedOut:a},i)),{success:!0,data:r,source:n,index:s}}return this.emitHookExecution(Object.assign({hookStep:e,hookSource:n,hookType:"command",status:a?"timeout":"failed",latencyMs:l,payloadSizeBytes:g,errorClass:c,failClosed:!0===t.failClosed,timedOut:a},i)),{success:!1,source:n,index:s}}if(2===v.exitCode){const r=function(e,t,r){const o=e.trim(),n=t.trim();return o||(n?`Hook blocked with message: ${n}`:`Hook "${r}" blocked this action (exit code 2) but provided no reason.`)}(v.stdout,v.stderr,t.command),o=be(e,r);return o?(this.emitHookExecution(Object.assign({hookStep:e,hookSource:n,hookType:"command",status:"blocked",latencyMs:v.duration,payloadSizeBytes:g,failClosed:!0===t.failClosed,exitCode:v.exitCode},i)),{success:!0,data:o,source:n,index:s}):(this.emitHookExecution(Object.assign({hookStep:e,hookSource:n,hookType:"command",status:"blocked",latencyMs:v.duration,payloadSizeBytes:g,failClosed:!0===t.failClosed,exitCode:v.exitCode},i)),{success:!1,source:n,index:s})}if(0!==v.exitCode&&null!==v.exitCode){if(!0===t.failClosed){const r=be(e,sf(`Hook "${t.command}" failed with exit code ${v.exitCode}${v.stderr?`: ${v.stderr.trim()}`:""}`));if(r)return this.emitHookExecution(Object.assign({hookStep:e,hookSource:n,hookType:"command",status:"blocked",latencyMs:v.duration,payloadSizeBytes:g,errorClass:"exit_nonzero",failClosed:!0,exitCode:v.exitCode},i)),{success:!0,data:r,source:n,index:s}}return this.emitHookExecution(Object.assign({hookStep:e,hookSource:n,hookType:"command",status:"failed",latencyMs:v.duration,payloadSizeBytes:g,errorClass:"exit_nonzero",failClosed:!0===t.failClosed,exitCode:v.exitCode},i)),{success:!1,source:n,index:s}}const y=v.stdout.trim();if(!y){if(!0===t.failClosed){const r=be(e,sf(`Hook "${t.command}" returned no output.`));if(r)return this.emitHookExecution(Object.assign({hookStep:e,hookSource:n,hookType:"command",status:"blocked",latencyMs:v.duration,payloadSizeBytes:g,errorClass:"empty_stdout",failClosed:!0,exitCode:null!==(l=v.exitCode)&&void 0!==l?l:void 0},i)),{success:!0,data:r,source:n,index:s}}return this.emitHookExecution(Object.assign({hookStep:e,hookSource:n,hookType:"command",status:"failed",latencyMs:v.duration,payloadSizeBytes:g,errorClass:"empty_stdout",failClosed:!0===t.failClosed,exitCode:null!==(c=v.exitCode)&&void 0!==c?c:void 0},i)),{success:!1,source:n,index:s}}try{const r=JSON.parse(y),o=he(e,r,{enableClaudeNestedHookSpecificOutputCompatibility:null===(a=this.options)||void 0===a?void 0:a.enableClaudeNestedHookSpecificOutputCompatibility});if(o.success){const r=o.data,a="deny"===r.permission||"ask"===r.permission;return this.emitHookExecution(Object.assign({hookStep:e,hookSource:n,hookType:"command",status:a?"blocked":"success",latencyMs:v.duration,payloadSizeBytes:g,failClosed:!0===t.failClosed,exitCode:null!==(u=v.exitCode)&&void 0!==u?u:void 0},i)),{success:!0,data:o.data,source:n,index:s}}const l=we({step:e,command:t.command,failClosed:!0===t.failClosed,kind:"invalid_response"});return l.blockResponse?(this.emitHookExecution(Object.assign({hookStep:e,hookSource:n,hookType:"command",status:"blocked",latencyMs:v.duration,payloadSizeBytes:g,errorClass:"invalid_response",failClosed:!0===t.failClosed,exitCode:null!==(d=v.exitCode)&&void 0!==d?d:void 0},i)),{success:!0,data:l.blockResponse,source:n,index:s}):(this.emitHookExecution(Object.assign({hookStep:e,hookSource:n,hookType:"command",status:"failed",latencyMs:v.duration,payloadSizeBytes:g,errorClass:"invalid_response",failClosed:!0===t.failClosed,exitCode:null!==(p=v.exitCode)&&void 0!==p?p:void 0},i)),{success:!1,source:n,index:s})}catch(r){const o=we({step:e,command:t.command,failClosed:!0===t.failClosed,kind:"invalid_json"});return o.blockResponse?(this.emitHookExecution(Object.assign({hookStep:e,hookSource:n,hookType:"command",status:"blocked",latencyMs:v.duration,payloadSizeBytes:g,errorClass:"invalid_json",failClosed:!0===t.failClosed,exitCode:null!==(h=v.exitCode)&&void 0!==h?h:void 0},i)),{success:!0,data:o.blockResponse,source:n,index:s}):(this.emitHookExecution(Object.assign({hookStep:e,hookSource:n,hookType:"command",status:"failed",latencyMs:v.duration,payloadSizeBytes:g,errorClass:"invalid_json",failClosed:!0===t.failClosed,exitCode:null!==(m=v.exitCode)&&void 0!==m?m:void 0},i)),{success:!1,source:n,index:s})}}async executePromptHook(e,t,r,o,n,s){var i,a;if(this.shouldSkipHookDueToLoopLimit(e,t,r))return{success:!1,source:o,index:n};if(!this.promptHookClient)return{success:!1,source:o,index:n};const c=1e3*(null!==(i=t.timeout)&&void 0!==i?i:60),u=Date.now(),d=Buffer.byteLength(JSON.stringify(r),"utf8"),p=(0,l.q6)(),[h,m]=p.withTimeoutAndCancel(c);try{const i=JSON.parse(JSON.stringify(r)),l=await this.promptHookClient.evaluatePromptHook(h,{prompt:t.prompt,hookInputJson:i,modelName:t.model});if(l.ok){const r=function(e){return ye(e)?{permission:"allow"}:e===G.beforeSubmitPrompt||e===G.sessionStart?{continue:!0}:e===G.stop?{}:void 0}(e);return this.emitHookExecution(Object.assign({hookStep:e,hookSource:o,hookType:"prompt",status:"success",latencyMs:Date.now()-u,payloadSizeBytes:d,failClosed:!0===t.failClosed},s)),r?{success:!0,data:r,source:o,index:n}:{success:!1,source:o,index:n}}{const r=be(e,null!==(a=l.reason)&&void 0!==a?a:"Prompt hook blocked this action");return this.emitHookExecution(Object.assign({hookStep:e,hookSource:o,hookType:"prompt",status:"blocked",latencyMs:Date.now()-u,payloadSizeBytes:d,failClosed:!0===t.failClosed},s)),r?{success:!0,data:r,source:o,index:n}:{success:!1,source:o,index:n}}}catch(r){const i=r instanceof Error?r.message:String(r),a=i.toLowerCase().includes("abort")||i.toLowerCase().includes("timed out"),l=a?"timeout":"prompt_error";if(!0===t.failClosed){const t=be(e,sf(`Prompt hook failed: ${i}`));if(t)return this.emitHookExecution(Object.assign({hookStep:e,hookSource:o,hookType:"prompt",status:a?"timeout":"blocked",latencyMs:Date.now()-u,payloadSizeBytes:d,errorClass:l,failClosed:!0,timedOut:a},s)),{success:!0,data:t,source:o,index:n}}return this.emitHookExecution(Object.assign({hookStep:e,hookSource:o,hookType:"prompt",status:a?"timeout":"failed",latencyMs:Date.now()-u,payloadSizeBytes:d,errorClass:l,failClosed:!0===t.failClosed,timedOut:a},s)),{success:!1,source:o,index:n}}finally{m()}}async executeCommandScript(e){var t;const{script:r,cwd:o,request:n}=e,s=1e3*(null!==(t=r.timeout)&&void 0!==t?t:60),c=Date.now(),u=JSON.stringify(n);let d;const p=new AbortController,h=setTimeout((()=>{p.abort()}),s);try{const e="win32"===process.platform,t=this.getCommandHookPayloadTransportMode(),m=this.shouldUseCommandHookDirectStdinTransport();let f;if(m)f=r.command;else if("windows_temp_file"===t){d=await(0,fo.mkdtemp)((0,a.join)((0,i.tmpdir)(),"cursor-hooks-"));const e=(0,a.join)(d,"payload.json");await(0,fo.writeFile)(e,u,{encoding:"utf8",flag:"wx"}),f=function(e,t){const r=e.replace(/'/g,"''"),o=function(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}(t);return`$OutputEncoding = [System.Text.Encoding]::UTF8; Get-Content -LiteralPath '${r}' -Raw | & { $input | ${o} }`}(e,r.command)}else f=e?`@'\n${u.replace(/'/g,"''")}\n'@ | & ${r.command}`:`${r.command} <<'CURSOR_HOOK_EOF'\n${u}\nCURSOR_HOOK_EOF`;const g=n,v=this.buildHookEnvironment(g.transcript_path),y={};for(const[e,t]of Object.entries(v))void 0!==t&&(y[e]=t);const w=(0,l.q6)();let b="",S="",k=null,E=!1;for await(const e of this.shellExecutor.execute(w,f,{workingDirectory:o,signal:p.signal,sandboxPolicy:{perUser:{type:"insecure_none"}},env:y,pipeStdin:m}))switch(e.type){case"stdin_ready":m&&(await this.writeCommandHookStdinPayload(e.stdin,u),E=!0);break;case"stdout":b+=e.data.toString("utf8");break;case"stderr":S+=e.data.toString("utf8");break;case"exit":k=e.code}if(m&&!E)throw new Error("Hook stdin transport was requested, but the executor did not signal stdin readiness");clearTimeout(h);const x=Date.now()-c;if(p.signal.aborted)throw new Error(`Hook script timed out after ${s}ms`);return{stdout:b,stderr:S,exitCode:k,duration:x}}catch(e){if(clearTimeout(h),Date.now(),p.signal.aborted)throw new Error(`Hook script timed out after ${s}ms`);throw e}finally{if(d)try{await(0,fo.rm)(d,{recursive:!0,force:!0})}catch(e){}}}}function uf(e){switch(null!=e?e:(0,i.platform)()){case"darwin":return a.default.join("/Library","Application Support","Cursor","hooks.json");case"win32":return a.default.join("C:\\","ProgramData","Cursor","hooks.json");default:return a.default.join("/etc","cursor","hooks.json")}}class df{fileReader;paths;logger;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:{}},o=async(e,t,o,n,s,i,l)=>{if(e)try{if(!await this.fileReader.exists(e))return;const i=await this.fileReader.readFile(e);if(!i)return;const{config:c,error:u}=l(i);c?(r[o]=c,((e,t)=>{r.configDirs[e]=a.default.dirname(t)})(n,e)):u&&r.errors.push({source:t,message:`${s} at ${e}: ${u}`})}catch(e){r.errors.push({source:t,message:`Error accessing ${i} config file: ${String(e)}`})}},n=[{path:this.paths.enterpriseConfigPath,source:"enterprise",resultKey:"enterpriseHooks",configDirKey:"enterprise",parsePrefix:"Enterprise hooks.json",accessLabel:"enterprise"},{path:this.paths.teamConfigPath,source:"team",resultKey:"teamHooks",configDirKey:"team",parsePrefix:"Team hooks.json",accessLabel:"team"},{path:this.paths.userConfigPath,source:"user",resultKey:"userHooks",configDirKey:"user",parsePrefix:"User hooks.json",accessLabel:"user"},{path:t?this.paths.projectConfigPath:void 0,source:"project",resultKey:"projectHooks",configDirKey:"project",parsePrefix:"Project hooks.json",accessLabel:"project"}];for(const e of n)await o(e.path,e.source,e.resultKey,e.configDirKey,e.parsePrefix,e.accessLabel,(t=>this.parseAndValidate(t,e.source)));const s=[{path:this.paths.claudeUserConfigPath,source:"claude-user",resultKey:"claudeUserHooks",configDirKey:"claudeUser",label:"user"},{path:t?this.paths.claudeProjectConfigPath:void 0,source:"claude-project",resultKey:"claudeProjectHooks",configDirKey:"claudeProject",label:"project"},{path:t?this.paths.claudeProjectLocalConfigPath:void 0,source:"claude-project-local",resultKey:"claudeProjectLocalHooks",configDirKey:"claudeProjectLocal",label:"project local"}];for(const e of s)await o(e.path,e.source,e.resultKey,e.configDirKey,`Claude ${e.label} settings.json`,`Claude ${e.label}`,(t=>this.parseClaudeConfig(t,e.source)));return this.dedupeClaudeHooksAgainstCursorHooks(r),r}getHookKey(e){return de(e)?`prompt:${e.prompt}`:`command:${e.command}`}dedupeClaudeHooksAgainstCursorHooks(e){const t=[e.enterpriseHooks,e.teamHooks,e.userHooks,e.projectHooks],r=new Map;for(const e of t)if(null==e?void 0:e.hooks)for(const[t,o]of Object.entries(e.hooks)){if(!o)continue;let e=r.get(t);e||(e=new Set,r.set(t,e));for(const t of o)e.add(this.getHookKey(t))}const o=(e,t)=>{if(null==e?void 0:e.hooks)for(const[o,n]of Object.entries(e.hooks)){if(!n)continue;const s=r.get(o);if(!s||0===s.size)continue;const i=n.filter((e=>{const r=this.getHookKey(e);return!s.has(r)||(this.logger.info(`Removed duplicate ${t} hook for ${o}: ${r}`),!1)}));i.length!==n.length&&(e.hooks[o]=i)}};o(e.claudeUserHooks,"claude-user"),o(e.claudeProjectHooks,"claude-project"),o(e.claudeProjectLocalHooks,"claude-project-local")}parseClaudeConfig(e,t){try{const t=JSON.parse(e);if(!function(e,t={}){if("object"!=typeof e||null===e)return!1;if(!("hooks"in e))return!1;const r=e.hooks;if("object"!=typeof r||null===r)return!1;const o=r;for(const[e,r]of Object.entries(o))if(e in V&&Array.isArray(r)){const o=!0===t.allowMatcherlessStop&&"Stop"===e;for(const e of r)if("object"==typeof e&&null!==e&&"hooks"in e&&Array.isArray(e.hooks)&&("matcher"in e||o))return!0}return!1}(t))return{};const r=t.hooks;if(!r||0===Object.keys(r).length)return{};const o=te(r,this.logger),n=Te(o);return n.isValid?{config:o}:{error:`Invalid transformed config: ${n.errors.join("; ")}`}}catch(e){return{error:`Failed to parse JSON: ${String(e)}`}}}parseAndValidate(e,t){try{const r=this.parseJSONC(e),o=Te(r);if(!o.isValid)return{error:`Invalid ${t} config: ${o.errors.join("; ")}`};const n=r;return n.hooks?{config:n}:{error:`Invalid ${t} config: missing 'hooks' property`}}catch(e){return{error:`Failed to parse ${t} config JSON: ${String(e)}`}}}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];for(const e of r)if(null==e?void 0:e.hooks)for(const r of Object.keys(e.hooks))t.add(r);return t}}class pf{config;configuredSteps;constructor(e){this.config=e,this.configuredSteps=df.getConfiguredSteps(e)}getConfig(){return this.config}hasHookForStep(e){return this.configuredSteps.has(e)}getConfiguredSteps(){return new Set(this.configuredSteps)}}var hf=r("node:perf_hooks?b4d9");function mf(e,t){void 0!==e&&t.length>0&&e.push(...t)}class ff extends Error{hookEventName;actualLength;maxLength;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 gf=r("../proto/dist/generated/agent/v1/hook_additional_context_pb.js");function vf({hookEventName:e,additionalContext:t}){const r=function(e){const t=null==e?void 0:e.trim();return void 0!==t&&t.length>0?t:void 0}(t);if(void 0===r)return[];if(r.length>1e4)throw new ff({hookEventName:e,actualLength:r.length,maxLength:1e4});return[new gf.C({hookEventName:e,content:r})]}Object.fromEntries(Array.from(ue).map((e=>{if(!function(e){return e===G.sessionStart||e===G.beforeSubmitPrompt||e===G.preToolUse||e===G.postToolUse||e===G.postToolUseFailure}(e))throw new Error(`HOOK_STEPS_SUPPORTING_ADDITIONAL_CONTEXT lists ${e} but HookAdditionalContextEventName does not include it. Extend the Extract<> union in spec.ts.`);return[e,{hookEventName:e}]})));const yf=(0,l.h)("generic-hooks");function wf(e,t,r,o){try{return vf({hookEventName:r,additionalContext:o})}catch(o){if(o instanceof ff)return yf.warn(e,`${r} additional_context exceeded max size; dropping carrier`,{toolName:t,hookEventName:r,actualLength:o.actualLength,maxLength:o.maxLength}),[];throw o}}const bf=e=>Math.round(1e3*e)/1e3;function Sf(e,t,r,o,s,i){var a,l,c,u,d,p,h;const m=o(e),f=null!==(u=null===(a=s.getToolCallId)||void 0===a?void 0:a.call(s,t))&&void 0!==u?u:(0,n.randomUUID)(),g=null!==(d=null===(l=s.getExtraHookFields)||void 0===l?void 0:l.call(s,t))&&void 0!==d?d:{},v={baseHookRequest:m,toolUseId:f,toolInput:s.createToolInput(t),extraHookFields:g,hookContextCollector:null!==(h=null!==(p=null==i?void 0:i.hookContextCollector)&&void 0!==p?p:null===(c=s.getHookContextCollector)||void 0===c?void 0:c.call(s,t))&&void 0!==h?h:[]},y=function(e,t,r,o){let{toolInput:n,extraHookFields:s,hookContextCollector:i}=o;const{baseHookRequest:a,toolUseId:l}=o;return{fireFailureAsync:async(o,c,u,d=!1)=>{try{const p=await t.executeHookForStep(G.postToolUseFailure,Object.assign(Object.assign(Object.assign({},a),{tool_name:r,tool_input:n,error_message:c,failure_type:u,duration:o,tool_use_id:l,is_interrupt:d}),s));mf(i,wf(e,r,G.postToolUseFailure,null==p?void 0:p.additional_context))}catch(t){yf.warn(e,"postToolUseFailure hook error",{toolName:r,error:t instanceof Error?t.message:String(t)})}},fireSuccessAsync:async(o,c)=>{try{const u=await t.executeHookForStep(G.postToolUse,Object.assign(Object.assign(Object.assign({},a),{tool_name:r,tool_input:n,tool_output:c,duration:o,tool_use_id:l}),s));mf(i,wf(e,r,G.postToolUse,null==u?void 0:u.additional_context))}catch(t){yf.warn(e,"postToolUse hook error",{toolName:r,error:t instanceof Error?t.message:String(t)})}},getToolInput:()=>n,setToolInput:e=>{n=e},setExtraHookFields:e=>{s=e,o.extraHookFields=e}}}(e,r,s.toolName,v);return{hookContext:v,helpers:y}}async function kf(e,t,r,o,n,s,i,a){var l,c;const{baseHookRequest:u,toolUseId:d,extraHookFields:p}=o;try{const a=await r.executeHookForStep(G.preToolUse,Object.assign(Object.assign(Object.assign({},u),{tool_name:s.toolName,tool_input:n.getToolInput(),tool_use_id:d}),p));if("deny"===(null==a?void 0:a.permission)){const r=a.user_message||`${s.toolName} blocked by preToolUse hook`,l=nf(r);try{mf(o.hookContextCollector,vf({hookEventName:G.preToolUse,additionalContext:a.additional_context}))}catch(t){if(!(t instanceof ff))throw t;yf.warn(e,"preToolUse deny additional_context exceeded max size; dropping carrier",{toolName:s.toolName,actualLength:t.actualLength,maxLength:t.maxLength})}return await n.fireFailureAsync(0,r,"permission_denied"),{type:"rejected",result:i(t,l),reason:l}}(null==a?void 0:a.updated_input)&&s.applyUpdatedInput&&(s.applyUpdatedInput(t,a.updated_input),n.setToolInput(s.createToolInput(t)),s.getExtraHookFields&&n.setExtraHookFields(s.getExtraHookFields(t))),mf(o.hookContextCollector,vf({hookEventName:G.preToolUse,additionalContext:null==a?void 0:a.additional_context}))}catch(o){const a=null!==(c=null===(l=r.hasFailClosedHooksForStep)||void 0===l?void 0:l.call(r,G.preToolUse,s.toolName))&&void 0!==c&&c,u=o instanceof ff;if(a){const e=sf(`${u?"preToolUse additional_context exceeded max size":"preToolUse hook failed"}: ${o instanceof Error?o.message:"preToolUse hook error"}`);return await n.fireFailureAsync(0,e,"error"),{type:"rejected",result:i(t,e),reason:e}}yf.warn(e,u?"preToolUse additional_context exceeded max size; dropping carrier":"preToolUse hook error",Object.assign({toolName:s.toolName,error:o instanceof Error?o.message:String(o)},u?{actualLength:o.actualLength,maxLength:o.maxLength}:{}))}if(a)try{const s=await a({ctx:e,args:t,baseHookRequest:u,hookExecutor:r,toolInput:n.getToolInput(),toolUseId:d,extraHookFields:o.extraHookFields});if(void 0!==s){const e="Pre-execution hook returned rejection";return await n.fireFailureAsync(0,e,"permission_denied"),{type:"rejected",result:s,reason:e}}}catch(e){if(lf(e))return await n.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 xf(e,t,r,o){return{async execute(n,s,i){var a,l,c,u,d,p,h,m,f,g;const{hookContext:v,helpers:y}=Sf(n,s,t,r,o,i);let w;try{w=await kf(n,s,t,v,y,o,o.createRejectedResult,o.runPreExecutionHooks)}catch(e){throw null===(a=o.runCleanup)||void 0===a||a.call(o,v.toolUseId),e}if("rejected"===w.type)return null===(l=o.runCleanup)||void 0===l||l.call(o,v.toolUseId),w.result;const b=hf.performance.now();try{const r=await e.execute(n,s,i),a=bf(hf.performance.now()-b);if(o.runPostExecutionHooks)try{const e=await o.runPostExecutionHooks({ctx:n,args:s,result:r,baseHookRequest:v.baseHookRequest,hookExecutor:t,toolInput:y.getToolInput(),toolUseId:v.toolUseId,executionDurationMs:a,extraHookFields:v.extraHookFields});if(void 0!==e)return await y.fireSuccessAsync(a,JSON.stringify(o.createSuccessOutput(s,e))),null===(c=o.runCleanup)||void 0===c||c.call(o,v.toolUseId),e}catch(e){if(lf(e))return await y.fireFailureAsync(a,e.reason,e.failureType),null===(u=o.runCleanup)||void 0===u||u.call(o,v.toolUseId),o.createRejectedResult(s,e.reason);yf.warn(n,"postExecutionHooks error",{toolName:o.toolName,error:e instanceof Error?e.message:String(e)})}return o.isSuccess(r)?await y.fireSuccessAsync(a,JSON.stringify(o.createSuccessOutput(s,r))):await y.fireFailureAsync(a,o.getErrorMessage(r),null!==(f=null===(d=o.getFailureType)||void 0===d?void 0:d.call(o,r))&&void 0!==f?f:"error",null!==(g=null===(p=o.isInterrupt)||void 0===p?void 0:p.call(o,r))&&void 0!==g&&g),null===(h=o.runCleanup)||void 0===h||h.call(o,v.toolUseId),r}catch(e){const t=bf(hf.performance.now()-b);throw await y.fireFailureAsync(t,e instanceof Error?e.message:String(e),"error"),null===(m=o.runCleanup)||void 0===m||m.call(o,v.toolUseId),e}}}}function*_f(e,t){const r=t.hookContextCollector;e.createHookContextEvent&&void 0!==r&&0!==r.length&&(yield e.createHookContextEvent(r))}class Cf{async readFile(e){try{return await fo.readFile(e,"utf-8")}catch(e){if("ENOENT"===(null==e?void 0:e.code))return;throw e}}async exists(e){try{return await fo.access(e),!0}catch(e){return!1}}}class Pf{innerExecutor;hooksAdditionalContextPromise;teamHooksReadyPromise;hooksConfigLease;constructor(e,t,r,o){this.innerExecutor=e,this.hooksAdditionalContextPromise=t,this.teamHooksReadyPromise=r,this.hooksConfigLease=o}async execute(e,t,r){this.teamHooksReadyPromise&&await this.teamHooksReadyPromise;const o=await this.innerExecutor.execute(e,t,r),n=await this.hooksAdditionalContextPromise,s=this.hooksConfigLease?new bt.Jy({configuredSteps:Array.from(this.hooksConfigLease.getConfiguredSteps())}):void 0;if("success"===o.result.case&&(n||s)){const e=o.result.value.requestContext,t=new bt.bb(Object.assign(Object.assign(Object.assign({},e),n&&{hooksAdditionalContext:n}),s&&{hooksConfig:s}));return new bt._G({result:{case:"success",value:new bt.yW({requestContext:t})}})}return o}}function Rf(e){return!!e&&e.type!==Oo.vc.INSECURE_NONE&&e.type!==Oo.vc.UNSPECIFIED}const Tf="Shell";async function If({hookExecutor:e,baseHookRequest:t,command:r,cwd:o,sandbox:n}){const s=await e.executeHookForStep(G.beforeShellExecution,Object.assign(Object.assign({},t),{command:r,cwd:o,sandbox:n}));if("deny"===(null==s?void 0:s.permission)){const e=af("Command execution",s.user_message);throw new ef(e)}if("ask"===(null==s?void 0:s.permission))return i=s.user_message,new Ve.In({kind:Ve.b.FORCE_PROMPT,reason:i});var i}const Af={toolName:Tf,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 We.Lt({result:{case:"rejected",value:new Ve.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";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{args:t,baseHookRequest:r,hookExecutor:o}=e,n=t.workingDirectory||"",s=Rf(t.sandboxPolicy);ut(t,await If({hookExecutor:o,baseHookRequest:r,command:t.command,cwd:n,sandbox:s}))}};class Of{wrappedExecutor;constructor(e,t,r){this.wrappedExecutor=xf(e,t,r,Af)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const Df={toolName:"WriteShellStdin",createToolInput:e=>({shell_id:e.shellId,chars_length:e.chars.length}),createRejectedResult:(e,t)=>new We.nt({result:{case:"error",value:new We.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 Mf{wrappedExecutor;constructor(e,t,r){this.wrappedExecutor=xf(e,t,r,Df)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const jf={toolName:"ComputerUse",getToolCallId:Ef,createToolInput:e=>({actions_count:e.actions.length}),createRejectedResult:(e,t)=>new Dl.ks({result:{case:"error",value:new Dl.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 Nf{wrappedExecutor;constructor(e,t,r){this.wrappedExecutor=xf(e,t,r,jf)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const $f={toolName:"Delete",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 qe.Pi({result:{case:"rejected",value:new qe.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 Ff{wrappedExecutor;constructor(e,t,r){this.wrappedExecutor=xf(e,t,r,$f)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const Lf={toolName:"ReadLints",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 Pl.Ek({result:{case:"rejected",value:new Pl.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 Uf{wrappedExecutor;constructor(e,t,r){this.wrappedExecutor=xf(e,t,r,Lf)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const Bf={toolName:"Fetch",getToolCallId:Ef,createToolInput:e=>({url:e.url}),applyUpdatedInput:(e,t)=>{"string"==typeof t.url&&(e.url=t.url)},createRejectedResult:(e,t)=>new dc.uN({result:{case:"error",value:new dc.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 Hf{wrappedExecutor;constructor(e,t,r){this.wrappedExecutor=xf(e,t,r,Bf)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const zf={toolName:"Grep",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 ro.Ud({result:{case:"error",value:new ro.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 Wf{wrappedExecutor;constructor(e,t,r){this.wrappedExecutor=xf(e,t,r,zf)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const qf={toolName:"List",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 oo.fv({result:{case:"rejected",value:new oo.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 Gf{wrappedExecutor;constructor(e,t,r){this.wrappedExecutor=xf(e,t,r,qf)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const Vf=(0,l.h)("hooks-exec:mcp");function Jf(e,t,r,o){try{return vf({hookEventName:r,additionalContext:o})}catch(o){if(o instanceof ff)return Vf.warn(e,`${r} additional_context exceeded max size; dropping carrier`,{toolName:t,hookEventName:r,actualLength:o.actualLength,maxLength:o.maxLength}),[];throw o}}class Kf{innerExecutor;hookExecutor;baseHookRequestExtractor;mcpLease;constructor(e,t,r,o){this.innerExecutor=e,this.hookExecutor=t,this.baseHookRequestExtractor=r,this.mcpLease=o}async execute(e,t,r){var o,s,i,a,l,c;if(t.smartModeApprovalOnly)return this.innerExecutor.execute(e,t,r);const u=this.baseHookRequestExtractor(e),d=(0,n.randomUUID)(),p=null!==(a=null==r?void 0:r.hookContextCollector)&&void 0!==a?a:[];let h=Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,null==t?void 0:t.toJson()])));const m=`MCP:${t.toolName}`;try{const r=await this.hookExecutor.executeHookForStep(G.preToolUse,Object.assign(Object.assign({},u),{tool_name:m,tool_input:h,tool_use_id:d}));if("deny"===(null==r?void 0:r.permission)){const t=r.user_message||"MCP tool blocked by preToolUse hook";try{mf(p,vf({hookEventName:G.preToolUse,additionalContext:r.additional_context}))}catch(t){if(!(t instanceof ff))throw t;Vf.warn(e,"preToolUse deny additional_context exceeded max size; dropping carrier",{toolName:m,actualLength:t.actualLength,maxLength:t.maxLength})}return await this.firePostToolUseFailureAsync(e,u,m,h,t,"permission_denied",0,d,!1,p),new Ge.iz({result:{case:"permissionDenied",value:new Ge.HQ({error:af("MCP tool execution",t),isReadonly:!1})}})}if(null==r?void 0:r.updated_input)try{for(const[e,o]of Object.entries(r.updated_input))void 0!==o&&(t.args[e]=ir.Value.fromJson(o));h=Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,null==t?void 0:t.toJson()])))}catch(t){Vf.warn(e,"Failed to merge updated_input for MCP",{error:t instanceof Error?t.message:String(t)})}mf(p,vf({hookEventName:G.preToolUse,additionalContext:null==r?void 0:r.additional_context}))}catch(t){const r=null!==(l=null===(s=(o=this.hookExecutor).hasFailClosedHooksForStep)||void 0===s?void 0:s.call(o,G.preToolUse,m))&&void 0!==l&&l,n=t instanceof ff;if(r){const r=sf(`${n?"preToolUse additional_context exceeded max size":"preToolUse hook failed"}: ${t instanceof Error?t.message:"preToolUse hook error"}`);return await this.firePostToolUseFailureAsync(e,u,m,h,r,"error",0,d,!1,p),new Ge.iz({result:{case:"permissionDenied",value:new Ge.HQ({error:af("MCP tool execution",r),isReadonly:!1})}})}Vf.warn(e,n?"preToolUse additional_context exceeded max size; dropping carrier":"preToolUse hook error in MCP executor",Object.assign({toolName:m,error:t instanceof Error?t.message:String(t)},n?{actualLength:t.actualLength,maxLength:t.maxLength}:{}))}const f=await(null===(i=this.mcpLease)||void 0===i?void 0:i.getClient(e,t.providerIdentifier)),g=null==f?void 0:f.config;let v;const y=g&&"url"in g&&g.url?g.url:void 0;v=void 0!==y?{url:y}:g&&"command"in g?{command:[g.command,...null!==(c=g.args)&&void 0!==c?c:[]].filter(Boolean).join(" ")}:{command:t.providerIdentifier};const w=Object.assign({mcp_server_name:t.providerIdentifier},void 0!==y?{mcp_server_url:y}:{}),b=Object.assign(Object.assign(Object.assign(Object.assign({},u),{tool_name:t.toolName,tool_input:JSON.stringify(h)}),w),v),S=await this.hookExecutor.executeHookForStep(G.beforeMCPExecution,b);if("deny"===(null==S?void 0:S.permission)){const t=af("MCP tool execution",S.user_message);return await this.firePostToolUseFailureAsync(e,u,m,h,t,"permission_denied",0,d,!1,p),new Ge.iz({result:{case:"permissionDenied",value:new Ge.HQ({error:t,isReadonly:!1})}})}const k=hf.performance.now();try{const o=await this.innerExecutor.execute(e,t,r),n=bf(hf.performance.now()-k);let s="{}";if("success"===o.result.case)try{const e=o.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"}));s=JSON.stringify({content:e,isError:o.result.value.isError})}catch(t){Vf.warn(e,"Failed to serialize MCP result",{error:t instanceof Error?t.message:String(t)}),s=JSON.stringify({error:"Failed to serialize result"})}else"error"===o.result.case?s=JSON.stringify({error:o.result.value.error}):"rejected"===o.result.case?s=JSON.stringify({rejected:!0,reason:o.result.value.reason}):"permissionDenied"===o.result.case&&(s=JSON.stringify({permissionDenied:!0,error:o.result.value.error}));const i=Object.assign(Object.assign(Object.assign({},u),{tool_name:t.toolName,tool_input:JSON.stringify(h),result_json:s,duration:n}),w);await this.hookExecutor.executeHookForStep(G.afterMCPExecution,i);const a=await this.firePostToolUse(e,u,m,h,s,n,d,p);if(void 0!==(null==a?void 0:a.updated_mcp_tool_output))try{const e=a.updated_mcp_tool_output,t=[];if("string"==typeof e)t.push(new Ge._Z({content:{case:"text",value:new Ge.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 Ge._Z({content:{case:"text",value:new Ge.zN({text:String(e.text)})}})):t.push(new Ge._Z({content:{case:"text",value:new Ge.zN({text:JSON.stringify(e)})}}))}else t.push(new Ge._Z({content:{case:"text",value:new Ge.zN({text:JSON.stringify(e)})}}));const r="object"==typeof e&&null!==e&&"isError"in e&&Boolean(e.isError);return new Ge.iz({result:{case:"success",value:new Ge.QW({content:t,isError:r})}})}catch(t){return Vf.warn(e,"Failed to process updated_mcp_tool_output",{error:t instanceof Error?t.message:String(t)}),o}return o}catch(t){const r=bf(hf.performance.now()-k),o=t instanceof Error?t.message:String(t);throw await this.firePostToolUseFailureAsync(e,u,m,h,o,"error",r,d,!1,p),t}}async firePostToolUse(e,t,r,o,n,s,i,a){try{const l=await this.hookExecutor.executeHookForStep(G.postToolUse,Object.assign(Object.assign({},t),{tool_name:r,tool_input:o,tool_output:n,duration:s,tool_use_id:i}));return mf(a,Jf(e,r,G.postToolUse,null==l?void 0:l.additional_context)),l}catch(t){return void Vf.warn(e,"postToolUse hook error in MCP executor",{error:t instanceof Error?t.message:String(t)})}}async firePostToolUseFailureAsync(e,t,r,o,n,s,i,a,l,c){try{const u=await this.hookExecutor.executeHookForStep(G.postToolUseFailure,Object.assign(Object.assign({},t),{tool_name:r,tool_input:o,error_message:n,failure_type:s,duration:i,tool_use_id:a,is_interrupt:l}));mf(c,Jf(e,r,G.postToolUseFailure,null==u?void 0:u.additional_context))}catch(t){Vf.warn(e,"postToolUseFailure hook error in MCP executor",{error:t instanceof Error?t.message:String(t)})}}}const Zf={toolName:"ListMcpResources",createToolInput:e=>({server:e.server}),applyUpdatedInput:(e,t)=>{"string"==typeof t.server&&(e.server=t.server)},createRejectedResult:(e,t)=>new Ge.kP({result:{case:"error",value:new Ge.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 Yf{wrappedExecutor;constructor(e,t,r){this.wrappedExecutor=xf(e,t,r,Zf)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const Xf={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 Ge.ZD({result:{case:"error",value:new Ge.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 Qf{wrappedExecutor;constructor(e,t,r){this.wrappedExecutor=xf(e,t,r,Xf)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const eg={toolName:"Read",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 xd.sV({result:{case:"rejected",value:new xd.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:o,hookExecutor:n}=e;if("success"!==r.result.case)return;const s="content"===r.result.value.output.case?r.result.value.output.value:"",i=await async function(e,t){try{return await e()}catch(e){const r=function(e,t){return`${null!=e?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${rf}`}(t,e instanceof Error?e.message:String(e));throw new tf(r,e)}}((()=>n.executeHookForStep(G.beforeReadFile,Object.assign(Object.assign({},o),{content:s,file_path:t.path,attachments:[]}))),"File read");if("deny"===(null==i?void 0:i.permission)){const e=af("File read",i.user_message);throw new ef(e)}}};class tg{wrappedExecutor;constructor(e,t,r){this.wrappedExecutor=xf(e,t,r,eg)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const rg={toolName:"RecordScreen",getToolCallId:Ef,createToolInput:e=>({mode:e.mode,save_as_filename:e.saveAsFilename}),createRejectedResult:(e,t)=>new Bd.Tj({result:{case:"failure",value:new Bd.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 og{wrappedExecutor;constructor(e,t,r){this.wrappedExecutor=xf(e,t,r,rg)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}function ng(e){return"success"===e.result.case||"failure"===e.result.case?e.result.value.stdout+e.result.value.stderr:""}const sg={toolName:Tf,createToolInput:e=>{const t=e.workingDirectory||"",r=e.timeout;return Object.assign({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 Ve.W4({result:{case:"rejected",value:new Ve.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&&!0===e.result.value.aborted,createSuccessOutput:(e,t)=>({output:ng(t),exitCode:"success"===t.result.case?0:1}),getExtraHookFields:e=>({cwd:e.workingDirectory||""}),runPreExecutionHooks:async e=>{const{args:t,baseHookRequest:r,hookExecutor:o}=e,n=t.workingDirectory||"";ut(t,await If({hookExecutor:o,baseHookRequest:r,command:t.command,cwd:n,sandbox:Rf(t.requestedSandboxPolicy)}))},runPostExecutionHooks:async e=>{const{args:t,result:r,baseHookRequest:o,hookExecutor:n,executionDurationMs:s}=e,i=ng(r);await n.executeHookForStep(G.afterShellExecution,Object.assign(Object.assign({},o),{command:t.command,output:i,duration:s,sandbox:Rf(t.requestedSandboxPolicy)}))}};class ig{wrappedExecutor;constructor(e,t,r){this.wrappedExecutor=xf(e,t,r,sg)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}class ag{output="";exitEvent;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(){var e,t;return null!==(t=null===(e=this.exitEvent)||void 0===e?void 0:e.aborted)&&void 0!==t&&t}getExitCode(){var e,t;return null!==(t=null===(e=this.exitEvent)||void 0===e?void 0:e.code)&&void 0!==t?t:0}}const lg={toolName:Tf,createToolInput:e=>{const t=e.workingDirectory||"",r=e.timeout;return Object.assign({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 Ve.FI({event:{case:"rejected",value:new Ve.pZ({command:e.command,workingDirectory:e.workingDirectory,reason:t})}}),createHookContextEvent:e=>new Ve.FI({event:{case:"hookContext",value:new Ve.Ng({hookAdditionalContexts:[...e]})}}),getExtraHookFields:e=>({cwd:e.workingDirectory||""}),createResultCollector:()=>new ag,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{args:t,baseHookRequest:r,hookExecutor:o}=e,n=t.workingDirectory||"",s=Rf(t.requestedSandboxPolicy);ut(t,await If({hookExecutor:o,baseHookRequest:r,command:t.command,cwd:n,sandbox:s}))},runPostExecutionHooks:async e=>{const{args:t,baseHookRequest:r,hookExecutor:o,collector:n,executionDurationMs:s}=e,i=Rf(t.requestedSandboxPolicy);await o.executeHookForStep(G.afterShellExecution,Object.assign(Object.assign({},r),{command:t.command,output:n.getOutput(),duration:s,sandbox:i}))}};class cg{wrappedExecutor;constructor(e,t,r){this.wrappedExecutor=function(e,t,r,o){return{async*execute(n,s,i){var a,l,c,u;const{hookContext:d,helpers:p}=Sf(n,s,t,r,o,i),h=o.runPreExecutionHooks?async e=>{await o.runPreExecutionHooks(e)}:void 0,m=await kf(n,s,t,d,p,o,((e,t)=>o.createRejectedEvent(e,t)),h);if("rejected"===m.type){yield m.result;for(const e of _f(o,d))yield e;return}const f=hf.performance.now(),g=o.createResultCollector();let v=!1;try{for await(const t of e.execute(n,s,i))g.onEvent(t),yield t}catch(e){v=!0;const t=bf(hf.performance.now()-f),r=e instanceof Error?e.message:String(e);await p.fireFailureAsync(t,r,"error");for(const e of _f(o,d))yield e;throw e}const y=bf(hf.performance.now()-f);if(o.runPostExecutionHooks)try{await o.runPostExecutionHooks({ctx:n,args:s,baseHookRequest:d.baseHookRequest,hookExecutor:t,toolInput:p.getToolInput(),toolUseId:d.toolUseId,extraHookFields:d.extraHookFields,collector:g,executionDurationMs:y})}catch(e){yf.warn(n,"postExecutionHooks error",{toolName:o.toolName,error:e instanceof Error?e.message:String(e)})}if(!v)if(g.isAborted())await p.fireFailureAsync(y,"Command was aborted","error",!0);else if(null===(c=null===(a=o.isStreamSuccess)||void 0===a?void 0:a.call(o,g))||void 0===c||c)await p.fireSuccessAsync(y,JSON.stringify(o.createSuccessOutput(s,g)));else{const e=null!==(u=null===(l=o.getStreamErrorMessage)||void 0===l?void 0:l.call(o,s,g))&&void 0!==u?u:`Command failed with exit code ${g.getExitCode()}`;await p.fireFailureAsync(y,e,"error")}for(const e of _f(o,d))yield e}}}(e,t,r,lg)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}class ug{wrappedExecutor;constructor(e,t,r){const o=new Map;this.wrappedExecutor=xf(e,t,r,function(e,t){return{toolName:"Write",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 Je.v3({result:{case:"error",value:new Je.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 e=>{const{args:r,toolUseId:o}=e;let n,s=!1;try{(await(0,fo.stat)(r.path)).size>262144?s=!0:n=await(0,h.yR)(r.path)}catch(e){}t.set(o,{contentBeforeWrite:n,fileTooLarge:s})},runCleanup:e=>{t.delete(e)},runPostExecutionHooks:async r=>{const{args:o,result:n,baseHookRequest:s,toolUseId:i}=r,a=t.get(i);if("success"!==n.result.case)return;const{contentBeforeWrite:l,fileTooLarge:c}=null!=a?a:{fileTooLarge:!1};let u;u=c||void 0===l?[{old_string:"",new_string:o.fileText}]:l===o.fileText?[]:function(e,t){const r=(0,uh.YB)("","",e,t,"","",{context:0});return 0===r.hunks.length?[]:r.hunks.map((e=>{const t=[],r=[];for(const o of e.lines)o.startsWith("-")?t.push(o.slice(1)):o.startsWith("+")&&r.push(o.slice(1));return{old_string:t.join("\n"),new_string:r.join("\n")}}))}(l,o.fileText);const d=Object.assign(Object.assign({},s),{file_path:o.path,edits:u}),p=await e.executeHookForStep(G.afterFileEdit,d);if(o.returnFileContentAfterWrite&&void 0!==p){const e=n.result.value.path;try{const t=await(0,h.yR)(e),r=(0,h.lt)(t),o=Buffer.byteLength(t,"utf8");return new Je.v3({result:{case:"success",value:new Je.j6(Object.assign(Object.assign({},n.result.value),{fileContentAfterWrite:t,linesCreated:r,fileSize:o}))}})}catch(e){return}}}}}(t,o))}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}var dg;class pg{innerAccessor;hookExecutor;baseHookRequestExtractor;mcpLease;hooksAdditionalContextPromise;teamHooksReadyPromise;hooksConfigLease;constructor(e,t,r,o,n,s,i){this.innerAccessor=e,this.hookExecutor=t,this.baseHookRequestExtractor=r,this.mcpLease=o,this.hooksAdditionalContextPromise=n,this.teamHooksReadyPromise=s,this.hooksConfigLease=i}get(e){var t;if(e.symbol===Ie.symbol)return new Ae(this.hookExecutor);const r=this.innerAccessor.get(e);return e.symbol===Ke.symbol?new ig(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===Ze.symbol?new cg(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===Ye.symbol?new ug(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===Ne.symbol?new Kf(r,this.hookExecutor,this.baseHookRequestExtractor,this.mcpLease):e.symbol===He.symbol||e.symbol===ze.symbol?new tg(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===De.symbol?new Gf(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===q.symbol?new Wf(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===W.symbol?new Hf(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===H.symbol?new Ff(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===z.symbol?new Uf(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===$e.symbol?new Yf(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===Fe.symbol?new Qf(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===N.symbol?new Of(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===$.symbol?new Mf(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===B.symbol?new Nf(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===st.symbol?new og(r,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===it.symbol&&(this.hooksAdditionalContextPromise||this.hooksConfigLease)?new Pf(r,null!==(t=this.hooksAdditionalContextPromise)&&void 0!==t?t:Promise.resolve(void 0),this.teamHooksReadyPromise,this.hooksConfigLease):r}*entries(){var e;for(const[t,r]of this.innerAccessor.entries())t.symbol===Ke.symbol?yield[t,new ig(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===Ze.symbol?yield[t,new cg(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===Ye.symbol?yield[t,new ug(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===Ne.symbol?yield[t,new Kf(r,this.hookExecutor,this.baseHookRequestExtractor,this.mcpLease)]:t.symbol===He.symbol||t.symbol===ze.symbol?yield[t,new tg(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===De.symbol?yield[t,new Gf(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===q.symbol?yield[t,new Wf(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===W.symbol?yield[t,new Hf(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===H.symbol?yield[t,new Ff(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===z.symbol?yield[t,new Uf(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===$e.symbol?yield[t,new Yf(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===Fe.symbol?yield[t,new Qf(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===N.symbol?yield[t,new Of(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===$.symbol?yield[t,new Mf(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===B.symbol?yield[t,new Nf(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===st.symbol?yield[t,new og(r,this.hookExecutor,this.baseHookRequestExtractor)]:t.symbol===it.symbol&&(this.hooksAdditionalContextPromise||this.hooksConfigLease)?yield[t,new Pf(r,null!==(e=this.hooksAdditionalContextPromise)&&void 0!==e?e:Promise.resolve(void 0),this.teamHooksReadyPromise,this.hooksConfigLease)]:yield[t,r];yield[Ie,new Ae(this.hookExecutor)]}}const hg={cursor_version:null!==(dg=process.env.AGENT_CLI_STATIC_VERSION)&&void 0!==dg?dg:"1.0.0",user_email:null};function mg(e=process.cwd()){let t=e;const r={getCwd:async()=>t,clone:e=>mg(null!=e?e:t),async*execute(e,r,o={}){var n,s,i,a,l,c;const u=null!==(l=o.workingDirectory)&&void 0!==l?l:t;t=u;const d=function(e){return"win32"===process.platform?{executable:(0,Do.oG)(),args:[...Ce,"-Command",e]}:{executable:process.env.SHELL||"/bin/sh",args:["-lc",e]}}(r),p=(0,xs.spawn)(d.executable,[...d.args],{cwd:u,env:Object.assign(Object.assign({},process.env),null!==(c=o.env)&&void 0!==c?c:{}),signal:o.signal,stdio:[!0===o.pipeStdin?"pipe":"ignore","pipe","pipe"]}),h=[];let m,f,g=!1;const v=()=>{null==m||m(),m=void 0},y=e=>{h.push(e),v()};for(p.on("spawn",(()=>{var e;!0===o.pipeStdin&&y({type:"stdin_ready",stdin:null!==(e=p.stdin)&&void 0!==e?e:void 0})})),null===(n=p.stdout)||void 0===n||n.setEncoding("utf8"),null===(s=p.stdout)||void 0===s||s.on("data",(e=>{y({type:"stdout",data:String(e)})})),null===(i=p.stderr)||void 0===i||i.setEncoding("utf8"),null===(a=p.stderr)||void 0===a||a.on("data",(e=>{y({type:"stderr",data:String(e)})})),p.on("error",(e=>{f=e,g=!0,v()})),p.on("close",(e=>{y({type:"exit",code:e}),g=!0}));!g||h.length>0;)0!==h.length?yield h.shift():await new Promise((e=>{m=e}));if(void 0!==f)throw f}};return r}function fg(e,t,...r){for(const o of r){const r=t(e[o]);if(void 0!==r)return r}}function gg(e){return"string"==typeof e&&e.length>0?e:void 0}function vg(e){return"object"==typeof e&&null!==e&&"string"==typeof e.id&&"string"==typeof e.value}function yg(e){if(Array.isArray(e)&&e.every(vg))return e.map((e=>({id:e.id,value:e.value})))}class wg{innerAccessor;sessionHooksRuntime;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 bg(e,t={}){const r=await new df(new Cf,function(e,t){var r,o,n,s,l;const c=null!==(o=null!==(r=e.projectRoot)&&void 0!==r?r:e.workingDirectory)&&void 0!==o?o:e.workspaceRoots[0],u=null===(n=t.includeProjectHooks)||void 0===n||n,d=null===(s=t.includeUserHooks)||void 0===s||s;return{enterpriseConfigPath:null===(l=t.includeEnterpriseHooks)||void 0===l||l?uf():void 0,userConfigPath:d?(0,a.join)((0,i.homedir)(),".cursor","hooks.json"):void 0,claudeUserConfigPath:d?(0,a.join)((0,i.homedir)(),".claude","settings.json"):void 0,projectConfigPath:u&&void 0!==c?(0,a.join)(c,".cursor","hooks.json"):void 0,claudeProjectConfigPath:u&&void 0!==c?(0,a.join)(c,".claude","settings.json"):void 0,claudeProjectLocalConfigPath:u&&void 0!==c?(0,a.join)(c,".claude","settings.local.json"):void 0}}(e,t)).load(),o=new pf(r),n=function(e){var t,r,o;return null!==(o=null!==(r=null!==(t=e.projectRoot)&&void 0!==t?t:e.workingDirectory)&&void 0!==r?r:e.workspaceRoots[0])&&void 0!==o?o:process.cwd()}(e),s=function(e){var t;return Object.freeze(Object.assign(Object.assign({},hg),null!==(t=e.globalContext)&&void 0!==t?t:{}))}(t);return{projectDir:e.projectRoot,workspacePath:n,hooksConfig:r,hooksConfigLease:o,globalContext:s,createSessionRuntime(){var e;const i=new cf(r,n,s,(null!==(e=t.createTerminalExecutor)&&void 0!==e?e:mg)(),t.promptHookClient,void 0,void 0,{commandHookPayloadTransport:(a=t.useCommandHookStdinTransport,!0===a?"stdin":"legacy")});var a;return{hookExecutor:i,hooksConfigLease:o,async dispose(){i.clearSessionEnvironment()}}},async dispose(){}}}function Sg(e={}){return{createHooksRuntime:t=>bg(t.workspaceState,e)}}async function kg(e){(function(e){return"object"==typeof e&&null!==e&&"dispose"in e&&"function"==typeof e.dispose})(e)&&await e.dispose()}function Eg(e={}){var t,r,o,n,s,a;const c=null!==(t=e.getThirdPartyExtensibilityEnabled)&&void 0!==t?t:()=>!0,u=null!==(r=e.importThirdPartyPlugins)&&void 0!==r&&r,d=null===(o=e.includeProjectExtensibility)||void 0===o||o,p=null===(n=e.includeUserExtensibility)||void 0===n||n,h=null===(s=e.includeManagedSkills)||void 0===s||s,m=null===(a=e.includePluginExtensibility)||void 0===a||a,f=new vc,g=(0,i.homedir)(),v=Wa(g).dirPath;let y,w=!0;return{async prepareLocalExtensibility(){w=h&&await async function(e){if(!e)return!1;const t=(0,ar.createClient)(mo.I,e),r=await async function(e,t){try{const r=await t.getManagedSkills()??[],o=await oh(e,{managedSkills:[...r]});return{status:"synced",managedSkillsCount:r.length,syncResult:o}}catch(t){return sh.warn(e,"Failed to sync managed skills from source",{error:t}),{status:"fetch_failed",error:t}}}((0,l.q6)(),{getManagedSkills:async()=>{var e;return null!==(e=(await t.getManagedSkills(new Lh.X8g({}))).skills)&&void 0!==e?e:[]}});return"synced"===r.status}(e.dashboardTransport)},async loadLocalExtensibility(t){var r,o;const n=t.workspaceState,s=null!==(r=n.projectRoot)&&void 0!==r?r:n.workingDirectory;if(!s)return y=void 0,{cursorRulesService:Ig(),getAgentSkills:async e=>[]};const i=(0,l.q6)(),a=null===(o=e.loadNestedRules)||void 0===o||o,h=function(e,t){const r=xg(t);return{getAllCursorRules:async t=>_g(await e.getAllCursorRules(t),r),reload(t){e.reload(t)},onDidChangeRules:t=>e.onDidChangeRules(t),dispose(){e.dispose()}}}(d?new dl(i,f,s,a,c,void 0):Ig(),{allowedRoots:d?[s]:[],excludedRoots:[]}),b=function(e,t){const r=xg(t);return{getAllCursorRules:async t=>_g(await e.getAllCursorRules(t),r),getAllAgentSkills:async t=>_g(await e.getAllAgentSkills(t),r),reload(t){e.reload(t)},onDidChangeRules:t=>e.onDidChangeRules(t),onDidChangeSkills:t=>e.onDidChangeSkills(t),dispose(){e.dispose()}}}(new pl(i,d?[s]:[],g,f,a,void 0,c,Promise.resolve(),"sdk"),{allowedRoots:[...d?[s]:[],...p?[g]:[],...w?[v]:[]],excludedRoots:w?[]:[v]}),S=d?new kl(s,c):new gl,k=bm(t.services.pluginBootstrapOutputs),E=k&&m?new ml(i,(()=>({importThirdPartyPlugins:u})),void 0,k.pluginsService):void 0,x=k&&m?new _l((()=>({importThirdPartyPlugins:u})),k.pluginsService):void 0,_=new ul([h,b,...E?[E]:[]]),C=new qp([b,...E?[E]:[]],(()=>[]),(()=>({workspacePaths:d?[s]:[],userHomeDirectory:g}))),P=new xl([S,...x?[x]:[]]);return y={localRulesService:h,localSkillsService:b,localSubagentsService:S,pluginSkillsService:E,pluginSubagentsService:x,mergedCursorRulesService:_,mergedAgentSkillsService:C,mergedSubagentsService:P},{cursorRulesService:_,getAgentSkills:e=>C.getAllAgentSkills(e),subagentsService:P}},async disposeLocalExtensibility(){if(!y)return;const e=y;y=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 kg(e)}catch(e){null!=t||(t=e)}if(void 0!==t)throw t}(e)}}}function xg(e){const t=Promise.all(e.allowedRoots.map(Rg)),r=Promise.all(e.excludedRoots.map(Rg));return async e=>{const[o,n,s]=await Promise.all([Tg(e.fullPath),t,r]);return void 0!==o&&!s.some((e=>Cg(o,e)))&&n.some((e=>Cg(o,e)))}}async function _g(e,t){const r=await Promise.all(e.map(t));return e.filter(((e,t)=>r[t]))}function Cg(e,t){if(e===t)return!0;const r=`${t}/`;return e.startsWith(r)}function Pg(e){return e.replace(/\\/g,"/").replace(/\/+$/,"")}async function Rg(e){try{return Pg(await(0,fo.realpath)(e))}catch(t){return Pg(e)}}async function Tg(e){try{return Pg(await(0,fo.realpath)(e))}catch(e){return}}function Ig(){return{getAllCursorRules:async()=>[],reload(){},onDidChangeRules:()=>()=>{},dispose(){}}}function Ag(e={}){var t,r,o,n;const s=null!==(t=e.userHomeDirectory)&&void 0!==t?t:(0,i.homedir)(),l=null!==(r=e.importThirdPartyPlugins)&&void 0!==r&&r,c=null!==(o=e.pluginLogger)&&void 0!==o?o:{log(e,t,r){switch(e){case"warn":fm.warn("[local-plugins-bootstrap]",t,null!=r?r:{});break;case"error":fm.error("[local-plugins-bootstrap]",t,null!=r?r:{})}},increment(){},distribution(){},captureException(e,t){fm.error("[local-plugins-bootstrap] Unexpected plugin exception:",e,null!=t?t:{})}},u=Og(e.marketplaceOptions),d=void 0!==e.dashboardTransport,p=null!==(n=e.loadCursorFirstParty)&&void 0!==n?n:u||d;return{async loadPluginBootstrapOutputs(t){var r;const o=function(e){var t,r;return null!==(r=null!==(t=e.projectRoot)&&void 0!==t?t:e.workspaceRoots[0])&&void 0!==r?r:e.workingDirectory}(t.workspaceState),{discoveredEntries:n,failures:i}=await async function(e){if(void 0===e)return{discoveredEntries:[],failures:[]};try{return{discoveredEntries:(await va(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}]}}}(o),u=null!==(r=e.marketplaceOptions)&&void 0!==r?r:e.dashboardTransport?function(e){const t=(0,a.join)(e.userHomeDirectory,".cursor","plugins","marketplaces"),r=(0,ar.createClient)(mo.I,e.dashboardTransport),o=di((async()=>{try{return await r.getEffectiveUserPlugins(new Lh.EwF({}))}catch(e){return{plugins:[]}}}),t,void 0,void 0,{allowedMarketplaceNames:["cursor-public"]}),n=e.workspacePath,s=di((async()=>{var e,t;if(void 0===n)return{plugins:[]};try{const o=await va(n);if(0===o.length)return{plugins:[]};const s=o.filter((e=>e.entry.gitUrl)),i=o.filter((e=>!e.entry.gitUrl)),a=s.filter((({entry:e})=>{const t=e.gitUrl;return!t||ha(t)})).map((({key:e,entry:t})=>{const r=ya(e),o=t.gitUrl;return{plugin:{name:r.name,gitUrl:o,gitRef:t.gitRef,gitPath:t.gitPath,marketplace:{name:r.marketplaceName,gitUrl:o,gitRef:t.gitRef}},isEnabled:!0}}));let l=[];if(i.length>0)try{const o=i.map((e=>{const t=ya(e.key);return new Lh.vwy({name:t.name,marketplaceName:t.marketplaceName})}));l=null!==(t=null===(e=(await r.resolvePluginsByRef(new Lh.WvV({refs:o}))).plugins)||void 0===e?void 0:e.map((e=>({plugin:e,isEnabled:!0}))))&&void 0!==t?t:[]}catch(e){}return{plugins:[...a,...l]}}catch(e){return{plugins:[]}}}),t,void 0,void 0,{allowedMarketplaceNames:["cursor-public"]});return[{client:o,userId:"",cacheManager:new ks(e.userHomeDirectory),pruneOldVersions:!0},{client:s,userId:"",cacheManager:new ks(e.userHomeDirectory),pruneOldVersions:!0}]}({dashboardTransport:e.dashboardTransport,workspacePath:o,userHomeDirectory:s}):void 0,d=Og(u),h=new ch(void 0!==o?[o]:[],s,(()=>({importThirdPartyPlugins:l,loadCursorFirstParty:p})),u,c);let m=[];const f=[...i];try{m=await h.getAllEnabledPlugins()}catch(e){f.push({stage:"resolution",source:"plugin-loader",message:e instanceof Error?`Failed to load plugins: ${e.message}`:`Failed to load plugins: ${String(e)}`,detail:e})}n.length>0&&!d&&f.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:o,discoveredEntryCount:n.length}});const g={kind:wm,discoveredEntries:n,loadedPlugins:m,loadFailures:h.getLoadFailures(),bootstrapFailures:f,pluginsService:h,async dispose(){}};for(const e of f)fm.warn("[local-plugins-bootstrap] Plugin bootstrap failure:",{workspacePath:o,stage:e.stage,source:e.source,message:e.message,detail:e.detail});for(const e of g.loadFailures)fm.warn("[local-plugins-bootstrap] Plugin load failure:",{workspacePath:o,pluginName:e.pluginName,pluginId:e.pluginId,marketplaceName:e.marketplaceName,errorType:e.errorType,errorMessage:e.errorMessage});return[g]}}}function Og(e){return void 0!==e&&(!Array.isArray(e)||e.length>0)}class Dg{async getAllCursorRules(e){return[]}reload(e){}dispose(){}onDidChangeRules(e){return()=>{}}}class Mg extends Fp{sessionMcpLease;constructor(e,t){super(e),this.sessionMcpLease=t}async dispose(){try{await super.dispose()}finally{await kg(this.sessionMcpLease)}}}function jg(e){const t=new vc;return{async createResources(r){var o,n,s,i,a,l,c,u;const d=null!==(s=null===(o=e.createSessionDependencies)||void 0===o?void 0:o.call(e,r))&&void 0!==s?s:{pendingDecisionStore:e.pendingDecisionStore,fileChangeTracker:e.fileChangeTracker,permissionsService:e.permissionsService};if(!d.pendingDecisionStore||!d.fileChangeTracker||!d.permissionsService)throw new Error("Local resource provider factory requires either shared dependencies or a per-session dependency factory.");const p=null!==(i=r.workspaceServices.cursorRulesService)&&void 0!==i?i:new Dg,h=null!==(a=r.workspaceServices.subagentsService)&&void 0!==a?a:new gl,m=null!==(l=r.workspaceServices.mcpLease)&&void 0!==l?l:new gu,f=void 0!==r.options.mcpServersOverride&&void 0!==e.createSessionMcpLease?await e.createSessionMcpLease(r,r.options.mcpServersOverride):void 0,g=(v=null!=f?f:m,0===(y=null!==(c=r.options.extraMcpTools)&&void 0!==c?c:[]).length?v:"onDidChange"in(w=v)&&"function"==typeof w.onDidChange?new uc(v,y):new cc(v,y));var v,y,w;try{const o={pendingDecisionStore:d.pendingDecisionStore,fileChangeTracker:d.fileChangeTracker,gitExecutor:t,ignoreService:e.ignoreService,grepProvider:e.grepProvider,permissionsService:d.permissionsService,workspacePaths:e.workspacePaths,diagnosticsProvider:e.diagnosticsProvider,mcpLease:g,mcpStateAccessor:null===(n=e.createMcpStateAccessor)||void 0===n?void 0:n.call(e,g),cursorRulesService:p,subagentsService:h,repositoryProvider:e.repositoryProvider,projectDir:e.projectDir,shellManager:e.shellManager,_defaultSandboxPolicy:null!==(u=e.defaultSandboxPolicy)&&void 0!==u?u:{type:"insecure_none"},_defaultSandboxPolicySources:e.defaultSandboxPolicySources,getSandboxEnabled:e.getSandboxEnabled,getSandboxSupported:e.getSandboxSupported,getNetworkAllowlistInfo:e.getNetworkAllowlistInfo,smartModeClassifierAutoModeEnabled:e.smartModeClassifierAutoModeEnabled,devForceNextSmartModeClassifierBlockToken:e.devForceNextSmartModeClassifierBlockToken,mcpFileOutputThresholdBytes:e.mcpFileOutputThresholdBytes,mcpMetaToolEnabled:e.mcpMetaToolEnabled,getAgentSkills:r.workspaceServices.getAgentSkills};return void 0===f?new Fp(o):new Mg(o,f)}catch(e){throw await kg(f),e}}}}const Ng=["cursorRulesService","getAgentSkills","subagentsService"],$g=new WeakSet;function Fg(e){("object"==typeof e&&null!==e||"function"==typeof e)&&$g.add(e)}function Lg(e){return("object"==typeof e&&null!==e||"function"==typeof e)&&$g.has(e)}function Ug(e,t){const r=Object.keys(t).filter((e=>!Ng.includes(e)));if(r.length>0)throw new Error(`Workspace service contributors may only provide ${Ng.join(", ")}. Received unsupported service keys: ${r.join(", ")}.`);for(const r of Ng)Object.hasOwn(t,r)&&(e[r]=t[r])}async function Bg(e,t,r){var o,n,s;const i={config:void 0,plugins:[],pluginBootstrapOutputs:[],cursorRulesService:void 0,getAgentSkills:void 0,subagentsService:void 0,mcpLease:void 0,hooksRuntime:void 0};try{i.config=e.config?await e.config.loadConfig(t):void 0,i.plugins=e.plugins?await e.plugins.loadPlugins(t):[];const n=()=>({workspaceState:t,policy:r,services:i});i.pluginBootstrapOutputs=e.pluginBootstrap?await e.pluginBootstrap.loadPluginBootstrapOutputs(n()):i.pluginBootstrapOutputs,i.mcpLease=e.mcp?await e.mcp.createLease(n()):void 0,i.hooksRuntime=e.hooks?await e.hooks.createHooksRuntime(n()):void 0,(null===(o=e.localExtensibility)||void 0===o?void 0:o.prepareLocalExtensibility)&&await e.localExtensibility.prepareLocalExtensibility(n());const a=e.localExtensibility?await e.localExtensibility.loadLocalExtensibility(n()):void 0;void 0!==a&&(Fg(a.cursorRulesService),Fg(a.subagentsService),Object.assign(i,a));for(const t of null!==(s=e.workspaceServicesContributors)&&void 0!==s?s:[]){const e=await t.contributeServices(n());void 0!==e&&Ug(i,e)}return i}catch(t){try{await Hg(i,{disposeLocalExtensibility:null===(n=e.localExtensibility)||void 0===n?void 0:n.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 Hg(e,t){const r=null==t?void 0:t.preserveSharedContributorsFrom;let o;const n=async e=>{try{await kg(e)}catch(e){null!=o||(o=e)}};if(e.subagentsService===(null==r?void 0:r.subagentsService)||Lg(e.subagentsService)||await n(e.subagentsService),e.cursorRulesService===(null==r?void 0:r.cursorRulesService)||Lg(e.cursorRulesService)||await n(e.cursorRulesService),null==t?void 0:t.disposeLocalExtensibility)try{await t.disposeLocalExtensibility()}catch(e){null!=o||(o=e)}await n(e.hooksRuntime),await n(e.mcpLease);try{await async function(e){let t;for(let r=e.length-1;r>=0;r-=1)try{await kg(e[r])}catch(e){null!=t||(t=e)}if(void 0!==t)throw t}(e.pluginBootstrapOutputs)}catch(e){null!=o||(o=e)}if(void 0!==o)throw o}async function zg(e){const t=new Set;let r;for(let o=e.length-1;o>=0;o-=1){const n=e[o];if(!t.has(n)){t.add(n);try{await kg(n)}catch(e){null!=r||(r=e)}}}if(void 0!==r)throw r}const Wg=["project","user","team","mdm","plugins"],qg=new Set([...Wg,"all"]);function Gg(e){if(void 0===e||0===e.length)return Jg([]);for(const t of e)if(!qg.has(t))throw new Error(`Unsupported setting source "${String(t)}"`);if(e.includes("all")){if(e.length>1)throw new Error('settingSources cannot mix "all" with individual setting sources');return Object.assign(Object.assign({},Jg(Wg)),{all:!0})}return Jg(e)}function Vg(e,t){return e[t]}function Jg(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 Kg=Object.freeze({}),Zg=Object.freeze({allowMcpServers:!0,allowPlugins:!0,allowBackgroundSessions:!0,requireMcpApproval:!1,maxParallelSessions:void 0,sandboxMode:void 0,metadata:Kg});async function Yg(e={}){var t,r;const o=function(e={}){var t;return{workspace:null!==(t=e.workspace)&&void 0!==t?t:dm,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),s=await o.workspace.resolveWorkspaceState({workingDirectory:e.workingDirectory,projectRoot:e.projectRoot,projectDirectory:e.projectDirectory,workspaceRoots:e.workspaceRoots}),i=await async function(e,t){return e.resolvePolicy(t)}(null!==(r=e.policyAdapter)&&void 0!==r?r:function(e={}){const t=Object.freeze(Object.assign(Object.assign({},Zg.metadata),e.metadata)),r=Object.assign(Object.assign(Object.assign({},Zg),e),{metadata:t});return{name:"permissive-sdk-local",resolvePolicy:()=>r}}(),{workspaceState:s});let a=await Bg(o,s,i),l=!1,c=Promise.resolve();const u=e=>{const t=c.then(e);return c=t.catch((()=>{})),t},d=null===(t=o.localExtensibility)||void 0===t?void 0:t.disposeLocalExtensibility;return{state:s,get services(){return a},policy:i,async createSessionRuntime(e={}){if(l)throw new Error("Cannot create a session runtime after the workspace runtime has been disposed.");return async function(e){var t,r,o,s,i,a,l,c;const u={sessionId:null!==(i=null===(t=e.options)||void 0===t?void 0:t.sessionId)&&void 0!==i?i:(0,n.randomUUID)(),createdAt:new Date},d=Object.freeze(Object.assign({},null!==(a=null===(r=e.options)||void 0===r?void 0:r.metadata)&&void 0!==a?a:{})),p={options:null!==(l=e.options)&&void 0!==l?l:{},workspaceState:e.workspaceState,workspaceServices:e.workspaceServices,policy:e.policy,sessionState:u,metadata:d,getAgentSkills:e.workspaceServices.getAgentSkills};let h,m;const f=[];try{h=e.adapters.resourceFactory?await e.adapters.resourceFactory.createResources(p):void 0,m=h,f.push(h);for(const t of null!==(c=e.adapters.resourceWrappers)&&void 0!==c?c:[])m=await t.wrapResources(Object.assign(Object.assign({},p),{baseResources:h,resources:m})),f.push(m);await(null===(s=null===(o=e.adapters.lifecycle)||void 0===o?void 0:o.onSessionCreated)||void 0===s?void 0:s.call(o,u))}catch(e){try{await zg(f)}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 g=!1;return{state:u,resources:{base:h,wrapped:m},metadata:d,workspaceServices:e.workspaceServices,policy:e.policy,async dispose(){var t,r;if(!g){g=!0;try{await zg(f)}finally{await(null===(r=null===(t=e.adapters.lifecycle)||void 0===t?void 0:t.onSessionDisposed)||void 0===r?void 0:r.call(t,u))}}}}}({options:e,workspaceState:s,workspaceServices:a,policy:i,adapters:o})},async reload(){l||await u((async()=>{var e,t;if(l)return;const r=a,n=await Bg(o,s,i);l?await Hg(n,{disposeLocalExtensibility:d}):(a=n,await Hg(r,{preserveSharedContributorsFrom:n,disposeLocalExtensibility:d}),await(null===(t=null===(e=o.lifecycle)||void 0===e?void 0:e.onWorkspaceReload)||void 0===t?void 0:t.call(e,s)))}))},async dispose(){l||(l=!0,await u((async()=>{var e;try{await Hg(a,{disposeLocalExtensibility:d})}finally{await(null===(e=o.lifecycle)||void 0===e?void 0:e.dispose())}})))}}}class Xg{async requestApproval(e){return{approved:!0}}}class Qg{approvalMode;userConfiguredPolicy;teamSettingsService;respectAdminControls;constructor(e,t,r,o){this.approvalMode=e,this.userConfiguredPolicy=t,this.teamSettingsService=r,this.respectAdminControls=o}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 ev{async open(e,t){}async getDiagnostics(e,t){return[]}}class tv{async getCodebaseReference(e,t){}}class rv{inner;constructor(e){this.inner=e}async getState(e){const t=await this.inner.getState(e);return Object.assign(Object.assign({},t),{servers:t.servers.filter((e=>"needsAuth"!==e.status))})}}class ov{subagents;constructor(e){this.subagents=e.map((e=>new nn.zz({fullPath:`sdk-inline://${e.name}`,name:e.name,description:e.description,tools:[],model:e.model,prompt:e.prompt,permissionMode:nn.b$.DEFAULT,isBackground:!1,source:"sdk"})))}async getAllSubagents(){return this.subagents}async reload(){return this.subagents}}const nv=em;async function sv(e,t){const r=(0,a.dirname)(e);await(0,fo.mkdir)(r,{recursive:!0}),await(0,fo.writeFile)(e,t,"utf-8")}class iv{transcriptStore;nestedSubagentTranscriptStore;projectDir;conversationId;workspacePath;parentConversationId;writeChain=Promise.resolve();constructor(e){this.workspacePath=e.workspacePath,this.conversationId=e.conversationId,this.parentConversationId=e.parentConversationId,this.projectDir=nv(this.workspacePath);const t=this.parentConversationId?(e,t)=>{const r=Am({conversationId:e,ext:t,kind:"subagent",parentConversationId:this.parentConversationId});return(0,a.join)(this.projectDir,r)}:void 0;this.transcriptStore=new Qm(this.projectDir,e.blobStore,sv,Object.assign({writeText:!1,writeJsonl:!0},t?{pathResolver:t}:{})),this.nestedSubagentTranscriptStore=new Qm(this.projectDir,e.blobStore,sv,{writeText:!1,writeJsonl:!0,pathResolver:(e,t)=>{const r=Am({conversationId:e,ext:t,kind:"subagent",parentConversationId:this.conversationId});return(0,a.join)(this.projectDir,r)}})}enqueueWrite(e,t){const r=this.writeChain;return this.writeChain=r.then((async()=>{try{await e()}catch(e){fm.warn(`${t} ${e instanceof Error?e.message:String(e)}`)}})),this.writeChain}async writeFromState(e,t){return this.enqueueWrite((async()=>{var r;await this.transcriptStore.writeFromStateFull(e,t,this.conversationId);const o=null!==(r=t.subagentStates)&&void 0!==r?r:{};for(const[t,r]of Object.entries(o))(null==r?void 0:r.conversationState)&&await this.nestedSubagentTranscriptStore.writeFromStateFull(e,r.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=Am({conversationId:this.conversationId,ext:"jsonl",kind:"subagent",parentConversationId:this.parentConversationId});return(0,a.join)(this.projectDir,e)}return function(e,t){const r=Am({conversationId:t,ext:"jsonl",kind:"primary"});return(0,a.join)(nv(e),r)}(this.workspacePath,this.conversationId)}getProjectDir(){return this.projectDir}}const av=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,lv="User aborted/interrupted manually.";class cv{sessions=new Map;backgroundRuns=new Map;backgroundPromises=new Set;pendingReleaseSessions=new Set;childParentIds=new Map;parentChildIds=new Map;queuedChildCompletions=new Map;childCompletionWaiters=new Map;lifecycleStore;agentClient;getResources;mcpTools;workspacePath;parentConversationId;headers;endlessRetries;onSessionCreated;onInteractionUpdate;onSessionCompleted;onSessionReleased;onSubagentTokenDelta;constructor(e){var t;this.agentClient=e.agentClient,this.getResources=e.getResources,this.mcpTools=null!==(t=e.mcpTools)&&void 0!==t?t:[],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 gt}async createOrResumeSession(e,t){var r;if(t.forkAgentId)throw new Error("forkAgentId is not supported in local subagents.");const o=t.resumeAgentId;if(o&&function(e){if(!av.test(e))throw new Error(`Invalid resumeAgentId format: ${e}`)}(o),o&&!t.prompt)return o;if(o&&vt(t.prompt)&&this.isBackgroundRunBusy(o))throw new Error("Sub-agent is currently running. You may send the follow-up message when it has completed.");if(o&&this.sessions.get(o))return o;const s=null!=o?o:(0,n.randomUUID)(),i=function(e){const t=new or.We,r=(0,or.sh)(e),o=new or.pH(new or.ve,t);return o.setMetadata("agentId",r.agentId),o.setMetadata("latestRootBlobId",r.latestRootBlobId),o.setMetadata("name",r.name),o.setMetadata("createdAt",r.createdAt),o.setMetadata("mode",r.mode),o.setMetadata("isRunEverything",r.isRunEverything),o.setMetadata("lastUsedModel",r.lastUsedModel),o.setMetadata("lastDebugServerPort",r.lastDebugServerPort),o.setMetadata("currentPlanUri",r.currentPlanUri),o}(s),a=new iv({workspacePath:this.workspacePath,conversationId:s,parentConversationId:this.parentConversationId,blobStore:i.getBlobStore()});return this.sessions.set(s,{agentStore:i,transcriptWriter:a,toolCallId:t.toolCallId}),this.registerParentChildLink(s,t.parentConversationId),null===(r=this.onSessionCreated)||void 0===r||r.call(this,{agentId:s,toolCallId:t.toolCallId,subagentType:t.subagentType,parentAgentId:t.parentConversationId}),s}async runSession(e,t,r,o){var n;if(this.isAwaitBackgroundMode(r))return this.awaitBackgroundRun(r.resumeAgentId,e.signal);const s=this.sessions.get(t);if(!s)return{status:"error",error:`Subagent session not found: ${t}`};if(r.runInBackground){const[o,n]=e.withCancel();return this.registerBackgroundRun(t,this.executeSubagent(o,t,r,s),n),{status:"background",backgroundReason:L.qL.AGENT_REQUEST,toolCallCount:0}}const i=await this.executeSubagent(e,t,r,s);return null===(n=this.onSessionCompleted)||void 0===n||n.call(this,t,i),i}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])}isBackgroundRunBusy(e){return this.lifecycleStore.isBusy(e)||this.backgroundRuns.has(e)}registerBackgroundRun(e,t,r){const o=this.lifecycleStore.startRun(e,{abort:r}),n=t.catch((e=>({status:"error",error:e instanceof Error?e.message:String(e)}))),s={runId:o,promise:n};this.backgroundRuns.set(e,s),this.backgroundPromises.add(n),n.then((t=>{var r;this.lifecycleStore.finishRun(e,o);const n=this.backgroundRuns.get(e);if((null==n?void 0:n.runId)===o){this.backgroundRuns.delete(e),this.enqueueChildCompletion(e,t),this.maybeCleanupReleasedSession(e);try{null===(r=this.onSessionCompleted)||void 0===r||r.call(this,e,t)}catch(t){fm.error("[LocalSubagentHostAdapter] onSessionCompleted threw after background run",{agentId:e,error:t instanceof Error?t.message:String(t)})}}return t})).finally((()=>this.backgroundPromises.delete(n)))}maybeCleanupReleasedSession(e){this.pendingReleaseSessions.has(e)&&!this.isBackgroundRunBusy(e)&&this.cleanupSession(e)}cleanupSession(e){var t;this.pendingReleaseSessions.delete(e);const r=this.sessions.get(e);if(!r)return;const o=this.parentChildIds.get(e);if(o)for(const e of o)this.childParentIds.delete(e);this.removeParentChildLink(e),this.parentChildIds.delete(e),this.queuedChildCompletions.delete(e),this.childCompletionWaiters.delete(e),r.transcriptWriter.waitForPendingWrites().catch((()=>{})),this.sessions.delete(e),null===(t=this.onSessionReleased)||void 0===t||t.call(this,e)}async executeSubagent(e,t,r,o){return r.continuationConfig?this.executeSubagentWithContinuation(e,t,r,o,r.continuationConfig):this.executeSubagentOnce(e,t,r,o)}async executeSubagentWithContinuation(e,t,r,o,n){const s=n.maxLoops>0?n.maxLoops:Number.POSITIVE_INFINITY;let i=await this.runContinuationLoop(e,t,r,o,n,s);if(!n.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(e){return{status:"error",error:"Subagent was aborted by the user"}}if(0===a.length)return i;const l=this.buildChildrenCompletedMessage(a,n.childrenCompletedMessageTemplate);if(i=await this.runContinuationLoop(e,t,new ht.Pw(Object.assign(Object.assign({},r),{prompt:l,resumeAgentId:t,runInBackground:!1})),o,n,s),"completed"!==i.status)return i}return i}async runContinuationLoop(e,t,r,o,s,i){var a,l;let c,u,d=0;for(let p=0;p<i;p++){if(e.signal.aborted)return{status:"error",error:"Subagent was aborted by the user"};const i=0===p?r.prompt:this.computeContinuationNudge(s,d,c),h=0===p?new ht.Pw(Object.assign(Object.assign({},r),{runInBackground:!1})):new ht.Pw(Object.assign(Object.assign({},r),{prompt:i,resumeAgentId:t,runInBackground:!1}));if(u=await this.executeSubagentOnce(e,t,h,o),"completed"!==u.status)return u;const m=null!==(a=u.toolCallCount)&&void 0!==a?a:0,f=null!==(l=u.finalMessage)&&void 0!==l?l:"";if(void 0!==c&&f.includes(c))return u;m>0?(d=0,c=void 0):(d+=1,c=d>=s.idleThreshold?`DONE_${(0,n.randomUUID)().replace(/-/g,"").slice(0,8)}`:void 0)}return null!=u?u:{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,o){var n,s,i;let a,l=0;const c=new L.QF({action:{case:"userMessageAction",value:new L.Vt({userMessage:new L.RG({text:r.prompt})})}}),u=new L.Gm({modelId:r.modelId,displayModelId:r.modelId,displayName:r.modelId});void 0!==r.credentials.case&&(u.credentials=r.credentials);const d=new xt,p={sendUpdate:async(e,r)=>{var o,n;"tokenDelta"===r.message.case&&(null===(o=this.onSubagentTokenDelta)||void 0===o||o.call(this,t,r.message.value.tokens)),"toolCallStarted"!==r.message.case&&"toolCallCompleted"!==r.message.case&&"partialToolCall"!==r.message.case||null===(n=this.onInteractionUpdate)||void 0===n||n.call(this,t,r),"toolCallCompleted"===r.message.case&&l++,"textDelta"===r.message.case&&(a=(null!=a?a:"")+r.message.value.text)},query:async(e,t)=>function(e){const t=e.query.case;switch(t){case"webSearchRequestQuery":return Wt(e.id,"Web search is not supported in local subagent");case"webFetchRequestQuery":return Gt(e.id,"Web fetch is not supported in local subagent");case"switchModeRequestQuery":return Kt(e.id,"Subagent mode switches are not supported in local subagent");case"askQuestionInteractionQuery":{const t=new Dt.tz({result:{case:"rejected",value:new Dt.ox({reason:"Interactive questions are not supported in local subagent mode"})}});return Vt(e.id,t)}default:throw new Error(`Unhandled interaction query type in local subagent: ${String(t)}`)}}(t)},h={handleCheckpoint:async(e,t)=>{await o.agentStore.handleCheckpoint(e,t),o.transcriptWriter.writeFromState(e,t)},getLatestCheckpoint:()=>o.agentStore.getLatestCheckpoint()};try{const i=null===(n=r.rootParentConversationId)||void 0===n?void 0:n.trim(),m=null===(s=r.parentConversationId)||void 0===s?void 0:s.trim(),f=void 0!==i&&""!==i?i:void 0!==m&&""!==m?m:t,g=await this.getResources({agentId:t,parentAgentId:r.parentConversationId}),v=r.readonly?new A(g,function(e){const t=[[Ye,(r=e.errorMessage,{execute:async(e,t)=>new Je.v3({result:{case:"permissionDenied",value:new Je.U7({path:t.path,error:r,isReadonly:!0})}})})],[H,rt(e.errorMessage)],[Ne,ot(e.errorMessage)]];var r;return e.wrapShell&&t.push([Ke,Qe(e.errorMessage)],[Ze,et(e.errorMessage)],[N,tt(e.errorMessage)]),e.includeWriteBackgroundShellStdin&&t.push([$,nt(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})):g;return await this.agentClient.run(e,o.agentStore.getConversationStateStructure(),c,u,p,v,o.agentStore.getBlobStore(),d,h,[...this.mcpTools],{conversationGroupId:f,conversationId:t,subagentTypeName:r.subagentType||void 0,headers:this.headers,endlessRetries:this.endlessRetries,subagentModelOverrides:[]}),await o.transcriptWriter.writeTurnEndedFromState(e,o.agentStore.getConversationStateStructure(),e.signal.aborted?{status:"aborted",error:lv}:{status:"success"}),{status:"completed",finalMessage:a,toolCallCount:l}}catch(r){const n=r instanceof Error?r.message:String(r);return fm.error("[LocalSubagentHostAdapter] Subagent session failed",{agentId:t,error:n}),await o.transcriptWriter.writeTurnEndedFromState(e,null!==(i=o.agentStore.getLatestCheckpoint())&&void 0!==i?i:o.agentStore.getConversationStateStructure(),this.getTurnEndedFromError(e,n)),e.signal.aborted?{status:"aborted",error:lv}:{status:"error",error:n}}}getTurnEndedFromError(e,t){return e.signal.aborted?{status:"aborted",error:lv}:{status:"error",error:t}}isAwaitBackgroundMode(e){var t;if(!Boolean(e.resumeAgentId&&!vt(e.prompt)&&!0===e.readonly&&!0!==e.runInBackground))return!1;if(0===(null!==(t=e.parentConversationId)&&void 0!==t?t:"").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 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((o=>{const n=()=>{o(r)};t.addEventListener("abort",n,{once:!0}),e.promise.then(o).finally((()=>t.removeEventListener("abort",n)))}))}registerParentChildLink(e,t){var r,o,n,s;const i=null==t?void 0:t.trim();if(!i||i===e||!this.sessions.has(i))return;const a=this.childParentIds.get(e);if(a===i)return;a&&(null===(r=this.parentChildIds.get(a))||void 0===r||r.delete(e),0===(null!==(n=null===(o=this.parentChildIds.get(a))||void 0===o?void 0:o.size)&&void 0!==n?n:0)&&this.parentChildIds.delete(a)),this.childParentIds.set(e,i);const l=null!==(s=this.parentChildIds.get(i))&&void 0!==s?s:new Set;l.add(e),this.parentChildIds.set(i,l)}removeParentChildLink(e){var t;const r=this.childParentIds.get(e);if(!r)return;this.childParentIds.delete(e);const o=this.parentChildIds.get(r);null==o||o.delete(e),0===(null!==(t=null==o?void 0:o.size)&&void 0!==t?t:0)&&this.parentChildIds.delete(r)}enqueueChildCompletion(e,t){var r,o;const n=this.childParentIds.get(e);if(!n)return;const s=null!==(r=this.queuedChildCompletions.get(n))&&void 0!==r?r:[];s.push({agentId:e,success:"completed"===t.status,finalMessage:"completed"===t.status?null!==(o=t.finalMessage)&&void 0!==o?o:"":"error"===t.status?t.error:"Subagent was aborted by the user"}),this.queuedChildCompletions.set(n,s),this.removeParentChildLink(e);const i=this.childCompletionWaiters.get(n);if(i){this.childCompletionWaiters.delete(n);for(const e of i)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){var t,r;return(null!==(r=null===(t=this.parentChildIds.get(e))||void 0===t?void 0:t.size)&&void 0!==r?r:0)>0}drainChildCompletions(e){var t;const r=null!==(t=this.queuedChildCompletions.get(e))&&void 0!==t?t:[];return this.queuedChildCompletions.delete(e),r}async waitForChildCompletion(e,t){if(t.aborted)throw new Error("aborted");await new Promise(((r,o)=>{var n;const s=null!==(n=this.childCompletionWaiters.get(e))&&void 0!==n?n:new Set,i=()=>{l(),r()},a=()=>{l(),o(new Error("aborted"))},l=()=>{s.delete(i),0===s.size&&this.childCompletionWaiters.delete(e),t.removeEventListener("abort",a)};s.add(i),this.childCompletionWaiters.set(e,s),t.addEventListener("abort",a,{once:!0})}))}buildChildrenCompletedMessage(e,t){const r=e.map((e=>{const t=e.success?"SUCCESS":"FAILED";return`## Agent ${e.agentId} -- ${t}\n\n${e.finalMessage}`})).join("\n\n---\n\n");return t.replace("{summaries}",r)}}var uv=r("../proto/dist/generated/agent/v1/agent_service_connect.js"),dv=r("../proto/dist/generated/agent/v1/selected_context_pb.js");function pv(e,t){const r=function(e){if(!(null==e?void 0:e.tool))return null;switch(e.tool.case){case"shellToolCall":{const{args:t,result:r}=e.tool.value;return t?Object.assign({type:"shell",args:Object.assign(Object.assign({command:t.command},t.workingDirectory?{workingDirectory:t.workingDirectory}:{}),t.timeout?{timeout:t.timeout}:{})},r?{result:yv(r)}:{}):null}case"deleteToolCall":{const{args:t,result:r}=e.tool.value;return t?Object.assign({type:"delete",args:{path:t.path}},r?{result:wv(r)}:{}):null}case"globToolCall":{const{args:t,result:r}=e.tool.value;return t?Object.assign({type:"glob",args:Object.assign({globPattern:t.globPattern},t.targetDirectory?{targetDirectory:t.targetDirectory}:{})},r?{result:bv(r)}:{}):null}case"grepToolCall":{const{args:t,result:r}=e.tool.value;return t?Object.assign({type:"grep",args:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({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:Sv(r)}:{}):null}case"readToolCall":{const{args:t,result:r}=e.tool.value;return t?Object.assign({type:"read",args:{path:t.path}},r?{result:Ev(r)}:{}):null}case"editToolCall":{const{args:t,result:r}=e.tool.value;if(!t)return null;const o={path:t.path};return Object.assign({type:"edit",args:o},r?{result:xv(r)}:{})}case"lsToolCall":{const{args:t,result:r}=e.tool.value;return t?Object.assign({type:"ls",args:Object.assign({path:t.path},t.ignore&&t.ignore.length>0?{ignore:t.ignore}:{})},r?{result:_v(r)}:{}):null}case"readLintsToolCall":{const{args:t,result:r}=e.tool.value;return t?Object.assign({type:"readLints",args:{paths:t.paths}},r?{result:Pv(r)}:{}):null}case"mcpToolCall":{const{args:t,result:r}=e.tool.value;return t?Object.assign({type:"mcp",args:Object.assign(Object.assign(Object.assign({},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:Rv(r)}:{}):null}case"generateImageToolCall":{const{args:t,result:r}=e.tool.value;return t?Object.assign({type:"generateImage",args:Object.assign({description:t.description},t.filePath?{filePath:t.filePath}:{})},r?{result:Iv(r)}:{}):null}case"recordScreenToolCall":{const{args:t,result:r}=e.tool.value;return t?Object.assign({type:"recordScreen",args:{mode:Av(t.mode)}},r?{result:Ov(r)}:{}):null}case"semSearchToolCall":{const{args:t,result:r}=e.tool.value;return t?Object.assign({type:"semSearch",args:Object.assign(Object.assign({query:t.query},t.targetDirectories&&t.targetDirectories.length>0?{targetDirectories:t.targetDirectories}:{}),t.explanation?{explanation:t.explanation}:{})},r?{result:Tv(r)}:{}):null}case"createPlanToolCall":{const{args:t,result:r}=e.tool.value;return t?Object.assign({type:"createPlan",args:{plan:t.plan}},r?{result:Dv(r)}:{}):null}case"updateTodosToolCall":{const{args:t,result:r}=e.tool.value;return t?Object.assign({type:"updateTodos",args:{todos:t.todos.map((e=>({content:e.content,status:jv(e.status)})))}},r?{result:Mv(r)}:{}):null}case"fetchToolCall":case"switchModeToolCall":case"computerUseToolCall":case"readTodosToolCall":case"webSearchToolCall":case"listMcpResourcesToolCall":case"readMcpResourceToolCall":return null;case"taskToolCall":{const{args:t,result:r}=e.tool.value;return t?Object.assign({type:"task",args:hv(t)},r?{result:gv(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"awaitToolCall":case"blameByFilePathToolCall":case"getMcpToolsToolCall":case"reportBugToolCall":case"setActiveBranchToolCall":case"communicateUpdateToolCall":case"sendFinalSummaryToolCall":case"updatePrCodeTourToolCall":case"recordCiInvestigationFindingsToolCall":case"sendMessageToolCall":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 hv(e){var t,r;return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({description:null!==(t=e.description)&&void 0!==t?t:"",prompt:null!==(r=e.prompt)&&void 0!==r?r:""},e.subagentType?{subagentType:mv(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:fv(e.mode)}:{}),e.respondingToMessageIds&&e.respondingToMessageIds.length>0?{respondingToMessageIds:e.respondingToMessageIds}:{})}function mv(e){const t=e.type.case;return t?"custom"===t?{kind:t,name:e.type.value.name}:{kind:t}:{kind:"unspecified"}}function fv(e){switch(e){case nn.FL.AGENT:return"agent";case nn.FL.PLAN:return"plan";default:return"unspecified"}}function gv(e){var t,r,o;if(null===(t=e.result)||void 0===t?void 0:t.case)switch(e.result.case){case"success":{const t=e.result.value;return{status:"success",value:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},t.conversationSteps&&t.conversationSteps.length>0?{conversationSteps:t.conversationSteps.map((e=>{var t,r;return null!==(r=null===(t=e.toJson)||void 0===t?void 0:t.call(e))&&void 0!==r?r:e}))}:{}),t.agentId?{agentId:t.agentId}:{}),{isBackground:null!==(r=t.isBackground)&&void 0!==r&&r}),void 0!==t.durationMs?{durationMs:Number(t.durationMs)}:{}),t.resultSuffix?{resultSuffix:t.resultSuffix}:{}),{backgroundReason:vv(t.backgroundReason)}),t.transcriptPath?{transcriptPath:t.transcriptPath}:{})}}case"error":return{status:"error",error:{message:null!==(o=e.result.value.error)&&void 0!==o?o:"Task failed"}};default:return}}function vv(e){switch(e){case L.qL.AGENT_REQUEST:return"agentRequest";case L.qL.USER_REQUEST:return"userRequest";case L.qL.QUEUED_FOLLOW_UP:return"queuedFollowUp";default:return"unspecified"}}function yv(e){var t,r,o,n,s,i,a,l;if(null===(t=e.result)||void 0===t?void 0:t.case)switch(e.result.case){case"success":case"failure":{const t=e.result.value;return{status:"success",value:{exitCode:null!==(r=t.exitCode)&&void 0!==r?r:0,signal:null!==(o=t.signal)&&void 0!==o?o:"",stdout:null!==(n=t.stdout)&&void 0!==n?n:"",stderr:null!==(s=t.stderr)&&void 0!==s?s:"",executionTime:null!==(i=t.executionTime)&&void 0!==i?i: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:null!==(a=e.result.value.reason)&&void 0!==a?a:"Command rejected",command:e.result.value.command,workingDirectory:e.result.value.workingDirectory}};case"spawnError":return{status:"error",error:{message:null!==(l=e.result.value.error)&&void 0!==l?l:"Failed to spawn command",command:e.result.value.command,workingDirectory:e.result.value.workingDirectory}};default:return}}function wv(e){var t,r,o,n,s;if(null===(t=e.result)||void 0===t?void 0:t.case)return"success"===e.result.case?{status:"success",value:{fileSize:Number(null!==(r=e.result.value.fileSize)&&void 0!==r?r:0)}}:{status:"error",error:{message:null!==(s=null!==(n=null!==(o=e.result.value.error)&&void 0!==o?o:e.result.value.reason)&&void 0!==n?n:e.result.value.clientVisibleError)&&void 0!==s?s:e.result.case,path:e.result.value.path}}}function bv(e){var t,r,o,n,s,i,a;if(null===(t=e.result)||void 0===t?void 0:t.case)return"success"===e.result.case?{status:"success",value:{files:null!==(r=e.result.value.files)&&void 0!==r?r:[],totalFiles:null!==(o=e.result.value.totalFiles)&&void 0!==o?o:0,clientTruncated:null!==(n=e.result.value.clientTruncated)&&void 0!==n&&n,ripgrepTruncated:null!==(s=e.result.value.ripgrepTruncated)&&void 0!==s&&s}}:{status:"error",error:{message:null!==(a=null!==(i=e.result.value.error)&&void 0!==i?i:e.result.value.reason)&&void 0!==a?a:e.result.case}}}function Sv(e){var t,r;if(null===(t=e.result)||void 0===t?void 0:t.case){if("success"===e.result.case){const t=e.result.value,r={};if(t.workspaceResults)for(const[e,o]of Object.entries(t.workspaceResults))r[e]=kv(o);return{status:"success",value:Object.assign(Object.assign({},Object.keys(r).length>0?{workspaceResults:r}:{}),t.activeEditorResult?{activeEditorResult:kv(t.activeEditorResult)}:{})}}return{status:"error",error:{message:null!==(r=e.result.value.error)&&void 0!==r?r:e.result.case}}}}function kv(e){var t,r,o,n,s,i,a,l,c;if(null===(t=null==e?void 0:e.result)||void 0===t?void 0:t.case)switch(e.result.case){case"content":return{type:"content",output:{matches:null!==(n=null===(r=e.result.value.matches)||void 0===r?void 0:r.map((e=>Object.assign(Object.assign(Object.assign(Object.assign({file:e.file},void 0!==e.lineNumber?{lineNumber:e.lineNumber}:{}),{line:e.line}),e.beforeContext?{beforeContext:e.beforeContext}:{}),e.afterContext?{afterContext:e.afterContext}:{}))))&&void 0!==n?n:[],totalMatches:null!==(s=e.result.value.totalMatches)&&void 0!==s?s:0}};case"files":return{type:"files",output:{files:null!==(i=e.result.value.files)&&void 0!==i?i:[],count:null!==(a=e.result.value.count)&&void 0!==a?a:0}};case"count":return{type:"count",output:{counts:null!==(l=null===(o=e.result.value.counts)||void 0===o?void 0:o.map((e=>({file:e.file,count:e.count}))))&&void 0!==l?l:[],total:null!==(c=e.result.value.total)&&void 0!==c?c:0}};default:return}}function Ev(e){var t,r,o,n,s;if(null===(t=e.result)||void 0===t?void 0:t.case)return"success"===e.result.case?{status:"success",value:{content:"content"===e.result.value.output.case?e.result.value.output.value:"",totalLines:null!==(r=e.result.value.totalLines)&&void 0!==r?r:0,fileSize:Number(null!==(o=e.result.value.fileSize)&&void 0!==o?o:0)}}:{status:"error",error:{message:null!==(s=null!==(n=e.result.value.error)&&void 0!==n?n:e.result.value.reason)&&void 0!==s?s:e.result.case,path:e.result.value.path}}}function xv(e){var t,r,o;if(null===(t=e.result)||void 0===t?void 0:t.case)return"success"===e.result.case?{status:"success",value:Object.assign(Object.assign(Object.assign({},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:null!==(o=null!==(r=e.result.value.error)&&void 0!==r?r:e.result.value.reason)&&void 0!==o?o:e.result.case,path:e.result.value.path}}}function _v(e){var t,r;if(null===(t=e.result)||void 0===t?void 0:t.case)return"success"===e.result.case?{status:"success",value:{directoryTreeRoot:Cv(e.result.value.directoryTreeRoot)}}:{status:"error",error:{message:null!==(r=e.result.value.error)&&void 0!==r?r:e.result.case}}}function Cv(e){var t,r,o,n,s,i,a,l;if(e)return{absPath:null!==(o=e.absPath)&&void 0!==o?o:"",childrenDirs:null!==(n=null===(t=e.childrenDirs)||void 0===t?void 0:t.map(Cv))&&void 0!==n?n:[],childrenFiles:null!==(s=null===(r=e.childrenFiles)||void 0===r?void 0:r.map((e=>({name:e.name}))))&&void 0!==s?s:[],childrenWereProcessed:null!==(i=e.childrenWereProcessed)&&void 0!==i&&i,fullSubtreeExtensionCounts:null!==(a=e.fullSubtreeExtensionCounts)&&void 0!==a?a:{},numFiles:null!==(l=e.numFiles)&&void 0!==l?l:0}}function Pv(e){var t,r,o,n,s,i;if(null===(t=e.result)||void 0===t?void 0:t.case)return"success"===e.result.case?{status:"success",value:{fileDiagnostics:null!==(o=null===(r=e.result.value.fileDiagnostics)||void 0===r?void 0:r.map((e=>{var t,r,o;return{path:e.path,diagnostics:null!==(r=null===(t=e.diagnostics)||void 0===t?void 0:t.map((e=>Object.assign(Object.assign({severity:Nv(e.severity)},e.range?{range:Object.assign(Object.assign({},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}))))&&void 0!==r?r:[],diagnosticsCount:null!==(o=e.diagnosticsCount)&&void 0!==o?o:0}})))&&void 0!==o?o:[],totalFiles:null!==(n=e.result.value.totalFiles)&&void 0!==n?n:0,totalDiagnostics:null!==(s=e.result.value.totalDiagnostics)&&void 0!==s?s:0}}:{status:"error",error:{message:null!==(i=e.result.value.error)&&void 0!==i?i:e.result.case}}}function Rv(e){var t,r,o,n,s,i;if(null===(t=e.result)||void 0===t?void 0:t.case)return"success"===e.result.case?{status:"success",value:{content:null!==(o=null===(r=e.result.value.content)||void 0===r?void 0:r.map((e=>{var t,r;const o={};return"text"===(null===(t=e.content)||void 0===t?void 0:t.case)?o.text={text:e.content.value.text}:"image"===(null===(r=e.content)||void 0===r?void 0:r.case)&&(o.image=Object.assign({data:e.content.value.data},e.content.value.mimeType?{mimeType:e.content.value.mimeType}:{})),o})))&&void 0!==o?o:[],isError:null!==(n=e.result.value.isError)&&void 0!==n&&n}}:{status:"error",error:{message:null!==(i=null!==(s=e.result.value.error)&&void 0!==s?s:e.result.value.reason)&&void 0!==i?i:e.result.case}}}function Tv(e){var t,r,o;if(null===(t=e.result)||void 0===t?void 0:t.case)return"success"===e.result.case?{status:"success",value:{results:null!==(r=e.result.value.results)&&void 0!==r?r:""}}:{status:"error",error:{message:null!==(o=e.result.value.error)&&void 0!==o?o:e.result.case}}}function Iv(e){var t,r,o;if(null===(t=e.result)||void 0===t?void 0:t.case)return"success"===e.result.case?{status:"success",value:{filePath:null!==(r=e.result.value.filePath)&&void 0!==r?r:""}}:{status:"error",error:{message:null!==(o=e.result.value.error)&&void 0!==o?o:e.result.case}}}function Av(e){switch(e){case Bd.$u.START_RECORDING:return"START_RECORDING";case Bd.$u.SAVE_RECORDING:return"SAVE_RECORDING";case Bd.$u.DISCARD_RECORDING:return"DISCARD_RECORDING";default:throw new Error(`Unknown RecordingMode: ${e}`)}}function Ov(e){var t,r,o,n,s;if(null===(t=e.result)||void 0===t?void 0:t.case)switch(e.result.case){case"startSuccess":return{status:"success",value:{wasPriorRecordingCancelled:null!==(r=e.result.value.wasPriorRecordingCancelled)&&void 0!==r&&r}};case"saveSuccess":return{status:"success",value:{path:null!==(o=e.result.value.path)&&void 0!==o?o:"",recordingDurationMs:Number(null!==(n=e.result.value.recordingDurationMs)&&void 0!==n?n:0)}};case"discardSuccess":return{status:"success",value:{}};case"failure":return{status:"error",error:{message:null!==(s=e.result.value.error)&&void 0!==s?s:"Unknown error"}};default:return}}function Dv(e){var t,r;if(null===(t=e.result)||void 0===t?void 0:t.case)return"success"===e.result.case?{status:"success",value:{}}:{status:"error",error:{message:null!==(r=e.result.value.error)&&void 0!==r?r:e.result.case}}}function Mv(e){var t,r,o,n,s;if(null===(t=e.result)||void 0===t?void 0:t.case)return"success"===e.result.case?{status:"success",value:{todos:null!==(o=null===(r=e.result.value.todos)||void 0===r?void 0:r.map((e=>({content:e.content,status:jv(e.status)}))))&&void 0!==o?o:[],totalCount:null!==(n=e.result.value.totalCount)&&void 0!==n?n:0}}:{status:"error",error:{message:null!==(s=e.result.value.error)&&void 0!==s?s:e.result.case}}}function jv(e){switch(e){case 0:case 1:default:return"pending";case 2:return"inProgress";case 3:return"completed";case 4:return"cancelled"}}function Nv(e){switch(e){case 0:case 1:default:return"error";case 2:return"warning";case 3:return"information";case 4:return"hint"}}const $v={type:"object",properties:{},additionalProperties:!0};function Fv(e){return{execute(t,r,o){return n=this,s=void 0,a=function*(){const t=r.toolName||function(e){const t=`${Me}-`;return e.startsWith(t)?e.slice(t.length):e}(r.name),o=e[t];if(void 0===o)return new Ge.iz({result:{case:"error",value:new Ge.Nh({error:`Unknown custom tool: ${t}`})}});try{return function(e){var t;const r=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:Uv(e)?e:void 0};var t}(e),o=void 0!==r.structuredContent?ir.Struct.fromJson(r.structuredContent):void 0;return new Ge.iz({result:{case:"success",value:new Ge.QW({content:r.content.map(Lv),isError:null!==(t=r.isError)&&void 0!==t&&t,structuredContent:o})}})}(yield o.execute(function(e){return Object.fromEntries(Object.entries(e.args).map((([e,t])=>[e,t.toJson()])))}(r),{toolCallId:r.toolCallId||void 0}))}catch(e){return new Ge.iz({result:{case:"error",value:new Ge.Nh({error:e instanceof Error?e.message:String(e)})}})}},new((i=void 0)||(i=Promise))((function(e,t){function r(e){try{l(a.next(e))}catch(e){t(e)}}function o(e){try{l(a.throw(e))}catch(e){t(e)}}function l(t){var n;t.done?e(t.value):(n=t.value,n instanceof i?n:new i((function(e){e(n)}))).then(r,o)}l((a=a.apply(n,s||[])).next())}));var n,s,i,a}}}function Lv(e){var t;return"text"===e.type?new Ge._Z({content:{case:"text",value:new Ge.zN({text:e.text})}}):new Ge._Z({content:{case:"image",value:new Ge.do({data:o.Buffer.from(e.data,"base64"),mimeType:null!==(t=e.mimeType)&&void 0!==t?t:""})}})}function Uv(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var Bv=r("./src/agent/errors.ts"),Hv=r("./src/agent/executor-common.ts"),zv=r("../../node_modules/.pnpm/@statsig+js-client@3.31.0/node_modules/@statsig/js-client/src/index.js"),Wv=r("./src/agent/utils/logger.ts"),qv=function(e,t,r,o){return new(r||(r=Promise))((function(n,s){function i(e){try{l(o.next(e))}catch(e){s(e)}}function a(e){try{l(o.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(i,a)}l((o=o.apply(e,t||[])).next())}))};const Gv={checkFeatureGate:()=>!1,getDynamicConfigValue:({defaultValue:e})=>e},Vv=new Map;var Jv=function(e,t,r,o){return new(r||(r=Promise))((function(n,s){function i(e){try{l(o.next(e))}catch(e){s(e)}}function a(e){try{l(o.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(i,a)}l((o=o.apply(e,t||[])).next())}))};function Kv(e,t){if(!function(e){return void 0!==e&&Object.keys(e).length>0}(t))return;const r=e.resources.base;if(!(r instanceof Fp))throw new Bv.j1("SDK custom tools require the default local workspace resource provider.",{isRetryable:!1});const o=r.getMcpExecutionPolicyDeps(),n=r.get(Ne),s=Fv(t);e.resources.base.register(Ne,{execute(e,t,r){return Jv(this,void 0,void 0,(function*(){if(function(e){return e.providerIdentifier===Me}(t)){const n=yield zu(e,t,Object.assign(Object.assign({},o),{toolDef:{source:"internal"}}));return void 0!==n?n:s.execute(e,t,r)}return n.execute(e,t,r)}))}})}const Zv={warn(){},error(){}},Yv={log(){}};class Xv{requestApproval(e){return Jv(this,void 0,void 0,(function*(){return{approved:!1,reason:`Local SDK runs cannot request interactive approval for ${Qv(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 Qv(e){switch(e.type){case ic.Shell:return"this shell command";case ic.Mcp:return"this MCP tool call";case ic.Write:return"this file edit";case ic.Delete:return"this file deletion";default:return"this operation"}}function ey(e){try{const t=(0,s.statSync)(e);return t.isFile()&&("win32"===process.platform||!!(73&t.mode))}catch(e){return!1}}function ty(e){const t=`${process.platform}-${process.arch}`,r=[`@cursor/sdk-${t}`,`@cursor/february-${t}`];if(!process.argv[1])return;let o=(0,a.dirname)((0,a.resolve)(process.argv[1]));const n=(0,a.parse)(o).root;for(;o!==n;){for(const t of r){const r=(0,a.join)(o,"node_modules",t,"bin",e);if(ey(r))return r}o=(0,a.dirname)(o)}}function ry(e){return void 0!==e&&"insecure_none"!==e.type}function oy(e,t){return Jv(this,void 0,void 0,(function*(){const r="string"==typeof e||void 0===e?{workingDirectory:e,apiKey:t}:e,s=(0,l.q6)().with(l._O,Yv);Gg(r.settingSources),/:\/\/(localhost|127\.0\.0\.1)/.test(Hv.EV)&&(process.env.NODE_TLS_REJECT_UNAUTHORIZED="0"),r.apiKey&&(yield Promise.all([(0,Hv.ly)(r.apiKey),(0,Hv.mU)(r.apiKey)]));const c=r.workingDirectory||process.cwd(),u=(0,h.Rv)((0,i.homedir)(),c);let d;const p="win32"===process.platform?"rg.exe":"rg",m=process.env.CURSOR_RIPGREP_PATH;d=m&&(0,a.isAbsolute)(m)?m:ty(p),d||(d=(0,Do.Qd)()),d&&(0,Do.J)(d);let f,g={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:[]}),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:()=>{}},v=!1;if(r.apiKey)try{f=(0,Hv.KU)(r.apiKey);const e=(0,ar.createClient)(mo.I,f),t=yield function(e){let t=Vv.get(e);return t||(t=function(e){return qv(this,void 0,void 0,(function*(){try{const t=yield function(e){return qv(this,void 0,void 0,(function*(){const t=yield(0,Hv.dC)(e,Hv.EV);if(!t)return;const r=Hv.EV.endsWith("/")?Hv.EV.slice(0,-1):Hv.EV,o=yield 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,Hv.tF)(),"x-ghost-mode":(0,Hv.U)(e)},body:JSON.stringify({})});if(!o.ok)return void Wv.v.log(`Failed to bootstrap SDK Statsig: ${o.status} ${o.statusText}`);const n=yield o.json();return"string"==typeof n.config&&n.config.length>0?n.config:void 0}))}(e);if(!t)return Gv;const r=new zv.StatsigClient("client-Bm4HJ0aDjXHQVsoACMREyLNxm5p6zzuzhO50MgtoT5D",function(e){try{const t=JSON.parse(e);if(t.user)return Object.assign(Object.assign({},t.user),{custom:Object.assign(Object.assign({},t.user.custom),{clientType:"sdk",clientVersion:(0,Hv.tF)()})})}catch(e){Wv.v.log(`Failed to parse SDK Statsig bootstrap user: ${e instanceof Error?e.message:String(e)}`)}return{custom:{clientType:"sdk",clientVersion:(0,Hv.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(e){return!1}},getDynamicConfigValue({configName:e,paramName:t,defaultValue:o}){try{return r.getDynamicConfig(e).get(t,o)}catch(e){return o}}}}catch(e){return Wv.v.log(`Failed to initialize SDK Statsig: ${e instanceof Error?e.message:String(e)}`),Gv}}))}(e),Vv.set(e,t),t.then((r=>{r===Gv&&Vv.get(e)===t&&Vv.delete(e)}),(()=>{Vv.get(e)===t&&Vv.delete(e)}))),t}(r.apiKey);v=t.checkFeatureGate("hooks_stdin_transport");const o={getDefaultNetworkAllowlist:()=>Jv(this,void 0,void 0,(function*(){return t.getDynamicConfigValue({configName:"sandbox_default_network_allowlist",paramName:"allowlist",defaultValue:[]})}))};g=new Xh(new Yh(e),o,{isMcpAccessNetworkAllowlistEnabled:()=>t.checkFeatureGate("mcp_access_network_allowlist"),isMcpSettingsOverhaulEnabled:e=>t.checkFeatureGate("mcp_settings_overhaul",e)})}catch(e){Wv.v.log(`Failed to initialize authenticated dashboard services: ${e instanceof Error?e.message:String(e)}`)}const y=r.apiKey?yield(0,Do.tv)(`${(0,i.homedir)()}/.cursor/sandbox.json`,(0,i.homedir)()):void 0,w=void 0!==r.apiKey?yield function(e){return Jv(this,void 0,void 0,(function*(){const{cwd:t,perUserSandboxPolicy:r,sandboxOptions:o}=e;if(!1===(null==o?void 0:o.enabled))return{defaultSandboxPolicy:{type:"insecure_none"},defaultSandboxPolicySources:void 0};const n=ry(r)?r:!0===(null==o?void 0:o.enabled)?function(e,t={}){return Object.assign({type:e},t)}("workspace_readwrite",{networkPolicy:(0,Do.Po)()}):void 0;if(void 0===n)return{defaultSandboxPolicy:{type:"insecure_none"},defaultSandboxPolicySources:void 0};if(function(){const e=ty("win32"===process.platform?"cursorsandbox.exe":"cursorsandbox");e&&(0,Do.St)({sandboxBinaryPath:e})}(),!(0,Do.K3)(void 0,{ctx:e.initializationCtx}))throw new Bv.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=n;const{policy:i}=yield(0,Do.resolveSandboxPolicyForWorkspace)(t,s);return{defaultSandboxPolicy:i,defaultSandboxPolicySources:s}}))}({cwd:c,perUserSandboxPolicy:y,sandboxOptions:r.sandboxOptions,initializationCtx:s}):void 0,b=null==w?void 0:w.defaultSandboxPolicy,S=null==w?void 0:w.defaultSandboxPolicySources,k=ry(b),E=yield async function(e){var t,r,o,n,s,i,a,l;const{workingDirectory:c,projectDir:u}=e,d=Gg(e.settingSources),p=null!==(t=e.teamSettingsService)&&void 0!==t?t:{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:[]}),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:()=>{}},h=null!==(r=e.defaultSandboxPolicy)&&void 0!==r?r:{type:"insecure_none"},m=null!==(o=e.getSandboxSupported)&&void 0!==o?o:()=>(0,Do.K3)(h,{ctx:e.initializationCtx}),f=null!==(n=e.getSandboxEnabled)&&void 0!==n?n:()=>"insecure_none"!==h.type&&m(),g=new vc,v=new Ia(g,p,[c]),y=new ev,w=new tv,b=new Qg(e.smartModeClassifierAutoModeEnabled?"allowlist":null!==(s=e.approvalMode)&&void 0!==s?s:"unrestricted",h,p,null!==(i=e.respectAdminControls)&&void 0!==i&&i),S=e.pendingDecisionProvider,k={executeIndexedGrep:void 0},E=()=>!0,x=Vg(d,"plugins"),_=null!==(a=e.importThirdPartyPlugins)&&void 0!==a&&a,C=null===(l=e.mcpMetaToolEnabled)||void 0===l||l,P=void 0!==e.mcpServers&&Object.keys(e.mcpServers).length>0,R=void 0!==e.customSubagents&&e.customSubagents.length>0,T=P||Vg(d,"project")||Vg(d,"user")||x,I=Vg(d,"project")||Vg(d,"user")||Vg(d,"mdm"),A=Vg(d,"team"),O=A&&void 0!==e.dashboardTransport,D=Vg(d,"project")||Vg(d,"user")||A||O||x,M=t=>Yg({workingDirectory:c,adapters:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},t.includeMcp?{mcp:_m({teamSettingsService:p,initializationCtx:e.initializationCtx,importThirdPartyPlugins:_,ignoreApprovals:!0,includeProjectMcp:Vg(d,"project"),includeUserMcp:Vg(d,"user"),includePluginMcp:x,inlineMcpServers:e.mcpServers})}:{}),x?{pluginBootstrap:Ag({importThirdPartyPlugins:_,dashboardTransport:e.dashboardTransport})}:{}),I?{hooks:Sg({includeProjectHooks:Vg(d,"project"),includeUserHooks:Vg(d,"user"),includeEnterpriseHooks:Vg(d,"mdm"),useCommandHookStdinTransport:e.useCommandHookStdinTransport})}:{}),D?{localExtensibility:Eg({includeProjectExtensibility:Vg(d,"project"),includeUserExtensibility:Vg(d,"user"),includeManagedSkills:O,includeTeamExtensibility:A,includePluginExtensibility:x,teamSettingsService:p,getThirdPartyExtensibilityEnabled:E,dashboardTransport:e.dashboardTransport,importThirdPartyPlugins:_})}:{}),{resourceFactory:jg({ignoreService:v,grepProvider:k,workspacePaths:[c],diagnosticsProvider:y,repositoryProvider:w,projectDir:null!=u?u:c,shellManager:void 0,defaultSandboxPolicy:h,defaultSandboxPolicySources:e.defaultSandboxPolicySources,getSandboxEnabled:f,getSandboxSupported:m,getNetworkAllowlistInfo:e.getNetworkAllowlistInfo,smartModeClassifierAutoModeEnabled:e.smartModeClassifierAutoModeEnabled,devForceNextSmartModeClassifierBlockToken:e.devForceNextSmartModeClassifierBlockToken,mcpFileOutputThresholdBytes:void 0,mcpMetaToolEnabled:C,createMcpStateAccessor:e=>new rv(new ip(e)),createSessionMcpLease:(t,r)=>_m({teamSettingsService:p,initializationCtx:e.initializationCtx,importThirdPartyPlugins:!1,ignoreApprovals:!0,includeProjectMcp:!1,includeUserMcp:!1,includePluginMcp:!1,inlineMcpServers:r}).createLease({workspaceState:t.workspaceState,services:t.workspaceServices,policy:t.policy}),createSessionDependencies:()=>{var t;const r=null!=S?S:new Xg;return{pendingDecisionStore:r,fileChangeTracker:new mc(c),permissionsService:new Fh(v,r,b,p,c,null!==(t=e.respectAdminControls)&&void 0!==t&&t)}}}),resourceWrappers:I?[{wrapResources(e){const t=e.workspaceServices.hooksRuntime;if(!("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 o=t.createSessionRuntime({sessionState:e.sessionState,metadata:e.metadata});return new wg(new pg(e.resources,o.hookExecutor,(()=>function(e,t){var r,o,n,s;const i=null!==(o=null!==(r=fg(t,gg,"conversationId","conversation_id"))&&void 0!==r?r:e.sessionId)&&void 0!==o?o:"",a=null!==(n=fg(t,gg,"generationId","generation_id"))&&void 0!==n?n:i,l=null!==(s=fg(t,gg,"model"))&&void 0!==s?s:"unknown",c=fg(t,gg,"modelId","model_id"),u=fg(t,yg,"modelParams","model_params");return Object.assign({conversation_id:i,generation_id:a,model:l},ce({modelId:c,modelParams:u}))}(e.sessionState,e.metadata)),e.workspaceServices.mcpLease,void 0,void 0,t.hooksConfigLease),o)}}]:[]}),R?{workspaceServicesContributors:[{contributeServices:t=>{var r;const o=new ov(null!==(r=e.customSubagents)&&void 0!==r?r:[]),n=t.services.subagentsService;return{subagentsService:void 0===n?o:new xl([o,n])}}}]}:{})});if(!T)return M({includeMcp:!1});try{return await M({includeMcp:!0})}catch(e){return fm.warn("[default-local-workspace-runtime] Failed to initialize MCP-enabled runtime, retrying without MCP:",{error:e,workingDirectory:c,projectDir:u,enablePlugins:x,importThirdPartyPlugins:_}),M({includeMcp:!1})}}({workingDirectory:c,projectDir:u,teamSettingsService:g,initializationCtx:s,dashboardTransport:f,settingSources:r.settingSources,mcpServers:r.mcpServers,customSubagents:r.customSubagents,defaultSandboxPolicy:b,defaultSandboxPolicySources:S,approvalMode:k?"allowlist":void 0,pendingDecisionProvider:k||!0===r.autoReview?new Xv:void 0,getNetworkAllowlistInfo:k?()=>async function(e,t,r){const[o,n]=await Promise.all([e.getDefaultNetworkAllowlist(),e.getNetworkAccessControls()]),s=[...n.allowlist],i=`${t}/.cursor/sandbox.json`,a=await(0,Do.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,Do.tv)(e,r);t&&"insecure_none"!==t.type&&t.networkPolicy?.allow&&s.push(...t.networkPolicy.allow)}const l=[...new Set(s)];return{hasDefaults:o.available&&o.allowlist.length>0,explicitEntries:l}}(g,(0,i.homedir)(),c):void 0,smartModeClassifierAutoModeEnabled:r.autoReview,devForceNextSmartModeClassifierBlockToken:r.devForceNextSmartModeClassifierBlockToken,respectAdminControls:void 0!==r.apiKey,useCommandHookStdinTransport:v});let x,_;return{run:(e,t,r)=>Jv(this,void 0,void 0,(function*(){return function(e,t){return hm.run(e,t)}(Zv,(()=>Jv(this,void 0,void 0,(function*(){var s,i,a,u;const d=(0,l.VI)((0,l.q6)().withName("sdk.run").with(l._O,Yv)),[p,h]=d.ctx.withCancel(),m=null!==(s=t.sessionId)&&void 0!==s?s:(0,n.randomUUID)(),f=t.mcpServersOverride,g=void 0===(v=t.customTools)?[]:Object.entries(v).map((([e,t])=>{var r,o;return{clientKey:Me,providerIdentifier:Me,toolName:e,name:`${Me}-${e}`,description:null!==(r=t.description)&&void 0!==r?r:"",inputSchema:null!==(o=t.inputSchema)&&void 0!==o?o:$v,source:"internal"}}));var v;let y;y=yield E.createSessionRuntime({sessionId:m,mcpServersOverride:f,extraMcpTools:g});const w=new Map;try{const s=y.resources.wrapped;Kv(y,t.customTools);const l=null!==(i=t.blobStore)&&void 0!==i?i:new or.ve;let d=null!==(a=t.initialState)&&void 0!==a?a:new L.Y9({});const v=void 0!==t.model?new L.G4({modelId:t.model.id,parameters:(null!==(u=t.model.params)&&void 0!==u?u:[]).map((e=>new L.SR({id:e.id,value:e.value})))}):void 0,S=Array.isArray(e.images)?e.images.map((e=>{const t=(0,n.randomUUID)(),r=new Uint8Array(o.Buffer.from(e.data,"base64")),s=(0,Hv.v8)(r);return new dv.d(Object.assign(Object.assign({uuid:t},s?{mimeType:s}:{}),{dataOrBlobId:{case:"data",value:r}}))})):[],k=S.length>0?new dv.xv({selectedImages:S}):void 0,C=function(e){switch(e){case"agent":return L.xy.AGENT;case"plan":return L.xy.PLAN;default:return}}(t.mode),P=new L.QF({action:{case:"userMessageAction",value:new L.Vt({userMessage:new L.RG(Object.assign({text:e.text,selectedContext:k},void 0!==C?{mode:C}:{}))})}}),R={sendUpdate:(e,t)=>Jv(this,void 0,void 0,(function*(){const e=function(e,t){var r,o,n,s,i,a,l,c,u;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:null!==(s=null===(r=e.message.value.userMessage)||void 0===r?void 0:r.text)&&void 0!==s?s:""}};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":return{type:"summary-completed"};case"shellOutputDelta":return{type:"shell-output-delta",event:e.message.value.event.case?{case:e.message.value.event.case,value:null!==(i=null===(n=null===(o=e.message.value.event.value)||void 0===o?void 0:o.toJson)||void 0===n?void 0:n.call(o))&&void 0!==i?i:e.message.value.event.value}:{}};case"toolCallStarted":return pv("tool-call-started",e.message.value);case"partialToolCall":return pv("partial-tool-call",e.message.value);case"toolCallCompleted":return pv("tool-call-completed",e.message.value);case"heartbeat":return null;case"turnEnded":{const t=e.message.value,r=void 0!==t.inputTokens||void 0!==t.outputTokens||void 0!==t.cacheReadTokens||void 0!==t.cacheWriteTokens;return Object.assign({type:"turn-ended"},r&&{usage:{inputTokens:Number(null!==(a=t.inputTokens)&&void 0!==a?a:BigInt(0)),outputTokens:Number(null!==(l=t.outputTokens)&&void 0!==l?l:BigInt(0)),cacheReadTokens:Number(null!==(c=t.cacheReadTokens)&&void 0!==c?c:BigInt(0)),cacheWriteTokens:Number(null!==(u=t.cacheWriteTokens)&&void 0!==u?u:BigInt(0))}})}case"toolCallDelta":return null;case"stepStarted":return{type:"step-started",stepId:Number(e.message.value.stepId)};case"stepCompleted":return{type:"step-completed",stepId:Number(e.message.value.stepId),stepDurationMs:Number(e.message.value.stepDurationMs)};case"promptSuggestion":case"postRequestPrompt":case"activeBranchChange":case"feedbackRequest":case void 0:return null;default:return e.message,null}}(t,m);null!==e&&(yield r.sendUpdate(e))})),query:(e,t)=>Jv(this,void 0,void 0,(function*(){return function(e){var t;switch(e.query.case){case"webSearchRequestQuery":return zt(e.id);case"webFetchRequestQuery":return qt(e.id);case"switchModeRequestQuery":return Jt(e.id);case"askQuestionInteractionQuery":return Vt(e.id,new Dt.tz({result:{case:"rejected",value:new Dt.ox({reason:"Interactive questions are not supported in local SDK runs"})}}));case"createPlanRequestQuery":return Zt(e.id,new Mt.bK({result:{case:"success",value:new Mt.Jo},planUri:""}));case"setupVmEnvironmentArgs":return Yt(e.id,new $t.r$({result:{case:"success",value:new $t.JH}}));case"replaceEnvArgs":return Xt(e.id,new Nt.dV({result:{case:"failure",value:new Nt.uq({errorMessage:"Environment replacement is not supported in local SDK runs",setupLogs:""})}}));case"prManagementRequestQuery":return Qt(e.id,new jt.HL({result:{case:"error",value:new jt.K$({error:"PR management is only available in cloud agents"})}}));case"mcpAuthRequestQuery":return er(e.id,"MCP authentication is not supported in local SDK runs");case"generateImageRequestQuery":return tr(e.id,null===(t=e.query.value.args)||void 0===t?void 0:t.description);case void 0:throw new Bv.j1("Missing interaction query type",{isRetryable:!1});default:throw e.query,new Bv.j1("Unhandled interaction query type",{isRetryable:!1})}}(t)}))};if(x!==t.apiKey||!_){yield Promise.all([(0,Hv.ly)(t.apiKey),(0,Hv.mU)(t.apiKey)]);const e=(0,Hv.KU)(t.apiKey),r=co((0,ar.createClient)(uv.N,e),{injectTraceHeaders:!0});_=new to(r),x=t.apiKey}const T=(0,Hv.Vh)(_,(()=>{const e=(0,Hv.KU)(t.apiKey),r=co((0,ar.createClient)(uv.N,e),{injectTraceHeaders:!0}),o=new to(r);return _=o,x=t.apiKey,o})),I=new cv({agentClient:T,getResources:e=>Jv(this,[e],void 0,(function*({agentId:e}){let r=w.get(e);return r||(r=yield E.createSessionRuntime({sessionId:e,mcpServersOverride:f,extraMcpTools:g}),Kv(r,t.customTools),r.resources.base.register(ft,A),w.set(e,r)),r.resources.wrapped})),mcpTools:g,workspacePath:c,parentConversationId:m,onSessionReleased:e=>{const t=w.get(e);t&&(t.dispose(),w.delete(e))}}),A=(b=I,{async execute(e,t,r){var o,n,s,i;let a;try{a=await b.createOrResumeSession(e,t);const i=await b.runSession(e,a,t,{execId:null==r?void 0:r.execId});return"error"===i.status?new ht.vS({result:{case:"error",value:new ht.od({agentId:a,error:i.error})}}):"aborted"===i.status?new ht.vS({result:{case:"error",value:new ht.od({agentId:a,error:null!==(o=i.error)&&void 0!==o?o:"Subagent was aborted by the user"})}}):"background"===i.status?new ht.vS({result:{case:"success",value:new ht.HJ({agentId:a,finalMessage:i.finalMessage,toolCallCount:null!==(n=i.toolCallCount)&&void 0!==n?n:0,backgroundReason:i.backgroundReason,transcriptPath:i.transcriptPath})}}):new ht.vS({result:{case:"success",value:new ht.HJ({agentId:a,finalMessage:i.finalMessage,toolCallCount:null!==(s=i.toolCallCount)&&void 0!==s?s:0})}})}catch(e){a&&b.releaseSession&&b.releaseSession(a);const r=e instanceof Error?e.message:String(e),o=null!==(i=null!=a?a:function(e){if(e instanceof mt&&e.agentId)return e.agentId;if(!e||"object"!=typeof e)return;const t=e;return"string"==typeof t.agentId?t.agentId:void 0}(e))&&void 0!==i?i:t.resumeAgentId;return new ht.vS({result:{case:"error",value:new ht.od(Object.assign(Object.assign({},o?{agentId:o}:{}),{error:r}))}})}}});y.resources.base.register(ft,A);const O=E.services.hooksRuntime,D=O?function(e){const{workspaceRuntime:t}=e;if(!(t.hooksConfigLease.hasHookForStep(G.sessionStart)||t.hooksConfigLease.hasHookForStep(G.sessionEnd)||t.hooksConfigLease.hasHookForStep(G.stop)||t.hooksConfigLease.hasHookForStep(G.beforeSubmitPrompt)))return{};const r=t.createSessionRuntime({sessionState:e.sessionState,metadata:e.metadata}),{hookExecutor:o}=r;let n;return{async onSessionStart(e){if(n=e,o.hasHooksForStep(G.sessionStart))try{const t=Object.assign(Object.assign({conversation_id:e.conversationId,generation_id:e.generationId,model:e.model},ce(e)),{is_background_agent:!1}),r=await o.executeHookForStep(G.sessionStart,t);if(r)return r.env&&o.setSessionEnvironment(r.env),{env:r.env,additionalContext:r.additional_context,blocked:!1===r.continue,blockedReason:r.user_message}}catch(e){fm.warn("[hooks-adapter] sessionStart hook failed:",e)}},async onSessionEnd(e,t){var r,s,i;if(o.hasHooksForStep(G.sessionEnd))try{const a=Object.assign(Object.assign({conversation_id:null!==(r=null==n?void 0:n.conversationId)&&void 0!==r?r:"",generation_id:null!==(s=null==n?void 0:n.generationId)&&void 0!==s?s:"",model:null!==(i=null==n?void 0:n.model)&&void 0!==i?i:"unknown"},n?ce(n):{}),{reason:e,duration_ms:t,is_background_agent:!1,final_status:e});await o.executeHookForStep(G.sessionEnd,a)}catch(e){fm.warn("[hooks-adapter] sessionEnd hook failed:",e)}finally{o.clearSessionEnvironment()}else o.clearSessionEnvironment()},async onBeforeSubmitPrompt(e){var t;if(o.hasHooksForStep(G.beforeSubmitPrompt))try{const r=Object.assign(Object.assign({conversation_id:e.conversationId,generation_id:e.generationId,model:e.model},ce(e)),{prompt:null!==(t=e.promptText)&&void 0!==t?t:"",attachments:[]});await o.executeHookForStep(G.beforeSubmitPrompt,r)}catch(e){fm.warn("[hooks-adapter] beforeSubmitPrompt hook failed:",e)}},async onTurnCompleted(e){if(!o.hasHooksForStep(G.stop))return;const t=Object.assign(Object.assign({conversation_id:e.conversationId,generation_id:e.generationId,model:e.model},ce(e)),{status:"completed",loop_count:e.loopCount}),r=await o.executeHookForStep(G.stop,t),n="string"==typeof(null==r?void 0:r.followup_message)?r.followup_message.trim():"";return n.length>0?n:void 0},async onTurnError(e){if(o.hasHooksForStep(G.stop))try{const t=Object.assign(Object.assign({conversation_id:e.conversationId,generation_id:e.generationId,model:e.model},ce(e)),{status:"error",loop_count:e.loopCount});await o.executeHookForStep(G.stop,t)}catch(e){fm.warn("[hooks-adapter] onTurnError stop hook failed:",e)}},async onTurnAborted(e){if(o.hasHooksForStep(G.stop))try{const t=Object.assign(Object.assign({conversation_id:e.conversationId,generation_id:e.generationId,model:e.model},ce(e)),{status:"aborted",loop_count:e.loopCount});await o.executeHookForStep(G.stop,t)}catch(e){fm.warn("[hooks-adapter] onTurnAborted stop hook failed:",e)}},async dispose(){await r.dispose()}}}({workspaceRuntime:O,sessionState:y.state,metadata:y.metadata}):void 0,M=new iv({workspacePath:c,conversationId:m,blobStore:l}),j=function(e,t,r){const{hooks:o}=r,[n,s]=e.withCancel(),i=new xt;let a=r.initialState;const l={async handleCheckpoint(e,t){var o;a=t,await(null===(o=r.onCheckpoint)||void 0===o?void 0:o.call(r,t))},getLatestCheckpoint:()=>a};let c="completed";const u=Date.now(),d=(async()=>{var e,s,u,d,p,h,m,f,g;const v=vm(r,0,gm(t));try{const t=await(null===(e=null==o?void 0:o.onSessionStart)||void 0===e?void 0:e.call(o,v));if(null==t?void 0:t.blocked)throw c="error",new Error(null!==(m=t.blockedReason)&&void 0!==m?m:"Session blocked by sessionStart hook")}catch(e){if("completed"!==c)throw e;fm.warn("[agent-session-runner] sessionStart hook failed:",e)}let y=t,w=0;for(;y;){const e=vm(r,w,gm(y));try{await(null===(s=null==o?void 0:o.onBeforeSubmitPrompt)||void 0===s?void 0:s.call(o,e))}catch(e){fm.warn("[agent-session-runner] beforeSubmitPrompt hook failed:",e)}const t=0===w?r.preFetchedBlobs:void 0;try{await r.agentClient.run(n,a,y,void 0,r.interactionListener,r.resources,r.blobStore,i,l,null!==(f=r.mcpTools)&&void 0!==f?f:[],Object.assign(Object.assign(Object.assign({conversationId:r.conversationId},r.runOptions),{subagentModelOverrides:null!==(g=null===(u=r.runOptions)||void 0===u?void 0:u.subagentModelOverrides)&&void 0!==g?g:[]}),void 0!==t?{preFetchedBlobs:t}:{}))}catch(t){throw c=ym(t)?"aborted":"error",null==(b="aborted"===c?null===(d=null==o?void 0:o.onTurnAborted)||void 0===d?void 0:d.call(o,e):null===(p=null==o?void 0:o.onTurnError)||void 0===p?void 0:p.call(o,e))||b.catch((e=>{fm.warn("[agent-session-runner] fire-and-forget hook failed:",e)})),t}let m;try{m=await(null===(h=null==o?void 0:o.onTurnCompleted)||void 0===h?void 0:h.call(o,e))}catch(e){throw c="error",e}const v="string"==typeof m?m.trim():"";0!==v.length?(w+=1,i.resetStream(),S=v,y=new L.QF({action:{case:"userMessageAction",value:new L.Vt({userMessage:new L.RG({text:S})})}})):y=void 0}var b,S})().finally((async()=>{var e,t;const r=Date.now()-u;try{await(null===(e=null==o?void 0:o.onSessionEnd)||void 0===e?void 0:e.call(o,c,r))}catch(e){fm.warn("[agent-session-runner] sessionEnd hook failed:",e)}try{await(null===(t=null==o?void 0:o.dispose)||void 0===t?void 0:t.call(o))}catch(e){fm.warn("[agent-session-runner] hooks dispose failed:",e)}}));return{done:d,abort(){s()}}}(p,P,Object.assign(Object.assign({agentClient:T,interactionListener:R,resources:s,blobStore:l,initialState:d,conversationId:m,mcpTools:g,runOptions:{generationUUID:t.requestId,requestedModel:v}},t.preFetchedBlobs&&t.preFetchedBlobs.length>0?{preFetchedBlobs:t.preFetchedBlobs}:{}),{hooks:D,onCheckpoint(e){return Jv(this,void 0,void 0,(function*(){var r;d=e,M.writeFromState(p,e),yield null===(r=t.onCheckpoint)||void 0===r?void 0:r.call(t,e)}))}})),N=j.done.finally((()=>Jv(this,void 0,void 0,(function*(){try{yield I.awaitBackgroundWorkers()}finally{yield M.waitForPendingWrites().catch((()=>{}));for(const e of w.values())try{yield e.dispose()}catch(e){Wv.v.log(`Failed to dispose subagent session runtime: ${e instanceof Error?e.message:String(e)}`)}w.clear(),yield y.dispose()}})))).catch((e=>{throw e}));return{abort(){j.abort(),h()},done:N}}catch(e){for(const e of w.values())try{yield e.dispose()}catch(e){}throw w.clear(),yield y.dispose(),e}var b}))))})),reload(){return Jv(this,void 0,void 0,(function*(){yield E.reload()}))},dispose(){return Jv(this,void 0,void 0,(function*(){yield E.dispose()}))}}}))}},"../constants/dist/index.js"(e,t,r){r.d(t,{pZ:()=>i,G$:()=>a,tl:()=>c,RJ:()=>d}),new Set(["agent-stores","shared-agent-stores"]);const o={clusters:{local:{managerUrl:"http://localhost:50051",httpProxyUrl:null,isLocal:!0,class:null,label:"Local",spaceliftStackId:null,portalWebsite:{vncWebsocketOrigin:null},anyrunDashboard:{group:null,show:!0},docsSite:{publishPublicIps:!1}},dev:{managerUrl:"https://dev.cursorvm-manager.com",httpProxyUrl:"10.0.29.128:8080",isLocal:!1,class:"external",label:"Dev",spaceliftStackId:"agent-runner-vpcs-dev",portalWebsite:{vncWebsocketOrigin:"wss://*.dev.cursorvm.com"},anyrunDashboard:{group:null,show:!0},docsSite:{publishPublicIps:!1}},train1:{awsRegion:"us-east-1",managerUrl:"https://train1.cursorvm-manager.com",httpProxyUrl:null,isLocal:!1,class:"internal",label:"train1",spaceliftStackId:"agent-runner-vpcs-train1",portalWebsite:{vncWebsocketOrigin:null},anyrunDashboard:{group:"training",show:!0},docsSite:{publishPublicIps:!1}},train2:{awsRegion:"us-east-1",managerUrl:"https://train2.cursorvm-manager.com",httpProxyUrl:null,isLocal:!1,class:"internal",label:"train2",spaceliftStackId:"agent-runner-vpcs-train2",portalWebsite:{vncWebsocketOrigin:null},anyrunDashboard:{group:"training",show:!0},docsSite:{publishPublicIps:!1}},train3:{awsRegion:"us-east-1",managerUrl:"https://train3.cursorvm-manager.com",httpProxyUrl:null,isLocal:!1,class:"internal",label:"train3",spaceliftStackId:"agent-runner-vpcs-train3",portalWebsite:{vncWebsocketOrigin:null},anyrunDashboard:{group:"training",show:!0},docsSite:{publishPublicIps:!1}},train4:{awsRegion:"us-east-2",managerUrl:"https://train4.cursorvm-manager.com",httpProxyUrl:null,isLocal:!1,class:"internal",label:"train4",spaceliftStackId:"agent-runner-vpcs-train4",portalWebsite:{vncWebsocketOrigin:null},anyrunDashboard:{group:"training",show:!0},docsSite:{publishPublicIps:!1}},train5:{awsRegion:"us-west-2",managerUrl:"https://train5.cursorvm-manager.com",httpProxyUrl:null,isLocal:!1,class:"internal",label:"train5",spaceliftStackId:"agent-runner-vpcs-train5",portalWebsite:{vncWebsocketOrigin:null},anyrunDashboard:{group:"training",show:!0},docsSite:{publishPublicIps:!1}},train6:{awsRegion:"eu-central-1",managerUrl:"https://train6.cursorvm-manager.com",httpProxyUrl:null,isLocal:!1,class:"internal",label:"train6",spaceliftStackId:"agent-runner-vpcs-train6",portalWebsite:{vncWebsocketOrigin:null},anyrunDashboard:{group:"training",show:!0},docsSite:{publishPublicIps:!1}},train7:{awsRegion:"eu-west-1",managerUrl:"https://train7.cursorvm-manager.com",httpProxyUrl:null,isLocal:!1,class:"internal",label:"train7",spaceliftStackId:"agent-runner-vpcs-train7",portalWebsite:{vncWebsocketOrigin:null},anyrunDashboard:{group:"training",show:!0},docsSite:{publishPublicIps:!1}},train8:{awsRegion:"us-east-1",managerUrl:"https://train8.cursorvm-manager.com",httpProxyUrl:null,isLocal:!1,class:"internal",label:"train8",spaceliftStackId:"agent-runner-vpcs-train8",portalWebsite:{vncWebsocketOrigin:null},anyrunDashboard:{group:"training",show:!0},docsSite:{publishPublicIps:!1}},train9:{awsRegion:"us-west-2",managerUrl:"https://train9.cursorvm-manager.com",httpProxyUrl:null,isLocal:!1,class:"internal",label:"train9",spaceliftStackId:"agent-runner-vpcs-train9",portalWebsite:{vncWebsocketOrigin:null},anyrunDashboard:{group:"training",show:!0},docsSite:{publishPublicIps:!1}},train10:{awsRegion:"us-west-2",managerUrl:"https://train10.cursorvm-manager.com",httpProxyUrl:null,isLocal:!1,class:"internal",label:"train10",spaceliftStackId:"agent-runner-vpcs-train10",portalWebsite:{vncWebsocketOrigin:null},anyrunDashboard:{group:"training",show:!0},docsSite:{publishPublicIps:!1}},train11:{awsRegion:"us-west-2",managerUrl:"https://train11.cursorvm-manager.com",httpProxyUrl:null,isLocal:!1,class:"internal",label:"train11",spaceliftStackId:"agent-runner-vpcs-train11",portalWebsite:{vncWebsocketOrigin:null},anyrunDashboard:{group:"training",show:!0},docsSite:{publishPublicIps:!1}},train12:{awsRegion:"eu-west-2",managerUrl:"https://train12.cursorvm-manager.com",httpProxyUrl:null,isLocal:!1,class:"internal",label:"train12",spaceliftStackId:"agent-runner-vpcs-train12",portalWebsite:{vncWebsocketOrigin:null},anyrunDashboard:{group:"training",show:!0},docsSite:{publishPublicIps:!1}},eval1:{awsRegion:"us-east-1",managerUrl:"https://eval1.cursorvm-manager.com",httpProxyUrl:null,isLocal:!1,class:"internal",label:"eval1",spaceliftStackId:"agent-runner-vpcs-eval1",portalWebsite:{vncWebsocketOrigin:null},anyrunDashboard:{group:"eval",show:!0},docsSite:{publishPublicIps:!1}},eval2:{awsRegion:"us-east-1",managerUrl:"https://eval2.cursorvm-manager.com",httpProxyUrl:null,isLocal:!1,class:"internal",label:"eval2",spaceliftStackId:"agent-runner-vpcs-eval2",portalWebsite:{vncWebsocketOrigin:null},anyrunDashboard:{group:"eval",show:!0},docsSite:{publishPublicIps:!1}},eval3:{awsRegion:"us-west-2",managerUrl:"https://eval3.cursorvm-manager.com",httpProxyUrl:null,isLocal:!1,class:"internal",label:"eval3",spaceliftStackId:"agent-runner-vpcs-eval3",portalWebsite:{vncWebsocketOrigin:null},anyrunDashboard:{group:"eval",show:!0},docsSite:{publishPublicIps:!1}},test1:{managerUrl:"https://test1.cursorvm-manager.com",httpProxyUrl:null,isLocal:!1,class:"internal",label:"test1",spaceliftStackId:"agent-runner-vpcs-test1",portalWebsite:{vncWebsocketOrigin:null},anyrunDashboard:{group:null,show:!0},docsSite:{publishPublicIps:!1}},"test2-gcp":{awsRegion:"us-east-1",managerUrl:"https://test2-gcp.cursorvm-manager.com",httpProxyUrl:null,isLocal:!1,class:"internal",label:"test2-gcp",spaceliftStackId:"agent-runner-vpcs-test2-gcp",portalWebsite:{vncWebsocketOrigin:null},anyrunDashboard:{group:null,show:!0},docsSite:{publishPublicIps:!1}},us1:{awsRegion:"us-west-2",managerUrl:"https://us1.cursorvm-manager.com",httpProxyUrl:"10.0.21.248:8080",isLocal:!1,class:"external",label:"us1",spaceliftStackId:"agent-runner-vpcs-us1",portalWebsite:{vncWebsocketOrigin:"wss://*.us1.cursorvm.com"},anyrunDashboard:{group:"us",show:!0},docsSite:{publishPublicIps:!0}},us1p:{awsRegion:"us-west-2",managerUrl:"https://us1p.cursorvm-manager.com",httpProxyUrl:"10.0.29.68:8080",isLocal:!1,class:"external",label:"us1 (Privacy)",spaceliftStackId:"agent-runner-vpcs-us1p",portalWebsite:{vncWebsocketOrigin:"wss://*.us1p.cursorvm.com"},anyrunDashboard:{group:"us",show:!0},docsSite:{publishPublicIps:!0}},us3:{awsRegion:"us-east-1",managerUrl:"https://us3.cursorvm-manager.com",httpProxyUrl:"10.0.25.8:8080",isLocal:!1,class:"external",label:"us3",spaceliftStackId:"agent-runner-vpcs-us3",portalWebsite:{vncWebsocketOrigin:"wss://*.us3.cursorvm.com"},anyrunDashboard:{group:"us",show:!0},docsSite:{publishPublicIps:!0}},us3p:{awsRegion:"us-east-1",managerUrl:"https://us3p.cursorvm-manager.com",httpProxyUrl:"10.0.26.30:8080",isLocal:!1,class:"external",label:"us3 (Privacy)",spaceliftStackId:"agent-runner-vpcs-us3p",portalWebsite:{vncWebsocketOrigin:"wss://*.us3p.cursorvm.com"},anyrunDashboard:{group:"us",show:!0},docsSite:{publishPublicIps:!0}},us4:{awsRegion:"us-west-2",managerUrl:"https://us4.cursorvm-manager.com",httpProxyUrl:"10.0.16.154:8080",isLocal:!1,class:"external",label:"us4",spaceliftStackId:"agent-runner-vpcs-us4",portalWebsite:{vncWebsocketOrigin:"wss://*.us4.cursorvm.com"},anyrunDashboard:{group:"us",show:!0},docsSite:{publishPublicIps:!0}},us4p:{awsRegion:"us-west-2",managerUrl:"https://us4p.cursorvm-manager.com",httpProxyUrl:"10.0.20.248:8080",isLocal:!1,class:"external",label:"us4 (Privacy)",spaceliftStackId:"agent-runner-vpcs-us4p",portalWebsite:{vncWebsocketOrigin:"wss://*.us4p.cursorvm.com"},anyrunDashboard:{group:"us",show:!0},docsSite:{publishPublicIps:!0}},us5:{awsRegion:"us-east-2",managerUrl:"https://us5.cursorvm-manager.com",httpProxyUrl:"10.0.28.203:8080",isLocal:!1,class:"external",label:"us5",spaceliftStackId:"agent-runner-vpcs-us5",portalWebsite:{vncWebsocketOrigin:"wss://*.us5.cursorvm.com"},anyrunDashboard:{group:"us",show:!0},docsSite:{publishPublicIps:!0}},us5p:{awsRegion:"us-east-2",managerUrl:"https://us5p.cursorvm-manager.com",httpProxyUrl:"10.0.25.35:8080",isLocal:!1,class:"external",label:"us5 (Privacy)",spaceliftStackId:"agent-runner-vpcs-us5p",portalWebsite:{vncWebsocketOrigin:"wss://*.us5p.cursorvm.com"},anyrunDashboard:{group:"us",show:!0},docsSite:{publishPublicIps:!0}},us6:{awsRegion:"us-east-2",managerUrl:"https://us6.cursorvm-manager.com",httpProxyUrl:"10.0.31.117:8080",isLocal:!1,class:"external",label:"us6",spaceliftStackId:"agent-runner-vpcs-us6",portalWebsite:{vncWebsocketOrigin:"wss://*.us6.cursorvm.com"},anyrunDashboard:{group:"us",show:!0},docsSite:{publishPublicIps:!0}},us6p:{awsRegion:"us-east-2",managerUrl:"https://us6p.cursorvm-manager.com",httpProxyUrl:"10.0.28.204:8080",isLocal:!1,class:"external",label:"us6 (Privacy)",spaceliftStackId:"agent-runner-vpcs-us6p",portalWebsite:{vncWebsocketOrigin:"wss://*.us6p.cursorvm.com"},anyrunDashboard:{group:"us",show:!0},docsSite:{publishPublicIps:!0}},us7:{awsRegion:"us-east-1",managerUrl:"https://us7.cursorvm-manager.com",httpProxyUrl:"10.0.56.33:8080",isLocal:!1,class:"external",label:"us7",spaceliftStackId:"agent-runner-vpcs-us7",portalWebsite:{vncWebsocketOrigin:"wss://*.us7.cursorvm.com"},anyrunDashboard:{group:"us",show:!0},docsSite:{publishPublicIps:!0}},us7p:{awsRegion:"us-east-1",managerUrl:"https://us7p.cursorvm-manager.com",httpProxyUrl:"10.0.26.89:8080",isLocal:!1,class:"external",label:"us7 (Privacy)",spaceliftStackId:"agent-runner-vpcs-us7p",portalWebsite:{vncWebsocketOrigin:"wss://*.us7p.cursorvm.com"},anyrunDashboard:{group:"us",show:!0},docsSite:{publishPublicIps:!0}}}},n=["dev","us1","us1p","us3","us3p","us4","us4p","us5","us5p","us6","us6p","us7","us7p","train1","train2","train3","train4","train5","train6","train7","train8","train9","train10","train11","train12","eval1","eval2","eval3","test1","test2-gcp","local"];var s;!function(){const e=Object.keys(o.clusters),t=n,r=e.filter((e=>!t.includes(e))),s=t.filter((t=>!e.includes(t)));if(r.length>0||s.length>0)throw new Error(["[@anysphere/constants] anyrunClusterOrdering must exactly match anyrunClusterConfig.clusters keys.",r.length>0?`Missing from ordering: ${r.join(", ")}`:void 0,s.length>0?`Unknown in ordering: ${s.join(", ")}`:void 0].filter(Boolean).join(" "))}(),function(){const e=Object.keys(o.clusters).filter((e=>o.clusters[e].docsSite.publishPublicIps)).filter((e=>!("awsRegion"in o.clusters[e])));if(e.length>0)throw new Error(["[@anysphere/constants] docsSite.publishPublicIps=true clusters must define awsRegion.",e.length>0?`Missing AWS regions: ${e.join(", ")}`:void 0].filter(Boolean).join(" "))}(),new Set(["image/png","image/jpeg","image/gif","image/webp","video/mp4","video/webm"]),function(e){e.github="github",e.githubEnterprise="github-enterprise",e.cursorGithub="cursor-github"}(s||(s={})),new Set(["Your environment snapshot has expired after inactivity.","Your environment snapshot is invalid.","The environment snapshot you requested does not exist, or you do not have permission to access it.","Failed to start the development environment. The update script in your configuration failed during VM startup.","Failed to start the development environment. The build process failed. Please check your Dockerfile."]);const i=8388608,a="https://ptht05hbb1ssoooe.public.blob.vercel-storage.com/assets/uploads/cursorlogomcpv3.svg",l=["cursor"],c="http://localhost:8787/callback";function u(e){return`${e}://anysphere.cursor-mcp/oauth/callback`}function d(e){const t=new Set,r=void 0!==e&&function(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(e){return!1}}(e);e&&!r&&t.add(e);for(const e of Array.from(new Set([...l])).map(u))t.add(e);return t.add("https://www.cursor.com/agents/mcp/oauth/callback"),t.add(c),e&&r&&t.add(e),Array.from(t)}const p={standard:{referralDiscountId:"cursor-for-startups",creditLabel:"$5,000",durationMonths:6,coupons:{production:{seats:"QmOizAV7",bugbot:"Tmc1ZTk7"},test:{seats:"CNmegx7g",bugbot:"upIo5KlJ"}}},yc:{referralDiscountId:"cursor-for-startups-yc",creditLabel:"$60,000",durationMonths:12,coupons:{production:{seats:"pvrVSY2a",bugbot:"qJcxrNlY"},test:{seats:"CNmegx7g",bugbot:"upIo5KlJ"}}}};function h(e){return p[e]}h("yc").creditLabel,h("standard").creditLabel,new Set(["github.com","gitlab.com","bitbucket.org","bitbucket.com","codeberg.org","gitea.com","sr.ht"]),new Set(["pr_tab_init","pr_tab_refresh","pr_branch_poll","pr_metadata_refresh","pr_reviews_subtab","pr_diff_view","pr_status_pill","cloud_agent_pr_state","agent_tool_call","unknown"])},"../mcp-agent-exec/dist/mcp-sandbox-policy.js"(e,t,r){r.d(t,{buildMcpSandboxPolicy:()=>o.Ic});var o=r("../mcp-core/dist/index.js")},"../mcp-core/dist/index.js"(e,t,r){r.d(t,{B1:()=>o,c8:()=>ve,Ic:()=>fe,O3:()=>H,tB:()=>L,ME:()=>$,Fm:()=>ge,jI:()=>me,VD:()=>Q,T4:()=>F,X5:()=>Y,PK:()=>ye,q2:()=>i});class o{ttl;state;staleDirty=!1;refreshInFlight;refreshGeneration=0;constructor(e=864e5){this.ttl=e}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(e){}finally{r&&this.refreshInFlight===r&&(this.refreshInFlight=void 0)}})(),this.refreshInFlight=r}return t}const r=await e();return this.state={expiresAt:performance.now()+this.ttl,value:r},this.staleDirty=!1,r}invalidate(){this.refreshGeneration++,this.state=void 0,this.staleDirty=!1,this.refreshInFlight=void 0}invalidateKeepingStale(){this.state&&(this.staleDirty=!0)}}function n(e){return Object.fromEntries(Object.entries(e).filter((([,e])=>void 0!==e)))}function s(e,t){const r=function(e){try{const t=new URL(e);return{host:t.host,origin:t.origin,pathname:t.pathname}}catch(e){return{host:null,origin:null,pathname:null}}}(e),o=!1!==(null==t?void 0:t.includePath);return{host:r.host,origin:r.origin,path:o?r.pathname:null}}function i(e,t){return s(e,t)}var a=r("crypto");const l=BigInt(0),c=BigInt(8),u=BigInt(16),d=BigInt(65535);function p(e){const t=e.split(".");if(4!==t.length)return;let r=l;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<<c|BigInt(t)}return{version:4,value:r}}function h(e){if(0===e.length)return[];const t=[],r=e.split(":");for(let e=0;e<r.length;e++){const o=r[e];if(0===o.length)return;if(o.includes(".")){if(e!==r.length-1)return;const n=p(o);if(!n)return;t.push(Number(n.value>>u&d)),t.push(Number(n.value&d))}else{if(!/^[0-9a-f]{1,4}$/i.test(o))return;t.push(Number.parseInt(o,16))}}return t}function m(e){var t;return null!==(t=p(e))&&void 0!==t?t:function(e){const t=j(e);if(0===t.length||t.includes(":::"))return;const r=t.indexOf("::");if(-1===r){const e=h(t);if(!e||8!==e.length)return;return{version:6,value:e.reduce(((e,t)=>e<<u|BigInt(t)),l)}}if(-1!==t.indexOf("::",r+1))return;const o=t.slice(0,r),n=t.slice(r+2),s=h(o),i=h(n);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<<u|BigInt(t)),l)}}(e)}function f(e,t){const r=j(e),o=j(t);if("*"===o)return!0;if(o.includes("/"))return function(e,t){const r=t.lastIndexOf("/");if(r<=0||r===t.length-1)return!1;const o=m(t.slice(0,r)),n=m(e);if(!o||!n||o.version!==n.version)return!1;const s=Number(t.slice(r+1)),i=4===o.version?32:128;if(!Number.isInteger(s)||s<0||s>i)return!1;const a=BigInt(i-s);return n.value>>a==o.value>>a}(r,o);if(o.startsWith("*.")){const e=o.slice(2);return r===e||r.endsWith(`.${e}`)}return r===o}const g="Blocked by MCP Network Admin Server Controls";function v(e){return/\s/.test(e)}const y="[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?",w=new RegExp(`^(?:${y}\\.)*${y}$`),b=new RegExp(`^\\*\\.(?:${y}\\.)*${y}$`),S="(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)",k=new RegExp(`^${S}(?:\\.${S}){3}$`),E=/^[0-9a-f:]+$/,x=new RegExp(`^(?:${S}(?:\\.${S}){3}|[0-9a-f:]+)\\/\\d{1,3}$`);function _(e){const t=j(e);return t.length>0&&t.length<=253&&w.test(t)}function C(e){const t=j(e);return k.test(t)||function(e){const t=j(e);if(!E.test(t))return!1;try{return new URL(`https://[${t}]`),!0}catch(e){return!1}}(t)}function P(e,t){return""===t||"http:"===e&&"80"===t||"https:"===e&&"443"===t}function R(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 P(t,e.port)||(r+=`:${e.port}`),r}const r=e.protocol.toLowerCase();let o=`${r}//${e.hostname.toLowerCase()}`;return P(r,e.port)||(o+=`:${e.port}`),`${o}${t.pathname}${t.search}`}function T(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("*")&&(_(t)||C(t))}(t.hostname)}catch(e){return!1}}(e);const t=j(e);return"*"===t||!!b.test(t)||(t.includes("/")?function(e){const t=j(e);if(!x.test(t))return!1;const[r]=t.split("/");return void 0!==r&&f(r,t)}(t):_(t)||C(t))}function I(e,t){if(!e.includes("*"))return e===t;const r=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${r}$`).test(t)}function A(e){return e.endsWith("/")&&e.length>1?e.slice(0,-1):e}function O(e,t){return function(e,t,r){const o=D(t);if(!o)return!1;let n;try{n=new URL(e)}catch(e){return!1}return""===n.username&&""===n.password&&""===o.username&&""===o.password&&n.protocol===o.protocol&&n.port===o.port&&(s=n.hostname,i=o.hostname,!s.includes("*")&&j(s)===j(i)&&(I(a=n.pathname,l=o.pathname)||I(A(a),A(l)))&&function(e,t,r){return""===e?r.allowRequestQueryWhenPatternOmitsQuery||""===t:I(e,t)}(n.search,o.search,r));var s,i,a,l}(e,t,{allowRequestQueryWhenPatternOmitsQuery:!0})}function D(e){const t=e.trim();if(0===t.length||v(t))return;if(function(e){const t=e.indexOf("[");return-1!==t&&-1===e.indexOf("]",t)}(t))return;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(e){return}}(t);if(r&&("http:"===r.protocol||"https:"===r.protocol)&&""===r.username&&""===r.password&&0!==r.hostname.length&&(!j(r.hostname).includes(":")||t.includes("["))){if(t.includes("[")){const e=t.indexOf("["),o=t.indexOf("]",e);if(-1===o)return;const n=t.slice(e+1,o);if(j(r.hostname)!==j(n))return}return r}}function M(e){return(null!=e?e:[]).flatMap((e=>{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=`${j(t.slice(0,r))}/${t.slice(r+1).trim()}`;return T(e)?e:void 0}if(v(t)||t.includes("?")||t.includes("#")||t.includes("@"))return;const o=t.indexOf("://");if(-1!==o){const e=t.slice(0,o).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,o=""!==e.search,n=!P(e.protocol,e.port);if(e.hostname.includes("*"))return;if(r||o){const t=R(e);if(!T(t))return;return t}{if(n)return;const t=R(e);if(!T(t))return;return t}}catch(e){return}}else if(t.includes("/"))return;const n=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}(n);return 0===s.length||!T(s)||s!==n&&"*"===s?void 0:s}(e);return void 0===t?[]:[t]}))}function j(e){const t=e.trim().toLowerCase();return t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t}function N(e){const t=e.mcpNetworkAllowlist,r=M(t);return r.length>0?r:(null!=(o=t)?o:[]).some((e=>e.trim().length>0))?[]:M(e.localAgentNetworkAllowlist);var o}function $(e,t){var r,o;if(!0!==t.enabled)return{allowed:!0};if(!D(e))return{allowed:!1,message:null!==(r=t.blockMessage)&&void 0!==r?r:g};const n=N(t);return n.length>0&&n.some((t=>function(e,t){const r=D(t);if(!r)return!1;if(!e.includes("://"))return f(j(r.hostname),e);if(O(e,t))return!0;const o=function(e){try{const t=new URL(e);if(""!==t.username||""!==t.password||!P(t.protocol,t.port)||"/"!==t.pathname||""!==t.search||""!==t.hash)return;return`${t.protocol}//${t.host}/*`}catch(e){return}}(e);return void 0!==o&&O(o,t)}(t,e)))?{allowed:!0}:{allowed:!1,message:null!==(o=t.blockMessage)&&void 0!==o?o:g}}function F(e,t){const r=$(e,t);return r.allowed?void 0:r.message}function L(e,t){const r=null==e?void 0:e.access_token,o="string"==typeof r?r.length:0,n=Boolean(null==e?void 0:e.refresh_token),s="number"==typeof(null==e?void 0:e.expires_in)&&Number.isFinite(e.expires_in)?e.expires_in:null;return{accessTokenLen:o,refreshTokenPresent:n,expiresAtTimestamp:(null==t?void 0:t.expiresInIsFresh)&&null!==s?Date.now()+Math.round(1e3*s):null}}function U(e){if(e)return(0,a.createHash)("sha256").update(e).digest("hex").slice(0,12)}function B(e){if(e&&0!==e.length)return U(JSON.stringify([...e].sort()))}function H(e){var t,r;return{clientIdHash:U(null==e?void 0:e.client_id),clientSecretHash:U(null==e?void 0:e.client_secret),redirectUrisHash:B(null==e?void 0:e.redirect_uris),redirectUriCount:null!==(r=null===(t=null==e?void 0:e.redirect_uris)||void 0===t?void 0:t.length)&&void 0!==r?r:0}}function z(e,t){let r=e;for(const e of t){if("object"!=typeof r||null===r||!(e in r))return;r=r[e]}return r}function W(e,t){for(const r of t)if("string"==typeof z(e,r.split(".")))return z(e,r.split("."))}const q="[REDACTED]",G=/(^|_|-)(token|secret|password|assertion|authorization|verifier|challenge|code)(_|-|$)/i;function V(e){return e.replace(/((?:access_token|refresh_token|id_token|client_secret|authorization|code|password|assertion|token|secret)[^:=\r\n]{0,32}[:=]\s*["']?)([^"',\s&}]+)/gi,`$1${q}`).replace(/(\bBearer\s+)([A-Za-z0-9\-._~+/]+=*)/gi,`$1${q}`)}function J(e,t=256){return e.length>t?`${e.slice(0,Math.max(0,t-3))}...`:e}function K(e,t){return J(V(e),null==t?void 0:t.maxLength)}function Z(e){if("string"==typeof e)return J(V(e));if(void 0!==e)try{const t=JSON.stringify(e,((e,t)=>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")||G.test(t)}(e)?q:"string"==typeof t?V(t):t));if(!t)return;return J(t)}catch(e){return}}function Y(e){var t,r,o,s,i;const a=e instanceof Error?e.name:null!=e?typeof e:void 0,l=e instanceof Error?e.message:null!=e?String(e):void 0,c=void 0!==l?K(l):void 0,u=W(e,["code","cause.code"]),d=null!==(t=function(e){if(!e||"object"!=typeof e)return;const t=e.errorCode;return"string"==typeof t?t:void 0}(e))&&void 0!==t?t:W(e,["errorCode","error","cause.errorCode","cause.error","body.error","response.body.error"]),p=null!==(r=function(e){for(const t of["status","statusCode","response.status","response.statusCode","cause.status","cause.statusCode","cause.response.status","cause.response.statusCode"]){const r=z(e,t.split("."));if("number"==typeof r&&Number.isFinite(r))return r}}(e))&&void 0!==r?r:function(e){var t;if(!e)return;const r=e.match(/\(HTTP (\d+)\)|Non-200 status code \((\d+)\)/),o=null!==(t=null==r?void 0:r[1])&&void 0!==t?t:null==r?void 0:r[2];if(!o)return;const n=Number.parseInt(o,10);return Number.isNaN(n)?void 0:n}(c),h=Z(null!==(i=null!==(s=null!==(o=z(e,["response","body"]))&&void 0!==o?o:z(e,["body"]))&&void 0!==s?s:z(e,["data"]))&&void 0!==i?i:z(e,["cause","body"])),m=function(e){var t,r;const o=null===(t=e.message)||void 0===t?void 0:t.toLowerCase(),n=null===(r=e.code)||void 0===r?void 0:r.toLowerCase();return(null==o?void 0:o.includes("timed out"))||(null==o?void 0:o.includes("timeout"))||(null==o?void 0:o.includes("etimedout"))||"etimedout"===n?"timeout":(null==o?void 0:o.includes("enotfound"))||(null==o?void 0:o.includes("eai_again"))||(null==o?void 0:o.includes("dns"))||"enotfound"===n||"eai_again"===n?"dns":(null==o?void 0:o.includes("certificate"))||(null==o?void 0:o.includes("tls"))||(null==o?void 0:o.includes("ssl"))?"tls":(null==o?void 0:o.includes("econnreset"))||(null==o?void 0:o.includes("connection reset"))||"econnreset"===n?"connection_reset":(null==o?void 0:o.includes("econnrefused"))||(null==o?void 0:o.includes("connection refused"))||"econnrefused"===n?"connection_refused":void 0}({message:c,code:u});return n({errorName:a,errorMessage:c,errorType:null!=e?typeof e:void 0,httpStatus:p,oauthErrorCode:d,errorResponseSummary:h,networkClassification:m,sdkErrorKind:d?"oauth_error":m?"auth_transport_error":c?"generic_error":void 0})}const X={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 Q(e){var t,r,o,s,i,a,l,c,u,d;const p=null!==(u=e.message)&&void 0!==u?u:X[e.event],h={event:e.event,cursorMcp:{oauth:n(Object.assign({},e.metadata))}},m=null!==(d=e.level)&&void 0!==d?d:"info";"error"!==m?"warn"!==m?"debug"!==m?null===(c=(l=e.logger).info)||void 0===c||c.call(l,p,h):null===(a=(i=e.logger).debug)||void 0===a||a.call(i,p,h):null===(s=(o=e.logger).warn)||void 0===s||s.call(o,p,h):null===(r=(t=e.logger).error)||void 0===r||r.call(t,p,e.error,h)}const ee=4096;function te(e){return"object"==typeof e&&null!==e&&"url"in e&&"string"==typeof e.url}function re(e){return"string"==typeof e?e:e instanceof URL?e.toString():e.url}function oe(e){const t=[];return e.forEach(((e,r)=>{t.push(r)})),t.sort()}function ne(e){if(null===e)return null;const t=Number.parseInt(e,10);return Number.isNaN(t)?null:t}function se(e,t){var r,o,n,s,i;if(null==e)return{kind:"none",bytes:0,contentLength:ne(t.get("content-length"))};if("string"==typeof e){const o=(new TextEncoder).encode(e).length;return{kind:"text",bytes:o,contentLength:null!==(r=ne(t.get("content-length")))&&void 0!==r?r:o}}if(e instanceof URLSearchParams){const r=e.toString(),n=(new TextEncoder).encode(r).length;return{kind:"text",bytes:n,contentLength:null!==(o=ne(t.get("content-length")))&&void 0!==o?o:n}}return e instanceof Blob?{kind:"blob",bytes:e.size,contentLength:null!==(n=ne(t.get("content-length")))&&void 0!==n?n:e.size}:e instanceof ArrayBuffer?{kind:"binary",bytes:e.byteLength,contentLength:null!==(s=ne(t.get("content-length")))&&void 0!==s?s:e.byteLength}:ArrayBuffer.isView(e)?{kind:"binary",bytes:e.byteLength,contentLength:null!==(i=ne(t.get("content-length")))&&void 0!==i?i:e.byteLength}:"object"==typeof e&&null!==e&&("getReader"in e||Symbol.asyncIterator in e)?{kind:"stream",bytes:null,contentLength:ne(t.get("content-length"))}:{kind:"unknown",bytes:null,contentLength:ne(t.get("content-length"))}}function ie(e,t){var r;if(null===e||!e.toLowerCase().startsWith("application/x-www-form-urlencoded"))return;const o="string"==typeof t?function(e){for(const t of e.split("&")){const e=t.indexOf("="),r=e>=0?t.slice(0,e):t;let o;try{o=decodeURIComponent(r.replaceAll("+"," "))}catch(e){return}if("grant_type"!==o)continue;const n=e>=0?t.slice(e+1):"";try{return decodeURIComponent(n.replaceAll("+"," "))}catch(e){return}}}(t):t instanceof URLSearchParams&&null!==(r=t.get("grant_type"))&&void 0!==r?r:void 0;return o?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"}}(o):void 0}function ae(e){var t,r,o,n;const{input:i,init:a}=e,l=s(re(i)),c=function(e,t){const r=new Headers(te(e)?e.headers:void 0);return new Headers(null==t?void 0:t.headers).forEach(((e,t)=>{r.set(t,e)})),r}(i,a),u=oe(c),d=c.get("content-type"),p=U(null!==(t=c.get("mcp-session-id"))&&void 0!==t?t:void 0),h=c.get("authorization"),m=h&&null!==(r=h.split(/\s+/,1)[0])&&void 0!==r?r:null;return{method:(null!==(n=null!==(o=null==a?void 0:a.method)&&void 0!==o?o:te(i)?i.method:void 0)&&void 0!==n?n:"GET").toUpperCase(),url:l,headers:{names:u,count:u.length},contentType:d,body:se(null==a?void 0:a.body,c),sessionIdHash:null!=p?p:null,authorizationScheme:m}}function le(e,t){var r,o,n,s,i;const a=oe(e.headers),l=ne(e.headers.get("content-length"));return{status:e.status,ok:e.ok,headers:{names:a,count:a.length},contentType:e.headers.get("content-type"),body:Object.assign({kind:null===e.body?"none":"stream",bytes:null===e.body?0:l,contentLength:l},void 0!==t?{errorSummary:t}:{}),sessionIdHash:null!==(o=U(null!==(r=e.headers.get("mcp-session-id"))&&void 0!==r?r:void 0))&&void 0!==o?o:null,wwwAuthenticateHash:null!==(s=U(null!==(n=e.headers.get("www-authenticate"))&&void 0!==n?n:void 0))&&void 0!==s?s:null,mcpProtocolVersion:null!==(i=e.headers.get("mcp-protocol-version"))&&void 0!==i?i:null}}function ce(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}async function ue(e,t){try{const r=await e.clone().text();return r.length>t?r.slice(0,t):r}catch(e){return}}async function de(e){if(!function(e,t){var r,o;const n=ae({input:e,init:t});if(void 0!==ie(n.contentType,null==t?void 0:t.body))return!0;const s=null!==(o=null===(r=n.url.path)||void 0===r?void 0:r.toLowerCase())&&void 0!==o?o:"";return s.endsWith("/token")||s.includes("/oauth/token")||s.includes("/connect/token")}(e.input,e.init))return;const t=await ue(e.response,ee);if(void 0!==t)try{return Z(JSON.parse(t))}catch(e){return K(t,{maxLength:ee})}}async function pe(e){const t=await async function(e,t){var r,o;try{if(t.ok)return;const n=null!==(o=null===(r=t.headers.get("content-type"))||void 0===r?void 0:r.toLowerCase())&&void 0!==o?o:"";if(!n.includes("json")&&!n.includes("text"))return;const i=await ue(t,ee);if(void 0===i)return;return function(e){if("/mcp"!==(t=s(re(e.input)).path)&&!0!==(null==t?void 0:t.endsWith("/mcp")))return K(e.rawText,{maxLength:ee});var t;try{const t=JSON.parse(e.rawText);return"object"==typeof t&&null!==t?function(e){const t=e.error;if("string"==typeof t)return JSON.stringify({error:t});if("object"!=typeof t||null===t)return;const r=t,o="number"==typeof r.code||"string"==typeof r.code?r.code:void 0,n="string"==typeof r.message?K(r.message,{maxLength:ee}):void 0;return void 0!==o||void 0!==n?JSON.stringify(Object.assign(Object.assign({},void 0!==o?{code:o}:{}),void 0!==n?{message:n}:{})):void 0}(t):void 0}catch(e){return}}({input:e,rawText:i})}catch(e){return}}(e.input,e.response);return{responseErrorSummary:t,oauthTokenErrorBodySummary:void 0===t?await de({input:e.input,response:e.response,init:e.init}):void 0}}function he(e,t,r){var o;try{e()}catch(e){null===(o=t.warn)||void 0===o||o.call(t,"MCP HTTP exchange logging failed",{event:"mcp_http_exchange_logging_failure",phase:r})}}function me(e){const{fetch:t,logger:r,metadata:o,logSuccessfulExchanges:n=!0}=e;return async(e,s)=>{const i=Date.now();try{const a=await t(e,s),{responseErrorSummary:l,oauthTokenErrorBodySummary:c}=a.ok?{}:await pe({input:e,init:s,response:a});return!n&&a.ok||he((()=>{!function(e){var t,r;const{logger:o,response:n}=e,s=function(e){const{input:t,init:r,response:o,durationMs:n,metadata:s,responseErrorSummary:i,oauthTokenErrorBodySummary:a}=e,l=ae({input:t,init:r}),c=ie(l.contentType,null==r?void 0:r.body);return{event:"mcp_http_exchange",outcome:o.ok?"success":"http_error",durationMs:n,cursorMcp:{transport:Object.assign(Object.assign(Object.assign(Object.assign({},s),{request:l,response:le(o,i)}),void 0!==c?{oauth:{grantType:c}}:{}),void 0!==a?{oauthTokenErrorBodySummary:a}:{})}}}(e);n.ok?null===(t=o.info)||void 0===t||t.call(o,"MCP HTTP exchange completed",s):null===(r=o.warn)||void 0===r||r.call(o,"MCP HTTP exchange completed",s)}({logger:r,input:e,init:s,response:a,durationMs:Date.now()-i,metadata:o,responseErrorSummary:l,oauthTokenErrorBodySummary:c})}),r,"success"),a}catch(t){const n=function(e){var t,r;if(!e||"object"!=typeof e)return;const o=[e.response,null===(t=e.cause)||void 0===t?void 0:t.response];for(const e of o)if(e&&"object"==typeof e&&"status"in e&&"number"==typeof e.status&&"headers"in e&&"function"==typeof(null===(r=e.headers)||void 0===r?void 0:r.get))return e}(t),{responseErrorSummary:a,oauthTokenErrorBodySummary:l}=n?await pe({input:e,init:s,response:n}):{};throw he((()=>{!function(e){var t;const{logger:r}=e;null===(t=r.warn)||void 0===t||t.call(r,"MCP HTTP exchange failed",function(e){var t;const{input:r,init:o,error:n,durationMs:s,metadata:i,responseFromError:a,responseErrorSummary:l,oauthTokenErrorBodySummary:c}=e,u=Y(n),d=ae({input:r,init:o}),p=ie(d.contentType,null==o?void 0:o.body),h=void 0!==a?le(a,l):{status:null!==(t=u.httpStatus)&&void 0!==t?t:null,ok:null,headers:{names:[],count:0},contentType:null,body:Object.assign({kind:"none",bytes:null,contentLength:null},void 0!==l?{errorSummary:l}:{}),sessionIdHash:null,wwwAuthenticateHash:null,mcpProtocolVersion:null};return{event:"mcp_http_exchange",outcome:"error",durationMs:s,cursorMcp:{transport:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},i),{request:d,response:h}),void 0!==p?{oauth:{grantType:p}}:{}),void 0!==c?{oauthTokenErrorBodySummary:c}:{}),{error:ce(u)})}}}(e))}({logger:r,input:e,init:s,error:t,durationMs:Date.now()-i,metadata:o,responseFromError:n,responseErrorSummary:a,oauthTokenErrorBodySummary:l})}),r,"failure"),t}}}async function fe(e,t){const{resolveSandboxPolicyForWorkspace:o}=await Promise.resolve().then(r.bind(r,"../shell-exec/dist/index.js")),n=N(e),s={type:"workspace_readwrite",sandboxWorkspaceRoot:t,networkPolicy:n.length>0?{version:1,default:"deny",allow:n}:{version:1,default:"deny"},networkPolicyStrict:!0},{policy:i}=await o(t,{perUser:s});return i}function ge(e){return JSON.stringify({enabled:!0===e.enabled,allow:N(e)})}new Set(["InvalidGrantError","InvalidRequestError"]),new Set(["SiblingAlreadyRefreshedError","OAuthRefreshTransientError","AbortError","TimeoutError","ServerError","TemporarilyUnavailableError"]);class ve extends Error{serverName;constructor(e,t){super(`MCP server "${e}" requires sandboxing because MCP Network Controls are enabled, but the sandbox is not supported on this platform or system. The server was not started.`),this.serverName=e,this.name="McpSandboxUnavailableError",void 0!==t&&(this.cause=t)}}function ye(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||"string"==typeof e.message?e.message:void 0;if(!r)return;const o=r.match(/\bHTTP\s+(\d{3})\b/i);if(!(null==o?void 0:o[1]))return;const n=Number.parseInt(o[1],10);return Number.isNaN(n)?void 0:n}(e);return void 0!==t?400===t||404===t||405===t:!!(e instanceof Error&&e.message.toLowerCase().includes("sessionid must be provided"))||function(e){var t;if(!(e instanceof Error))return!1;const r=e,o=null===(t=e.cause)||void 0===t?void 0:t.code;return"ECONNREFUSED"===r.code||"ECONNREFUSED"===o||e.message.includes("ECONNREFUSED")}(e)}new Map,new Set,new Set(["connection_attempt"]),new Set(["health_probe"]),r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=09ddafc9053ad92a2da409aa9fafaaf83fd21f6a2f2_a311751907fe46e96a8ec737cd50c013/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js"),r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=09ddafc9053ad92a2da409aa9fafaaf83fd21f6a2f2_a311751907fe46e96a8ec737cd50c013/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/errors.js"),Error,r("../constants/dist/index.js"),new Set(["EAI_AGAIN","ECONNABORTED","ECONNREFUSED","ECONNRESET","EHOSTUNREACH","ENETDOWN","ENETUNREACH","ENOTFOUND","EPIPE","ETIMEDOUT","EADDRNOTAVAIL","UND_ERR_CONNECT_TIMEOUT"]),new Set(["ECONNRESET","EPIPE"]),new Set([429,502,503,504]),new Set(["ENOENT","EACCES","ENOTDIR","EPERM"]),new Set(["invalid_grant","invalid_token","invalid_client","unauthorized_client"]),Error},"../shell-exec/dist/index.js"(e,t,r){r.d(t,{BM:()=>wt,Ls:()=>lt,SandboxUnsupportedError:()=>se,J:()=>u,St:()=>ae,Fn:()=>yt,oG:()=>Ge,Ko:()=>m,CG:()=>Ee,G6:()=>vt,_B:()=>L,OK:()=>j,$b:()=>F,Nl:()=>ut,K3:()=>ue,tv:()=>ht,fZ:()=>Pe,s9:()=>_e,T6:()=>B,Po:()=>U,$6:()=>pt,l7:()=>mt,Qd:()=>c,resolveSandboxPolicyForWorkspace:()=>Ie,spawnInSandbox:()=>le});var o=r("node:path"),n=r("../utils/dist/index.js"),s=r("node:fs/promises"),i=r("node:os"),a=r("../context/dist/index.js");let l;function c(){const e=(0,n.Ef)("rg",[]).cmd;return"rg"!==e?e:void 0}function u(e){if(!e)throw new Error("configureRipgrepPath: path must not be empty");l=e}function d(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,o.dirname)(t);if(!r||"."===r)return e;const n=function(e){const t=d(e);return void 0!==t?e[t]??"":""}(e).split(o.delimiter).filter(Boolean);return function(e,t){const r=d(e)??("win32"===process.platform?"Path":"PATH"),o={...e};for(const e of Object.keys(o))e!==r&&"path"===e.toLowerCase()&&delete o[e];return o[r]=t,o}(e,[r,...n.filter((e=>e!==r))].join(o.delimiter))}function h(e){return l&&(0,o.isAbsolute)(l)?{...p(e,l),CURSOR_RIPGREP_PATH:l}:e}function m(){if(!l)throw new Error("Ripgrep path not configured. Call configureRipgrepPath() at startup.");return l}var f=r("node:child_process"),g=r("node:fs");function v(e){const t=e||process.env,{ELECTRON_RUN_AS_NODE:r,...o}=t;return o}const y=["SSH_AUTH_SOCK","DBUS_SESSION_BUS_ADDRESS","XDG_RUNTIME_DIR","WAYLAND_DISPLAY"];function w(e){const t={...e};for(const e of y)delete t[e];return t}var b=r("node:crypto?8af2");let S;function k(){const e=(0,o.join)((0,i.tmpdir)(),"cursor-sandbox-cache",(S||(S=(0,b.randomBytes)(16).toString("hex")),S));return{NPM_CONFIG_CACHE:(0,o.join)(e,"npm"),PNPM_STORE_PATH:(0,o.join)(e,"pnpm-store"),GOCACHE:(0,o.join)(e,"go-build"),GOMODCACHE:(0,o.join)(e,"go-mod"),CARGO_TARGET_DIR:(0,o.join)(e,"cargo-target"),PIP_CACHE_DIR:(0,o.join)(e,"pip"),UV_CACHE_DIR:(0,o.join)(e,"uv"),BUN_INSTALL_CACHE_DIR:(0,o.join)(e,"bun"),YARN_CACHE_FOLDER:(0,o.join)(e,"yarn"),npm_config_devdir:(0,o.join)(e,"node-gyp"),PLAYWRIGHT_BROWSERS_PATH:(0,o.join)(e,"playwright"),PUPPETEER_CACHE_DIR:(0,o.join)(e,"puppeteer"),TURBO_CACHE_DIR:(0,o.join)(e,"turbo"),GRADLE_USER_HOME:(0,o.join)(e,"gradle"),CONDA_PKGS_DIRS:(0,o.join)(e,"conda"),POETRY_CACHE_DIR:(0,o.join)(e,"poetry"),GEM_SPEC_CACHE:(0,o.join)(e,"gem-specs"),BUNDLE_PATH:(0,o.join)(e,"bundle"),COMPOSER_HOME:(0,o.join)(e,"composer"),HOMEBREW_CACHE:(0,o.join)(e,"homebrew"),CYPRESS_CACHE_FOLDER:(0,o.join)(e,"cypress"),NX_CACHE_DIRECTORY:(0,o.join)(e,"nx"),NUGET_PACKAGES:(0,o.join)(e,"nuget"),CCACHE_DIR:(0,o.join)(e,"ccache"),CP_HOME_DIR:(0,o.join)(e,"cocoapods")}}var E=r("../../node_modules/.pnpm/ignore@7.0.5/node_modules/ignore/index.js");const x=[{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:"**/*.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:"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:".ssh"}];function _(e){const t=x.filter((e=>"workspace"===e.type)).map((e=>e.pattern));return{[e]:t}}function C(e){const t=x.filter((e=>"worktree"===e.type)).map((e=>e.pattern));return{[e]:t}}x.filter((e=>"git"===e.type)).map((e=>e.pattern)),x.filter((e=>"workspace"===e.type&&e.pattern.startsWith("!")&&!e.pattern.endsWith("/**"))).map((e=>e.pattern.replace(/^!(\*\*\/)?/,"")));const P=[];let R=null,T=null;let I=null;const A=new Map;const O="win32"===process.platform||"darwin"===process.platform;function D(e,t){const r=t.endsWith(o.sep)?t.slice(0,-1):t;if(O){const t=e.toLowerCase(),n=r.toLowerCase();return t===n||t.startsWith(n+o.sep)}return e===r||e.startsWith(r+o.sep)}function M(e,t){const r=e.endsWith(o.sep)?e.slice(0,-1):e;return O?(0,o.relative)(r.toLowerCase(),t.toLowerCase()).replace(/\\/g,"/"):(0,o.relative)(r,t).replace(/\\/g,"/")}async function j(e,t){if(D(e,t)){const r=M(t,e);if((null===R&&(R=E({ignoreCase:!0}),R.add(x.filter((e=>"workspace"===e.type)).map((e=>e.pattern)))),R).ignores(r))return!0}const{isWorktree:r,gitDirParent:a}=await async function(e){const t=A.get(e);if(t)return t;const r=await(0,s.stat)((0,o.join)(e,".git")).catch((()=>null));if(!r?.isFile()){const t={isWorktree:!1,gitDirParent:e};return A.set(e,t),t}const i=await async function(e){try{const t=await(0,n.DP)("git",["rev-parse","--git-common-dir"],{cwd:e});return(0,o.dirname)((0,o.resolve)(e,t.trim()))}catch{return null}}(e),a={isWorktree:!0,gitDirParent:i??e};return A.set(e,a),a}(t);if(D(e,a)){const t=M(a,e);if((null===T&&(T=E({ignoreCase:!0}),T.add(x.filter((e=>"git"===e.type)).map((e=>e.pattern)))),T).ignores(t))return!0}if(r&&D(e,t)&&".git"===M(t,e))return!0;for(const t of function(){if(null!==I)return I;const e=i.default.homedir(),t=[];for(const r of x)switch(r.type){case"absolute":t.push(r.pattern);break;case"home":e.length>0&&t.push((0,o.join)(e,r.pattern))}return I=t,t}())if(D(e,t))return!0;return!1}const N=new WeakMap;function $(e,t,r){return e===t?"related":r?.has(e)?"probably_unrelated":"maybe_related"}function F(e){return void 0!==e&&("allow"===e.default||void 0!==e.allow&&e.allow.length>0)}function L(e){return void 0!==e&&"allow"===e.default}function U(){return{version:1,default:"deny"}}function B(){return{version:1,default:"allow"}}const H="darwin"===process.platform,z="linux"===process.platform,W=(0,a.h)("shell-exec:sandbox");function q(e){const t=b.randomBytes(8).toString("hex"),r=o.join(i.tmpdir(),`sandbox-policy-${t}`);return g.writeFileSync(r,e,{encoding:"utf-8",mode:384}),r}let G;function V(){return G}function J(e){"linux"===process.platform&&Object.assign(e,h(e))}let K=null,Z=null,Y=null,X=null;function Q(e){if(null!==K)return!!K;try{const t=V();return W.info(e,`[checkBinaryAvailable] Resolved binary path: ${t}`),t?(K=g.existsSync(t),K?W.info(e,`[checkBinaryAvailable] Binary path exists: ${K}`):(Z=new Error(`Sandbox binary not found at ${t}`),W.info(e,`[checkBinaryAvailable] Binary not found at: ${t}`)),!!K):(Z=new Error("Sandbox binary path was not configured"),K=!1,W.info(e,"[checkBinaryAvailable] Binary path not set, returning false"),!1)}catch(t){return Z=t,K=!1,W.info(e,`[checkBinaryAvailable] Exception checking binary: ${t}`),!1}}function ee(e){if(null!==X)return X;const t=e??(0,a.q6)();if(W.info(t,"[isSandboxHelperSupported] Starting sandbox support check..."),!Q(t)){const e=Z?.message||"Binary check failed";return Y=e,W.info(t,`[isSandboxHelperSupported] Binary not available, returning false. Reason: ${e}`),X=!1,X}if("win32"===process.platform)return Y="Windows sandbox helper only provides network proxy, not filesystem isolation",W.info(t,"[isSandboxHelperSupported] win32: returning false (proxy-only, no filesystem sandbox)"),X=!1,X;if("darwin"===process.platform)return Y=null,W.info(t,`[isSandboxHelperSupported] ${process.platform} platform, binary available, sandbox supported!`),X=!0,X;try{const e=process.cwd(),r={sandbox:{type:"workspace_readwrite",cwd:e,additionalReadwritePaths:[],networkAccess:!1,disableTmpWrite:!1,ignoreMapping:void 0}},o=String(V());W.info(t,`[isSandboxHelperSupported] Running preflight with binary: ${o}`),W.info(t,`[isSandboxHelperSupported] CWD: ${e}`);const n={...process.env};J(n);const s=q(JSON.stringify(r));return(0,f.execFileSync)(o,["--policy",s,"--preflight-only","--","/bin/true"],{stdio:["ignore","ignore","pipe"],timeout:15e3,env:n,shell:!1}),Y=null,W.info(t,"[isSandboxHelperSupported] Preflight succeeded, sandbox supported!"),X=!0,X}catch(e){const r=e,o=r.stderr?.toString?.()||"";return W.error(t,`[isSandboxHelperSupported] Preflight failed: ${r.message}`),W.error(t,`[isSandboxHelperSupported] Exit status: ${r?.status}`),o&&W.error(t,`[isSandboxHelperSupported] Stderr: ${o}`),"number"==typeof r?.status&&2===r.status?(Y=`Linux preflight failed with exit code 2 (unsupported kernel features). stderr: ${o||"none"}`,X=!1,X):(Y=`Linux preflight failed: ${r.message||"unknown error"}. Exit status: ${r?.status}. stderr: ${o||"none"}`,X=!1,X)}}function te(e,t=[],r={},n){const s=(0,a.q6)();if(r.env=v(r.env),!Q(s))throw new Error(`Sandbox binary not available: ${Z?.message||"binary not configured"}. Please build the binary or use 'insecure_none' policy.`);if("insecure_none"===n.type)return(0,f.spawn)(e,t,r);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()),i=n.sandboxWorkspaceRoot??s;let a,l=e,c=t;r.shell&&("win32"===process.platform?(l="string"==typeof r.shell?r.shell:"cmd.exe",c=["/c",`${e} ${t.join(" ")}`]):(l="string"==typeof r.shell?r.shell:"/bin/sh",c=["-c",`${e} ${t.join(" ")}`])),n.ignoreMapping&&(a=re(n.ignoreMapping));const u=function(e,t,r){const n=e&&e.length>0?function(...e){const t={};for(const r of e){let e=!1;try{e=(0,g.existsSync)(r)&&(0,g.statSync)(r).isDirectory()}catch{}if(e)t[r]||(t[r]=[]),t[r].push("**");else{const e=r.lastIndexOf("/"),o=e>0?r.slice(0,e):"/",n=e>=0?r.slice(e+1):r;t[o]||(t[o]=[]),n?t[o].push(n,`${n}/**`):t[o].push("**")}}return t}(...e):{},s=function(e){let t=o.resolve(e);for(;;){try{const e=o.join(t,".git");if(g.existsSync(e))return!0}catch{}const e=o.dirname(t);if(e===t)return!1;t=e}}(r),i=!z||s?t??{}:{},a={...n};for(const[e,t]of Object.entries(i))a[e]?a[e]=[...a[e],...t]:a[e]=t;if(0!==Object.keys(a).length)return re(a)}(n.additionalReadonlyPaths,n.writeProtectionMapping,i),d=F(n.networkPolicy),p="workspace_readonly"===n.type?{type:"workspace_readonly",cwd:i,additionalReadonlyPaths:u,networkAccess:d,ignoreMapping:a}:{type:"workspace_readwrite",cwd:i,additionalReadwritePaths:n.additionalReadwritePaths||[],additionalReadonlyPaths:u,networkAccess:d,disableTmpWrite:n.disableTmpWrite||!1,ignoreMapping:a},h=function(e){if("insecure_none"===e.type)return;const t=e.networkPolicy;if(void 0===t)return;if(!F(t))return;const r=void 0!==t.deny&&t.deny.length>0;return"allow"!==t.default||r?{version:1,...t}:void 0}(n),m={sandbox:p};void 0!==h&&(m.networkPolicy=h),!1===n.networkPolicyStrict&&(m.networkPolicyStrict=!1);const v=["--policy",q(JSON.stringify(m)),"--",l,...c],y={..."linux"===process.platform?w(process.env):process.env,..."linux"===process.platform&&r.env?w(r.env):r.env,CURSOR_SANDBOX:"native"};J(y);const b={cwd:r.cwd||s,env:y,stdio:r.stdio||["pipe","pipe","pipe"]};try{const e=new Date,t=(0,f.spawn)(String(V()),v,b);return H&&t.pid&&function(e,t){N.set(e,t)}(t,{startTime:e,pid:t.pid}),t}catch(e){throw new Error(`Failed to spawn sandboxed process: ${e}`)}}(e,t,r,n);throw new Error(`Unsupported sandbox policy: ${String(n)}`)}function re(e,t,r,o){const n={};for(const[t,r]of Object.entries(e)){const e=t.startsWith("file://")?oe(t):t;n[e]=r;const o=ne(e);o!==e&&(n[o]=r)}return n}function oe(e){let t=e.replace(/^file:\/\//,"");return t=decodeURIComponent(t),t.length>1&&t.endsWith("/")&&(t=t.slice(0,-1)),t}function ne(e){try{return(0,g.realpathSync)(e)}catch{return e}}class se extends Error{reason;constructor(e,t){super(e),this.reason=t,this.name="SandboxUnsupportedError"}}const ie="darwin"===process.platform;function ae(e){!function(e){m();const{sandboxBinaryPath:t}=e;G||(G=t)}(e)}function le(e,t=[],r={},o){if(r.env=v(r.env),o.enableSharedBuildCache&&(r={...r,env:{...v(process.env),...k(),...r.env}}),"insecure_none"!==o.type){if(ee())return te(e,t,r,o);const n=Y;throw new se(`Sandbox policy '${o.type}' is not supported on this system. Ensure the sandbox helper binary is available, or use 'insecure_none'. Reason: ${n||"unknown"}`,n??void 0)}return function(e,t,r){return(0,f.spawn)(e,t,r)}(e,t,r)}function ce(e){return ie?async function(e){const t=N.get(e);return t?(r=t.pid,o=t.startTime,n=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()-o.getTime())/1e3).toString()];(0,f.execFile)("/usr/bin/log",s,((t,o,s)=>{if(t)return void e([{raw:t.message}]);const i=o.split(/\r?\n/).filter((e=>e.trim().length>0)),a=[];for(const e of i)try{const t=JSON.parse(e),o=t?.eventMessage??"";if(!o||"string"!=typeof o)continue;const s=/^Sandbox:\s+([^(]+)\((\d+)\)\s+([a-zA-Z-]+)\((\d+)\)\s+([^\s]+)\s+(.+)$/.exec(o);if(s){const[,e,i,l,c,u,d]=s,p=Number(i);a.push({timestamp:t.timestamp,processName:e.trim(),pid:p,decision:l.toLowerCase(),decisionCode:Number(c),operation:u,target:d,duplicateCount:1,raw:o,relationship:$(p,r,n)});continue}const i=/^(\d+) duplicate report for Sandbox: (.+)$/.exec(o);if(i){const e=Number(i[1]),s=i[2],l=/^([^(]+)\((\d+)\)\s+([a-zA-Z-]+)\((\d+)\)\s+([^\s]+)\s+(.+)$/.exec(s);if(l){const[,s,i,c,u,d,p]=l,h=Number(i);a.push({timestamp:t.timestamp,processName:s.trim(),pid:h,decision:c.toLowerCase(),decisionCode:Number(u),operation:d,target:p,duplicateCount:e,raw:o,relationship:$(h,r,n)})}else a.push({timestamp:t.timestamp,duplicateCount:e,raw:o});continue}a.push({timestamp:t.timestamp,raw:o})}catch{}e(a)}))}catch(t){e([{raw:String(t)}])}}))):(console.log("No sandbox metadata found on child process"),[]);var r,o,n}(e):Promise.resolve([])}function ue(e,t){if(ie)try{(0,g.accessSync)("/usr/bin/sandbox-exec",g.constants.X_OK)}catch{return!1}return ee(t?.ctx)}var de;!function(e){e.Zsh="zsh",e.ZshLight="zsh-light",e.Bash="bash",e.PowerShell="powershell",e.Naive="naive"}(de||(de={}));const pe={TERM:"dumb",NO_COLOR:"1",FORCE_COLOR:"0",_ZO_DOCTOR:"0"};function he(e,t=[],r={},o,n){if(n?.aborted){const e=new Error("Operation was aborted");e.name="AbortError";const t=new(require("node:events").EventEmitter);return process.nextTick((()=>{t.emit("error",e)})),t}const s=le(e,t,{...r,env:h(r.env??process.env)},o);if(n){const e=()=>{if(s.pid)try{if(r.detached)try{process.kill(-s.pid,"SIGTERM")}catch{s.kill("SIGTERM")}else s.kill("SIGTERM");const e=setTimeout((()=>{if(!s.killed&&s.pid)try{if(r.detached)try{process.kill(-s.pid,"SIGKILL")}catch{s.kill("SIGKILL")}else s.kill("SIGKILL")}catch(e){}}),1e3);s.once("exit",(()=>{clearTimeout(e)}))}catch(e){}};n.addEventListener("abort",e,{once:!0}),s.once("exit",(()=>{n.removeEventListener("abort",e)}))}return s}function me(e){const t=e.indexOf("\n");return{cwd:e.substring(0,t),rest:e.substring(t)}}function fe(e,t){const r=`${t}\n`,o=e.indexOf(r);return o>=0?e.slice(o+r.length):e}const ge="__CURSOR_BASH_STATE_START__",ve="__CURSOR_BASH_STATE_END__",ye=50,we=262144;class be{writable;pending=[];pendingBytes=0;flushTimeout;flushPromise;flushIntervalMs;maxBufferedBytes;constructor(e,t){this.writable=e,this.flushIntervalMs=t?.flushIntervalMs??ye,this.maxBufferedBytes=t?.maxBufferedBytes??we}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,o=[e[0].data];for(let n=1;n<e.length;n++){const s=e[n];s.type!==r?(t.push({type:r,data:Buffer.concat(o)}),r=s.type,o=[s.data]):o.push(s.data)}return t.push({type:r,data:Buffer.concat(o)}),t}(e))try{await this.writable.write(t)}catch{}}}function Se(e){if(!e.bufferOutputEvents){const t=(t,r)=>{e.writable.write({type:t,data:r}).catch((()=>{}))};return e.stdout?.on("data",(e=>{t("stdout",e)})),e.stderr?.on("data",(e=>{t("stderr",e)})),{async waitForOutput(){},async flush(){}}}const t=new be(e.writable,e.outputLimiterOptions);let r;const o=Promise.all([ke(e.stdout,"stdout",t),ke(e.stderr,"stderr",t)]).then((()=>{})).catch((e=>{r=e}));return{async waitForOutput(){if(await o,void 0!==r)throw(e=r)instanceof Error?e:new Error(String(e));var e},async flush(){await t.flush()}}}async function ke(e,t,r){if(e)for await(const o of e)await r.push(t,o)}function Ee(e){return e.teamAdmin?.type??e.perRepo?.type??e.perUser?.type??"insecure_none"}function xe(...e){return e.some((e=>!0===e))}function _e(...e){const t=new Set;for(const r of e)if(r)for(const e of r)t.add(Ce(e));return[...t]}function Ce(e){const t=e.replace(/\\/g,"/").replace(/\/+$/,"");return""===t?"/":/^[a-zA-Z]:$/.test(t)?`${t}/`:t}function Pe(...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 o=new Set;for(const e of t)if(e.deny)for(const t of e.deny)o.add(t);const n=new Set;for(const e of t)if(e.allow)for(const t of e.allow)n.add(t);const s=n.size>0?[...n]: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),o.size>0&&(a.deny=[...o]),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 Re(...e){const t=e.filter((e=>void 0!==e));if(0===t.length)return;const r={};for(const e of t)for(const[t,o]of Object.entries(e)){const e=r[t];if(e){const n=new Set(e);for(const e of o)n.has(e)&&n.delete(e),n.add(e);r[t]=[...n]}else r[t]=[...o]}return 0!==Object.keys(r).length?r:void 0}function Te(...e){for(let t=e.length-1;t>=0;t--)if(void 0!==e[t])return e[t]}async function Ie(e,t){if(!t)return{policy:{type:"insecure_none"}};const r=await(0,s.stat)((0,o.join)(e,".git")).then((e=>e),(()=>null)),i=r?.isFile()??!1,a=null!==r;if("workspace_readwrite"===Ee(t)){let r=e;if(i){const s=await(0,n.DP)("git",["rev-parse","--git-common-dir"],{cwd:e}).then((t=>(0,o.resolve)(e,t.trim())),(()=>null));if(s){r=(0,o.dirname)(s);const n=t.perRepo,i=n?.ignoreMapping;t={...t,perRepo:{...n,type:"workspace_readwrite",additionalReadwritePaths:[...n?.additionalReadwritePaths??[],s],ignoreMapping:i,writeProtectionMapping:Re(n?.writeProtectionMapping,C(e))}}}}if(a)return Ae(t,{workspaceDir:e,gitDirParent:r})}return Ae(t,{workspaceDir:e})}function Ae(e,t){const r=function(e){const{perUser:t,perRepo:r,teamAdmin:o}=e,n=[t,r,o].filter((e=>void 0!==e));if(0===n.length)return;const s=n[0].type;for(const e of n)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}(e);if(void 0===r)return Me(e,t);switch(r){case"workspace_readwrite":return Me(e,t);case"workspace_readonly":return function(e,t){const r=t?.debug,o=Oe(e,t),n={policy:De({type:"workspace_readonly",disableTmpWrite:o.disableTmpWrite,networkPolicyStrict:o.networkPolicyStrict,additionalReadonlyPaths:o.additionalReadonlyPaths,networkPolicy:o.networkPolicy,debugOutputDir:o.debugOutputDir,captureDenies:o.captureDenies,enableSharedBuildCache:o.enableSharedBuildCache,ignoreMapping:o.ignoreMapping,writeProtectionMapping:o.writeProtectionMapping},"workspace_readonly")};return r&&(n.debug={fieldSources:o.fieldSources}),n}(e,t);case"insecure_none":return function(e,t){const{perUser:r,perRepo:o,teamAdmin:n}=e,s=t?.debug,i={type:"insecure_none",allowlistEscalated:xe(r?.allowlistEscalated,o?.allowlistEscalated,n?.allowlistEscalated)||void 0,debugOutputDir:Te(r?.debugOutputDir,o?.debugOutputDir,n?.debugOutputDir),captureDenies:xe(r?.captureDenies,o?.captureDenies,n?.captureDenies)||void 0,enableSharedBuildCache:Te(r?.enableSharedBuildCache,o?.enableSharedBuildCache,n?.enableSharedBuildCache)},a=Object.fromEntries(Object.entries(i).filter((([e,t])=>void 0!==t)));a.type="insecure_none";const l={policy:a};return s&&(l.debug={fieldSources:{}}),l}(e,t);default:throw new Error(`Unknown policy type: ${r}`)}}function Oe(e,t){const r=t?.debug,{perUser:n,perRepo:s,teamAdmin:a}=e,l=t?.workspaceDir??process.cwd(),c=function(e){const t=function(){if(0!==P.length)return{version:1,deny:[...P]}}(),r=i.default.homedir(),n=[];for(const e of x)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,o.join)(r,e.pattern));break;default:{const t=e.type;throw new Error(`Unknown entry type: ${t}`)}}return{type:"workspace_readwrite",additionalReadonlyPaths:n,writeProtectionMapping:_(e),...t&&{networkPolicy:t},networkPolicyStrict:!0}}(l),u={},d=[n,s,a],p=["perUser","perRepo","teamAdmin","hardcoded"],h=(e,t)=>{r&&(u[e]=p[t]??"unknown")},m=xe(n?.disableTmpWrite,s?.disableTmpWrite,a?.disableTmpWrite);for(let e=d.length-1;e>=0;e--)if(!0===d[e]?.disableTmpWrite){h("disableTmpWrite",e);break}const f=xe(n?.networkPolicyStrict,s?.networkPolicyStrict,a?.networkPolicyStrict,c.networkPolicyStrict);c.networkPolicyStrict&&h("networkPolicyStrict",3);const g=_e(n?.additionalReadonlyPaths,s?.additionalReadonlyPaths,a?.additionalReadonlyPaths,c.additionalReadonlyPaths),v=g.length>0?g:void 0;let y=Pe(n?.networkPolicy,s?.networkPolicy,a?.networkPolicy,c.networkPolicy);const w=a?.networkPolicy?.allow;void 0!==w&&w.length>0&&void 0!==y&&(y={...y,allow:[...w]},r&&(u["networkPolicy.allow"]="teamAdmin (replace)"));const b=void 0!==(S=y)?S:{version:1,default:"deny"};var S;const k=Te(n?.debugOutputDir,s?.debugOutputDir,a?.debugOutputDir),E=xe(n?.captureDenies,s?.captureDenies,a?.captureDenies),C=Te(n?.enableSharedBuildCache,s?.enableSharedBuildCache,a?.enableSharedBuildCache),R=Re(n?.ignoreMapping,s?.ignoreMapping,a?.ignoreMapping,c.ignoreMapping),T=function(e){const t=x.filter((e=>"git"===e.type)).map((e=>e.pattern));return{[e]:t}}(t?.gitDirParent??l);return{disableTmpWrite:m||void 0,networkPolicyStrict:f,additionalReadonlyPaths:v,networkPolicy:b,debugOutputDir:k,captureDenies:E||void 0,enableSharedBuildCache:C,ignoreMapping:R,writeProtectionMapping:Re(n?.writeProtectionMapping,s?.writeProtectionMapping,a?.writeProtectionMapping,c.writeProtectionMapping,T),fieldSources:u}}function De(e,t){const r=Object.fromEntries(Object.entries(e).filter((([e,t])=>void 0!==t)));return r.type=t,r}function Me(e,t){const{perUser:r,perRepo:o,teamAdmin:n}=e,s=t?.debug,i=Oe(e,t),a=_e(r?.additionalReadwritePaths,o?.additionalReadwritePaths,n?.additionalReadwritePaths),l={policy:De({type:"workspace_readwrite",disableTmpWrite:i.disableTmpWrite,networkPolicyStrict:i.networkPolicyStrict,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&&(l.debug={fieldSources:i.fieldSources}),l}const je="win32"===process.platform;function Ne(e){return!je&&!!e?.SUDO_ASKPASS}function $e(e){return Ne(e)?"alias sudo='sudo -A'; ":""}function Fe(e){const t=[];let r=0;for(;r<e.length;){const o=0===r||"&&"===e.slice(Math.max(0,r-2),r)||"||"===e.slice(Math.max(0,r-2),r)||"|"===e[r-1]||";"===e[r-1],n=Math.max(0,r-10),s=e.slice(n,r),i=/(?:&&|\|\||[|;])\s*$/.test(s)||0===r&&/^\s*$/.test(s);if((o||i)&&"sudo"===e.slice(r,r+4)){const o=r+4;if(o>=e.length||/\s/.test(e[o])){let n=o;for(;n<e.length&&/\s/.test(e[n]);)n++;let s=!1;if(n<e.length&&"-"===e[n]){let t=n+1;for(;t<e.length&&/[^\s]/.test(e[t]);)t++;const r=e.slice(n,t);s=/^-[a-zA-Z]*A[a-zA-Z]*$/.test(r)}s?(t.push("sudo"),r=o):(t.push("sudo -A"),r=o);continue}}t.push(e[r]),r++}return t.join("")}var Le=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 o,n=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===n)return n=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var s=o.dispose.call(o.value);if(o.async)return n|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else n|=1}catch(e){r(e)}if(1===n)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var o=new Error(r);return o.name="SuppressedError",o.error=e,o.suppressed=t,o});function Ue(e){if("win32"===process.platform){const t=/git.*bash/i;if(e&&t.test(e))return e;const r=(0,n.Ef)("bash",[],t).cmd;return t.test(r)?r:null}const t=process.env.SHELL;return t?.includes("bash")?t:(0,n.Ef)("bash",[]).cmd}function Be(e){if("win32"!==process.platform)return e;const t=o.default.normalize(e),r=t[0]?.toLowerCase();return r&&":"===t[1]&&t[2]===o.default.sep?`/${r}${t.slice(2).replace(/\\/g,"/")}`:t.replace(/\\/g,"/")}class He{cwd;state;userTerminalHint;useFileStateTransport;constructor(e,t,r,o=!1){this.cwd=e,this.state=t,this.userTerminalHint=r,this.useFileStateTransport=o}async getCwd(){return this.cwd}clone(e){return new He(e??this.cwd,this.state,this.userTerminalHint,this.useFileStateTransport)}async*execute(e,t,r){const l={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 o,n;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");o=t[Symbol.asyncDispose]}if(void 0===o){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");o=t[Symbol.dispose],r&&(n=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");n&&(o=function(){try{n.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:o,async:r})}else r&&e.stack.push({async:!0});return t}(l,(0,a.VI)(e.withName("BashState.execute")),!1),u=r?.pipeStdin??!1,d=(0,n.Jt)(),p=r?.workingDirectory??this.cwd,h={...process.env,...pe,...r?.env};let m='builtin eval "$1"';u||(m+=" < /dev/null");const f=$e(h),g=this.useFileStateTransport;let v,y,w;if(g){v=await(0,s.mkdtemp)(o.default.join(i.default.tmpdir(),"cursor-bash-state-")),o.default.basename(v),y=o.default.join(v,"state-in"),w=o.default.join(v,"state-out"),await(0,s.writeFile)(y,this.state,"utf8"),await(0,s.writeFile)(w,"","utf8").catch((()=>{}));const e=Be(y),t=Be(w);h.CURSOR_STATE_INPUT_FILE=e,h.CURSOR_STATE_OUTPUT_FILE=t}const b=["-O","extglob","-c",`${g?'snap=$(command cat "$CURSOR_STATE_INPUT_FILE")':"snap=$(command cat <&3)"} && builtin shopt -s extglob && builtin eval -- "$snap" && { builtin set +u 2>/dev/null || true; builtin eval "\${__CURSOR_SANDBOX_ENV_RESTORE:-}" 2>/dev/null; builtin export PWD="$(builtin pwd)"; builtin shopt -s expand_aliases 2>/dev/null; ${f}${m}; }; COMMAND_EXIT_CODE=$?; ${g?'mkdir -p "$(dirname "$CURSOR_STATE_OUTPUT_FILE")" 2>/dev/null; dump_bash_state > "$CURSOR_STATE_OUTPUT_FILE"':"dump_bash_state >&4"}; builtin exit $COMMAND_EXIT_CODE`,"--",t],S=Ue(this.userTerminalHint);if(!S)throw new Error("Can't find Bash");const k=r?.sandboxWorkspaceRoot??p,E=(await Ie(k,r?.sandboxPolicy)).policy,x="insecure_none"!==E.type?{...E,sandboxWorkspaceRoot:k}:E;let _="";const C=async()=>{if(g){if(!w)return void(_=this.state);try{_=await(0,s.readFile)(w,"utf8")}catch(e){console.warn("[shell-exec] Failed to read bash state file",e),_=this.state}}},P=async()=>{if(v)try{await(0,s.rm)(v,{recursive:!0,force:!0})}catch{}};let R;try{R=he(S,b,{env:h,stdio:[u?"pipe":"ignore","pipe","pipe","pipe","pipe"],cwd:p,detached:!0},x,r?.signal)}catch(e){throw await P(),e}R.on("spawn",(async()=>{try{await d.write({type:"stdin_ready",stdin:R.stdin??void 0,pid:R.pid})}catch(e){}}));const T=Se({stdout:R.stdout,stderr:R.stderr,writable:d,bufferOutputEvents:r?.bufferOutputEvents,outputLimiterOptions:r?.outputLimiterOptions});R.on("error",(async e=>{await P(),d.throw(e)}));let I=null,A=null,O=!1;const D=async e=>{if(!O){if(O=!0,A&&(clearTimeout(A),A=null),(0,a.HF)(c.ctx,"exit"),e)try{await T.waitForOutput()}catch(e){return await P(),void d.throw(e instanceof Error?e:new Error(String(e)))}if(await T.flush(),!r?.signal?.aborted){await C();const e=`${ge}\n`,t=`${ve}\n`;if(_.startsWith(e)&&_.endsWith(t)){let t=_.slice(e.length);t=t.slice(0,-26);const{cwd:r,rest:o}=me(t);this.state=o,"win32"!==process.platform&&r?.startsWith("/")&&(this.cwd=r)}}if(x.captureDenies)try{const e=await ce(R);e&&e.length>0&&await d.write({type:"sandbox_denies",events:e})}catch{}try{await d.write({type:"exit",code:I,data:"",aborted:r?.signal?.aborted??!1}),d.close()}catch{d.close()}await P()}};R.on("exit",((e,t)=>{I=e;const o=r?.closeTimeout??5e3;o>0&&(A=setTimeout((()=>{console.warn(`[shell-exec] Close event did not fire within ${o}ms after exit. This may indicate a background process is holding file descriptors open. Proceeding anyway to prevent hang.`),D(!1)}),o))})),R.on("close",(async()=>{await D(!0)}));const M=R.stdio[3],j=R.stdio[4];g||(M?.write(this.state),M?.end(),j?.on("data",(e=>{_+=e.toString()}))),yield*d}catch(e){l.error=e,l.hasError=!0}finally{Le(l)}}}var ze=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 o,n=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===n)return n=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var s=o.dispose.call(o.value);if(o.async)return n|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else n|=1}catch(e){r(e)}if(1===n)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var o=new Error(r);return o.name="SuppressedError",o.error=e,o.suppressed=t,o});class We{promise;constructor(e){this.promise=e}async getCwd(){return(await this.promise).getCwd()}clone(e){return new We(this.promise.then((t=>t.clone(e))))}async*execute(e,t,r){const o={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 o,n;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");o=t[Symbol.asyncDispose]}if(void 0===o){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");o=t[Symbol.dispose],r&&(n=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");n&&(o=function(){try{n.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:o,async:r})}else r&&e.stack.push({async:!0})}(o,(0,a.VI)(e.withName("LazyTerminalExecutor.execute")),!1);const n=await this.promise;for await(const o of n.execute(e,t,r))yield o}catch(e){o.error=e,o.hasError=!0}finally{ze(o)}}}var qe=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 o,n=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===n)return n=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var s=o.dispose.call(o.value);if(o.async)return n|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else n|=1}catch(e){r(e)}if(1===n)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var o=new Error(r);return o.name="SuppressedError",o.error=e,o.suppressed=t,o});function Ge(){if("win32"!==process.platform){const e=process.env.SHELL;if(e?.includes("pwsh")||e?.includes("powershell"))return e}let e=(0,n.Ef)("pwsh",[]).cmd;if("pwsh"!==e)return e;if(e=(0,n.Ef)("powershell",[]).cmd,"powershell"!==e)return e;if("win32"===process.platform&&(e=o.join(process.env.SYSTEMROOT,"System32","WindowsPowerShell","v1.0","powershell.exe"),(0,g.existsSync)(e)))return e;throw new Error("Neither 'pwsh' (PowerShell Core) nor 'powershell' (Windows PowerShell) found in PATH")}class Ve{cwd;state;constructor(e,t){this.cwd=e,this.state=t}async getCwd(){return this.cwd}clone(e){return new Ve(e??this.cwd,this.state)}async*execute(e,t,r){const l={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 o,n;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");o=t[Symbol.asyncDispose]}if(void 0===o){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");o=t[Symbol.dispose],r&&(n=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");n&&(o=function(){try{n.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:o,async:r})}else r&&e.stack.push({async:!0});return t}(l,(0,a.VI)(e.withName("PowerShellState.execute")),!1),u=r?.pipeStdin??!1,d=r?.workingDirectory??this.cwd,p=(0,n.Jt)(),h={...process.env,...pe,...r?.env},m=Ne(h)?Fe(t):t,f=i.tmpdir(),g=o.join(f,`ps-state-out-${(0,b.randomUUID)()}.txt`),v=((e,t,r,o)=>`\n${e}\n\nSet-Location '${t}'\n\n# Execute user command\n${r}\n$COMMAND_EXIT_CODE = $LASTEXITCODE\n\n\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\n Emit $PWD.Path\n #Log-Timing "working_dir"\n\n $envVars = Get-ChildItem Env: | Sort-Object Name\n foreach ($var in $envVars) {\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}\n\nDump-PowerShellState -OutputFile "${o}"\n\nexit $COMMAND_EXIT_CODE\n`)(this.state,d,m,g),y=o.join(f,`ps-script-${(0,b.randomUUID)()}.ps1`);await async function(e,t){await s.writeFile(e,"\ufeff"+t,{encoding:"utf8"})}(y,v);const w=["-ExecutionPolicy","Bypass"];u||w.push("-NonInteractive"),w.push("-File",y);const S=Ge(),k="win32"===process.platform,E=r?.sandboxWorkspaceRoot??d,x=(await Ie(E,r?.sandboxPolicy)).policy,_=he(S,w,{env:h,stdio:[u?"pipe":"ignore","pipe","pipe"],cwd:d,detached:!k},"insecure_none"!==x.type?{...x,sandboxWorkspaceRoot:E}:x,r?.signal);_.on("spawn",(async()=>{try{await p.write({type:"stdin_ready",stdin:_.stdin??void 0,pid:_.pid})}catch(e){}}));const C=Se({stdout:_.stdout,stderr:_.stderr,writable:p,bufferOutputEvents:r?.bufferOutputEvents,outputLimiterOptions:r?.outputLimiterOptions}),P=async()=>{try{const e=await s.readFile(g,"utf8"),{cwd:t,rest:r}=me(e);this.state=r,this.cwd=t.trim(),await(0,s.rm)(g).catch((()=>{}))}catch(e){}await(0,s.rm)(y).catch((()=>{}))};let R=null,T=null,I=!1;const A=async e=>{if(!I){if(I=!0,T&&(clearTimeout(T),T=null),(0,a.HF)(c.ctx,"exit"),e)try{await C.waitForOutput()}catch(e){return await P(),void p.throw(e instanceof Error?e:new Error(String(e)))}await C.flush();try{await p.write({type:"exit",code:R,data:"",aborted:r?.signal?.aborted??!1}),await P(),p.close()}catch(e){p.close()}}};_.on("exit",((e,t)=>{R=e;const o=r?.closeTimeout??5e3;o>0&&(T=setTimeout((()=>{console.warn(`[shell-exec] Close event did not fire within ${o}ms after exit. This may indicate a background process is holding file descriptors open. Proceeding anyway to prevent hang.`),A(!1)}),o))})),_.on("close",(async()=>{await A(!0)})),_.on("error",(e=>{P().catch((()=>{})),p.throw(e)})),yield*p}catch(e){l.error=e,l.hasError=!0}finally{qe(l)}}}var Je=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 o,n=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===n)return n=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var s=o.dispose.call(o.value);if(o.async)return n|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else n|=1}catch(e){r(e)}if(1===n)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var o=new Error(r);return o.name="SuppressedError",o.error=e,o.suppressed=t,o});class Ke{cwd;options;constructor(e,t){this.cwd=e,this.options=t}async getCwd(){return this.cwd}clone(e){return new Ke(e??this.cwd,this.options)}async*execute(e,t,r){const o={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 o,n;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");o=t[Symbol.asyncDispose]}if(void 0===o){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");o=t[Symbol.dispose],r&&(n=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");n&&(o=function(){try{n.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:o,async:r})}else r&&e.stack.push({async:!0});return t}(o,(0,a.VI)(e.withName("NaiveTerminalExecutor.execute")),!1),i=(0,n.Jt)(),l=r?.pipeStdin??!1,c={...process.env,...pe,...r?.env},u=Ne(c)?Fe(t):t,d=r?.workingDirectory??this.cwd,p=r?.sandboxWorkspaceRoot??d,h=(await Ie(p,r?.sandboxPolicy)).policy,m="insecure_none"!==h.type?{...h,sandboxWorkspaceRoot:p}:h,f=he(this.options?.shell||process.env.SHELL||"/bin/sh",[...this.options?.shellArgs??[],"-c",u],{env:c,cwd:d,stdio:[l?"pipe":"ignore","pipe","pipe"]},m,r?.signal);f.on("spawn",(async()=>{try{await i.write({type:"stdin_ready",stdin:f.stdin??void 0,pid:f.pid})}catch(e){}}));const g=Se({stdout:f.stdout,stderr:f.stderr,writable:i,bufferOutputEvents:r?.bufferOutputEvents,outputLimiterOptions:r?.outputLimiterOptions});f.on("error",(e=>{i.throw(e)})),f.on("exit",(async e=>{if((0,a.HF)(s.ctx,"exit"),await g.flush(),m.captureDenies)try{const e=await ce(f);e&&e.length>0&&await i.write({type:"sandbox_denies",events:e})}catch{}try{await i.write({type:"exit",code:e,data:"",aborted:r?.signal?.aborted??!1}),i.close()}catch(e){i.close()}})),yield*i}catch(e){o.error=e,o.hasError=!0}finally{Je(o)}}}const Ze="__CURSOR_ZSH_STATE_START__",Ye="__CURSOR_ZSH_STATE_END__";var Xe=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 o,n=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===n)return n=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var s=o.dispose.call(o.value);if(o.async)return n|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else n|=1}catch(e){r(e)}if(1===n)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var o=new Error(r);return o.name="SuppressedError",o.error=e,o.suppressed=t,o});function Qe(){const e=process.env.SHELL;return e?.includes("zsh")?e:(0,n.Ef)("zsh",[]).cmd}class et{cwd;state;constructor(e,t){this.cwd=e,this.state=t}async getCwd(){return this.cwd}clone(e){return new et(e??this.cwd,this.state)}async*execute(e,t,r){const o={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 o,n;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");o=t[Symbol.asyncDispose]}if(void 0===o){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");o=t[Symbol.dispose],r&&(n=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");n&&(o=function(){try{n.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:o,async:r})}else r&&e.stack.push({async:!0});return t}(o,(0,a.VI)(e.withName("ZshState.execute")),!1),i=r?.pipeStdin??!1,l=(0,n.Jt)(),c=r?.workingDirectory??this.cwd,u={...process.env,...pe,...r?.env};let d='builtin eval "$1"';i||(d+=" < /dev/null");const p=["-c",`snap=$(command cat <&3); builtin unsetopt aliases 2>/dev/null; builtin unalias -m '*' 2>/dev/null || true; builtin eval "$snap" && { builtin unsetopt nounset 2>/dev/null || true; builtin eval "\${__CURSOR_SANDBOX_ENV_RESTORE:-}" 2>/dev/null; builtin export PWD="$(builtin pwd)"; builtin setopt aliases 2>/dev/null; ${$e(u)}${d}; }; COMMAND_EXIT_CODE=$?; dump_zsh_state >&4; builtin exit $COMMAND_EXIT_CODE`,"--",t],h=r?.sandboxWorkspaceRoot??c,m=(await Ie(h,r?.sandboxPolicy)).policy,f="insecure_none"!==m.type?{...m,sandboxWorkspaceRoot:h}:m,g=he(Qe(),p,{env:u,stdio:[i?"pipe":"ignore","pipe","pipe","pipe","pipe"],cwd:c,detached:!0},f,r?.signal);let v="";g.on("spawn",(async()=>{try{await l.write({type:"stdin_ready",stdin:g.stdin??void 0,pid:g.pid})}catch(e){}}));const y=Se({stdout:g.stdout,stderr:g.stderr,writable:l,bufferOutputEvents:r?.bufferOutputEvents,outputLimiterOptions:r?.outputLimiterOptions});g.on("error",(e=>{l.throw(e)}));let w=null,b=null,S=!1;const k=async e=>{if(!S){if(S=!0,b&&(clearTimeout(b),b=null),(0,a.HF)(s.ctx,"exit"),e)try{await y.waitForOutput()}catch(e){return void l.throw(e instanceof Error?e:new Error(String(e)))}if(await y.flush(),!r?.signal?.aborted){const e=`${Ze}\n`,t=`${Ye}\n`;if(v.startsWith(e)&&v.endsWith(t)){let t=v.slice(e.length);t=t.slice(0,-25);const{cwd:r,rest:o}=me(t);r?.startsWith("/")&&(this.state=o,this.cwd=r)}}if(f.captureDenies)try{const e=await ce(g);e&&e.length>0&&await l.write({type:"sandbox_denies",events:e})}catch{}try{await l.write({type:"exit",code:w,data:"",aborted:r?.signal?.aborted??!1}),l.close()}catch(e){l.close()}}};g.on("exit",((e,t)=>{w=e;const o=r?.closeTimeout??5e3;o>0&&(b=setTimeout((()=>{S||(console.warn(`[shell-exec] Close event did not fire within ${o}ms after exit. This may indicate a background process is holding file descriptors open. Killing detached process group.`),function(e,t){if(e)try{process.kill(-e,t)}catch{return}}(g.pid,"SIGKILL"),k(!1))}),o))})),g.on("close",(async()=>{await k(!0)}));const E=g.stdio[3],x=g.stdio[4];E?.write(this.state),E?.end(),x?.on("data",(e=>{v+=e.toString()})),yield*l}catch(e){o.error=e,o.hasError=!0}finally{Xe(o)}}}const tt="__CURSOR_ZSH_STATE_LIGHT_VALID__",rt='#!/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 # Use here-document to avoid argument list length limits entirely\n builtin printf \'cursor_snap_%s=$(command base64 -d <<\'\'\'CURSOR_SNAP_EOF_%s\'\'\'\n\' "$var_name" "$var_name"\n command base64 <<<"$content" | command tr -d \'\n\'\n builtin printf \'\nCURSOR_SNAP_EOF_%s\n\' "$var_name"\n builtin printf \')\n\'\n builtin printf \'eval "$cursor_snap_%s"\n\' "$var_name"\n fi\n }\n\n _log_timing "init"\n\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 # Environment variables (exported)\n # Filter out: proxy settings, sandbox vars, and sudo askpass vars (session-specific)\n local env_vars\n env_vars=$(builtin typeset -xp 2>/dev/null | command grep -viE \'_proxy=|CURSOR_SANDBOX|SUDO_ASKPASS|CURSOR_ASKPASS\' || true)\n _emit_encoded "$env_vars" "ENV_VARS_B64"\n _log_timing "env_variables"\n\n # Options (replayable as setopt lines; exclude nounset which we enable locally)\n local zsh_opts\n zsh_opts=$(setopt 2>/dev/null | command grep -v \'^nounset$\' | 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 "# end of zsh state dump (light)"\n _log_timing "finalize"\n}\n';var ot,nt,st=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 o,n=0;return function e(){for(;o=t.stack.pop();)try{if(!o.async&&1===n)return n=0,t.stack.push(o),Promise.resolve().then(e);if(o.dispose){var s=o.dispose.call(o.value);if(o.async)return n|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else n|=1}catch(e){r(e)}if(1===n)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var o=new Error(r);return o.name="SuppressedError",o.error=e,o.suppressed=t,o});function it(){const e=process.env.SHELL;return e?.includes("zsh")?e:(0,n.Ef)("zsh",[]).cmd}class at{cwd;state;constructor(e,t){this.cwd=e,this.state=t}async getCwd(){return this.cwd}clone(e){return new at(e??this.cwd,this.state)}async*execute(e,t,r){const o={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 o,n;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");o=t[Symbol.asyncDispose]}if(void 0===o){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");o=t[Symbol.dispose],r&&(n=o)}if("function"!=typeof o)throw new TypeError("Object not disposable.");n&&(o=function(){try{n.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:o,async:r})}else r&&e.stack.push({async:!0});return t}(o,(0,a.VI)(e.withName("ZshLightState.execute")),!1),i=r?.pipeStdin??!1,l=(0,n.Jt)(),c=r?.workingDirectory??this.cwd,u={...process.env,...pe,...r?.env};let d='builtin eval "$1"';i||(d+=" < /dev/null");const p=$e(u),h=["-c",`snap=$(command cat <&3); builtin unsetopt aliases 2>/dev/null; builtin unalias -m '*' 2>/dev/null || true; ${rt} builtin eval "$snap" && { builtin unsetopt nounset 2>/dev/null || true; builtin eval "\${__CURSOR_SANDBOX_ENV_RESTORE:-}" 2>/dev/null; builtin export PWD="$(builtin pwd)"; builtin setopt aliases 2>/dev/null; ${p}${d}; }; COMMAND_EXIT_CODE=$?; dump_zsh_state_light >&4; builtin exit $COMMAND_EXIT_CODE`,"--",t],m=r?.sandboxWorkspaceRoot??c,f=(await Ie(m,r?.sandboxPolicy)).policy,g="insecure_none"!==f.type?{...f,sandboxWorkspaceRoot:m}:f,v=he(it(),h,{env:u,stdio:[i?"pipe":"ignore","pipe","pipe","pipe","pipe"],cwd:c,detached:!0},g,r?.signal);let y="";v.on("spawn",(async()=>{try{await l.write({type:"stdin_ready",stdin:v.stdin??void 0,pid:v.pid})}catch(e){}}));const w=Se({stdout:v.stdout,stderr:v.stderr,writable:l,bufferOutputEvents:r?.bufferOutputEvents,outputLimiterOptions:r?.outputLimiterOptions});v.on("error",(e=>{l.throw(e)}));let b=null,S=null,k=!1;const E=async e=>{if(!k){if(k=!0,S&&(clearTimeout(S),S=null),(0,a.HF)(s.ctx,"exit"),e)try{await w.waitForOutput()}catch(e){return void l.throw(e instanceof Error?e:new Error(String(e)))}if(await w.flush(),!r?.signal?.aborted){const e=`${tt}\n`;if(y.startsWith(e)){const t=y.slice(e.length),{cwd:r,rest:o}=me(t);r?.startsWith("/")&&(this.state=o,this.cwd=r)}}if(g.captureDenies)try{const e=await ce(v);e&&e.length>0&&await l.write({type:"sandbox_denies",events:e})}catch{}try{await l.write({type:"exit",code:b,data:"",aborted:r?.signal?.aborted??!1}),l.close()}catch(e){l.close()}}};v.on("exit",((e,t)=>{b=e;const o=r?.closeTimeout??5e3;o>0&&(S=setTimeout((()=>{console.warn(`[shell-exec] Close event did not fire within ${o}ms after exit. This may indicate a background process is holding file descriptors open. Proceeding anyway to prevent hang.`),E(!1)}),o))})),v.on("close",(async()=>{await E(!0)}));const x=v.stdio[3],_=v.stdio[4];x?.write(this.state),x?.end(),_?.on("data",(e=>{y+=e.toString()})),yield*l}catch(e){o.error=e,o.hasError=!0}finally{st(o)}}}r("node:perf_hooks?b4d9"),function(e){e[e.EventLoopDelayP95Ms=50]="EventLoopDelayP95Ms",e[e.EventLoopUtilization=.7]="EventLoopUtilization"}(ot||(ot={})),function(e){e[e.SampleIntervalMs=250]="SampleIntervalMs",e[e.EventLoopResolutionMs=20]="EventLoopResolutionMs"}(nt||(nt={}));const lt="\n[This shell is producing too much output to stream. The command will still run.]\n",ct=new Set(["cat","grep"]);function ut(e){return ct.has(e)}function dt(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 pt(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 o;if(Array.isArray(e.additionalReadonlyPaths)){const t=e.additionalReadonlyPaths;o=t.length>0?t:void 0}const n={...r,networkAccess:e.networkAccess,networkPolicy:dt(e.networkPolicy),networkPolicyStrict:e.networkPolicyStrict,additionalReadonlyPaths:o,disableTmpWrite:e.disableTmpWrite};return"workspace_readonly"===t?{type:"workspace_readonly",...n}:{type:"workspace_readwrite",...n,additionalReadwritePaths:e.additionalReadwritePaths}}async function ht(e,t){const r=await async function(e,t){try{const r=await(0,s.readFile)(e,"utf-8"),o=JSON.parse(r),n=function(e){if("object"!=typeof e||null===e)return"Expected an object";const t=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 o=["debugOutputDir"];for(const e of o)if(void 0!==t[e]&&"string"!=typeof t[e])return`Invalid ${e}: expected string`;const n=["additionalReadwritePaths"];for(const e of n)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.networkPolicy){if("object"!=typeof t.networkPolicy||null===t.networkPolicy)return"Invalid networkPolicy: expected object";const e=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"}}(o);if(n)return{success:!1,error:`Invalid sandbox policy: ${n}`};let i=pt(o);return t&&(i=mt(i,t)),{success:!0,policy:i}}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 mt(e,t){if("insecure_none"===e.type)return e;const r=e.additionalReadonlyPaths?.map((e=>(0,n.o1)(e,t)));if("workspace_readonly"===e.type)return{...e,additionalReadonlyPaths:r};const o=e.additionalReadwritePaths?.map((e=>(0,n.o1)(e,t)));return{...e,additionalReadonlyPaths:r,additionalReadwritePaths:o}}function ft(e){try{return(0,n.Ef)(e,[]).cmd!==e}catch(e){return!1}}function gt(){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=o.default.win32.basename(t).toLowerCase();return"bash.exe"===r?t:"bin"===r?o.default.win32.join(t,"bash.exe"):o.default.win32.join(t,"bin","bash.exe")}(e);const t=["C:\\Program Files\\Git\\bin\\bash.exe","C:\\Program Files (x86)\\Git\\bin\\bash.exe"];for(const e of t)try{if((0,n.Ef)(e,[]).cmd===e)return e}catch{}return"C:\\Program Files\\Git\\bin\\bash.exe"}function vt(e){if(e===de.ZshLight)return de.ZshLight;const t=e||process.env.SHELL||"",r="win32"===process.platform,o=r&&!e?gt():void 0,n=void 0!==o||/git.*bash\.exe$/i.test(t)||/program.*git.*bin.*bash\.exe$/i.test(t),s=!r||n;return t.includes("zsh")?de.Zsh:t.includes("bash")&&s?de.Bash:t.includes("pwsh")||t.includes("powershell")?de.PowerShell:o?de.Bash:r&&(ft("pwsh")||ft("powershell"))?de.PowerShell:ft("zsh")?de.Zsh:ft("bash")&&s?de.Bash:ft("pwsh")||ft("powershell")?de.PowerShell:de.Naive}function yt(e){let t=e;if(!e?.userTerminalHint){const r=gt();r&&(t={...e,userTerminalHint:r})}switch(vt(t?.userTerminalHint??"")){case de.Zsh:return new We(async function(e){const t={...process.env,...pe,...e?.env},r="__CURSOR_STATE_MARKER__",o=["-o","extendedglob","-ilc",`#!/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\n _emit_encoded() {\n local content="$1"\n local var_name="$2"\n if [[ -n "$content" ]]; then\n # Use here-document to avoid argument list length limits entirely\n builtin printf 'cursor_snap_%s=$(command base64 -d <<'''CURSOR_SNAP_EOF_%s'''\n' "$var_name" "$var_name"\n command base64 <<<"$content" | command tr -d '\n'\n builtin printf '\nCURSOR_SNAP_EOF_%s\n' "$var_name"\n builtin printf ')\n'\n builtin printf 'eval "$cursor_snap_%s"\n' "$var_name"\n fi\n }\n\n _log_timing "init"\n\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 # Environment variables (exported)\n # Filter out: proxy settings, sandbox vars, and sudo askpass vars (session-specific)\n local env_vars\n env_vars=$(builtin typeset -xp 2>/dev/null | command grep -viE '_proxy=|CURSOR_SANDBOX|SUDO_ASKPASS|CURSOR_ASKPASS' || true)\n _emit_encoded "$env_vars" "ENV_VARS_B64"\n _log_timing "env_variables"\n\n # Options (replayable as setopt lines; exclude nounset which we enable locally)\n local zsh_opts\n zsh_opts=$(setopt 2>/dev/null | command grep -v '^nounset$' | 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 # Functions: dump all functions at once (much faster than individual processing)\n local all_functions\n all_functions=$(builtin typeset -f 2>/dev/null || true)\n _emit_encoded "$all_functions" "FUNCTIONS_B64"\n _log_timing "functions"\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 "# end of zsh state dump"\n _emit "__CURSOR_ZSH_STATE_END__"\n _log_timing "finalize"\n}\n builtin printf '${r}\\n'; dump_zsh_state`],n=he(Qe(),o,{env:t,stdio:["ignore","pipe","pipe"],detached:!0},{type:"insecure_none"},e?.signal);let s="";n.stdout?.on("data",(e=>{s+=e.toString()})),await new Promise((e=>{n.on("close",(()=>{e(void 0)}))}));const i=fe(s,r),a=`${Ze}\n`,l=`${Ye}\n`;let c;i.startsWith(a)&&i.endsWith(l)?(c=i.slice(a.length),c=c.slice(0,-25)):c=`${process.cwd()}\n`;const{cwd:u,rest:d}=me(c);return new et(u,d)}(t));case de.Bash:return new We(async function(e){const t={...process.env,...pe,...e?.env},r="__CURSOR_STATE_MARKER__",o=["-O","extglob","-ilc",`#!/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 # Require base64 for safe encoding of emitted sections\n if ! command -v base64 >/dev/null 2>&1; then\n echo "Error: base64 command is required" >&2\n return 1\n fi\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\n _emit_encoded() {\n local content="$1"\n local var_name="$2"\n if [[ -n "$content" ]]; then\n builtin printf 'cursor_snap_%s=$(command base64 -d <<'''CURSOR_SNAP_EOF_%s'''\n' "$var_name" "$var_name"\n command base64 <<<"$content" | command tr -d '\n'\n builtin printf '\nCURSOR_SNAP_EOF_%s\n' "$var_name"\n builtin printf ')\n'\n builtin printf 'eval "$cursor_snap_%s"\n' "$var_name"\n fi\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 # Environment variables (export statements)\n # Filter out: proxy settings, sandbox vars, and sudo askpass vars (session-specific)\n local env_vars\n env_vars=$(builtin export -p 2>/dev/null | command grep -viE '_proxy=|CURSOR_SANDBOX|SUDO_ASKPASS|CURSOR_ASKPASS' || true)\n _emit_encoded "$env_vars" "ENV_VARS_B64"\n _log_timing "environment"\n\n # POSIX shell options (replayable as set +/-o lines; exclude nounset which we enable locally)\n local posix_opts\n posix_opts=$(builtin shopt -po 2>/dev/null | command grep -v '^set -o nounset$' | command grep -v '^set +o nounset$' || true)\n _emit_encoded "$posix_opts" "POSIX_OPTS_B64"\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_B64"\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_B64"\n _log_timing "functions"\n\n # Aliases\n local aliases\n aliases=$(builtin alias -p 2>/dev/null || true)\n _emit_encoded "$aliases" "ALIASES_B64"\n _log_timing "aliases"\n\n # Done\n _emit "# end of bash state dump"\n _emit "__CURSOR_BASH_STATE_END__"\n _log_timing "finalize"\n}\n builtin printf '${r}\\n'; dump_bash_state`],n=Ue(e?.userTerminalHint);if(!n)throw new Error("Can't find Bash");const s=he(n,o,{env:t,detached:!0,stdio:["ignore","pipe","pipe"]},{type:"insecure_none"},e?.signal);let i="";s.stdout?.on("data",(e=>{i+=e.toString()})),await new Promise((e=>{s.on("close",(()=>{e(void 0)}))}));const a=fe(i,r),l=`${ge}\n`,c=`${ve}\n`;let u;a.startsWith(l)&&a.endsWith(c)?(u=a.slice(l.length),u=u.slice(0,-26)):u=`${process.cwd()}\n`;const{cwd:d,rest:p}=me(u),h="win32"===process.platform,m="win32"===process.platform?process.cwd():d;return new He(m,p,e?.userTerminalHint,h)}(t));case de.PowerShell:return new We(async function(){return new Ve(process.cwd(),"")}());case de.ZshLight:return new We(async function(e){const t={...process.env,...pe,...e?.env},r="__CURSOR_STATE_MARKER__",o=["-o","extendedglob","-ilc",`${rt} builtin printf '${r}\\n'; dump_zsh_state_light`],n=he(it(),o,{env:t,stdio:["ignore","pipe","pipe"],detached:!0},{type:"insecure_none"},e?.signal);let s="";n.stdout?.on("data",(e=>{s+=e.toString()})),await new Promise((e=>{n.on("close",(()=>{e(void 0)}))}));const i=fe(s,r),a=`${tt}\n`,l=i.startsWith(a)?i.slice(a.length):i,{cwd:c,rest:u}=me(l);return new at(c,u)}(t));default:return function(e){const t="win32"===process.platform,r=e?.shell??(t?Ge():void 0),o=process.cwd();return new Ke(o,{...e,shell:r})}(t)}}process.platform;const wt={perUser:{type:"insecure_none"}}}};
|