@cursor/sdk 1.0.39 → 1.0.40
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bundled/index.js +302 -278
- package/dist/bundled/sqlite.js +15 -15
- package/dist/cjs/18.js +1 -1
- package/dist/cjs/331.js +1 -0
- package/dist/cjs/448.js +1 -1
- package/dist/cjs/agent/options.d.ts +16 -0
- package/dist/cjs/agent/options.d.ts.map +1 -1
- package/dist/cjs/agent.d.ts +21 -0
- package/dist/cjs/agent.d.ts.map +1 -1
- package/dist/cjs/cloud-agent.d.ts +2 -1
- package/dist/cjs/cloud-agent.d.ts.map +1 -1
- package/dist/cjs/cloud-api-client.d.ts +2 -1
- package/dist/cjs/cloud-api-client.d.ts.map +1 -1
- package/dist/cjs/executor-common.d.ts +1 -1
- package/dist/cjs/executor-common.d.ts.map +1 -1
- package/dist/cjs/index.js +1 -1
- package/dist/cjs/local-executor.d.ts +2 -0
- package/dist/cjs/local-executor.d.ts.map +1 -1
- package/dist/cjs/local-store-open-failure.d.ts +11 -0
- package/dist/cjs/local-store-open-failure.d.ts.map +1 -0
- package/dist/cjs/options.d.ts +16 -0
- package/dist/cjs/options.d.ts.map +1 -1
- package/dist/cjs/platform.d.ts +3 -1
- package/dist/cjs/platform.d.ts.map +1 -1
- package/dist/cjs/sqlite.js +1 -1
- package/dist/cjs/team-id.d.ts +12 -0
- package/dist/cjs/team-id.d.ts.map +1 -0
- package/dist/esm/18.js +1 -1
- package/dist/esm/331.js +1 -0
- package/dist/esm/448.js +1 -1
- package/dist/esm/agent/options.d.ts +16 -0
- package/dist/esm/agent/options.d.ts.map +1 -1
- package/dist/esm/agent.d.ts +21 -0
- package/dist/esm/agent.d.ts.map +1 -1
- package/dist/esm/cloud-agent.d.ts +2 -1
- package/dist/esm/cloud-agent.d.ts.map +1 -1
- package/dist/esm/cloud-api-client.d.ts +2 -1
- package/dist/esm/cloud-api-client.d.ts.map +1 -1
- package/dist/esm/executor-common.d.ts +1 -1
- package/dist/esm/executor-common.d.ts.map +1 -1
- package/dist/esm/index.js +1 -1
- package/dist/esm/local-executor.d.ts +2 -0
- package/dist/esm/local-executor.d.ts.map +1 -1
- package/dist/esm/local-store-open-failure.d.ts +11 -0
- package/dist/esm/local-store-open-failure.d.ts.map +1 -0
- package/dist/esm/options.d.ts +16 -0
- package/dist/esm/options.d.ts.map +1 -1
- package/dist/esm/platform.d.ts +3 -1
- package/dist/esm/platform.d.ts.map +1 -1
- package/dist/esm/sqlite.js +1 -1
- package/dist/esm/team-id.d.ts +12 -0
- package/dist/esm/team-id.d.ts.map +1 -0
- package/package.json +6 -6
- package/dist/cjs/220.js +0 -1
- package/dist/esm/220.js +0 -1
package/dist/esm/331.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createRequire as e}from"node:module";const t=e(import.meta.url);export const __webpack_esm_id__=331;export const __webpack_esm_ids__=[331];export const __webpack_esm_modules__={"./src/agent/local-executor.ts"(e,t,r){r.d(t,{createLocalExecutor:()=>TR});var o=r("node:buffer"),n=r("node:os"),s=r("node:path"),i=r("../context/dist/otel.js"),a=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var 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 c{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,i.VI)(this.ctx.withName("CheckpointController.run")),!1).ctx,r=[];for await(const e of this.checkpointStream)r.push(this.checkpointHandler.handleCheckpoint(t,e.checkpoint,e.metadata));await Promise.all(r)}catch(t){e.error=t,e.hasError=!0}finally{a(e)}}}function l(e){return e instanceof Error?e.message:String(e)}function u(e){return"Failed to read skill file: "+l(e)}function d(e){return"Invalid skill frontmatter: "+l(e)}function h(e,t){return e||t?void 0:"Description is required"}new Set(["EACCES","EPERM","ENOENT","ENOTDIR","EISDIR","ELOOP","ENAMETOOLONG"]);const p=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function f(e){return e.toLocaleString("en-US")}var m=r("../context/dist/logger.js"),g=r("../metrics/dist/index.js"),w=r("../proto/dist/generated/agent/v1/exec_pb.js"),y=r("../utils/dist/writable-iterable.js");const v=/https?:\/\/\S+/gi,b=/[)"'<>,.;:\]}]$/;function S(e){const{url:t,wrappers:r}=function(e){let t=e.length;for(;t>0&&b.test(e.slice(t-1,t));)t-=1;return{url:e.slice(0,t),wrappers:e.slice(t)}}(e),o=t.search(/[?#]/),n=-1===o?t:t.slice(0,o),s=n.indexOf("//")+2,i=n.slice(s).search(/[/?#]/),a=-1===i?n.length:s+i,c=n.lastIndexOf("@",a-1);return c<s?n+r:n.slice(0,s)+n.slice(c+1)+r}const k=/ \[git: ([^\]]*)\]/;function E(e,t,r){if("object"!=typeof t||null===t)return e;if(k.test(e))return e;const o=t,n=[];if("string"==typeof o.gitErrorCode&&o.gitErrorCode.length>0&&n.push(`gitErrorCode=${o.gitErrorCode}`),"number"==typeof o.exitCode&&Number.isFinite(o.exitCode)&&n.push(`exitCode=${o.exitCode}`),0===n.length)return e;let s=`${e} [git: ${n.join(" ")}]`;var i,a;return!0===r?.includeStderr&&"string"==typeof o.stderr&&o.stderr.length>0&&(s+=`\n--- git stderr ---\n${a=o.stderr,i=a.replace(v,S),i.length<=2048?i:`${i.slice(0,2048)}… [truncated to 2048 chars]`}`),s}const C=(0,m.h)("SimpleControlledExecManager"),x=(0,g.v5)("agent_exec.controlled.exec.duration_ms",{description:"Duration of controlled exec operations in milliseconds",labelNames:["exec_case"]}),_=(0,g.Pu)("agent_exec.controlled.exec.success",{description:"Count of successful controlled exec operations",labelNames:["exec_case"]}),P=(0,g.Pu)("agent_exec.controlled.exec.error",{description:"Count of failed controlled exec operations",labelNames:["exec_case"]}),I={computerUseArgs:"Computer use is not enabled for this environment, so the Computer tool and the computerUse subagent cannot run here. Do not retry computer actions; verify with non-GUI methods (automated tests, shell commands) instead. (No computer-use handler is registered on this exec daemon.)",recordScreenArgs:"Screen recording is not enabled for this environment, so recordings cannot be captured here. Do not retry; skip the recording and present other evidence instead. (No record-screen handler is registered on this exec daemon.)"};class R extends Error{constructor(e){super(e),this.name="ControlledExecDisposedError"}}function T(e){return e instanceof R?"EXEC_BACKEND_UNAVAILABLE":e instanceof Error&&"AgentExecStreamStartTimeoutError"===e.name?"AGENT_EXEC_STREAM_START_TIMEOUT":void 0}class A{constructor(e,t,r){this.exec=e,this.deserializeArgs=t,this.serializeResult=r}handle(e,t){const r=this.deserializeArgs(t);if(void 0===r)return;const{id:o,args:n}=r;return async function*(r){const s=performance.now(),i=[],a=await r.exec.execute(e,n,{execId:t.execId,hookContextCollector:i,deliverAgentStoreConflictNotices:!0===t.acceptHookAdditionalContexts}),c=r.serializeResult(o,a);c.localExecutionTimeMs=Math.round(Math.max(0,performance.now()-s)),i.length>0&&(c.hookAdditionalContexts=i),yield c}(this)}}class M{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=[],a=r.exec.execute(e,n,{execId:t.execId,hookContextCollector:i,deliverAgentStoreConflictNotices:!0===t.acceptHookAdditionalContexts});try{for await(const e of a){const t=r.serializeStream(o,e);t.localExecutionTimeMs=Math.round(Math.max(0,performance.now()-s)),yield t}}finally{const e=i.filter((e=>"agentStoreConflict"===e.hookEventName));e.length>0&&(yield new w.yT({id:o,hookAdditionalContexts:e}))}}(this)}}class D{constructor(e){this.handlers=[],this.runningExecs=new Map;const t=e?.includeGitStderrInThrows??!1;this.includeGitStderrInThrows="function"==typeof t?t:()=>t}register(e){this.handlers.push(e)}handleControlMessage(e){if("abort"===e.message.case){const t=e.message.value.id,r=this.runningExecs.get(t);r&&r()}}handle(e,t){const[r,o]=e.withCancel();this.runningExecs.set(t.id,o);const n=t.message.case??"unknown";for(const e of this.handlers){const s=e.handle(r,t);if(void 0===s)continue;const i=s,a=(0,y.Jt)();let c;const l=()=>{c=setTimeout((()=>{a.write(new w.$Y({message:{case:"heartbeat",value:new w.VA({id:t.id})}})).then(l).catch((()=>{}))}),3e3)};l();const u=performance.now();return(async()=>{try{for await(const e of i)await a.write(e);await a.write(new w.$Y({message:{case:"streamClose",value:new w.D9({id:t.id})}})),_.increment(r,1,{exec_case:n})}catch(e){if(e instanceof y.W2)return;P.increment(r,1,{exec_case:n}),await a.write(new w.$Y({message:{case:"throw",value:new w.Fu({id:t.id,error:e instanceof Error?E(e.message,e,{includeStderr:this.includeGitStderrInThrows()}):"Unknown error",stackTrace:e instanceof Error?e.stack:void 0,errorCode:T(e)})}}))}finally{const e=performance.now()-u;x.histogram(r,e,{exec_case:n}),clearTimeout(c),a.close(),this.runningExecs.delete(t.id),o()}})(),a}this.runningExecs.delete(t.id),o();const s=t.message.case,i=(void 0===s?void 0:I[s])??`No handler found for server message of type ${s}`;return C.error(e,i,{messageCase:s}),P.increment(e,1,{exec_case:n}),async function*(){yield new w.$Y({message:{case:"throw",value:new w.Fu({id:t.id,error:i})}}),yield new w.$Y({message:{case:"streamClose",value:new w.D9({id:t.id})}})}()}static fromResources(e,t){const r=new D(t);for(const[t,o]of e.entries())t.registerControlledImplementation(o,r);return r}}async function O(e){const t=e[Symbol.asyncIterator](),r=await t.next();if(r.done)return;const o={async*[Symbol.asyncIterator](){for(;;){const e=await t.next();if(e.done)return;yield e.value}}};return{firstItem:r.value,rest:o}}var 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},$=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 F=(0,m.h)("ExecutorResource"),j=(0,g.Pu)("agent_exec.hook_additional_context.delivered",{description:"Hook additional_context carriers drained into the caller collector",labelNames:["hook_event_name"]});class L{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=N(o,(0,i.VI)(e.withName("ExecutorResource.execute")),!1),s=n.ctx;void 0!==r?.execId&&n.span.setAttribute("exec.id",r.execId);const a=(0,i.mJ)(s),c=a?new w.Kg(a):void 0,l=this.execManager.createExecInstance(s,(e=>{const o=this.serializeArgs(e,t);return new w.Ye({id:o.id,message:o.message,execId:r?.execId,machineId:r?.machineId,spanContext:c,acceptHookAdditionalContexts:void 0!==r?.hookContextCollector})})),u=await O(l);if(void 0===u)throw new Error("No exec result");let{firstItem:d,rest:h}=u;const p=e=>{if(void 0!==r?.hookContextCollector&&e.hookAdditionalContexts.length>0){r.hookContextCollector.push(...e.hookAdditionalContexts);for(const t of e.hookAdditionalContexts)j.increment(s,1,{hook_event_name:t.hookEventName})}};p(d);let f=this.deserializeResult(d);for(;void 0===f;){const e=await O(h);if(void 0===e)throw new Error("No result value");d=e.firstItem,h=e.rest,p(d),f=this.deserializeResult(d)}return(async()=>{try{for await(const e of h)p(e)}catch(e){F.info(s,"Ignoring exec stream shutdown during detached drain",{error:e})}})().catch((()=>{})),f}catch(e){o.error=e,o.hasError=!0}finally{$(o)}}}class U{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=N(o,(0,i.VI)(e.withName("StreamExecutorResource.execute")),!1).ctx,s=(0,i.mJ)(n),a=s?new w.Kg(s):void 0,c=this.execManager.createExecInstance(n,(e=>{const o=this.serializeArgs(e,t);return new w.Ye({id:o.id,message:o.message,execId:r?.execId,machineId:r?.machineId,spanContext:a,acceptHookAdditionalContexts:void 0!==r?.hookContextCollector||!0===r?.deliverAgentStoreConflictNotices})}));for await(const e of c){void 0!==r?.hookContextCollector&&e.hookAdditionalContexts.length>0&&r.hookContextCollector.push(...e.hookAdditionalContexts);const t=this.deserializeStream(e);void 0!==t&&(yield t)}}catch(e){o.error=e,o.hasError=!0}finally{$(o)}}}function B(e){return Symbol.for(`@anysphere/agent-exec/resource/${e}`)}function W(e,t,r){return{name:e,symbol:B(e),remoteImplementation:t,registerControlledImplementation:r}}class H{constructor(e,t){this.resource=e,this.value=t}}function q(e,t){return[e,t]}function z(e,t){return t}class G{constructor(){this.resources=new Map}register(e,t){this.resources.set(e.symbol,new H(e,t))}get(e){return z(0,this.resources.get(e.symbol)?.value)}entries(){return Array.from(this.resources.values()).map((e=>[e.resource,e.value]))}}class V{constructor(e,t){this.remoteAccessor=e,this.localResources=new Map;for(const[e,r]of t)this.localResources.set(e.symbol,{resource:e,implementation:r})}get(e){const t=this.localResources.get(e.symbol);return t?z(0,t.implementation):this.remoteAccessor.get(e)}*entries(){for(const{resource:e,implementation:t}of this.localResources.values())yield[e,t];for(const e of this.remoteAccessor.entries())this.localResources.has(e[0].symbol)||(yield e)}}function J(e){return function(t,r){return new w.Ye({id:t,message:{case:e,value:r}})}}function K(e){return t=>{if(t.message.case===e)return t.message.value}}function Z(e){return function(t,r){const o={case:e,value:r};return new w.yT({id:t,message:o})}}function X(e){return function(t){if(t.message.case===e)return{id:t.id,args:t.message.value}}}const Q=W("agent-store-conflict-executor",(e=>new L(e,J("agentStoreConflictArgs"),K("agentStoreConflictResult"))),((e,t)=>{t.register(new A(e,X("agentStoreConflictArgs"),Z("agentStoreConflictResult")))}));new Set(["write_conflict","create_conflict","truncate_conflict_failed","conflict_fallback_failed","quota_exceeded","gap"]);class Y{async execute(e,t){return"ack"===t.op?{kind:"acked",count:0}:"release"===t.op?{kind:"released",count:0}:"noteDeferredEagerWrittenPaths"===t.op?{kind:"noted",count:0}:{kind:"not-applicable"}}}W("agent-store-conflict-notice-executor",(e=>new Y),((e,t)=>{}));const ee=W("background-shell-executor",(e=>new L(e,J("backgroundShellSpawnArgs"),K("backgroundShellSpawnResult"))),((e,t)=>{t.register(new A(e,X("backgroundShellSpawnArgs"),Z("backgroundShellSpawnResult")))})),te=W("write-background-shell-input-executor",(e=>new L(e,J("writeShellStdinArgs"),K("writeShellStdinResult"))),((e,t)=>{t.register(new A(e,X("writeShellStdinArgs"),Z("writeShellStdinResult")))}));function re(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}const oe="local",ne=W("canvas-diagnostics-executor",(e=>new L(e,J("canvasDiagnosticsArgs"),K("canvasDiagnosticsResult"))),((e,t)=>{t.register(new A(e,X("canvasDiagnosticsArgs"),Z("canvasDiagnosticsResult")))}));Error;const se=W("computer-use-executor",(e=>new L(e,J("computerUseArgs"),K("computerUseResult"))),((e,t)=>{t.register(new A(e,X("computerUseArgs"),Z("computerUseResult")))})),ie=(W("conversation-search-executor",(e=>new L(e,J("conversationSearchArgs"),K("conversationSearchResult"))),((e,t)=>{t.register(new A(e,X("conversationSearchArgs"),Z("conversationSearchResult")))})),W("delete-executor",(e=>new L(e,J("deleteArgs"),K("deleteResult"))),((e,t)=>{t.register(new A(e,X("deleteArgs"),Z("deleteResult")))}))),ae=W("diagnostics-executor",(e=>new L(e,J("diagnosticsArgs"),K("diagnosticsResult"))),((e,t)=>{t.register(new A(e,X("diagnosticsArgs"),Z("diagnosticsResult")))}));var ce=r("../context/dist/core.js");(0,ce.cF)(Symbol("execConversationId"),void 0),(0,ce.cF)(Symbol("execRequestId"),void 0),(0,ce.cF)(Symbol("execBrowserOperationSource"),void 0);const le=W("fetch-executor",(e=>new L(e,J("fetchArgs"),K("fetchResult"))),((e,t)=>{t.register(new A(e,X("fetchArgs"),Z("fetchResult")))})),ue=W("git-diff-executor",(e=>new L(e,J("gitDiffRequest"),K("gitDiffResponse"))),((e,t)=>{t.register(new A(e,X("gitDiffRequest"),Z("gitDiffResponse")))})),de=W("grep-executor",(e=>new L(e,J("grepArgs"),K("grepResult"))),((e,t)=>{t.register(new A(e,X("grepArgs"),Z("grepResult")))})),he={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"},pe={PreToolUse:he.preToolUse,PermissionRequest:null,PostToolUse:he.postToolUse,UserPromptSubmit:he.beforeSubmitPrompt,Stop:he.stop,SubagentStop:he.subagentStop,SessionStart:he.sessionStart,SessionEnd:he.sessionEnd,PreCompact:he.preCompact,Notification:null},fe=Object.fromEntries(Object.entries(pe).filter((e=>me(e[0])&&null!==e[1])).map((([e,t])=>[t,e])));function me(e){return Object.prototype.hasOwnProperty.call(pe,e)}const ge={Bash:"Shell",Read:"Read",Write:"Write",Edit:"Write",Glob:null,Grep:"Grep",WebFetch:"WebFetch",WebSearch:"WebSearch",Task:"Task"},we=["Glob"],ye=["Notification","PermissionRequest"],ve=e=>"string"==typeof e,be=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),Se=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),ke=(e,t=[])=>({isValid:e,errors:t});function Ee(e,t,r){void 0===e||ve(e)||r.push(`${t} must be a string if provided`)}const Ce={warn:()=>{},info:()=>{}};function xe(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?{type:"prompt",prompt:e.prompt,...r}:null:e.command?{type:"command",command:e.command,...r}:null}function _e(e,t,r=Ce){const o=[];let n;if("PreToolUse"===t||"PostToolUse"===t){const t=function(e,t=Ce){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=ge[t];null!==r?void 0!==r?o.includes(r)||o.push(r):o.push(t):we.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=xe(t,n);e&&o.push(e)}return o}function Pe(e,t=Ce){const r={};for(const[o,n]of Object.entries(e)){if(!me(o)){t.warn(`Unknown Claude Code event "${o}", skipping`);continue}if(ye.includes(o)){t.warn(`Claude Code event "${o}" is not supported in Cursor and will be ignored`);continue}const e=pe[o];if(!e){t.warn(`Unknown Claude Code event "${o}", skipping`);continue}const s=[];if(Array.isArray(n))for(const e of n){const r=_e(e,o,t);s.push(...r)}else void 0!==n&&t.warn(`Claude Code event "${o}" has invalid value (expected array), skipping`);if(s.length>0){const t=r[e]||[];r[e]=[...t,...s]}}return{version:1,hooks:r}}const Ie="Agent note: Do not suggest workarounds to the blocked tool.";function Re(e){return e.includes(Ie)?e:`${e}\n\n${Ie}`}function Te(e,t){const r=Reflect.get(e,t);return"string"==typeof r&&""!==r?r:void 0}function Ae(e,t){return e.filter((e=>function(e,t){if(!e.matcher||""===e.matcher||"*"===e.matcher)return!0;if(void 0===t)return!0;try{return new RegExp(e.matcher).test(t)}catch{return!0}}(e,t)))}const Me=e=>{const t=[];return be(e)?ke(!0):(t.push("Expected an object"),ke(!1,t))},De=e=>{const t=[],r=Me(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"),ke(0===t.length,t)};function Oe(e){const t=e.modelId,r=e.modelParams;return{...void 0!==t&&{model_id:t},...void 0!==r&&r.length>0?{model_params:r.map((e=>({id:e.id,value:e.value})))}:{}}}const Ne=new Set([he.sessionStart,he.beforeSubmitPrompt,he.preToolUse,he.postToolUse,he.postToolUseFailure]);function $e(e){return"prompt"===e.type}function Fe(e){return"command"===e.type||void 0===e.type}const je={[he.beforeShellExecution]:De,[he.beforeMCPExecution]:De,[he.afterShellExecution]:e=>{const t=Me(e);return t.isValid,t},[he.afterMCPExecution]:e=>{const t=Me(e);return t.isValid,t},[he.beforeReadFile]:e=>{const t=[],r=Me(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"),ke(0===t.length,t)},[he.afterFileEdit]:e=>{const t=Me(e);return t.isValid,t},[he.beforeTabFileRead]:e=>{const t=[],r=Me(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"),ke(0===t.length,t)},[he.afterTabFileEdit]:e=>Me(e),[he.beforeSubmitPrompt]:e=>{const t=Me(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||ve(e.additional_context)||r.push("additional_context must be a string if provided"),ke(0===r.length,r)},[he.stop]:e=>{const t=Me(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"),ke(0===r.length,r)},[he.afterAgentResponse]:e=>{const t=Me(e);return t.isValid,t},[he.afterAgentThought]:e=>{const t=Me(e);return t.isValid,t},[he.sessionStart]:e=>{const t=Me(e);if(!t.isValid)return t;const r=[];if(void 0!==e.env)if(be(e.env))for(const[t,o]of Object.entries(e.env))ve(t)||r.push(`env key "${t}" must be a string`),ve(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||ve(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||ve(e.user_message)||r.push("user_message must be a string if provided"),ke(0===r.length,r)},[he.sessionEnd]:e=>{const t=Me(e);return t.isValid?ke(!0,[]):t},[he.preCompact]:e=>{const t=Me(e);if(!t.isValid)return t;if(null==e||0===Object.keys(e).length)return ke(!0,[]);const r=[];if(!Se(e))return r.push("PreCompact response must be an object"),ke(!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"),ke(0===r.length,r)},[he.subagentStart]:e=>{const t=Me(e);if(!t.isValid)return t;if(!Se(e))return ke(!1,["Expected an object"]);const r=[],o=e;if(void 0!==o.permission){const e=["allow","deny","ask"];"string"==typeof o.permission&&e.includes(o.permission)||r.push(`Invalid permission value. Expected one of: ${e.join(", ")}, or undefined`)}return void 0===o.user_message||ve(o.user_message)||r.push("user_message must be a string if provided"),ke(0===r.length,r)},[he.subagentStop]:e=>{const t=Me(e);if(!t.isValid)return t;const r=[];return Se(e)&&void 0!==e.followup_message&&"string"!=typeof e.followup_message&&r.push("followup_message must be a string if provided"),ke(0===r.length,r)},[he.preToolUse]:e=>{const t=[],r=Me(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"),Ee(e.additional_context,"additional_context",t),ke(0===t.length,t)},[he.postToolUse]:e=>{const t=[],r=Me(e);return r.isValid?(Ee(e.additional_context,"additional_context",t),ke(0===t.length,t)):r},[he.postToolUseFailure]:e=>{const t=Me(e);if(!t.isValid)return t;const r=[];return Ee(e.additional_context,"additional_context",r),ke(0===r.length,r)},[he.workspaceOpen]:e=>{const t=Me(e);if(!t.isValid)return t;const r=[];return void 0!==e.pluginPaths&&(Array.isArray(e.pluginPaths)?e.pluginPaths.forEach(((e,t)=>{"string"==typeof e?0===e.trim().length&&r.push(`pluginPaths[${t}] must be a non-empty string`):r.push(`pluginPaths[${t}] must be a string`)})):r.push("pluginPaths must be an array of strings if provided")),ke(0===r.length,r)}},Le=(e,t,r)=>{const o=function(e,t,r){let o;o=e===he.preToolUse?function(e,t){if(!Ze(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(!Ke(t))return r;const o=Xe(e);if(!Qe(o,"PreToolUse"))return r;const n={...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),Ze(o.updatedInput)&&(n.updated_input=o.updatedInput,s=!0),s?n:r}(t,r):e===he.stop?Ye(t,r,"Stop"):e===he.subagentStop?Ye(t,r,"SubagentStop"):t;const n=function(e,t,r,o){if(!Ne.has(e)||!Ze(r)||void 0!==r.additional_context)return r;const n=Ze(t)?function(e){return"string"==typeof e.additionalContext?e.additionalContext:void 0}(t)??function(e,t,r){if(!Ke(r))return;const o=fe[e];if(void 0===o)return;const n=Xe(t);return Qe(n,o)&&"string"==typeof n.additionalContext?n.additionalContext:void 0}(e,t,o):void 0;return void 0===n?r:{...r,additional_context:n}}(e,t,o,r);return n}(e,t,r),n=(0,je[e])(o);return n.isValid?{success:!0,data:o}:{success:!1,errors:n.errors}},Ue=[he.beforeShellExecution,he.beforeMCPExecution,he.beforeReadFile,he.beforeTabFileRead,he.subagentStart,he.preToolUse],Be=[he.workspaceOpen];function We(e,t){const r=[];return"string"==typeof e&&e.trim()&&r.push(e.trim()),"string"==typeof t&&t.trim()&&r.push(t.trim()),r.length>0?r.join("\n\n---\n\n"):void 0}function He(e,t){return{..."object"==typeof e&&null!==e?e:{},...t}}function qe(e){return Ue.includes(e)}function ze({step:e,command:t,failClosed:r,kind:o}){const n=qe(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:Ve(e,s),cause:r?"script_fail_closed":"permission_hook_invalid_output",reason:s,shouldNotifyUser:n&&!r}}function Ge(e,t){return t}function Ve(e,t){return qe(e)?Ge(0,{permission:"deny",user_message:t}):e===he.beforeSubmitPrompt||e===he.sessionStart?Ge(0,{continue:!1,user_message:t}):e===he.stop?Ge(0,{}):void 0}function Je(e){try{return{value:JSON.parse(e)}}catch{return}}function Ke(e){return e?.enableClaudeNestedHookSpecificOutputCompatibility??!1}function Ze(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function Xe(e){if(!Ze(e))return;const t=e.hookSpecificOutput;return Ze(t)?t:void 0}function Qe(e,t){if(!e)return!1;const r=e.hookEventName;return void 0===r||""===r||r===t}function Ye(e,t,r){if(!Ze(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{...o,followup_message:o.reason.trim()};if(!Ke(t))return o;const n=Xe(e),s=Qe(n,r)?n:void 0,i=void 0!==s?{...o,...s}:o;return"block"===i.decision&&"string"==typeof i.reason&&i.reason.trim().length>0?{...i,followup_message:i.reason.trim()}:o}const et=["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass"];function tt(e){let t=e.trim();t.startsWith("&")&&(t=t.slice(1).trim());const r=t.charAt(0);if("'"!==r&&'"'!==r)return t.split(/\s/)[0]??"";let o="";for(let e=1;e<t.length;e++){const n=t.charAt(e);if("'"!==r||"'"!==n||"'"!==t.charAt(e+1)){if(n===r)return o;o+=n}else o+="'",e+=1}return o}function rt(e){return e.slice(Math.max(e.lastIndexOf("\\"),e.lastIndexOf("/"))+1)}const ot=new Set(["cat","cd","chdir","clc","clear","cli","cls","clv","compare","copy","cp","curl","del","diff","dir","echo","erase","fc","fl","foreach","ft","fw","gal","gc","gci","gcm","gi","gl","gm","gp","gps","group","gsv","gu","gv","h","history","icm","iex","ii","kill","lp","ls","man","md","mi","mount","move","mp","mv","ni","nv","ogv","oh","popd","ps","pushd","pwd","r","rd","ren","ri","rm","rmdir","rni","rv","sal","sc","select","set","si","sl","sleep","sls","sort","sp","start","sv","tee","type","wget","where","write"]);function nt(e){const t=tt(e),r=rt(t);return!ot.has(r.toLowerCase())&&(!!/\.(exe|bat|cmd|com)$/i.test(r)||t===r&&/^[A-Za-z0-9_]+$/.test(r))}function st(e){if(nt(e))return"; if ($null -ne $LASTEXITCODE -and $LASTEXITCODE -ne 0) { exit $LASTEXITCODE } elseif ($null -eq $LASTEXITCODE -and @($Error | Where-Object { $_.Exception -is [System.Management.Automation.CommandNotFoundException] }).Count -gt 0) { exit 127 }";const t=tt(e),r=rt(t);return/\.ps1$/i.test(r)?`; $literalHookCommand = '${t.replace(/'/g,"''")}'; $expectedHookCommand = $ExecutionContext.InvokeCommand.ExpandString($literalHookCommand); if ($null -eq $LASTEXITCODE -and @($Error | Where-Object { $_.Exception -is [System.Management.Automation.CommandNotFoundException] -and ($_.Exception.CommandName -eq $expectedHookCommand -or $_.Exception.CommandName -eq $literalHookCommand -or $_.Exception.CommandName -eq $expectedHookCommand.Replace('\\','/') -or $_.Exception.CommandName -eq $expectedHookCommand.Replace('/','\\') -or $_.Exception.CommandName -eq $literalHookCommand.Replace('\\','/') -or $_.Exception.CommandName -eq $literalHookCommand.Replace('/','\\')) }).Count -gt 0) { exit 127 }`:function(e){const t=tt(e);if(0===t.length||nt(e))return!1;const r=rt(t);return!/\.ps1$/i.test(r)&&(!(t!==r||!/^[a-z0-9]+(?:-[a-z0-9]+)+$/.test(r))||t.includes("/")||t.includes("\\")||r.includes("."))}(e)?"; if ($null -eq $LASTEXITCODE -and @($Error | Where-Object { $_.Exception -is [System.Management.Automation.CommandNotFoundException] }).Count -gt 0) { exit 127 }":""}const it=[".ps1",".exe",".bat",".cmd"];function at(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}const ct=e=>{const t=[];if(!be(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)"),ke(!1,t);const r=e.type;return"prompt"===r?((e,t)=>{ve(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&&(ve(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)=>{ve(e.command)||t.push("Hook script command must be a string")})(e,t):t.push(`Invalid hook type: "${r}". Must be "command", "prompt", or omitted (defaults to "command")`),((e,t)=>{if(void 0!==e.matcher)if(ve(e.matcher)){if(""!==e.matcher&&"*"!==e.matcher)try{new RegExp(e.matcher)}catch(r){t.push(`Hook script matcher "${e.matcher}" is not a valid regex: ${r?.message??String(r)}`)}}else t.push("Hook script matcher must be a string if provided");if(void 0!==e.timeout&&("number"!=typeof e.timeout?t.push("Hook script timeout must be a number (seconds)"):e.timeout<=0?t.push("Hook script timeout must be a positive number"):e.timeout>3600&&console.warn(`[hooks] Hook timeout of ${e.timeout}s is very long (>1 hour)`)),void 0!==e.loop_limit){const r=e.loop_limit;null!==r&&("number"!=typeof r?t.push("Hook script loop_limit must be a positive integer or null"):Number.isInteger(r)?r<=0&&t.push("Hook script loop_limit must be a positive integer (use null for no limit)"):t.push("Hook script loop_limit must be an integer"))}void 0!==e.failClosed&&"boolean"!=typeof e.failClosed&&t.push("Hook script failClosed must be a boolean")})(e,t),ke(0===t.length,t)},lt=(e,t)=>{const r=[];if(!Array.isArray(e))return r.push(`${t} must be an array of hook scripts`),ke(!1,r);for(let o=0;o<e.length;o++){const n=ct(e[o]);n.isValid||r.push(`${t}[${o}]: ${n.errors.join(", ")}`)}return ke(0===r.length,r)},ut=e=>{const t=[];if(!be(e))return t.push("Hooks config must be an object"),ke(!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"),!be(e.hooks))return t.push("Config hooks must be an object"),ke(!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(he),o=e.hooks;for(const[e,n]of Object.entries(o))if(r.includes(e)){if(void 0!==n){const r=lt(n,e);r.isValid||t.push(...r.errors)}}else t.push(`Unknown hook type: ${e}. Valid types are: ${r.join(", ")}`);return ke(0===t.length,t)};var dt=r("../proto/dist/generated/agent/v1/hooks_pb.js");const ht=W("hook-executor",(e=>new L(e,J("executeHookArgs"),K("executeHookResult"))),((e,t)=>{t.register(new A(e,X("executeHookArgs"),Z("executeHookResult")))})),pt=new Set(Object.values(he));function ft(e){switch(e){case"completed":case"aborted":case"error":return e;default:return"error"}}function mt(e){switch(e){case"error":case"timeout":case"permission_denied":return e;default:return"error"}}function gt(e){const t=e?.toJson();return"object"!=typeof t||null===t||Array.isArray(t)?{}:t}class wt{constructor(e){this.hookExecutor=e}hasFailClosedHooksForStep(e,t){return!!function(e){return pt.has(e)}(e)&&(this.hookExecutor.hasFailClosedHooksForStep?.(e,t)??!1)}async execute(e,t){const r=t.request;if(!r)return new w.S1({response:void 0});switch(r.request.case){case"preCompact":{const e=r.request.value,t={conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...Oe(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},o=await this.hookExecutor.executeHookForStep(he.preCompact,t);return new w.S1({response:new w.w5({response:{case:"preCompact",value:new dt.$_({userMessage:o?.user_message})}})})}case"subagentStart":{const e=r.request.value,t={conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...Oe(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},o=await this.hookExecutor.executeHookForStep(he.subagentStart,t);return new w.S1({response:new w.w5({response:{case:"subagentStart",value:new dt.W0({permission:o?.permission,userMessage:o?.user_message,additionalContext:o?.additional_context})}})})}case"subagentStop":{const e=r.request.value,t={conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...Oe(e),subagent_id:e.subagentId,subagent_type:e.subagentType,status:ft(e.status),duration_ms:Number(e.durationMs),summary:e.summary,parent_conversation_id:e.parentConversationId,message_count:e.messageCount,tool_call_count:e.toolCallCount,error_message:e.errorMessage,modified_files:e.modifiedFiles,git_branch:e.gitBranch,loop_count:e.loopCount??0,task:e.task,description:e.description,...e.childConversationId?{child_conversation_id:e.childConversationId}:{}},o=await this.hookExecutor.executeHookForStep(he.subagentStop,t);return new w.S1({response:new w.w5({response:{case:"subagentStop",value:new dt.AH({followupMessage:o?.followup_message,additionalContext:o?.additional_context})}})})}case"beforeSubmitPrompt":{const e=r.request.value,t=await this.hookExecutor.executeHookForStep(he.beforeSubmitPrompt,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...Oe(e),prompt:e.prompt,attachments:(o=e.attachments,o.flatMap((e=>"file"===e.type||"rule"===e.type?[{type:e.type,file_path:e.filePath}]:[]))),composer_mode:e.composerMode});return new w.S1({response:new w.w5({response:{case:"beforeSubmitPrompt",value:new dt.u1({continue:t?.continue,userMessage:t?.user_message,additionalContext:t?.additional_context})}})})}case"afterAgentResponse":{const e=r.request.value;return await this.hookExecutor.executeHookForStep(he.afterAgentResponse,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...Oe(e),text:e.text,input_tokens:void 0!==e.inputTokens?Number(e.inputTokens):void 0,output_tokens:void 0!==e.outputTokens?Number(e.outputTokens):void 0,cache_read_tokens:void 0!==e.cacheReadTokens?Number(e.cacheReadTokens):void 0,cache_write_tokens:void 0!==e.cacheWriteTokens?Number(e.cacheWriteTokens):void 0}),new w.S1({response:new w.w5({response:{case:"afterAgentResponse",value:new dt.FW}})})}case"afterAgentThought":{const e=r.request.value;return await this.hookExecutor.executeHookForStep(he.afterAgentThought,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...Oe(e),text:e.text,duration_ms:void 0!==e.durationMs?Number(e.durationMs):void 0}),new w.S1({response:new w.w5({response:{case:"afterAgentThought",value:new dt.H}})})}case"stop":{const e=r.request.value,t=await this.hookExecutor.executeHookForStep(he.stop,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...Oe(e),status:ft(e.status),loop_count:e.loopCount,input_tokens:void 0!==e.inputTokens?Number(e.inputTokens):void 0,output_tokens:void 0!==e.outputTokens?Number(e.outputTokens):void 0,cache_read_tokens:void 0!==e.cacheReadTokens?Number(e.cacheReadTokens):void 0,cache_write_tokens:void 0!==e.cacheWriteTokens?Number(e.cacheWriteTokens):void 0});return new w.S1({response:new w.w5({response:{case:"stop",value:new dt.rT({followupMessage:t?.followup_message})}})})}case"preToolUse":{const e=r.request.value,t=gt(e.toolInput),o={conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...Oe(e),...e.parentToolCallId?{parent_tool_call_id:e.parentToolCallId}:{},tool_name:e.toolName,tool_input:t,tool_use_id:e.toolUseId,cwd:e.cwd},n=await this.hookExecutor.executeHookForStep(he.preToolUse,o);return new w.S1({response:new w.w5({response:{case:"preToolUse",value:new dt.Wn({permission:n?.permission,userMessage:n?.user_message,agentMessage:n?.agent_message,updatedInput:n?.updated_input?JSON.stringify(n.updated_input):void 0,additionalContext:n?.additional_context})}})})}case"postToolUse":{const e=r.request.value,t=gt(e.toolInput),o={conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...Oe(e),...e.parentToolCallId?{parent_tool_call_id:e.parentToolCallId}:{},tool_name:e.toolName,tool_input:t,tool_output:e.toolOutput,duration:Number(e.durationMs),tool_use_id:e.toolUseId,cwd:e.cwd},n=await this.hookExecutor.executeHookForStep(he.postToolUse,o);return new w.S1({response:new w.w5({response:{case:"postToolUse",value:new dt.uB({additionalContext:n?.additional_context})}})})}case"postToolUseFailure":{const e=r.request.value,t=gt(e.toolInput),o={conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...Oe(e),...e.parentToolCallId?{parent_tool_call_id:e.parentToolCallId}:{},tool_name:e.toolName,tool_input:t,error_message:e.errorMessage,failure_type:mt(e.failureType),duration:Number(e.durationMs),tool_use_id:e.toolUseId,is_interrupt:e.isInterrupt},n=await this.hookExecutor.executeHookForStep(he.postToolUseFailure,o);return new w.S1({response:new w.w5({response:{case:"postToolUseFailure",value:new dt.U1({additionalContext:n?.additional_context})}})})}default:return new w.S1({response:void 0})}var o}}(0,ce.cF)(Symbol("execHookConversationId"),void 0),(0,ce.cF)(Symbol("execHookGenerationId"),void 0),(0,ce.cF)(Symbol("execHookModel"),void 0);const yt=(0,ce.cF)(Symbol("execHookWorkspaceRoots"),void 0),vt=W("ls-executor",(e=>new L(e,J("lsArgs"),K("lsResult"))),((e,t)=>{t.register(new A(e,X("lsArgs"),Z("lsResult")))})),bt="cursor-ide-browser",St="cursor-dev-control",kt="custom-user-tools",Et=new Set(["cursor-app-control","cursor-backend-control","cursor-browser-extension",bt,St,kt,"fsd","cursor-subscriptions","cursor-cloud","suggestions","Cursor Slack Tools","Cursor Automation Tools"]);function Ct(e){return!Et.has(e)}const xt=new Set([St,bt]);function _t(e){if(void 0!==e&&0!==Object.keys(e).length)try{return JSON.stringify(e)}catch{return}}function Pt(e){return{name:e.toolName,description:e.description,arguments:e.inputSchema,outputSchema:e.outputSchema,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId}}var It;function Rt(e){return void 0===e||void 0===e.serverIdentifiers}function Tt(e){switch(e.kind){case"ready":return"connected";case"requires_authentication":return"needsAuth";case"error":return"error";default:return"loading"}}(0,ce.cF)(Symbol("mcpHostFilledArguments"),[]),function(e){e.Snapshots="cursor_mcp_lease_snapshot_store",e.Status="cursor_mcp_lease_server_status",e.Settings="cursor_mcp_lease_settings",e.Providers="cursor_mcp_lease_providers",e.Unknown="cursor_mcp_lease_unknown"}(It||(It={}));const At=W("mcp-executor",(e=>new L(e,J("mcpArgs"),K("mcpResult"))),((e,t)=>{t.register(new A(e,X("mcpArgs"),Z("mcpResult")))})),Mt=W("list-mcp-resources-executor",(e=>new L(e,J("listMcpResourcesExecArgs"),K("listMcpResourcesExecResult"))),((e,t)=>{t.register(new A(e,X("listMcpResourcesExecArgs"),Z("listMcpResourcesExecResult")))})),Dt=W("read-mcp-resource-executor",(e=>new L(e,J("readMcpResourceExecArgs"),K("readMcpResourceExecResult"))),((e,t)=>{t.register(new A(e,X("readMcpResourceExecArgs"),Z("readMcpResourceExecResult")))})),Ot=W("mcp-state-executor",(e=>new L(e,J("mcpStateExecArgs"),K("mcpStateExecResult"))),((e,t)=>{t.register(new A(e,X("mcpStateExecArgs"),Z("mcpStateExecResult")))})),Nt=W("mcp-allowlist-precheck-executor",(e=>new L(e,J("mcpAllowlistPrecheckArgs"),K("mcpAllowlistPrecheckResult"))),((e,t)=>{t.register(new A(e,X("mcpAllowlistPrecheckArgs"),Z("mcpAllowlistPrecheckResult")))}));class $t extends Error{constructor(e,t){super(`Tool ${e} not found, available tools: ${t.join(", ")}`),this.toolName=e,this.availableTools=t,this.name="McpToolNotFoundError"}}function Ft(e){if(e instanceof $t)return!0;if(!(e instanceof Error)||"McpToolNotFoundError"!==e.name)return!1;const t=e;return"string"==typeof t.toolName&&Array.isArray(t.availableTools)}const jt=8388608;var Lt=r("../proto/dist/generated/agent/v1/mcp_exec_pb.js"),Ut=r("../proto/dist/generated/agent/v1/read_exec_pb.js");function Bt(e,t){const r=function(e){return e.split(/[/\\]/).filter((e=>e))}(e);for(let e=0;e<r.length-2;e++)if(".cursor"===r[e]&&"projects"===r[e+1]&&r[e+3]===t)return{workspaceId:r[e+2],remainingPath:r.slice(e+4)};return null}function Wt(e){return e.replace(/[^a-zA-Z0-9._-]/g,"_")}var Ht=r("../utils/dist/promise-extras.js"),qt=r("@bufbuild/protobuf");const zt=new TextEncoder;async function Gt(e){const t=zt.encode(e),r=await crypto.subtle.digest("SHA-256",t);return{sha256:[...new Uint8Array(r)].map((e=>e.toString(16).padStart(2,"0"))).join(""),bytes:t.byteLength}}class Vt{constructor(e){this.inner=e}async execute(e,t,r){if(!0!==t.digestOnly)return this.inner.execute(e,t,r);const o=t.clone();return o.digestOnly=void 0,async function(e){if("success"!==e.result.case)return e;const t=e.result.value;if("content"!==t.output.case)return e;const{sha256:r,bytes:o}=await Gt(t.output.value),n=t.clone();return n.output={case:void 0},n.outputBlobId=void 0,n.sha256=r,n.sizeBytes=BigInt(o),new Ut.sV({result:{case:"success",value:n}})}(await this.inner.execute(e,o,r))}}const Jt=W("read-executor",(e=>new L(e,J("readArgs"),K("readResult"))),((e,t)=>{t.register(new A(e,X("readArgs"),Z("readResult")))})),Kt=W("redacted-read-executor",(e=>new L(e,J("redactedReadArgs"),K("redactedReadResult"))),((e,t)=>{t.register(new A(e,X("redactedReadArgs"),Z("redactedReadResult")))})),Zt="$file:";const Xt=(0,g.Pu)("mcp.symbolic_args.expansion",{description:"Outcome of late-binding $file:/abs/path MCP argument expansion at the executor boundary",labelNames:["route","outcome"]}),Qt=(0,g.v5)("mcp.symbolic_args.bytes",{description:"Total bytes substituted into one MCP tool call by $file:/abs/path arguments",labelNames:["route"]}),Yt=(0,g.Pu)("mcp.symbolic_args.describe",{description:"Per-file $file:/abs/path describe reads: `vm_digest` when the read executor hashed the file where it lives, `outdated_executor` when it returned the text instead (it predates $file: expansion, so the call is refused)",labelNames:["source"]}),er=(0,g.v5)("mcp.symbolic_args.paths",{description:"Number of distinct $file:/abs/path arguments expanded in one MCP tool call",labelNames:["route"]});function tr(e,t,r){return{kind:e,message:`Could not resolve the symbolic argument "${Zt}${t}": ${r} A string argument of the form "${Zt}/absolute/path" is replaced with that file's contents before the tool runs; pass the literal text instead if you did not intend that.`}}class rr extends Error{constructor(e){super(e.message),this.failure=e}}async function or(e,t,{route:r,getReadExecutor:o,...n}){if(0===t.symbolicPathArguments.length)return{kind:"none"};const s=new Map(t.symbolicPathArguments.map((e=>[e.path,e]))),i=[...s.keys()],a=t=>(Xt.increment(e,1,{route:r,outcome:t.kind}),{kind:"failed",failure:t,result:new Lt.iz({result:{case:"error",value:new Lt.Nh({error:t.message})}})});let c;try{c=await async function(e,t,r,o,n,{maxFileBytes:s=8388608,maxTotalBytes:i=16777216}){if(t.length>4)throw new rr(tr("too_many",t[4]??"",`at most 4 symbolic arguments may be used in one call (${t.length} given). Split the call or pass paths to tools that accept them.`));const a=r();if(void 0===a)throw new rr(tr("no_read_executor",t[0]??"","this environment cannot read files on behalf of a tool call."));const c=await(0,Ht.xb)(t,(t=>async function(e,t,r,o,n,s){const i=await t.execute(e,new Ut.a2({path:r,toolCallId:o,...s?{digestOnly:!0}:{}}));switch(i.result.case){case"success":{const t=i.result.value,o=s&&void 0!==t.sha256&&void 0!==t.sizeBytes?{sha256:t.sha256,bytes:Number(t.sizeBytes)}:void 0;if(void 0===o&&"content"!==t.output.case)throw new rr(tr("not_text",r,"the file is not a text file."));if(s&&(Yt.increment(e,1,{source:void 0!==o?"vm_digest":"outdated_executor"}),void 0===o))throw new rr(tr("outdated_executor",r,"the computer that would run this tool has an older tool runner that cannot substitute files. Read the file and pass its contents instead."));const a="content"===t.output.case?t.output.value:void 0,{sha256:c,bytes:l}=o??await Gt(a??"");if(t.truncated||l>n)throw new rr(tr("too_large",r,`the file is too large to inline (${Number(t.fileSize)||l} bytes; at most ${n} bytes per file may be substituted). Pass the path to a tool that accepts one, or read a range of it.`));return{content:a,bytes:l,sha256:c}}case"fileNotFound":throw new rr(tr("not_found",r,"the file does not exist."));case"permissionDenied":throw new rr(tr("permission_denied",r,"reading it was not permitted."));case"rejected":throw new rr(tr("rejected",r,`${i.result.value.reason||"the read was rejected"}. Only files the Read tool can read without approval can be substituted; read it with Read instead.`));case"invalidFile":throw new rr(tr("not_text",r,"the file cannot be read as text."));case"error":throw new rr(tr("read_error",r,i.result.value.error));default:throw new rr(tr("read_error",r,"the read returned no result."))}}(e,a,t,o,s,n)),{max:4});let l=0;for(const[e,r]of c)if(l+=r.bytes,l>i)throw new rr(tr("over_budget",e,`together the ${t.length} symbolic arguments exceed the ${i} bytes that may be substituted per call. Pass paths to tools that accept them instead.`));return c}(e,i,o,t.toolCallId,!1,n)}catch(e){return a(function(e,t){return e instanceof rr?e.failure:tr("read_error",t,e instanceof Error?e.message:String(e))}(e,i[0]??""))}let l=0;for(const[e,t]of c){l+=t.bytes;const r=s.get(e);if(r?.sha256!==t.sha256)return a(tr("content_changed",e,`the file changed after the call was reviewed (${r?.sizeBytes??0} bytes then, ${t.bytes} bytes now), so its new contents were not sent. Re-run the call to review the current contents.`))}const u=new Map([...c].map((([e,t])=>[e,t.content??""]))),d=function(e,t){const r=e=>{const o=function(e){if("string"!=typeof e||!e.startsWith(Zt))return;const t=e.slice(6);return(r=t).startsWith("/")||/^[a-zA-Z]:[\\/]/.test(r)||r.startsWith("\\\\")?t:void 0;var r}(e);return void 0!==o?t.get(o)??e:Array.isArray(e)?e.map(r):null!==e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map((([e,t])=>[e,r(t)]))):e};return Object.fromEntries(Object.entries(e).map((([e,t])=>[e,r(t)])))}(Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t.toJson()]))),u),h=t.clone();return h.args=Object.fromEntries(Object.entries(d).map((([e,t])=>[e,qt.Value.fromJson(t)]))),h.symbolicPathArguments=[],h.argumentsRepaired=!1,Xt.increment(e,1,{route:r,outcome:"expanded"}),Qt.record(e,l,{route:r}),er.record(e,i.length,{route:r}),{kind:"expanded",expansion:{args:h,files:[...c].map((([e,t])=>({path:e,bytes:t.bytes}))),paths:i.length,bytes:l}}}const nr=/\b413\b|payload too large|request entity too large|body.*too large|too large.*body|ECONNRESET|EPIPE|socket hang up|max(?:imum)? (?:body|payload|request|content) (?:size|length)/i;function sr(e,t,r,o){return nr.test(t)?(Xt.increment(e,1,{route:o,outcome:"server_rejected_body"}),`${t}\n\nThe request carried ${r.bytes} bytes of file contents substituted from ${r.paths} "${Zt}/abs/path" argument(s), and the server appears to have rejected the request body as too large. Do not retry the same call: pass a smaller file or a range of it, or use a tool that accepts a path or upload instead.`):t}function ir(e){return e.files.map((e=>`"${Zt}${e.path}" was replaced with the contents of ${e.path} (${e.bytes} bytes) before the call.`)).join("\n")}class ar{constructor(e,t){this.inner=e,this.getReadExecutor=t}isBackendRouted(e){return this.inner.isBackendRouted?.(e)??!1}async execute(e,t,r){if(0===t.symbolicPathArguments.length)return this.inner.execute(e,t,r);const o=await or(e,t,{route:"local",getReadExecutor:this.getReadExecutor});if("none"===o.kind)return this.inner.execute(e,t,r);if("failed"===o.kind)return o.result;let n;try{n=await this.inner.execute(e,o.expansion.args,r)}catch(t){throw t instanceof Error&&(t.message=sr(e,t.message,o.expansion,"local")),t}return function(e,t,r){const o=t.clone();return"success"===o.result.case?o.result.value.content.push(new Lt._Z({content:{case:"text",value:new Lt.zN({text:ir(r)})}})):"error"===o.result.case&&(o.result.value.error=sr(e,o.result.value.error,r,"local")),o}(e,n,o.expansion)}}const cr=W("mini-swe-agent-bash-executor",(e=>new L(e,J("miniSweAgentBashArgs"),K("miniSweAgentBashResult"))),((e,t)=>{t.register(new A(e,X("miniSweAgentBashArgs"),Z("miniSweAgentBashResult")))})),lr=W("pi-bash-executor",(e=>new L(e,J("piBashArgs"),K("piBashResult"))),((e,t)=>{t.register(new A(e,X("piBashArgs"),Z("piBashResult")))})),ur=W("pi-edit-executor",(e=>new L(e,J("piEditArgs"),K("piEditResult"))),((e,t)=>{t.register(new A(e,X("piEditArgs"),Z("piEditResult")))})),dr=W("pi-find-executor",(e=>new L(e,J("piFindArgs"),K("piFindResult"))),((e,t)=>{t.register(new A(e,X("piFindArgs"),Z("piFindResult")))})),hr=W("pi-grep-executor",(e=>new L(e,J("piGrepArgs"),K("piGrepResult"))),((e,t)=>{t.register(new A(e,X("piGrepArgs"),Z("piGrepResult")))})),pr=W("pi-ls-executor",(e=>new L(e,J("piLsArgs"),K("piLsResult"))),((e,t)=>{t.register(new A(e,X("piLsArgs"),Z("piLsResult")))})),fr=W("pi-read-executor",(e=>new L(e,J("piReadArgs"),K("piReadResult"))),((e,t)=>{t.register(new A(e,X("piReadArgs"),Z("piReadResult")))})),mr=W("pi-write-executor",(e=>new L(e,J("piWriteArgs"),K("piWriteResult"))),((e,t)=>{t.register(new A(e,X("piWriteArgs"),Z("piWriteResult")))}));var gr=r("../proto/dist/generated/agent/v1/background_shell_exec_pb.js"),wr=r("../proto/dist/generated/agent/v1/delete_exec_pb.js"),yr=r("../proto/dist/generated/agent/v1/shell_exec_pb.js"),vr=r("../proto/dist/generated/agent/v1/write_exec_pb.js");const br=W("shell-executor",(e=>new L(e,J("shellArgs"),K("shellResult"))),((e,t)=>{t.register(new A(e,X("shellArgs"),Z("shellResult")))})),Sr=W("shell-stream-executor",(e=>new U(e,J("shellStreamArgs"),K("shellStream"))),((e,t)=>{t.register(new M(e,X("shellStreamArgs"),Z("shellStream")))})),kr=((0,ce.cF)(Symbol("optionalPendingPodWrite"),!1),W("write-executor",(e=>new L(e,J("writeArgs"),K("writeResult"))),((e,t)=>{t.register(new A(e,X("writeArgs"),Z("writeResult")))})));function Er(e,t){return new yr.jn({command:t.command??"",workingDirectory:t.workingDirectory??"",error:e,isReadonly:!0})}function Cr(e){return{execute:async(t,r)=>new vr.v3({result:{case:"permissionDenied",value:new vr.U7({path:r.path,error:e,isReadonly:!0})}})}}function xr(e){return{execute:async(t,r)=>new wr.Pi({result:{case:"permissionDenied",value:new wr.QG({path:r.path,clientVisibleError:e,isReadonly:!0})}})}}function _r(e){return{execute:async(t,r)=>new Lt.iz({result:{case:"permissionDenied",value:new Lt.HQ({error:`${e} Tool: ${r.name}`,isReadonly:!0})}})}}const Pr=W("record-screen-executor",(e=>new L(e,J("recordScreenArgs"),K("recordScreenResult"))),((e,t)=>{t.register(new A(e,X("recordScreenArgs"),Z("recordScreenResult")))})),Ir=W("request-context-executor",(e=>new L(e,J("requestContextArgs"),K("requestContextResult"))),((e,t)=>{t.register(new A(e,X("requestContextArgs"),Z("requestContextResult")))}));var Rr=r("../proto/dist/generated/agent/v1/request_context_exec_pb.js");const Tr=W("shell-allowlist-precheck-executor",(e=>new L(e,J("shellAllowlistPrecheckArgs"),K("shellAllowlistPrecheckResult"))),((e,t)=>{t.register(new A(e,X("shellAllowlistPrecheckArgs"),Z("shellAllowlistPrecheckResult")))})),Ar=W("force-background-shell-executor",(e=>new L(e,J("forceBackgroundShellArgs"),K("forceBackgroundShellResult"))),((e,t)=>{t.register(new A(e,X("forceBackgroundShellArgs"),Z("forceBackgroundShellResult")))}));function Mr(e,t){e.hookApprovalRequirement=void 0!==t?new yr.In(t):void 0}function Dr(e){return e.hookApprovalRequirement}function Or(e){return e?.kind===yr.b.FORCE_PROMPT}W("smart-mode-classifier-executor",(e=>new L(e,J("smartModeClassifierArgs"),K("smartModeClassifierResult"))),((e,t)=>{t.register(new A(e,X("smartModeClassifierArgs"),Z("smartModeClassifierResult")))}));var Nr=r("../proto/dist/generated/agent/v1/agent_pb.js"),$r=r("../proto/dist/generated/agent/v1/connect_scm_tool_pb.js"),Fr=r("../proto/dist/generated/agent/v1/create_plan_tool_pb.js"),jr=r("../proto/dist/generated/agent/v1/generate_image_tool_pb.js"),Lr=r("../proto/dist/generated/agent/v1/mcp_auth_tool_pb.js"),Ur=r("../proto/dist/generated/agent/v1/switch_mode_tool_pb.js"),Br=r("../proto/dist/generated/agent/v1/web_fetch_tool_pb.js"),Wr=r("../proto/dist/generated/agent/v1/web_search_tool_pb.js");class Hr extends Error{constructor(e){super(`Deferred interaction response requested for query ${e.id} (${e.query.case??"unknown"})`),this.query=e,this.name="DeferredInteractionResponseError",Object.setPrototypeOf(this,new.target.prototype)}}const qr=e=>new Nr.Y5({id:e,result:{case:"webSearchRequestResponse",value:new Wr.lI({result:{case:"approved",value:new Wr.XJ}})}}),zr=(e,t)=>new Nr.Y5({id:e,result:{case:"webSearchRequestResponse",value:new Wr.lI({result:{case:"rejected",value:new Wr.yc({reason:t??""})}})}}),Gr=e=>new Nr.Y5({id:e,result:{case:"webFetchRequestResponse",value:new Br.fS({result:{case:"approved",value:new Br.Hs}})}}),Vr=(e,t)=>new Nr.Y5({id:e,result:{case:"webFetchRequestResponse",value:new Br.fS({result:{case:"rejected",value:new Br.m$({reason:t??""})}})}}),Jr=(e,t)=>new Nr.Y5({id:e,result:{case:"askQuestionInteractionResponse",value:new Nr.zT({result:t})}}),Kr=e=>new Nr.Y5({id:e,result:{case:"switchModeRequestResponse",value:new Ur.w$({result:{case:"approved",value:new Ur.q5}})}}),Zr=(e,t)=>new Nr.Y5({id:e,result:{case:"switchModeRequestResponse",value:new Ur.w$({result:{case:"rejected",value:new Ur.rA({reason:t??""})}})}}),Xr=(e,t)=>new Nr.Y5({id:e,result:{case:"createPlanRequestResponse",value:new Fr.gz({result:t})}}),Qr=(e,t)=>new Nr.Y5({id:e,result:{case:"setupVmEnvironmentResult",value:t}}),Yr=(e,t)=>new Nr.Y5({id:e,result:{case:"replaceEnvResult",value:t}}),eo=(e,t)=>new Nr.Y5({id:e,result:{case:"prManagementResult",value:t}}),to=(e,t)=>new Nr.Y5({id:e,result:{case:"mcpAuthRequestResponse",value:new Lr.h({result:{case:"rejected",value:new Lr.OI({reason:t??"Authentication was rejected"})}})}}),ro=(e,t)=>new Nr.Y5({id:e,result:{case:"connectScmRequestResponse",value:new $r.qG({result:{case:"rejected",value:new $r.lB({reason:t??"Connecting GitHub was skipped"})}})}}),oo=(e,t)=>new Nr.Y5({id:e,result:{case:"generateImageRequestResponse",value:new jr.vW({result:{case:"approved",value:new jr.l3({description:t??""})}})}}),no=(e,t)=>new Nr.Y5({id:e,result:{case:"generateImageRequestResponse",value:new jr.vW({result:{case:"rejected",value:new jr.Uq({reason:t??""})}})}});var so=r("../proto/dist/generated/agent/v1/subagent_exec_pb.js"),io=r("../proto/dist/generated/agent/v1/subagents_pb.js");(0,ce.cF)(Symbol("pendingSubagentReplay"),void 0);class ao extends Error{constructor(e,t){super(e),this.name="SubagentHostError",this.agentId=t?.agentId,this.cause=t?.cause}}const co=W("subagent-executor",(e=>new L(e,J("subagentArgs"),K("subagentResult"))),((e,t)=>{t.register(new A(e,X("subagentArgs"),Z("subagentResult")))})),lo=W("subagent-await-executor",(e=>new L(e,J("subagentAwaitArgs"),K("subagentAwaitResult"))),((e,t)=>{t.register(new A(e,X("subagentAwaitArgs"),Z("subagentAwaitResult")))})),uo=W("force-background-subagent-executor",(e=>new L(e,J("forceBackgroundSubagentArgs"),K("forceBackgroundSubagentResult"))),((e,t)=>{t.register(new A(e,X("forceBackgroundSubagentArgs"),Z("forceBackgroundSubagentResult")))}));class ho{constructor(e={}){this.options=e,this.states=new Map,this.runCounterBySession=new Map,this.dispatchQueueBySession=new Map,this.dispatchInProgress=new Set,this.releaseRequestedBySession=new Set}getState(e){return this.states.get(e)??{status:"idle"}}isBusy(e){return"idle"!==this.getState(e).status}startRun(e,t){const r=this.nextRunId(e);return this.enqueueEvent(e,{type:"startRun",runId:r,abort:t?.abort}),r}queueResume(e,t){this.enqueueEvent(e,{type:"queueResume",queuedResume:t.queuedResume,targetRunId:t.targetRunId,mergeQueuedResume:t.mergeQueuedResume})}finishRun(e,t){this.enqueueEvent(e,{type:"runFinished",runId:t})}clearQueuedResume(e){this.enqueueEvent(e,{type:"clearQueuedResume"})}abort(e){this.enqueueEvent(e,{type:"abort"})}release(e){this.enqueueEvent(e,{type:"release"})}nextRunId(e){const t=(this.runCounterBySession.get(e)??0)+1;return this.runCounterBySession.set(e,t),t}enqueueEvent(e,t){const r=this.dispatchQueueBySession.get(e)??[];r.push(t),this.dispatchQueueBySession.set(e,r),this.drainEventQueue(e)}drainEventQueue(e){if(this.dispatchInProgress.has(e))return;let t;this.dispatchInProgress.add(e);try{const r=this.dispatchQueueBySession.get(e);if(!r)return;for(;r.length>0;){const o=r.shift();if(o)try{this.processEvent(e,o)}catch(e){t??=e}}}finally{this.dispatchQueueBySession.delete(e),this.dispatchInProgress.delete(e)}if(t)throw t}processEvent(e,t){const r=this.getState(e),{nextState:o,effects:n}=function(e,t){switch(e.status){case"idle":return function(e,t){switch(t.type){case"startRun":return{nextState:{status:"running",runId:t.runId,abort:t.abort},effects:[]};case"queueResume":return void 0===t.targetRunId?{nextState:e,effects:[]}:{nextState:{status:"runningWithQueuedResume",runId:t.targetRunId,queuedResume:t.queuedResume},effects:[]};case"runFinished":case"clearQueuedResume":case"abort":case"release":return{nextState:e,effects:[]};default:throw new Error(`Unhandled idle-state event: ${String(t)}`)}}(e,t);case"running":return function(e,t){switch(t.type){case"startRun":return{nextState:{status:"running",runId:t.runId,abort:t.abort},effects:[{type:"abortActiveRun",abort:e.abort}]};case"queueResume":return{nextState:{status:"runningWithQueuedResume",runId:e.runId,abort:e.abort,queuedResume:t.queuedResume},effects:[]};case"runFinished":return t.runId!==e.runId?{nextState:e,effects:[]}:{nextState:{status:"idle"},effects:[]};case"clearQueuedResume":case"release":return{nextState:e,effects:[]};case"abort":return{nextState:{status:"idle"},effects:[{type:"abortActiveRun",abort:e.abort}]};default:throw new Error(`Unhandled running-state event: ${String(t)}`)}}(e,t);case"runningWithQueuedResume":return function(e,t){switch(t.type){case"startRun":return{nextState:{status:"runningWithQueuedResume",runId:t.runId,abort:t.abort,queuedResume:e.queuedResume},effects:[{type:"abortActiveRun",abort:e.abort}]};case"queueResume":return{nextState:{...e,queuedResume:t.mergeQueuedResume(e.queuedResume,t.queuedResume)},effects:[]};case"runFinished":return t.runId!==e.runId?{nextState:e,effects:[]}:{nextState:{status:"running",runId:e.runId,abort:e.abort},effects:[{type:"startQueuedRun",sourceRunId:e.runId,queuedResume:e.queuedResume}]};case"clearQueuedResume":return{nextState:{status:"running",runId:e.runId,abort:e.abort},effects:[]};case"abort":return{nextState:{status:"idle"},effects:[{type:"abortActiveRun",abort:e.abort}]};case"release":return{nextState:e,effects:[]};default:throw new Error(`Unhandled runningWithQueuedResume-state event: ${String(t)}`)}}(e,t);default:return{nextState:e,effects:[]}}}(r,t);this.states.set(e,o),this.options.onStateChange?.({sessionId:e,previousState:r,nextState:o});for(const t of n)switch(t.type){case"abortActiveRun":t.abort?.();break;case"startQueuedRun":this.options.onQueuedRunReady?.({sessionId:e,sourceRunId:t.sourceRunId,queuedResume:t.queuedResume});break;default:throw new Error(`Unhandled lifecycle manager effect: ${String(t)}`)}const s=this.getState(e);"release"===t.type&&"idle"!==s.status&&this.releaseRequestedBySession.add(e),"idle"!==s.status||"release"!==t.type&&!this.releaseRequestedBySession.has(e)||(this.states.delete(e),this.runCounterBySession.delete(e),this.releaseRequestedBySession.delete(e))}}function po(e){return"string"==typeof e&&e.trim().length>0}const fo=W("web-fetch-allowlist-precheck-executor",(e=>new L(e,J("webFetchAllowlistPrecheckArgs"),K("webFetchAllowlistPrecheckResult"))),((e,t)=>{t.register(new A(e,X("webFetchAllowlistPrecheckArgs"),Z("webFetchAllowlistPrecheckResult")))})),mo=e=>String(e).replace(/[\r\n]/g,"");function go(e){return{...void 0!==e.parentRequestId?{"x-parent-request-id":mo(e.parentRequestId)}:{},...void 0!==e.rootParentRequestId?{"x-root-parent-request-id":mo(e.rootParentRequestId)}:{},...void 0!==e.parentAgentToolCallId?{"x-parent-agent-tool-call-id":mo(e.parentAgentToolCallId)}:{},...!0===e.directMetaParentChildSubagent?{"x-direct-meta-parent-child-subagent":"true"}:{}}}const wo="x-inference-authentication-jwt";function yo(){const e=globalThis.process?.env,t=e?.INFERENCE_PROXY_JWT?.trim();return void 0===t||""===t||t.startsWith("$")?{}:{[wo]:t}}const vo={textDelta:(e,t)=>new Nr.Uq({messageStartedAtMs:t,message:{case:"textDelta",value:new Nr.PtE({text:e})}}),toolCallStarted:(e,t,r)=>new Nr.Uq({messageStartedAtMs:t.startedAtMs,message:{case:"toolCallStarted",value:new Nr.xuG({callId:e,toolCall:t,modelCallId:r})}}),toolCallCompleted:(e,t,r)=>new Nr.Uq({messageStartedAtMs:t.startedAtMs,message:{case:"toolCallCompleted",value:new Nr.LLS({callId:e,toolCall:t,modelCallId:r})}}),toolCallDelta:(e,t,r,o)=>new Nr.Uq({messageStartedAtMs:o,message:{case:"toolCallDelta",value:new Nr.I0n({callId:e,toolCallDelta:t,modelCallId:r})}}),thinkingDelta:(e,t,r)=>new Nr.Uq({messageStartedAtMs:r,message:{case:"thinkingDelta",value:new Nr.cHB({text:e,thinkingStyle:t})}}),thinkingCompleted:(e,t)=>new Nr.Uq({messageStartedAtMs:t,message:{case:"thinkingCompleted",value:new Nr.tr3({thinkingDurationMs:e})}}),thinkingNote:e=>new Nr.Uq({message:{case:"thinkingNote",value:new Nr.Y$k({text:e})}}),taskChild:(e,t,r)=>"thinkingNote"===t.message.case?t:vo.toolCallDelta(e,new Nr.V1v({delta:{case:"taskToolCallDelta",value:new Nr.aon({interactionUpdate:t})}}),r),userMessageAppended:e=>new Nr.Uq({messageStartedAtMs:e.startedAtMs,message:{case:"userMessageAppended",value:new Nr.v$T({userMessage:e})}}),partialToolCall:(e,t,r)=>new Nr.Uq({messageStartedAtMs:t.startedAtMs,message:{case:"partialToolCall",value:new Nr.fxF({callId:e,toolCall:t,modelCallId:r})}}),tokenDelta:e=>new Nr.Uq({message:{case:"tokenDelta",value:new Nr.Fyz({tokens:e})}}),summary:e=>new Nr.Uq({message:{case:"summary",value:new Nr.ECk({summary:e})}}),summaryStarted:()=>new Nr.Uq({message:{case:"summaryStarted",value:new Nr.lWT}}),heartbeat:()=>new Nr.Uq({message:{case:"heartbeat",value:new Nr.ih1}}),summaryCompleted:(e,t)=>new Nr.Uq({message:{case:"summaryCompleted",value:new Nr.ZM9({hookMessage:e,failed:t})}}),shellOutputDelta:e=>new Nr.Uq({message:{case:"shellOutputDelta",value:new Nr.Nn_({event:e})}}),turnEnded:(e,t)=>new Nr.Uq({message:{case:"turnEnded",value:new Nr.lJj({...e?{inputTokens:BigInt(e.inputTokens),outputTokens:BigInt(e.outputTokens),cacheReadTokens:BigInt(e.cacheReadTokens),cacheWriteTokens:BigInt(e.cacheWriteTokens),reasoningTokens:BigInt(e.reasoningTokens??0)}:{},...void 0!==t?{endedAtMs:t}:{}})}}),stepStarted:e=>new Nr.Uq({message:{case:"stepStarted",value:new Nr.dwJ({stepId:BigInt(e)})}}),toolRequestsListed:e=>new Nr.Uq({message:{case:"toolRequestsListed",value:new Nr.BU$({callCount:Math.max(0,e)})}}),voiceCallUtterance:e=>new Nr.Uq({message:{case:"voiceCallUtterance",value:e}}),stepCompleted:(e,t)=>new Nr.Uq({message:{case:"stepCompleted",value:new Nr.Lrv({stepId:BigInt(e),stepDurationMs:BigInt(t)})}}),activeBranchChange:(e,t)=>new Nr.Uq({message:{case:"activeBranchChange",value:new Nr.PSN({path:e,branchName:t})}}),feedbackRequest:(e,t,r,o=[],n={})=>new Nr.Uq({message:{case:"feedbackRequest",value:new Nr.apn({requestId:e,canonicalModelName:t,categories:[...r],categoryGroups:[...o],title:n.title,negativeTitle:n.negativeTitle,commentPlaceholder:n.commentPlaceholder})}})};class bo{constructor(e=0){this.nextId=e}next(){return this.nextId++}peekNext(){return this.nextId}observe(e){Number.isSafeInteger(e)&&e>=this.nextId&&(this.nextId=e+1)}}var So=r("../agent-kv/dist/index.js");function ko(e){return e instanceof Error?{abortReasonType:"error",abortReasonName:e.name,abortReasonMessage:e.message}:"string"==typeof e?{abortReasonType:"string",abortReasonMessage:e}:void 0===e?{abortReasonType:"undefined"}:{abortReasonType:typeof e}}var Eo=r("../proto/dist/generated/agent/v1/agent_service_pb.js"),Co=r("../utils/dist/fresh-uuid.js"),xo=r("@connectrpc/connect"),_o=r("../../node_modules/.pnpm/@connectrpc+connect@1.6.1_patch_hash=c9c7616ccfc0246b19c6537f56676d8501713cb6c94b440d13_c9bdc997d82622067cc922804d7b4f50/node_modules/@connectrpc/connect/dist/esm/protocol/async-iterable.js"),Po=r("../proto/dist/generated/aiserver/v1/utils_pb.js"),Io=r("zod/v4");const Ro="relayedAttemptFailure",To=Io.object({transport:Io.boolean(),stallAborted:Io.boolean(),errorName:Io.string(),connectCode:Io.number().optional(),connectCodeName:Io.string().optional(),connectCause:Io.object({code:Io.union([Io.string(),Io.number()]).optional(),name:Io.string().optional()}).optional(),transportFailureKind:Io.string().optional(),loop:Io.string().optional(),transportMode:Io.string().optional()});function Ao(e){const t=e?.details?.additionalInfo[Ro];if(void 0!==t)try{const e=To.safeParse(JSON.parse(t));return e.success?e.data:void 0}catch{return}}class Mo extends Error{constructor(e,t={}){super(e),Object.setPrototypeOf(this,new.target.prototype),this.cause=t.cause,this.requestId=t.requestId,this.displayInfo=t.displayInfo,this.isTransport=t.isTransport}get name(){return this.kind}}class Do extends Mo{get kind(){return"RetriableError"}}class Oo extends Mo{constructor(e,t,r={}){super(e,r),this.action=t}get kind(){return"ActionRequiredError"}}class No extends Mo{get kind(){return"NonRetriableError"}}class $o extends No{constructor(e){const t=`This turn's step limit (${e}) needs an in-process agent loop; the network client cannot send it.`;super(t,{displayInfo:{title:"Step limit not supported",detail:t,isRetryable:!1}}),this.maxSteps=e}}class Fo extends Mo{get kind(){return"CancelledError"}}const jo=new Set([Po.yM.NOT_LOGGED_IN,Po.yM.AGENT_REQUIRES_LOGIN,Po.yM.AUTH_TOKEN_NOT_FOUND,Po.yM.AUTH_TOKEN_EXPIRED,Po.yM.INVALID_AUTH_ID,Po.yM.UNAUTHORIZED,Po.yM.GITHUB_NO_USER_CREDENTIALS,Po.yM.GITHUB_USER_NO_ACCESS]),Lo=new Set([Po.yM.FREE_USER_USAGE_LIMIT,Po.yM.FREE_USER_RATE_LIMIT_EXCEEDED,Po.yM.PRO_USER_ONLY,Po.yM.PRO_USER_USAGE_LIMIT,Po.yM.PRO_USER_RATE_LIMIT_EXCEEDED,Po.yM.RATE_LIMITED,Po.yM.RATE_LIMITED_CHANGEABLE,Po.yM.GENERIC_RATE_LIMIT_EXCEEDED]),Uo=new Set([Po.yM.USAGE_PRICING_REQUIRED,Po.yM.USAGE_PRICING_REQUIRED_CHANGEABLE]),Bo=new Set([Po.yM.BAD_API_KEY,Po.yM.BAD_USER_API_KEY,Po.yM.OUTDATED_CLIENT]),Wo=new Set([Po.yM.USER_ABORTED_REQUEST,Po.yM.DEBOUNCED]),Ho=new Set([Po.yM.CUSTOM_MESSAGE]),qo=new Map([[xo.Code.PermissionDenied,"Permission Denied"]]),zo=["NGHTTP2","ECONNRESET","ECONNREFUSED","ETIMEDOUT","EPIPE","socket hang up","Premature close","UND_ERR_SOCKET","ERR_STREAM","protocol error","http/2 stream","ERR_HTTP2_SESSION_ERROR","Session closed with error code","connection aborted","PING timed out"],Go=new Set(["ENOTFOUND","EAI_AGAIN","EAI_FAIL","ENODATA","ESERVFAIL","EHOSTUNREACH","ENETDOWN","ENETUNREACH","ECONNABORTED"]),Vo=new RegExp(`\\b(${[...Go].join("|")})\\b`),Jo=["IMAGE_TOO_LARGE","MAX_TOKENS","CONVERSATION_TOO_LONG","CONTENT_POLICY","DEPRECATED","MAX_MODE_REQUIRED","MODEL_NO_LONGER_SUPPORTED","UNSUPPORTED_REGION","OUTDATED_CLIENT"],Ko="x-cursor-inference-request-error-type",Zo="AgentWebSocketDeliveryAmbiguousError";function Xo(e,t={}){const{requestId:r}=t;if(e instanceof Mo)return e;if(Qo(e))return function(e,t){const r=en(e),o=r.code,n=tn(e),s=void 0===n?void 0:function(e){if(void 0===e.details?.additionalInfo[Ro])return e;const t=e.clone();return void 0!==t.details&&(delete t.details.additionalInfo[Ro],t.details.equals(new Po.ej)&&(t.details=void 0)),t}(n),i={title:s?.details?.title,detail:s?.details?.detail,isRetryable:s?.details?.isRetryable,connectCode:o,errorCode:s?.error,inferenceRequestErrorType:rn(r,Ko)??rn(e,Ko),errorDetails:s},a={cause:e,requestId:t,displayInfo:i,...!0===Ao(n)?.transport?{isTransport:!0}:{}};if(o===xo.Code.Canceled||o===xo.Code.Aborted)return un(e)?new Do(e.message,a):new Fo(e.message,a);if(void 0!==s?.error){const t=s.error;if(Wo.has(t))return new Fo(an(e,s),a);const r=s.details?.analyticsMetadata?.actionRequired;if(void 0!==r&&""!==r)return new Oo(an(e,s),r,a);if(jo.has(t))return new Oo(an(e,s),"login",a);if(Lo.has(t))return new Oo(an(e,s),"upgrade",a);if(Uo.has(t))return new Oo(an(e,s),"payment",a);if(Bo.has(t))return new Oo(an(e,s),"config",a);if(Ho.has(t)&&!0!==s.details?.isRetryable)return new No(an(e,s),a);if(!1===s.details?.isRetryable)return new No(an(e,s),a)}if(o===xo.Code.Unauthenticated)return new Oo(e.message,"login",{...a,displayInfo:Yo(i,"Sign in required",r)});const c=qo.get(o);return void 0===c||!0===s?.details?.isRetryable||un(e)?new Do(e.message,a):new No(an(e,s),{...a,displayInfo:Yo(i,c,r)})}(e,r);const o=(0,So.y_)(e);if(void 0!==o)return new No(o.message,{cause:e instanceof Error?e:void 0,requestId:r,displayInfo:{title:"Conversation data missing",detail:o.message,isRetryable:!1}});const n=function(e){const t=new Set;let r=e;for(;r instanceof Error&&!t.has(r);){if(r.name===cn)return r;t.add(r),r=r.cause}}(e);if(void 0!==n)return new No(n.message,{cause:e instanceof Error?e:void 0,requestId:r,displayInfo:{title:"Context summarization failed",detail:n.message,isRetryable:!1}});if(function(e){const t=new Set;let r=e;for(;r instanceof Error&&!t.has(r);){const{code:e,errcode:o}=r;if("ENOSPC"===e||"ERR_SQLITE_ERROR"===e&&"number"==typeof o&&13==(255&o))return!0;t.add(r),r=r.cause}return!1}(e))return new No(ln,{cause:e instanceof Error?e:void 0,requestId:r,displayInfo:{title:"Out of disk space",detail:ln,isRetryable:!1}});if(e instanceof Error){if("AbortError"===e.name)return new Fo(e.message,{cause:e,requestId:r});if(e.name===Zo)return new Do(e.message,{cause:e,requestId:r,isTransport:!0});if(un(e))return new Do(e.message,{cause:e,requestId:r})}const s=e instanceof Error?e.message:String(e);return new Do(s,{cause:e instanceof Error?e:void 0,requestId:r})}function Qo(e){if(null===e||"object"!=typeof e||!("code"in e)||!("name"in e))return!1;if("ConnectError"===e.name)return!0;const t=e;return"string"==typeof t.rawMessage&&Array.isArray(t.details)&&"function"==typeof t.findDetails}function Yo(e,t,r){return{...e,title:e.title||t,detail:e.detail||sn(r),isRetryable:e.isRetryable??!1}}function en(e){let t=e;for(let e=0;e<10&&t.code===xo.Code.Unknown;e++){const e=t.cause;if(!Qo(e))break;t=e}return t}function tn(e){let t=e;for(let e=0;e<10&&Qo(t);e++){try{const e=t.findDetails?.(Po.vj);if(void 0!==e&&e.length>0)return e[0]}catch{}t=t.cause}}function rn(e,t){const r=e.metadata;if(null!==r&&"object"==typeof r&&"function"==typeof r.get)return r.get(t)??void 0}function on(e){let t=e;for(let e=0;e<10&&"object"==typeof t&&null!==t;e++){if(Qo(t))return t;t="cause"in t?t.cause:void 0}}function nn(e){const t=on(e);return void 0===t?void 0:en(t)}function sn(e){const t=e.rawMessage;return"string"==typeof t?t:e.message.replace(/^\[[a-z_]+\] /,"")}function an(e,t){if(t?.details){const{title:r,detail:o}=t.details;return r&&o?`${r} ${o}`:r||o||e.message}return e.message}const cn="SummaryPlaceholderRejectedError",ln="Out of disk space. Free some space and try again.";function un(e){const t=new Set;let r=e;for(;r instanceof Error&&!t.has(r);){t.add(r);const e=`${r.name}: ${r.message}`;if(zo.some((t=>e.includes(t)))||Vo.test(e))return!0;const o=r.code;if("string"==typeof o&&(zo.some((e=>o.includes(e)))||Go.has(o)))return!0;r=r.cause}return!1}function dn(e){return zo.some((t=>e.includes(t)))||Vo.test(e)}function hn(e){return e instanceof Mo&&e.cause instanceof Error?un(e.cause):e instanceof Error?un(e):"string"==typeof e&&dn(e)}function pn(e){return void 0!==e&&e>0}function fn(e){return e+1}function mn(e){return Object.defineProperty(e,"code",{value:"connection_stalled",enumerable:!0,configurable:!0}),e}function gn(e){const{cause:t,requestId:r,transportErrorRetries:o,connectCode:n}=e;return pn(o)?mn(new Do("Connection stalled repeatedly",{cause:t,requestId:r,displayInfo:{title:"Connection stalled",detail:`The connection stalled ${fn(o)} times. Please check your network connection and try again.`,isRetryable:!0,connectCode:n}})):mn(new Do("Connection stalled",{cause:t,requestId:r,displayInfo:{title:"Connection stalled",detail:"The connection stalled. Please try again.",isRetryable:!0,connectCode:n}}))}function wn(e){let t=e.cause;for(let e=0;e<10&&void 0!==t;e++){if(t instanceof Error&&"AbortError"===t.name)return!0;if(Qo(t)&&(t.code===xo.Code.Canceled||t.code===xo.Code.Aborted))return!0;t=null!==t&&"object"==typeof t&&"cause"in t?t.cause:void 0}return!1}var yn=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},vn=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 bn extends Error{constructor(e){super(e),this.name="LostConnection"}}class Sn{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{yn(t,(0,i.VI)(e.withName("ClientExecController.run")),!1);const r=[];try{for await(const t of this.serverStream){if((0,qt.isMessage)(t,w.Nv)){this.controlledExecManager.handleControlMessage(t);continue}const o=(async()=>{const r={stack:[],error:void 0,hasError:!1};try{let o,n;if(t.spanContext){const r=t.spanContext;o=(0,i.V5)({traceId:r.traceId,spanId:r.spanId,traceFlags:r.traceFlags??1},"exec.handle",e),n=(0,i.fU)(o)}else o=e;yn(r,n?new i.r2(o,n):void 0,!1);const s=this.controlledExecManager.handle(o,t);for await(const e of s)await this.clientStream.write(e)}catch(e){r.error=e,r.hasError=!0}finally{vn(r)}})();r.push(o)}await Promise.all(r)}catch(e){if(e instanceof xo.ConnectError&&"protocol error: missing EndStreamResponse"===e.rawMessage)throw new bn(e.message);if(e instanceof xo.ConnectError&&e.code===xo.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 bn(e.message)}else{if(e instanceof y.W2)throw new bn(e.message);if(e instanceof xo.ConnectError&&e.code===xo.Code.Internal){const t=e.cause;if(t instanceof Error&&t.message.includes("NGHTTP2_PROTOCOL_ERROR"))throw new bn(e.message)}}throw e}}catch(e){t.error=e,t.hasError=!0}finally{vn(t)}}}var kn=r("../proto/dist/generated/agent/v1/ask_question_tool_pb.js"),En=r("../proto/dist/generated/agent/v1/pr_management_tool_pb.js"),Cn=r("../proto/dist/generated/agent/v1/replace_env_tool_pb.js"),xn=r("../proto/dist/generated/agent/v1/setup_vm_environment_tool_pb.js");class _n extends Error{constructor(e,t={}){super(e),this.name="InteractionListenerStreamClosedError",this.cause=t.cause,Object.setPrototypeOf(this,new.target.prototype)}}_n.telemetryName="InteractionListenerStreamClosedError";var Pn=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 In=(0,m.h)("ClientInteractionController"),Rn=new Set(["askQuestionInteractionQuery","switchModeRequestQuery","mcpAuthRequestQuery","connectScmRequestQuery"]);class Tn{constructor(e,t,r,o){this.interactionStream=e,this.interactionListener=t,this.queryResponseStream=r,this.stallSuspender=o,this.pendingHumanQueries=0}async run(e){const t={stack:[],error:void 0,hasError:!1};try{const r=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var 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,i.VI)(e.withName("ClientInteractionController.run")),!1);e=r.ctx;let o,n=Promise.resolve();for await(const t of this.interactionStream){const r=()=>"interactionQuery"===t.case?this.handleInteractionQuery(e,t.value):this.handleInteractionUpdate(e,t.value);n=n.then(r).catch((r=>{In.error(e,"Error handling interaction message",r,{messageCase:t.case}),o??=r}))}if(await n,void 0!==o)throw o}catch(e){t.error=e,t.hasError=!0}finally{Pn(t)}}async handleInteractionUpdate(e,t){await this.interactionListener.sendUpdate(e,t)}handleInteractionQuery(e,t){const r=void 0!==t.query.case&&Rn.has(t.query.case);let o=!1;const n=()=>{r&&!o&&(o=!0,this.pendingHumanQueries--,0===this.pendingHumanQueries&&this.stallSuspender?.setPaused(!1))};r&&(this.pendingHumanQueries++,1===this.pendingHumanQueries&&this.stallSuspender?.setPaused(!0)),(async()=>this.interactionListener.query(e,t))().catch((r=>{const o=function(e,t){switch(e.query.case){case"webSearchRequestQuery":return zr(e.id,t);case"webFetchRequestQuery":return Vr(e.id,t);case"askQuestionInteractionQuery":return Jr(e.id,new kn.tz({result:{case:"rejected",value:new kn.ox({reason:t})}}));case"switchModeRequestQuery":return Zr(e.id,t);case"createPlanRequestQuery":return Xr(e.id,new Fr.bK({result:{case:"error",value:new Fr.iY({error:t})}}));case"setupVmEnvironmentArgs":return Qr(e.id,new xn.r$({result:{case:"success",value:new xn.JH({})}}));case"replaceEnvArgs":return Yr(e.id,new Cn.dV({result:{case:"failure",value:new Cn.uq({errorMessage:t,setupLogs:""})}}));case"prManagementRequestQuery":return eo(e.id,new En.HL({result:{case:"error",value:new En.K$({error:t})}}));case"mcpAuthRequestQuery":return to(e.id,t);case"connectScmRequestQuery":return ro(e.id,t);case"generateImageRequestQuery":return no(e.id,t);case void 0:return;default:return e.query}}(t,"The client could not show this request to the user");if(!(o instanceof Nr.Y5))throw r;return In.error(e,"Error handling interaction query; answering with a fail-closed response",{queryCase:t.query.case,error:r}),o})).then((e=>(n(),this.queryResponseStream.write(e)))).catch((t=>{In.error(e,"Error handling interaction query",t)})).finally(n)}}async function An(e,t){let r;try{r=await e(t.signal)}catch(e){if(t.isCanceled())throw new Fo("User aborted request");throw new No("Failed to mint LLM Gateway credential",{cause:e instanceof Error?e:void 0,requestId:t.requestId})}if(void 0===r)throw new No("LLM Gateway credential minter returned no credential",{requestId:t.requestId});if(""===r.bearerToken.trim())throw new No("LLM Gateway credential minter returned an empty bearer token",{requestId:t.requestId});return new Nr.Ibo({bearerToken:r.bearerToken})}const Mn=15728640,Dn=(0,g.Pu)("agent_client.request_context_blob.prepared",{description:"Prepared RequestContext blob references"}),On=(0,g.v5)("agent_client.request_context_blob.bytes",{description:"Serialized RequestContext bytes staged by the client"}),Nn=(0,g.v5)("agent_client.request_context_blob.preparation_ms",{description:"Time to hydrate, serialize, and hash RequestContext"});class $n{constructor(e,t=62914560){this.parent=e,this.maxTransientBytes=t,this.transientBlobs=new Map,this.persistedBlobIds=new Set,this.transientBytes=0}seed(e,t){return this.seedAll([{blobId:e,blobData:t}])}seedAll(e){const t=new Map;for(const{blobId:r,blobData:o}of e)t.set((0,So.nj)(r),o.byteLength);let r=this.transientBytes;for(const[e,o]of t)r-=this.transientBlobs.get(e)?.byteLength??0,r+=o;if(r>this.maxTransientBytes)return!1;for(const{blobId:t,blobData:r}of e)this.transientBlobs.set((0,So.nj)(t),r);return this.transientBytes=r,!0}has(e){return this.transientBlobs.has((0,So.nj)(e))}hasAll(e){return e.every((e=>this.has(e)))}async getBlob(e,t){const r=(0,So.nj)(t),o=this.transientBlobs.get(r);return void 0===o?await this.parent.getBlob(e,t):o}async persistForRemoteRead(e,t){const r=(0,So.nj)(t),o=this.transientBlobs.get(r);void 0===o||this.persistedBlobIds.has(r)||(await(0,Ht.O$)((()=>this.parent.setBlob(e,t,o)),2),this.persistedBlobIds.add(r))}async setBlob(e,t,r){await this.parent.setBlob(e,t,r)}async setBlobLocallyOnly(e,t,r){await this.parent.setBlobLocallyOnly(e,t,r)}async flush(e){await this.parent.flush(e)}}async function Fn({ctx:e,action:t,resources:r,blobStore:o,mode:n,maxBlobBytes:s,maxInlineDynamicBytes:i=1048576,notesSessionId:a}){const c=performance.now(),l=function(e){switch(e.action.case){case"userMessageAction":case"subscriptionNotificationAction":case"resumeAction":case"executePlanAction":return e.action.value;default:return}}(t);if(void 0===l)return{kind:"not_applicable"};if("legacy"===n)return t.requestContextParts=void 0,{kind:"legacy"};if(void 0!==t.requestContextParts){const e=void 0===(u=t.requestContextParts)?[]:[u.rulesBlobId,u.skillsBlobId,u.subagentsBlobId,u.mcpsBlobId],r=void 0!==l.requestContext,s=e.length>0&&o.hasAll(e);if(r||s){const e=t.requestContextParts;return"ref_only"===n&&r&&s&&void 0!==e?.dynamicContext&&(l.requestContext=void 0),{kind:"already_prepared"}}}var u;t.requestContextParts=void 0;const d=void 0===l.requestContext,h=l.requestContext??await async function({ctx:e,resources:t,notesSessionId:r}){const o=t.get(Ir),n=await o.execute(e,new Rr._K({notesSessionId:r})),s="success"===n.result.case?n.result.value.requestContext:void 0;if(void 0===s)throw new Error(`Failed to compute request context: ${n.result.case}`);return s}({ctx:e,resources:r,notesSessionId:a}),p=Math.min(Math.max(0,s),Mn),f=await async function({requestContext:e,mode:t,maxBlobBytes:r,maxInlineDynamicBytes:o}){const n=function(e){const t=e.clone();return t.rules=[],t.nonFileRules=[],t.cloudRule=void 0,t.agentSkills=[],t.skillOptions=void 0,t.customSubagents=[],t.tools=[],t.mcpInstructions=[],t.mcpFileSystemOptions=void 0,t.mcpMetaToolOptions=void 0,{dynamicContext:t,rules:new Rr.T3({rules:e.rules.map((e=>e.clone())),nonFileRules:e.nonFileRules.map((e=>e.clone())),cloudRule:e.cloudRule}),skills:new Rr.CB({agentSkills:e.agentSkills.map((e=>e.clone())),skillOptions:e.skillOptions?.clone()}),subagents:new Rr.yb({customSubagents:e.customSubagents.map((e=>e.clone()))}),mcps:new Rr.vB({tools:e.tools.map((e=>e.clone())),mcpInstructions:e.mcpInstructions.map((e=>e.clone())),mcpFileSystemOptions:e.mcpFileSystemOptions?.clone(),mcpMetaToolOptions:e.mcpMetaToolOptions?.clone()})}}(e);let s;if("ref_only"===t&&(s=n.dynamicContext.toBinary().byteLength,s>o))return;const i=n.rules.toBinary(),a=n.skills.toBinary(),c=n.subagents.toBinary(),l=n.mcps.toBinary(),u=i.byteLength+a.byteLength+c.byteLength+l.byteLength;if(u>r)return;const[d,h,p,f]=await Promise.all([(0,So.Bk)(i),(0,So.Bk)(a),(0,So.Bk)(c),(0,So.Bk)(l)]),m=[{blobId:d,blobData:i},{blobId:h,blobData:a},{blobId:p,blobData:c},{blobId:f,blobData:l}],g=new Rr.sG({rulesBlobId:d,rulesByteLength:i.byteLength,skillsBlobId:h,skillsByteLength:a.byteLength,subagentsBlobId:p,subagentsByteLength:c.byteLength,mcpsBlobId:f,mcpsByteLength:l.byteLength,dynamicContext:"ref_only"===t?n.dynamicContext:void 0});return"dual"===t?{kind:"dual",inlineContext:e,byteLength:u,parts:g}:{kind:"ref_only",stagedBlobs:m,byteLength:u,parts:g,dynamicByteLength:s}}({requestContext:h,mode:n,maxBlobBytes:p,maxInlineDynamicBytes:Math.min(Math.max(0,i),p)});if(void 0===f)return l.requestContext=h,t.requestContextParts=void 0,Dn.increment(e,1,{mode:n,outcome:"oversized"}),{kind:"oversized"};if("ref_only"===f.kind&&!o.seedAll(f.stagedBlobs))return l.requestContext=h,t.requestContextParts=void 0,Dn.increment(e,1,{mode:n,outcome:"transient_budget_exceeded"}),{kind:"transient_budget_exceeded"};l.requestContext="dual"===f.kind?f.inlineContext:void 0,t.requestContextParts=f.parts;const m=f.byteLength;return Dn.increment(e,1,{mode:n,outcome:d?"hydrated":"inline"}),On.histogram(e,m,{mode:n}),Nn.histogram(e,performance.now()-c,{mode:n}),{kind:"prepared",byteLength:m,hydrated:d,rulesByteLength:f.parts.rulesByteLength,skillsByteLength:f.parts.skillsByteLength,subagentsByteLength:f.parts.subagentsByteLength,mcpsByteLength:f.parts.mcpsByteLength,dynamicByteLength:"ref_only"===f.kind?f.dynamicByteLength:void 0}}function jn(e){return void 0!==e&&Number.isFinite(e)&&Number.isInteger(e)}function Ln(e,t){const{rulesByteLength:r,skillsByteLength:o}=e,{subagentsByteLength:n,mcpsByteLength:s}=e;if(!(jn(r)&&jn(o)&&jn(n)&&jn(s)))return;const i=t?.dynamicByteLength;return{bytes:r+o+n+s+(i??0),bytesSource:"blob_parts",rulesBytes:r,skillsBytes:o,mcpBytes:s,subagentsBytes:n,...jn(i)?{dynamicBytes:i}:{}}}const Un=["alpn_failure","poll_seqno_gap","append_fatal","http_464","http_404_unimplemented","socket_reset","stream_closed_early","idle_deadline","stall","other"],Bn=/\bHTTP (\d{3})\b/;function Wn(e){const t=e.message;return"string"==typeof t?t:""}function Hn(e){return e instanceof Error&&("AbortError"===e.name||e.name===Zo)}const qn={serverCap:3,transportCap:10},zn={alpn_failure:"server",poll_seqno_gap:"server",append_fatal:"by_signature",http_464:"server",http_404_unimplemented:"server",socket_reset:"transport",stream_closed_early:"server",idle_deadline:"server",stall:"transport",other:"server"};function Gn(e){return{action:"retry",countAsServerError:!0,countAsTransportError:!1,transportFailureKind:e}}function Vn(e,t,r){const o=r.attemptRequestId,n=!0===t.endless,s=r.retriesEnabled||n;let i=e instanceof Mo?e:Xo(e,{requestId:o});const a=i instanceof Fo&&("owner"===r.abortOrigin||function(e){const t=e.displayInfo?.errorCode;return void 0!==t&&Wo.has(t)}(i)),c="stall_detector"===r.abortOrigin&&!a&&(i instanceof Fo||i instanceof Do),l="owner"===r.abortOrigin&&i instanceof Do&&wn(i),u=function(e,t,r){return t.stalled?"stall":t.userStop?"other":function(e,t={}){const r=function(e){const t=[],r=new Set;let o=e;for(;"object"==typeof o&&null!==o&&!r.has(o);)r.add(o),t.push(o),o="cause"in o?o.cause:void 0;return t}(e);if(r.some((e=>"cursorBidiAppendFatal"in e)))return"append_fatal";const o=r.map(Wn),n=e=>o.some((t=>t.includes(e))),s=function(e){return nn(e)?.code}(e),i=void 0===t.transportMode;if(i&&s===xo.Code.Unavailable&&n("ALPN protocol failed to negotiate"))return"alpn_failure";if((i||"http1_poll"===t.transportMode)&&s===xo.Code.Unavailable&&n("Unexpected seqno"))return"poll_seqno_gap";const a=o.map((e=>Bn.exec(e)?.[1])).find((e=>void 0!==e));return i&&s===xo.Code.Unknown&&"464"===a?"http_464":i&&s===xo.Code.Unimplemented&&"404"===a?"http_404_unimplemented":s===xo.Code.DeadlineExceeded&&function(e){const t=on(e);return void 0===t?void 0:tn(t)?.error}(e)===Po.yM.TIMEOUT?"idle_deadline":i&&s===xo.Code.Unknown&&n("unsupported content type null")?"stream_closed_early":hn(e)||function(e){return e instanceof Error&&!0===e.isTransport}(e)||r.some(Hn)?"socket_reset":"other"}(e,r)}(e,{stalled:c,userStop:a||l},{transportMode:r.attemptTransportMode}),d=(e,t={})=>({action:"throw",error:e,...t,transportFailureKind:u}),h=(e,o)=>s?!n&&r.transportErrorRetries>=t.transportCap?d(e(),{countAsTransportError:!0}):function(e){return{action:"retry",countAsServerError:!1,countAsTransportError:!0,transportFailureKind:e}}(u):d(o(),{countAsTransportError:!0}),p=()=>({cause:i.cause,requestId:o,transportErrorRetries:r.transportErrorRetries,connectCode:i.displayInfo?.connectCode});if(c){if(s&&void 0!==r.stallRetryElapsedMs&&r.stallRetryElapsedMs>=18e4)return d(gn(p()),{countAsTransportError:!0});const e=h((()=>gn(p())),(()=>gn({...p(),transportErrorRetries:void 0})));return"retry"===e.action?{...e,stall:!0}:e}return i instanceof Fo&&!a&&wn(i)&&(i=new Do(i.message,{cause:i.cause,requestId:o,displayInfo:i.displayInfo,isTransport:!0})),l?d(new Fo(i.message,{cause:i.cause,requestId:o,displayInfo:i.displayInfo})):!0===t.retryAllInference&&(i instanceof Oo||i instanceof No)&&function(e){const t=e.displayInfo?.inferenceRequestErrorType;return void 0!==t&&!Jo.some((e=>e===t))}(i)?!n&&r.serverErrorRetries>=t.serverCap?d(i):Gn(u):i instanceof Fo||i instanceof Oo||i instanceof No?d(i):i instanceof Do&&(!0===i.isTransport||function(e,t){const r=zn[e];return"by_signature"===r?hn(t):"transport"===r}(u,i)||"owner"!==r.abortOrigin&&wn(i))?h((()=>function(e){const{cause:t,requestId:r,transportErrorRetries:o,connectCode:n}=e;return pn(o)?new Do("Connection failed repeatedly",{cause:t,requestId:r,displayInfo:{title:"Connection failed",detail:`The connection failed ${fn(o)} times. Please check your network connection and try again.`,isRetryable:!0,connectCode:n}}):new Do("Connection failed",{cause:t,requestId:r,displayInfo:{title:"Connection failed",detail:"The connection was interrupted. Please check your network connection and try again.",isRetryable:!0,connectCode:n}})}(p())),(()=>i)):s?!n&&r.serverErrorRetries>=t.serverCap?d(function(e){const{classified:t,requestId:r,serverErrorRetries:o}=e,n=t.displayInfo;return new Do(t.message,{cause:t.cause,requestId:r,displayInfo:{...n,title:n?.title||"Server error",detail:n?.detail||`The server failed ${fn(o)} times. Please try again, or contact support if the issue persists.`,isRetryable:!0}})}({classified:i,requestId:o,serverErrorRetries:r.serverErrorRetries})):Gn(u):d(i)}var Jn=r("../proto/dist/generated/agent/v1/mcp_pb.js");const Kn=(0,m.h)("@anysphere/agent-client:stall-detector"),Zn=e=>"number"==typeof e&&Number.isFinite(e)?e:void 0,Xn={nal:"[NAL client stall detector]",local_loop:"[local-loop client stall detector]",module:"[module client stall detector]"},Qn=(0,g.Pu)("agent_client.stream.stall.count",{description:"Number of bidirectional stream stalls detected",labelNames:["activity_type","message_type","loop"]}),Yn=(0,g.v5)("agent_client.stream.stall.duration_ms",{description:"Duration of stream stalls in milliseconds",labelNames:["activity_type","loop"]}),es=(0,g.Pu)("agent_client.stream.did_stall",{description:"Number of streams that experienced at least one stall",labelNames:["loop"]}),ts=(0,g.Pu)("agent_client.stream.total",{description:"Total number of streams monitored",labelNames:["loop"]});class rs{constructor(){this.handlers=new Map}track(e,t){return this.handlers.set(e,{name:e,state:"started",startedAt:Date.now()}),t.then((t=>{const r=this.handlers.get(e);return r&&(r.state="completed",r.endedAt=Date.now()),t})).catch((t=>{const r=this.handlers.get(e);throw r&&(r.state="errored",r.endedAt=Date.now(),r.error=t instanceof Error?t.message:String(t)),t}))}getHandlerStates(){const e=Date.now(),t={};for(const[r,o]of this.handlers)t[r]={state:o.state,durationMs:(o.endedAt??e)-o.startedAt,error:o.error};return t}}class os{constructor(e,t,r){this.lastActivityTime=Date.now(),this.lastMeaningfulActivityTime=Date.now(),this.hasLogged=!1,this.hasLoggedAdvisory=!1,this.hasLoggedHeartbeatOnly=!1,this.hasEverStalled=!1,this.paused=!1,this.disposed=!1,this.activityHistory=[],this.ctx=e,"number"==typeof t?(this.thresholdMs=t,this.advisoryThresholdMs=void 0,this.heartbeatOnlyThresholdMs=3*t,this.onStall=r,this.onStallCallback=void 0,this.handlerTracker=void 0,this.loop="nal"):(this.thresholdMs=t.thresholdMs,this.advisoryThresholdMs=t.advisoryThresholdMs,this.heartbeatOnlyThresholdMs=t.heartbeatOnlyThresholdMs??3*t.thresholdMs,this.onStall=t.onStall,this.onStallCallback=t.onStallCallback,this.handlerTracker=t.handlerTracker,this.loop=t.loop??"nal"),this.logPrefix=Xn[this.loop],this.startTimer(),this.startAdvisoryTimer(),this.startHeartbeatOnlyTimer(),ts.increment(this.ctx,1,{loop:this.loop}),this.onCtxSignalAbort=()=>{this.trackActivity("ctx.signal","abort"),this.abortedAt=Date.now(),this.emitLifecycleLog(`${this.logPrefix} Stream aborted while stall detector active`,"aborted")},e.signal.addEventListener("abort",this.onCtxSignalAbort)}trackActivity(e,t){const r={type:e,messageType:t};this.lastActivity=r,"inbound_message"===e?this.lastInboundMessage=r:"outbound_write"===e&&(this.lastOutboundMessage=r);const o=this.activityHistory.at(-1);o?.type===e&&o.messageType===t?o.repeat=(o.repeat??1)+1:(this.activityHistory.push(r),this.activityHistory.length>10&&this.activityHistory.shift())}reset(e="inbound_message",t,r=!0){if(this.trackActivity(e,t),"inbound_message"===e){const e=this.hasLogged,t=this.hasLoggedAdvisory,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()}setPaused(e){if(!this.disposed&&e!==this.paused&&(this.paused=e,!e)){const e=Date.now();this.lastActivityTime=e,this.lastMeaningfulActivityTime=e,void 0===this.timer&&this.startTimer(),void 0===this.advisoryTimer&&this.startAdvisoryTimer(),void 0===this.heartbeatOnlyTimer&&this.startHeartbeatOnlyTimer()}}startTimer(){if(this.disposed||this.thresholdMs<=0||void 0!==this.timer)return;const e=()=>{if(this.paused)return void(this.timer=setTimeout(e,this.thresholdMs));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(this.disposed||void 0===this.advisoryThresholdMs||this.advisoryThresholdMs<=0||void 0!==this.advisoryTimer)return;const e=this.advisoryThresholdMs,t=()=>{if(this.paused)return void(this.advisoryTimer=setTimeout(t,e));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.disposed||this.thresholdMs<=0||this.heartbeatOnlyThresholdMs<=0||void 0!==this.heartbeatOnlyTimer)return;const e=()=>{if(this.paused)return void(this.heartbeatOnlyTimer=setTimeout(e,this.heartbeatOnlyThresholdMs));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){const t=this.ctx.get(ps),r={...e};t?.modelDetails?.displayName&&(r.model_name=t.modelDetails.displayName),this.abortedAt&&(r.aborted_ago_ms=Date.now()-this.abortedAt),this.disposedAt&&(r.disposed_ago_ms=Date.now()-this.disposedAt),this.lastClientSentHeartbeatAt&&(r.last_client_sent_heartbeat_ago_ms=Date.now()-this.lastClientSentHeartbeatAt),this.lastServerSentHeartbeatAt&&(r.last_server_sent_heartbeat_ago_ms=Date.now()-this.lastServerSentHeartbeatAt),this.streamEndedAt&&(r.stream_ended_ago_ms=Date.now()-this.streamEndedAt),this.lastInboundMessage&&(r.last_inbound_message_type=this.lastInboundMessage.messageType),this.lastOutboundMessage&&(r.last_outbound_message_type=this.lastOutboundMessage.messageType);const o=[];let n;for(let e=this.activityHistory.length-1;e>=0;e--){const{type:t,messageType:r,repeat:s}=this.activityHistory[e];n!==t&&(n?o.push(`[${t}]`):o.push(`[${t}] (MOST RECENT)`),n=t),o.push(`${r}${s?` (x${s})`:""}`)}return r.activities=o.join("\n"),{reqId:t?.requestId,loop:this.loop,stall:r}}onAdvisoryDetected(){if(this.hasLogged||this.hasLoggedAdvisory)return;if(void 0===this.advisoryThresholdMs||this.advisoryThresholdMs<=0)return;const e=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"});Kn.warn(this.ctx,`${this.logPrefix} Advisory stall detected - no activity for advisory threshold period`,r)}catch(e){console.error("Error logging advisory stall:",e)}}onStallDetected(e){if("heartbeat_only"===e){const t=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){const r=this.lastActivity,o=this.lastInboundMessage,n=this.lastOutboundMessage,s=this.ctx.get(ps);try{const i=this.buildLogMetadata({duration_ms:t,threshold_ms:"heartbeat_only"===e?this.heartbeatOnlyThresholdMs:this.thresholdMs,stall_type:e}),a="heartbeat_only"===e?`${this.logPrefix} Stream receiving heartbeats only - no meaningful data for threshold period`:`${this.logPrefix} Bidirectional stream stall detected - no activity for threshold period`;if(Kn.warn(this.ctx,a,i),Qn.increment(this.ctx,1,{activity_type:r?.type??"unknown",message_type:r?.messageType??"unknown",loop:this.loop}),this.hasEverStalled||(this.hasEverStalled=!0,es.increment(this.ctx,1,{loop:this.loop})),this.onStallCallback){const t=Date.now(),i={type:e,lastActivityAgoMs:t-this.lastActivityTime,lastMeaningfulActivityAgoMs:t-this.lastMeaningfulActivityTime,lastActivityType:r?.messageType,lastInboundMessageType:o?.messageType,lastOutboundMessageType:n?.messageType,requestId:s?.requestId,modelName:s?.modelDetails?.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:this.handlerTracker?.getHandlerStates(),loop:this.loop};try{this.onStallCallback(i)}catch(e){console.error("Error in stall callback:",e)}}}catch(e){console.error("Error in stall detection:",e)}try{this.onStall?.()}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});Kn.info(this.ctx,e,o)}catch(e){console.error("Error logging stream lifecycle:",e)}}emitLogAndMetric(){const e=Date.now()-this.lastActivityTime;this.emitLifecycleLog(`${this.logPrefix} Stream activity resumed after stall`,"recovered"),Yn.histogram(this.ctx,e,{activity_type:this.lastActivity?.type??"unknown",loop:this.loop})}[Symbol.dispose](){this.disposed=!0,this.paused=!1,void 0!==this.timer&&(clearTimeout(this.timer),this.timer=void 0),void 0!==this.advisoryTimer&&(clearTimeout(this.advisoryTimer),this.advisoryTimer=void 0),void 0!==this.heartbeatOnlyTimer&&(clearTimeout(this.heartbeatOnlyTimer),this.heartbeatOnlyTimer=void 0),this.ctx.signal.removeEventListener("abort",this.onCtxSignalAbort),this.trackActivity("disposed","disposed"),this.disposedAt=Date.now(),this.emitLifecycleLog(`${this.logPrefix} Stream stall detector disposed`,"disposed")}}const ns=(0,ce.cF)(Symbol("agentTransportTimingRecorder"),void 0),ss=(0,m.h)("@anysphere/agent-client:turn-runner"),is=1e3,as=6e4;function cs(e,t){return e.length===t.length&&e.every(((e,r)=>{const o=t[r];return void 0!==o&&e.byteLength===o.byteLength&&e.every(((e,t)=>e===o[t]))}))}function ls(e){const{connectCode:t,connectCodeName:r,...o}=e;return void 0===r?o:{...o,connectCode:r}}async function us(e){const{ctx:t,checkpointHandler:r,runOptions:o,requestId:n,hooks:s,cancellation:i}=e,a=e.originalRequestId??n;let c=is;const l=async(r,n,s,i,a)=>{if(s||(c=is),void 0!==e.backoff)return void await e.backoff(r,n,i.retryAfterMs);const l=s?function(e,t){const r=Math.min(3e5,3*e);return t??is+(r-is)*Math.random()}(c,o.fixedRetryDelayMs):function(e,t,r){const o=t?100:is,n=r??Math.min(o*2**e,as);return n+(void 0===r?.2*n*Math.random():0)}(r,o.isRunningInTest,o.fixedRetryDelayMs),u=function(e,t){if(void 0===t||t<=e)return e;const r=Math.min(t,as),o=Math.min(r+.2*r*Math.random(),as);return Math.max(e,o)}(l,i.retryAfterMs);u!==l&&e.logging&&ss.info(t,`[${e.logging.tag}] Waiting for Retry-After`,{attempt:r,retryAfterMs:i.retryAfterMs,computedDelayMs:l,selectedDelayMs:u,endlessRetries:s}),s&&(c=l,e.logging&&ss.info(t,`[${e.logging.tag}] Endless retry delay selected`,{selectedDelayMs:u,attempt:r,retryCategory:i.countAsServerError?"server":"transport",endlessRetries:s}));const{retryWake:d}=o;await async function(e,t,r){await new Promise(((o,n)=>{if(t?.aborted)return void n(new Fo("Cancelled during backoff"));const s=new AbortController,i=setTimeout(a,e);function a(){clearTimeout(i),t?.removeEventListener("abort",c),s.abort(),o()}function c(){clearTimeout(i),s.abort(),n(new Fo("Cancelled during backoff"))}t?.addEventListener("abort",c,{once:!0});try{r?.(s.signal)?.then(a,(()=>{}))}catch{}}))}(u,n,void 0===d?void 0:e=>d({error:a,delayMs:u,waitEnded:e}))};let u,d,h,p=e.state,f=e.action,m=0,g=n,w=0,y=0,v=!1,b=0,S=!1;const k=()=>{v&&(o.onConnectionStateChange?.({state:"connected"}),v=!1)},E=()=>{S=!0,k()},C=e=>({handleCheckpoint:async(t,o,n)=>{e===m&&(S=!0),await r.handleCheckpoint(t,o,n),e===m&&(u=o,d=n?.resumeEligibility??"eligible",k())},getLatestCheckpoint:()=>r.getLatestCheckpoint()});for(;;){if(t.canceled)throw i.toCancelledError(void 0,g);if(u=void 0,d=void 0,S=!1,s.beginAttempt?.({attempt:m,originalRequestId:a}),m>0?(g=(0,Co.C)(),await(o.onRetryStarting?.(m,{actionCase:f.action.case,conversationState:p,isResume:"resumeAction"===f.action.case,attemptRequestId:g})),e.logging&&ss.info(t,`[${e.logging.tag}] Retrying attempt ${m}`,{attempt:m,actionCase:f.action.case,requestId:g,originalRequestId:a}),"resumeAction"===f.action.case&&(await(o.onRetryResuming?.({checkpointState:p,nextAttempt:m,reason:"resume_action"})),e.logging&&ss.info(t,`[${e.logging.tag}] Resuming from checkpoint`,{nextAttempt:m,reason:"resume_action"}))):(e.logging&&ss.info(t,`[${e.logging.tag}] Initial request`,{attempt:m,actionCase:f.action.case,requestId:g}),!0===e.notifyInitialResume&&"resumeAction"===f.action.case&&(await(o.onRetryResuming?.({checkpointState:p,nextAttempt:m,reason:"resume_action"})),e.logging&&ss.info(t,`[${e.logging.tag}] Resuming from checkpoint`,{nextAttempt:m,reason:"resume_action"}))),t.canceled)throw i.toCancelledError(void 0,g);try{return await s.runAttempt({state:p,action:f,checkpointHandler:C(m),attempt:m,attemptRequestId:g,notifyConnected:k,notifyApplicationProgress:E}),k(),void(e.logging&&ss.info(t,`[${e.logging.tag}] Request successful`,{attempt:m,actionCase:f.action.case,requestId:g,originalRequestId:a}))}catch(r){if(!0===i.shortCircuit?.(r))throw i.toCancelledError(r,g);const n=!0===o.endlessRetries?.(),k=e.nowMs?.()??Date.now();S&&(h=void 0);const E=void 0===h?void 0:k-h;let C=s.classify(r,{attempt:m,attemptRequestId:g,originalRequestId:a,serverErrorRetries:w,transportErrorRetries:y,stallRetryElapsedMs:E,endlessRetries:n});"retry"===C.action&&(void 0!==u?b=0:"resumeAction"===f.action.case&&S&&(b++,b>=2&&(e.logging&&ss.warn(t,`[${e.logging.tag}] Resume attempts are streaming but not producing checkpoints; stopping automatic resume`,{noProgressResumeFailures:b,attempt:m,requestId:g,originalRequestId:a,errorName:r instanceof Error?r.name:typeof r}),C={action:"throw",error:new Do("Agent turn stopped after repeated resume attempts made no progress",{cause:r instanceof Error?r:void 0,requestId:g,displayInfo:{title:"Agent stopped retrying",detail:"The connection was interrupted repeatedly without saving progress, so the agent stopped to avoid repeating the same work. Retry to continue from the last saved state.",isRetryable:!0}}),transportFailureKind:C.transportFailureKind})));const P={...void 0===C.transportFailureKind?{}:{transportFailureKind:C.transportFailureKind},...void 0===e.loop?{}:{loop:e.loop}},I=e.logging?.diagnostics?.(r);if(e.logging){const e="retry"===C.action?`RETRY (countAsServerError=${C.countAsServerError}, countAsTransportError=${C.countAsTransportError})`:`THROW ${C.error.kind}`;ss.warn(t,`[AGENT_ERROR_DIAGNOSTICS] requestId=${g} originalRequestId=${a} decision=${e}`,{decision:e,willRetry:"retry"===C.action,enableAgentRetries:o.enableAgentRetries??!1,endlessRetries:n,isRunningInTest:o.isRunningInTest??!1,serverErrorRetries:w,transportErrorRetries:y,attempt:m,requestId:g,originalRequestId:a,...P,...I})}if("throw"===C.action){if(0===m){const r={attempt:0,actionCase:f.action.case,error:C.error,requestId:g,originalRequestId:a,enableAgentRetries:!0===o.enableAgentRetries,endlessRetries:n,stallAborted:!1,abortSources:[]};try{await(o.onErrorNotRetried?.(s.buildNonRetriedErrorInfo?.(r)??r))}catch(r){e.logging&&ss.warn(t,`[${e.logging.tag}] onErrorNotRetried callback failed`,{error:String(r),requestId:g,originalRequestId:a})}}throw e.logging&&ss.warn(t,`[${e.logging.tag}] Error not retryable`,{...P,...I,attempt:m,actionCase:f.action.case,requestId:g,originalRequestId:a,errorName:C.error.name,...!0===e.logging.includeErrorObjects?{error:C.error}:{},serverErrorRetries:w,transportErrorRetries:y}),C.error}const R=m+1;if("ineligible_terminal_turn"===d)return void(e.logging&&ss.warn(t,`[${e.logging.tag}] Terminal checkpoint received before retryable error; completing without automatic resume`,{errorName:r instanceof Error?r.name:typeof r,errorMessage:r instanceof Error?r.message:String(r)}));!0!==C.immediate&&(o.onConnectionStateChange?.({state:"reconnecting",attempt:R,trigger:{...P,...s.reconnectTrigger?.(r,C,{originalRequestId:a,failedAttemptRequestId:g,nextAttempt:R})??{originatingRequestId:a,attemptRequestId:g}}}),v=!0),C.countAsServerError&&w++,C.countAsTransportError&&y++,!0===C.stall?h??=k:h=void 0,m=R,void 0!==u&&(_=u,cs((x=p).turns,_.turns)&&cs(x.rootPromptMessagesJson,_.rootPromptMessagesJson)||(c=is),p=u,f=new Nr.QFf({action:{case:"resumeAction",value:new Nr.qKo}})),s.onRetryCommitted?.(),!0!==C.immediate&&await l(m,t.signal,n,C,r)}}var x,_}new Set(["textDelta","thinkingDelta","thinkingCompleted","partialToolCall","toolCallDelta","toolCallStarted","toolCallCompleted","tokenDelta"]);var ds=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},hs=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 ps=(0,ce.cF)(Symbol("agentStreamMetadata"),void 0),fs=(0,m.h)("@anysphere/agent-client:abort"),ms=(0,m.h)("@anysphere/agent-client:retry"),gs=(0,m.h)("@anysphere/agent-client:request-context-blob");async function ws({ctx:e,action:t,resources:r,blobStore:o,options:n,source:s,transportMode:i,notifyBytes:a}){try{const s=await Fn({ctx:e,action:t,resources:r,blobStore:o,mode:i??n.requestContextBlobTransportMode??"legacy",maxBlobBytes:n.requestContextBlobMaxBytes??Mn,maxInlineDynamicBytes:n.requestContextDynamicInlineMaxBytes??1048576,notesSessionId:n.conversationId});if(!0===a){const e=function({prepared:e,parts:t}){return"prepared"===e.kind?Ln(e,{dynamicByteLength:e.dynamicByteLength}):"already_prepared"===e.kind&&void 0!==t?Ln(t):void 0}({prepared:s,parts:t.requestContextParts});void 0!==e&&n.onRequestContextBytes?.(e)}}catch(r){t.requestContextParts=void 0,gs.warn(e,"Failed to prepare request context blob; using legacy fallback",{actionCase:t.action.case,errorName:r instanceof Error?r.name:typeof r,source:s})}}const ys=e=>{const t=[];switch(t.push(e.message.case),e.message.case){case"conversationAction":t.push(e.message.value.action.case);break;case"execClientMessage":case"execClientControlMessage":case"kvClientMessage":case"execServerMessage":case"execServerControlMessage":t.push(e.message.value.message.case);break;case"interactionResponse":t.push(e.message.value.result.case);break;case"interactionUpdate":switch(t.push(e.message.value.message.case),e.message.value.message.case){case"partialToolCall":case"toolCallCompleted":case"toolCallStarted":t.push(e.message.value.message.value.toolCall?.tool.case);break;case"toolCallDelta":t.push(e.message.value.message.value.toolCallDelta?.delta.case)}break;case"interactionQuery":t.push(e.message.value.query.case)}return t.filter((e=>void 0!==e)).join(":")};async function vs(e,t,r){for await(const o of t)switch(o.event.case){case"stdout":await r.sendUpdate(e,vo.shellOutputDelta({case:"stdout",value:new yr.o0({data:o.event.value.data})}));break;case"stderr":await r.sendUpdate(e,vo.shellOutputDelta({case:"stderr",value:new yr.Db({data:o.event.value.data})}));break;case"exit":await r.sendUpdate(e,vo.shellOutputDelta({case:"exit",value:new yr.vb({code:o.event.value.code,aborted:o.event.value.aborted})}))}}function bs(e){return e instanceof Error?e.name:void 0}class Ss{constructor(e,t,r={}){this.client=e,this.endpointUrl=t,this.options=r,this.hasStartedStream=!1}async run(e,t,r,o,n,s,a,c,l,u,d){const h={stack:[],error:void 0,hasError:!1};try{if(void 0!==d.maxSteps)throw new $o(d.maxSteps);const g=new $n(a),w=d.generationUUID??(0,Co.C)(),y=new bo,v=(m=y,p=n,f=e=>{m.observe(e.id)},{sendUpdate:(e,t)=>p.sendUpdate(e,t),query:(e,t)=>(f(t),p.query(e,t)),enqueuePostTurnEndedWork:p.enqueuePostTurnEndedWork?.bind(p),flushPostTurnEndedWork:p.flushPostTurnEndedWork?.bind(p)}),b={sources:[],abortReasonName:void 0,abortReasonMessage:void 0},S=e=>{const t=function(e){const t=on(e);return void 0===t?void 0:Ao(tn(t))}(e),r=b.sources.includes("stall_detector")||!0===t?.stallAborted,o=(n=b.sources).some((e=>"stall_detector"!==e))?"owner":n.includes("stall_detector")?"stall_detector":"none";var n;const s=function(e){const t={errorName:bs(e)},r=nn(e);if(void 0===r)return t;const o=function(e){if(null!==e&&"object"==typeof e&&"cause"in e)return e.cause}(r),n=function(e){if(null===e||"object"!=typeof e||!("code"in e))return;const t=e.code;return"string"==typeof t||"number"==typeof t?t:void 0}(o),s=bs(o);return{...t,underlyingConnectError:{code:r.code,codeName:xo.Code[r.code],cause:void 0!==n||void 0!==s?{code:n,name:s}:void 0}}}(e),i=s.underlyingConnectError;return{relayed:t,stallAborted:r,abortOrigin:"none"===o&&r?"stall_detector":o,reading:void 0===t?{errorName:s.errorName,connectCode:i?.code,connectCodeName:i?.codeName,connectCause:i?.cause,abortSources:[...b.sources],abortReasonName:b.abortReasonName,...void 0===i?{}:{underlyingConnectError:i}}:{errorName:t.errorName,connectCode:t.connectCode,connectCodeName:t.connectCodeName,connectCause:t.connectCause,...(a=t.loop,"nal"===a||"local_loop"===a||"module"===a?{loop:t.loop}:{}),...void 0===t.transportMode?{}:{transportMode:t.transportMode}}};var a};let k=0,E=0;try{d.onNetworkPhaseStart?.()}catch(t){ms.warn(e,"onNetworkPhaseStart callback failed",{error:String(t)})}const C=ds(h,(0,i.VI)(e.withName("networkPhase")),!1);e=C.ctx,await(0,i.MG)(C.span,(()=>us({ctx:e,state:t,action:r,checkpointHandler:l,runOptions:d,requestId:w,loop:this.options.loop??"nal",notifyInitialResume:!0,logging:{...this.options.retryLogging??{tag:"nal_agent_retries",includeErrorObjects:!0},diagnostics:e=>{const{stallAborted:t,abortOrigin:r,reading:o}=S(e);return{stallAborted:t,abortOrigin:r,...ls(o)}}},cancellation:{toCancelledError:()=>new Fo("Request cancelled")},hooks:{beginAttempt:()=>{b.sources=[],b.abortReasonName=void 0,b.abortReasonMessage=void 0,E=++k},runAttempt:async({state:t,action:r,checkpointHandler:n,attempt:i,attemptRequestId:a,notifyConnected:l,notifyApplicationProgress:h})=>{const p=function(e,t,r){return{sendUpdate:async(o,n)=>{if(t===r())return e.sendUpdate(o,n);"toolCallCompleted"===n.message?.case&&ms.warn(o,"nal.await_stall.stale_completion_dropped",{attemptGen:t,currentGen:r()})},query:async(o,n)=>{if(t!==r())throw new Fo("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}}(v,E,(()=>k));await this.runInternal(e,t,r,o,p,s,g,c,n,u,d,a,w,y,b,l,h,i)},classify:(e,t)=>{const{abortOrigin:r,relayed:o}=S(e),n=Vn(e,function(e,t,r=qn){return{serverCap:r.serverCap,transportCap:!0===e.isRunningInTest?Math.min(r.transportCap,2):r.transportCap,endless:t.endlessRetries,retryAllInference:!0===e.retryAllInferenceErrors}}(d,t),{...t,retriesEnabled:d.enableAgentRetries??!1,abortOrigin:r}),s=o?.transportFailureKind;return"string"==typeof(i=s)&&Un.includes(i)?{...n,transportFailureKind:s}:n;var i},buildNonRetriedErrorInfo:e=>({...e,enableAgentRetries:d.enableAgentRetries??!1,stallAborted:S(e.error).stallAborted,abortSources:[...b.sources],abortReasonName:b.abortReasonName,abortReasonMessage:b.abortReasonMessage}),reconnectTrigger:(e,t,r)=>{const{relayed:o,stallAborted:n,reading:s}=S(e),i=e instanceof Mo?e:Xo(e,{requestId:r.failedAttemptRequestId});return{errorClass:o?.errorName??i.name,connectCode:s.connectCode,connectCodeName:s.connectCodeName,errorCode:i.displayInfo?.errorCode,countAsServerError:t.countAsServerError,countAsTransportError:t.countAsTransportError,stallAborted:n,originatingRequestId:r.originalRequestId,attemptRequestId:r.failedAttemptRequestId,...void 0===s.transportMode?{}:{transportMode:s.transportMode},endpointUrl:this.endpointUrl}},onRetryCommitted:()=>c.reopen()}})))}catch(e){h.error=e,h.hasError=!0}finally{hs(h)}var p,f,m}async runInternal(e,t,r,o,n,s,a,l,u,d,h,p,f,m,g,v,b,S,k="agent.request.attempt"){const E={stack:[],error:void 0,hasError:!1};try{const _=e;e=this.options.prepareAttemptContext?.(e,{attempt:S,attemptRequestId:p,originalRequestId:f,runOptions:h})??e;const P=ds(E,(0,i.VI)(e.withName(k)),!1);P.span.setAttribute("agent.attempt",S),P.span.setAttribute("agent.request_id",p),P.span.setAttribute("agent.original_request_id",f),e=P.ctx,e=(0,i.Mf)(e,"agent.request_id",p),e=(e=(0,i.Mf)(e,"agent.original_request_id",f)).with(ps,{requestId:p,rootParentRequestId:h.rootParentRequestId,modelDetails:o});const I=new Set(g.sources);let R=void 0!==g.abortReasonName||void 0!==g.abortReasonMessage;const T=(t,r)=>{if(I.has(t))return;I.add(t),g.sources=[...I];const o=(e=>{const t="string"==typeof e?.abortReasonName?e.abortReasonName:void 0,r="string"==typeof e?.abortReasonMessage?e.abortReasonMessage:void 0;if(void 0!==t||void 0!==r)return{abortReasonName:t,abortReasonMessage:r}})(r);R||void 0===o||(R=!0,g.abortReasonName=o.abortReasonName,g.abortReasonMessage=o.abortReasonMessage),fs.error(e,"Agent client stream abort",new Error(t),{abortSource:t,requestId:p,conversationId:h.conversationId,...r??{}})};if(e.signal.aborted){const t=e.signal.reason;T("ctx_signal_abort",ko(t))}else e.signal.addEventListener("abort",(()=>{const t=e.signal.reason;T("ctx_signal_abort",ko(t))}),{once:!0});const[A,M]=e.withCancel();if(l.signal?.aborted){const e=l.signal?.reason;T("conversation_action_abort",ko(e)),M()}else l.signal?.addEventListener("abort",(()=>{const e=l.signal?.reason;T("conversation_action_abort",ko(e)),M()}),{once:!0});if(e.canceled||A.canceled){const t={ctxCanceled:e.canceled,softCancel:A.canceled};throw T("pre_run_cancel",t),new Fo("User aborted request")}const O=(0,i.VI)(e.withName("createControlledExecManager")),N=D.fromResources(s);O[Symbol.dispose]();const[$,F]=e.withCancel(),j=new rs,{failThresholdMs:L,advisoryThresholdMs:U}=function(e,t){const r=Zn(e?.failTimeoutMs)??3e4,o=r>0&&!0!==t?.isRunningInTest?Math.max(r,2e4):r,n=Zn(e?.advisoryTimeoutMs);return{failThresholdMs:o,advisoryThresholdMs:void 0!==n&&n>0&&(o<=0||n<o)?n:void 0}}(h.stallDetectorConfig,{isRunningInTest:h.isRunningInTest}),B=ds(E,new os($,{thresholdMs:L,advisoryThresholdMs:U,loop:this.options.loop,onStall:()=>{T("stall_detector",{thresholdMs:L,advisoryThresholdMs:U}),F()},onStallCallback:h.onStall,handlerTracker:j}),!1);let W,H;const q=(0,_o.Jt)(),z=new y.F8(q,(e=>(B.reset("outbound_write",ys(e)),e))),G=ds(E,(0,i.VI)(e.withName("writeInitialRequest")),!1);let V;const J=function(e){return new Jn.Or({mcpTools:e.map((e=>({name:e.name,providerIdentifier:e.providerIdentifier,toolName:e.toolName,description:e.description,inputSchema:e.inputSchema?qt.Value.fromJson(e.inputSchema):void 0,outputSchemaJson:void 0!==e.outputSchema?JSON.stringify(e.outputSchema):void 0})))})}(d),K=h.requestContextBlobTransportMode??"legacy",Z=0===S&&"userMessageAction"===r.action.case&&0===t.turns.length,X="ref_only"===K&&Z?"dual":K,[,Q]=await Promise.all([ws({ctx:e,action:r,resources:s,blobStore:a,options:h,source:"run_request",transportMode:X,notifyBytes:0===S}),void 0===h.mintLlmGatewayCredential?Promise.resolve(void 0):An(h.mintLlmGatewayCredential,{signal:A.signal,isCanceled:()=>A.canceled,requestId:p})]),Y={action:r,headers:h.headers??{}},ee=this.options.decorateAttempt?.(Y,h)??Y,te=new Nr.Mpn({conversationState:t,action:ee.action,modelDetails:o,requestedModel:h.requestedModel,clientLlmGatewayCredential:Q,mcpTools:J,conversationGroupId:h.conversationGroupId,conversationId:h.conversationId,agentSessionId:h.agentSessionId,mcpFileSystemOptions:h.mcpFileSystemOptions,customSystemPrompt:h.customSystemPrompt,systemPromptSpec:h.systemPromptSpec,harness:h.harness,computerUseCoordinateMode:h.computerUseCoordinateMode,subagentTypeName:h.subagentTypeName,excludeWorkspaceContext:h.excludeWorkspaceContext,devRawModelSlug:h.devRawModelSlug,selectedSubagentModels:h.selectedSubagentModels,subagentModelOverrides:h.subagentModelOverrides??[],selectedSubagentModelDetails:h.selectedSubagentModelsLegacy,clientSupportsInlineImages:h.clientSupportsInlineImages,clientSupportsPreviewCard:h.clientSupportsPreviewCard,startedAsNewProject:h.startedAsNewProject,firstProjectOnboarding:h.firstProjectOnboarding,clientSupportsSendToUser:h.clientSupportsSendToUser,clientSupportsRoutedModelUpdate:h.clientSupportsRoutedModelUpdate,canCreateCloudSubagents:h.canCreateCloudSubagents,suppressSubagentProgressUpdateTool:h.suppressSubagentProgressUpdateTool,transcriptParentConversationId:h.transcriptParentConversationId,runId:f,nextInteractionQueryId:m.peekNext(),voiceCallNotes:h.voiceCallNotes});if(V=z.write(new Eo.KS({message:{case:"runRequest",value:te}})),A.canceled){const t={ctxCanceled:e.canceled,softCancel:A.canceled};throw T("post_write_cancel",t),G[Symbol.dispose](),new Fo("User aborted request")}const re={...ee.headers,"x-request-id":p,"x-original-request-id":f,...go(h),...yo()};W=(0,i.VI)(e.withName("handshakeEstablishment")),W.span.setAttribute("handshake.firstStreamOnClient",!this.hasStartedStream),this.hasStartedStream=!0;const oe=function(e){return e?.get(ns)}(e)?.startTransportRun(),ne=void 0===oe?W.ctx:function(e,t){return e.with(ns,t)}(W.ctx,oe),se=void 0===oe?q:(C=q,x=()=>oe.markFirstRequestSent(),{[Symbol.asyncIterator](){const e=C[Symbol.asyncIterator]();let t=!1;const r={next:()=>(t||(t=!0,x()),e.next())};return void 0!==e.return&&(r.return=t=>e.return(t)),void 0!==e.throw&&(r.throw=t=>e.throw(t)),r}}),ie=this.client.run(ne,se,{signal:$.signal,headers:re,onHeader:h.onHeader,onNetworkStarted:()=>{void 0===H&&(H=performance.now())}}),ae=performance.now(),ce=e=>{W&&(W.span.setAttribute("handshake.firstMessageHeartbeat",e),void 0!==H&&W.span.setAttribute("handshake.preNetworkMs",H-ae),W[Symbol.dispose](),W=void 0),v();const t=performance.now();h.onFirstMessage?.(t-ae),void 0!==H&&h.onFirstMessageNetwork?.(t-H)},le=()=>{b(),h.onFirstNonHeartbeatResponse?.(performance.now()-ae,S)},ue=h.onTtftBreakdown?e=>{h.onTtftBreakdown(e,S)}:void 0,{interactionStream:de,execStream:he,checkpointStream:pe,kvStream:fe,done:me}=function(e,t,r,o,n,s,i,a){const c=(0,_o.Jt)(),l=(0,_o.Jt)(),u=(0,_o.Jt)(),d=(0,_o.Jt)();let h=!1,p=!1;return{interactionStream:c,execStream:l,checkpointStream:u,kvStream:d,done:async function(){let f,m,g=!1,w=!1;try{for await(const n of t){if(void 0!==n.ttftBreakdown){const t=n.ttftBreakdown;try{a?.({serverFirstTokenMs:t.serverFirstTokenMs,preStreamSetupMs:t.preStreamSetupMs,waitForFirstEventMs:t.waitForFirstEventMs,providerTtftMs:t.providerTtftMs,slowPoolWaitMs:t.slowPoolWaitMs,...void 0===t.clientPrepMs?{}:{clientPrepMs:t.clientPrepMs},clock:t.clientClock?"client":"server"})}catch(t){ms.warn(e,"onTtftBreakdown callback failed",{error:String(t)})}}const t="interactionUpdate"===n.message.case&&"heartbeat"===n.message.value.message.case;if(h||(h=!0,o(t)),t)r.onServerSentHeartbeat(),r.reset("inbound_message","heartbeat");else{if(!p){p=!0;try{i?.()}catch(t){ms.warn(e,"onFirstNonHeartbeatMessage callback failed",{error:String(t)})}}r.reset("inbound_message",ys(n))}if("interactionUpdate"===n.message.case&&"turnEnded"===n.message.value.message.case&&(g=!0),"interactionUpdate"!==n.message.case&&"interactionQuery"!==n.message.case||await c.write(n.message).catch((()=>{})),"execServerMessage"!==n.message.case&&"execServerControlMessage"!==n.message.case||await l.write(n.message.value),"conversationCheckpointUpdate"===n.message.case){const e=g?"ineligible_terminal_turn":"eligible";"ineligible_terminal_turn"===e&&(w=!0),await u.write({checkpoint:n.message.value,metadata:{resumeEligibility:e}})}"kvServerMessage"===n.message.case&&await d.write(n.message.value)}r.onStreamEnded()}catch(e){f=e}finally{if(m=f,g&&w&&void 0!==f&&!n?.aborted&&!s?.aborted&&function(e){const t=e instanceof Mo?e:Xo(e);return t instanceof Do&&function(e){return!0===e.isTransport||(e.cause instanceof Error?un(e.cause):dn(e.message))}(t)}(f)&&(ms.debug(e,"Ignoring transport close after terminal agent stream",{caughtError:f instanceof Error?`${f.name}: ${f.message}`:String(f)}),r.onStreamEnded(),m=void 0),g||n?.aborted||s?.aborted){if(!g&&!n?.aborted){const t=`Stream ended without turnEnded, abort signals: signal.aborted=${n?.aborted}, parentSignal.aborted=${s?.aborted}; firstMessageFired=${h}`;ms.warn(e,t)}}else{const t="Stream ended without turnEnded — connection likely dropped mid-stream";void 0===f?(ms.warn(e,t),m=new Do(t,{isTransport:!0})):f instanceof Error&&"[aborted] aborted"===f.message?(ms.warn(e,`${t}; retrying caught [aborted] aborted error`),m=new Do(t,{cause:f,isTransport:!0})):ms.warn(e,`${t}; caught non-retriable stream error, rethrowing as-is`,{caughtError:f instanceof Error?`${f.name}: ${f.message}`:String(f)})}c.close(),l.close(),u.close(),d.close()}if(void 0!==m)throw m}()}}(e,ie,B,ce,A.signal,e.signal,le,ue);let ge;const we={handleCheckpoint:async(e,t,r)=>{await u.handleCheckpoint(e,t,r),ge=r?.resumeEligibility??"eligible"},getLatestCheckpoint:()=>u.getLatestCheckpoint()};G[Symbol.dispose]();const ye=5e3;let ve;const be=()=>{ve=setTimeout((()=>{z.write(new Eo.KS({message:{case:"clientHeartbeat",value:new Eo.kA}})).then((()=>B.onClientSentHeartbeat()),(()=>{})),be()}),ye)},Se=()=>{void 0!==ve&&(clearTimeout(ve),ve=void 0)};be();try{let t;if("shellCommandAction"===r.action.case&&r.action.value.execId){const o=r.action.value,i=new yr.a({command:o.shellCommand?.command||"",parsingResult:new yr.HO,skipApproval:!0}),a=s.get(Sr).execute(e,i,{execId:o.execId}),c=new Tn(de,n,new y.F8(z,(e=>new Eo.KS({message:{case:"interactionResponse",value:e}}))),B);t={run:async e=>{await Promise.all([j.track("handleShellStream",vs(e,a,n)),j.track("interactionController",c.run(e))])}}}else{const e=new Tn(de,n,new y.F8(z,(e=>new Eo.KS({message:{case:"interactionResponse",value:e}}))),B);t={run:async t=>{await j.track("interactionController",e.run(t))}}}void 0!==V&&await Promise.race([V,me.catch((()=>{}))]);const i=new y.F8(z,(e=>{if((0,qt.isMessage)(e,w.yT))return new Eo.KS({message:{case:"execClientMessage",value:e}});if((0,qt.isMessage)(e,w.$Y))return new Eo.KS({message:{case:"execClientControlMessage",value:e}});throw new Error(`Unknown exec message (type: ${(0,qt.isMessage)(e)?e.getType().typeName:typeof e})`)})),u=new Sn(he,i,N),S=new So.hC(fe,new y.F8(z,(e=>new Eo.KS({message:{case:"kvClientMessage",value:e}}))),a,{beforeGetBlob:async(e,t)=>a.persistForRemoteRead(e,t)}),k=new c(pe,we,e);let E,C;const x={promise:new Promise(((e,t)=>{E=e,C=t})),resolve:E,reject:C};A.canceled?(x.resolve(),de.close()):A.signal.addEventListener("abort",(()=>{x.resolve(),de.close()}),{once:!0}),u.run(A).then(x.resolve).catch(x.reject);const P=Promise.allSettled([j.track("streamSplitter",me.finally((()=>{Se(),l.close(),i.close()}))),j.track("execHandler",x.promise),t.run(e),j.track("checkpointController",k.run()),j.track("kvHandler",S.run(e)),j.track("conversationActionManager",l.run(e,{write:async t=>{await ws({ctx:e,action:t,resources:s,blobStore:a,options:h,source:"queued_action"}),await z.write(new Eo.KS({message:{case:"conversationAction",value:t}}))}}))]);let I,R;const T={promise:new Promise(((e,t)=>{I=e,R=t})),resolve:I,reject:R};P.then(T.resolve).catch(T.reject),e.canceled?T.reject(new Fo("User aborted request")):e.signal.addEventListener("abort",(()=>T.reject(new Fo("User aborted request"))),{once:!0});const M=()=>{e.signal.aborted?F():function(e){const t=e.lingerMs??6e3;return new Promise((r=>{let o=!1;const n=e=>{o||(o=!0,clearTimeout(s),r(e))},s=setTimeout((()=>n("linger_timed_out")),t);e.done.then((()=>n("stream_ended")),(()=>n("stream_ended")))}))}({done:me,lingerMs:h.softCancelLingerMs}).then((t=>{ms.info(e,"Soft-cancel transport linger finished",{outcome:t,requestId:p}),F()}))};A.canceled?(M(),T.reject(new Fo("User aborted request"))):A.signal.addEventListener("abort",(()=>{M(),T.reject(new Fo("User aborted request"))}),{once:!0});const D=await T.promise,O=D[0],$=D[1],L=D[3],U=e=>e.reason instanceof Error?`${e.reason.name}: ${e.reason.message}`:String(e.reason);if("rejected"===L.status)throw new No("Checkpoint persistence failed",{cause:L.reason instanceof Error?L.reason:void 0,requestId:p,displayInfo:{title:"Checkpoint persistence failed",detail:U(L),isRetryable:!1}});const W="ineligible_terminal_turn"===ge;if(W){const t={..."rejected"===O.status?{streamSplitter:U(O)}:{},..."rejected"===$.status?{execHandler:U($)}:{}};Object.keys(t).length>0&&ms.debug(e,"Ignoring handler errors after terminal checkpoint",t)}if("rejected"===O.status&&!W)throw O.reason;if("rejected"===$.status&&!W)throw $.reason;A.canceled||await this.processUnprocessedMessages(_,l,we,o,n,s,a,d,h,p,f,m,g,B,v,b)}finally{Se(),W&&(W[Symbol.dispose](),W=void 0)}}catch(e){E.error=e,E.hasError=!0}finally{hs(E)}var C,x}async processUnprocessedMessages(e,t,r,o,n,s,i,a,c,l,u,d,h,p,f,m){if(!t.hasUnprocessedMessages())return;const g=t.getUnprocessedUserMessages(),w=r.getLatestCheckpoint();if(!w||0===g.length)return;const y=g[0];t.markMessageAsProcessed(y),t.resetStream(),p[Symbol.dispose]();const v=r.getLatestCheckpoint();try{await this.runInternal(e,w,new Nr.QFf({action:{case:"userMessageAction",value:new Nr.Vtf({userMessage:y})}}),o,n,s,i,t,r,a,c,l,u,d,h,f,m,0,"agent.request.queuedMessage")}catch(e){throw v===r.getLatestCheckpoint()&&t.requeueMessage(y),e}}}new RegExp([String.raw`"type"\s*:\s*"response\.(?:output_text|reasoning_summary_text|reasoning_text|function_call_arguments|refusal)\.(?:delta|done)"`,String.raw`"(?:content|reasoning_content|reasoning|refusal)"\s*:\s*"(?!")`,String.raw`"tool_calls"\s*:\s*\[\s*\{`,String.raw`"type"\s*:\s*"content_block_delta"`].join("|"));var ks=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/status.js"),Es=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/span_kind.js");const Cs=(0,xo.createContextKey)(void 0,{description:"anysphere.callerContext"});function xs(e){return null!==e&&"object"==typeof e&&Symbol.asyncIterator in e}function _s(e){return e instanceof Error?e:new Error(String(e))}function Ps(e,t,r){return{[Symbol.asyncIterator](){const o=e[Symbol.asyncIterator]();let n=!1;const s=e=>{n||(n=!0,e?(t?.recordException(_s(e)),t?.setStatus({code:ks.s.ERROR,message:e instanceof Error?e.message:"Stream failed"})):t?.setStatus({code:ks.s.OK}),t?.end(),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 Is(...e){const t=new Headers;for(const r of e)r&&(r instanceof Headers?r:new Headers(r)).forEach(((e,r)=>{t.set(r,e)}));return t}function Rs(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:(a,c,l={})=>{const u=(0,i.fR)(a.withName(`rpc.${String(n)}`),{kind:Es.v.CLIENT,attributes:{"rpc.method":String(n),"rpc.system":"connect"}}),d=(0,i.fU)(u);let h;try{let n;if(r&&(n=function(e){const t=new Headers;try{const r=(0,i.fU)(e),o=r?.spanContext?.();if(o?.traceId&&o.spanId){const e=o.traceFlags??0,r=`00-${o.traceId}-${o.spanId}-${e.toString(16).padStart(2,"0")}`;t.set("traceparent",r),t.set("backend-traceparent",r),o.traceState&&t.set("tracestate",o.traceState.serialize())}}catch{}return t}(u)),o){const e=o(u);e&&(n=Is(n,e))}const a=Is(l.headers,n),{signal:f,cleanup:m}=!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,l.signal):{signal:l.signal,cleanup:void 0};h=m;const g=(l.contextValues??(0,xo.createContextValues)()).set(Cs,u),w={...l,headers:a,signal:f,contextValues:g},y=s.call(e,c,w);return xs(y)?Ps(y,d,h):null!==(p=y)&&"object"==typeof p&&"then"in p&&"function"==typeof p.then?Promise.resolve(y).then((e=>xs(e)?Ps(e,d,h):(d?.setStatus({code:ks.s.OK}),d?.end(),h?.(),e))).catch((e=>{throw d?.recordException(_s(e)),d?.setStatus({code:ks.s.ERROR,message:e instanceof Error?e.message:"RPC call failed"}),d?.end(),h?.(),e})):(d?.setStatus({code:ks.s.OK}),d?.end(),h?.(),y)}catch(e){throw d?.recordException(_s(e)),d?.setStatus({code:ks.s.ERROR,message:e instanceof Error?e.message:"RPC call failed"}),d?.end(),h?.(),e}var p}}})}var Ts=r("node:crypto?8af2"),As=r("../utils/dist/workspace-paths.js");function Ms(){return(0,s.join)(function(){const e=process.env.CURSOR_DATA_DIR;return e?.trim()?e:(0,s.join)((0,n.homedir)(),".cursor")}(),"projects")}function Ds(e){return(0,s.join)(Ms(),(0,As.r_)(e))}var Os=r("node:fs/promises"),Ns=r("../../node_modules/.pnpm/lru-cache@11.2.5/node_modules/lru-cache/dist/esm/index.js"),$s=r("node:fs"),Fs=r("../shell-exec/dist/api/index.js"),js=r("./src/agent/native/tree-sitter.webpack.cjs"),Ls=r("./src/agent/native/tree-sitter-bash.webpack.cjs");const Us=function(e,t=console.warn){let r;return()=>{if(void 0!==r)return r;try{const t=e();t.setLanguage(Ls),r=t}catch(e){if(!function(e){return"object"==typeof e&&null!==e&&"CURSOR_TREE_SITTER_STUBBED"===e.code}(e))throw e;r=null,t("shell-parser: tree-sitter natives are unavailable in this artifact; shell command analysis degrades to parsingFailed")}return r}}((()=>new js)),Bs=new Set(["file_redirect","heredoc_redirect","herestring_redirect","heredoc","here_string","redirect","redirection"]),Ws=new Set(["<",">",">>",">|","<>","<&",">&","&>","&>>"]);function Hs(e,t){if(null===e)return{legacy:{simpleCommands:[],hasInputRedirect:!1,hasOutputRedirect:!1},structured:{parsingFailed:!0,executableCommands:[],hasRedirects:!1,hasCommandSubstitution:!1,redirects:[]}};const r=e.parse(t),o=new WeakSet;let n=!1,s=!0;const i={simpleCommands:[],hasInputRedirect:!1,hasOutputRedirect:!1},a={parsingFailed:!1,executableCommands:[],hasRedirects:!1,hasCommandSubstitution:!1,redirects:[]},c=e=>{n=!0,a.hasRedirects=!0,s=s&&e},l=e=>{if(e&&/^\d+$/.test(e.text))return Number.parseInt(e.text,10)},u=()=>({fdTargets:new Map([[0,"original-stdin"],[1,"original-stdout"],[2,"original-stderr"]])}),d=(e,t)=>{const r=(e=>{const t=e.children,r=t.findIndex((e=>Ws.has(e.type)));if(-1!==r)return{operator:t[r]?.type??"",target:t.slice(r+1).find((e=>"comment"!==e.type))}})(e);if(!r)return!1;const{operator:o,target:n}=r,s=((e,t)=>{if("&>"===t||"&>>"===t)return[1,2];const r=(e=>l(e.children.find((e=>"file_descriptor"===e.type))))(e);return void 0!==r?[r]:t.startsWith("<")?[0]:[1]})(e,o),i=(e=>{if(e){if("word"===e.type)return 0===e.namedChildren.length?e.text:void 0;if("number"===e.type)return e.text;if("raw_string"===e.type){if(e.text.length<2)return;return e.text.slice(1,-1)}if("string"===e.type){const t=e.namedChildren;if(0===t.length||t.some((e=>"string_content"!==e.type)))return;return t.map((e=>e.text)).join("")}}})(n),c={operator:o,destinationFds:s,targetNodeType:n?.type??""};if(void 0!==i&&(c.targetText=i),a.redirects.push(c),">&"===o){const e=l(n),r=void 0===e?void 0:t.fdTargets.get(e);if(!(e=>"original-stdout"===e||"original-stderr"===e||"dev-null"===e)(r)){for(const e of s)t.fdTargets.set(e,"unsafe");return!1}for(const e of s)t.fdTargets.set(e,r);return!0}if("<&"===o){const e=l(n),r=void 0===e?void 0:t.fdTargets.get(e);if("dev-null"!==r){for(const e of s)t.fdTargets.set(e,"unsafe");return!1}for(const e of s)t.fdTargets.set(e,r);return!0}if(!(e=>{if(!e)return!1;if("word"===e.type)return"/dev/null"===e.text;if("raw_string"===e.type)return"'/dev/null'"===e.text;if("string"===e.type){const t=e.namedChildren;return 1===t.length&&"string_content"===t[0]?.type&&"/dev/null"===t[0].text}return!1})(n)){for(const e of s)t.fdTargets.set(e,"unsafe");return!1}for(const e of s)t.fdTargets.set(e,"dev-null");return!0},h=(e,t)=>{if(!o.has(e)){if(o.add(e),(e=>{var t;t=e.text,/(^|\s)[0-9]*<<?<?/.test(t)&&(i.hasInputRedirect=!0),(/(^|\s)[0-9]*>>/.test(t)||/(^|\s)[0-9]*>(\||&)?/.test(t)||/(^|\s)&>/.test(t)||/(^|\s)[0-9]+>&[0-9]+/.test(t))&&(i.hasOutputRedirect=!0),"heredoc_redirect"!==e.type&&"herestring_redirect"!==e.type||(i.hasInputRedirect=!0)})(e),"heredoc_redirect"===e.type){const{redirect:t,isAllowlistSafe:r}=(e=>{const t=(e=>{const t=e.parent;if("redirected_statement"!==t?.type)return;const r=t.children.find((e=>"command"===e.type)),o=r?.childForFieldName("name");return o?.text})(e),r=void 0!==t&&!(e=>{let t=e.parent;for(;t;){if("command_substitution"===t.type&&"string"!==t.parent?.type)return!0;t=t.parent}return!1})(e),o={operator:r?"<<":"",destinationFds:r?[0]:[],targetNodeType:e.type};return r&&(o.targetText=t),{redirect:o,isAllowlistSafe:r}})(e);return a.redirects.push(t),void c(r)}if("file_redirect"!==e.type)return a.redirects.push({operator:"",destinationFds:[],targetNodeType:e.type}),void c(!1);c(d(e,t))}};return function e(t){const r=t.type;if((e=>{const t=u();for(const r of e.children)Bs.has(r.type)&&h(r,t)})(t),Bs.has(r)&&!o.has(t)&&h(t,u()),"command"===r){const e=t.childForFieldName("name");if(null===e)a.parsingFailed=!0;else{i.simpleCommands.push(e.text);let r=e.text;const o=[];for(const e of t.childrenForFieldName("argument"))o.push({type:e.type,value:e.text}),r+=` ${e.text}`;a.executableCommands.push({name:e.text,args:o,fullText:r})}}if("command_name"===r||"simple_command"===r)if("command_name"!==r||i.simpleCommands.includes(t.text)){if("simple_command"===r){const e=t.firstNamedChild;e&&"command_name"===e.type?i.simpleCommands.includes(e.text)||i.simpleCommands.push(e.text):i.simpleCommands.push(t.text)}}else i.simpleCommands.push(t.text);"command_substitution"!==r&&"process_substitution"!==r||(a.hasCommandSubstitution=!0);for(const r of t.children)e(r)}(r.rootNode),n&&(a.allRedirectsAreDevNull=s),{legacy:i,structured:a}}function qs(e){return Hs(Us(),e)}var zs=r("../../node_modules/.pnpm/re2js@1.2.2/node_modules/re2js/build/index.esm.js"),Gs=r("../utils/dist/path-utils.js");const Vs="path is empty or only whitespace",Js=async e=>{const t=(0,Gs.o1)(e);try{return await(0,Os.realpath)(t)}catch{return t}},Ks=1048576,Zs=52428800;var Xs=r("../utils/dist/test-resets.js");const Qs="CURSOR_FORCED_SHELL_EGRESS_NETWORK_DEFAULT",Ys="CURSOR_FORCED_SHELL_EGRESS_DEPENDENCY_DENY_DOMAINS",ei=/\$\(|`|<\(|>\(/,ti=/[;&|]/;let ri,oi,ni,si;function ii(){if(void 0===ri){const e=(process.env.CURSOR_FORCED_SHELL_EGRESS??"").trim().toLowerCase();ri=""!==e&&"0"!==e&&"false"!==e&&"off"!==e}return ri}function ai(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 ci(e){return(process.env[e]??"").split(",").map((e=>e.trim())).filter((e=>e.length>0))}function li(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 ui(){if(void 0===si){const e=(process.env[Qs]??"").trim().toLowerCase();let t="deny";"allow"===e||"deny"===e?t=e:""!==e&&console.error(`[forced-egress] ignoring invalid value in ${Qs} (expected "allow" or "deny"); using "deny".`);const r=ci("CURSOR_FORCED_SHELL_EGRESS_DENY_DOMAINS"),o=(process.env[Ys]??"").trim();let n=r;"none"===o.toLowerCase()?n=[]:""!==o&&(n=ci(Ys)),si={networkDefault:t,denyDomains:r,dependencyDenyDomains:n,allowDomains:ci("CURSOR_FORCED_SHELL_EGRESS_ALLOW_DOMAINS"),writablePaths:li("CURSOR_FORCED_SHELL_EGRESS_WRITABLE_PATHS")}}return si}function di(e,t,r={}){const o=[ai(e),ai(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 hi(e,t){const r=function(){const e=ui();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===oi&&(oi=di("CURSOR_FORCED_SHELL_EGRESS_DEPENDENCY_REGEX","CURSOR_FORCED_SHELL_EGRESS_EXTRA_DEPENDENCY_REGEX",{anchorToExecutable:!0})),oi);if(null===o)return r;const n=t?.executableCommands??[];if(t?.parsingFailed||0===n.length)return r;if(ei.test(e))return r;const s=(void 0===ni&&(ni=di("CURSOR_FORCED_SHELL_EGRESS_SOURCE_REGEX","CURSOR_FORCED_SHELL_EGRESS_EXTRA_SOURCE_REGEX")),ni);for(const e of n){const t=e.fullText?.trim()||e.name?.trim()||"";if(!t||s?.test(t)||ti.test(t))return r}return n.every((e=>o.test(e.fullText?.trim()||e.name?.trim()||"")))?function(){const e=ui();return{type:"workspace_readwrite",...e.writablePaths.length>0?{additionalReadwritePaths:e.writablePaths}:{},networkPolicy:{version:1,default:"allow",...e.dependencyDenyDomains.length>0?{deny:e.dependencyDenyDomains}:{}},skipStatsigDefaults:!0,enableSharedBuildCache:!0}}():r}(0,Xs.J)((function(){ri=void 0,oi=void 0,ni=void 0,si=void 0}));var pi=r("../proto/dist/generated/agent/v1/sandbox_pb.js");function fi(e){if(!e)return;let t;return"allow"===e.default?t=pi.h1.ALLOW:"deny"===e.default&&(t=pi.h1.DENY),new pi.RB({version:e.version,defaultAction:t,deny:e.deny??[],allow:e.allow??[],logging:e.logging?(r=e.logging,new pi.Qq({decisionLogPath:r.decisionLogPath,logFormat:r.logFormat})):void 0});var r}function mi(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 pi.h1.ALLOW:t.default="allow";break;case pi.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,Fs.T6)():(0,Fs.Po)())}function gi(e){switch(e){case"system":return pi.Sz.SYSTEM;case"workspace":return pi.Sz.WORKSPACE;default:return pi.Sz.UNSPECIFIED}}function wi(e){const t=function(e){switch(e){case pi.Sz.SYSTEM:return"system";case pi.Sz.WORKSPACE:return"workspace";case pi.Sz.UNSPECIFIED:default:return}}(e.readBoundary),r=e.additionalReadPaths??[];return{readBoundary:t,additionalReadPaths:"workspace"===t&&r.length>0?r:void 0}}function yi(e){if(!e)return{type:"insecure_none"};switch(e.type){case pi.vc.INSECURE_NONE:case pi.vc.UNSPECIFIED:return{type:"insecure_none",allowlistEscalated:e.allowlistEscalated,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies};case pi.vc.WORKSPACE_READWRITE:return{type:"workspace_readwrite",networkPolicy:mi(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,...wi(e)};case pi.vc.WORKSPACE_READONLY:return{type:"workspace_readonly",networkPolicy:mi(e),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadonlyPaths:e.additionalReadonlyPaths,disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicyStrict:e.networkPolicyStrict,...wi(e)};default:return{type:"insecure_none"}}}function vi(e){if(e)return"insecure_none"===e.type?new pi.Mw({type:pi.vc.INSECURE_NONE,allowlistEscalated:e.allowlistEscalated,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies}):"workspace_readwrite"===e.type?new pi.Mw({type:pi.vc.WORKSPACE_READWRITE,networkAccess:(0,Fs.$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:fi(e.networkPolicy),networkPolicyStrict:e.networkPolicyStrict,readBoundary:gi(e.readBoundary),additionalReadPaths:"workspace"===e.readBoundary?e.additionalReadPaths??[]:[]}):"workspace_readonly"===e.type?new pi.Mw({type:pi.vc.WORKSPACE_READONLY,networkAccess:(0,Fs.$b)(e.networkPolicy),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadonlyPaths:e.additionalReadonlyPaths??[],disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicy:fi(e.networkPolicy),networkPolicyStrict:e.networkPolicyStrict,readBoundary:gi(e.readBoundary),additionalReadPaths:"workspace"===e.readBoundary?e.additionalReadPaths??[]:[]}):new pi.Mw({type:pi.vc.INSECURE_NONE})}function bi(e){return" "===e||"\t"===e||"\n"===e||"\r"===e||" "===e||""===e||""===e||""===e||"\ufeff"===e}function Si(e){let t="",r=!1;for(const o of e)bi(o)?r=!0:(r&&t.length>0&&(t+=" "),r=!1,t+=o);return t}function ki(e){return e.length>0&&[...e].every((e=>"*"===e))}function Ei(e){const t=e.indexOf(":");if(t<=0)return;const r=e.slice(0,t).trim();return[...r].some((e=>0===e.trim().length))?void 0:{executablePattern:r,argsPattern:e.slice(t+1).trim()}}function Ci(e){const t=e.trim();return{trimmedPattern:t,regexSource:`^${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\\\*/g,".*")}$`}}function xi(e,t){const{trimmedPattern:r,regexSource:o}=Ci(e);try{return new RegExp(o).test(t)}catch{return r===t}}function _i({command:e,parsingResult:t}){return[...new Set([e,...t.executableCommands.map((e=>e.fullText))])]}const Pi={a:"",b:"\b",e:"",E:"",f:"\f",n:"\n",r:"\r",t:"\t",v:"\v","\\":"\\","'":"'",'"':'"',"?":"?"};function Ii(e){let t="",r="plain",o=0;for(;o<e.length;){const n=e[o];if("plain"===r){"$"===n&&"'"===e[o+1]?(r="ansi",o+=2):"$"===n&&'"'===e[o+1]?(r="double",o+=2):"'"===n?(r="single",o++):'"'===n?(r="double",o++):"\\"===n&&o+1<e.length?("\n"!==e[o+1]&&(t+=e[o+1]),o+=2):(t+=n,o++);continue}if("single"===r){"'"===n?r="plain":t+=n,o++;continue}if("double"===r){if('"'===n){r="plain",o++;continue}if("\\"===n&&o+1<e.length){const r=e[o+1];if("$"===r||"`"===r||'"'===r||"\\"===r||"\n"===r){"\n"!==r&&(t+=r),o+=2;continue}}t+=n,o++;continue}if("'"===n){r="plain",o++;continue}if("\\"!==n||o+1>=e.length){t+=n,o++;continue}const s=e[o+1],i=Pi[s];if(void 0!==i){t+=i,o+=2;continue}const a="x"===s?e.slice(o+2).match(/^[0-9a-fA-F]{1,2}/)?.[0]:"u"===s?e.slice(o+2).match(/^[0-9a-fA-F]{1,4}/)?.[0]:"U"===s?e.slice(o+2).match(/^[0-9a-fA-F]{1,8}/)?.[0]:e.slice(o+1).match(/^[0-7]{1,3}/)?.[0],c="u"===s||"U"===s,l="x"===s||c?16:8;if(void 0!==a){const e=Number.parseInt(a,l);if(!c||e<=1114111){t+=c?String.fromCodePoint(e):String.fromCharCode(e),o+=a.length+(16===l?2:1);continue}}t+=s,o+=2}return Si(t)}function Ri({rule:e,command:t}){const r=Si(e).trim();return 0!==r.length&&(null!==function(e){const t=Si(e).trim();if(0===t.length)return"Rule cannot be empty";if(t.length>512)return"Rule cannot exceed 512 characters";if(ki(t))return"Rule cannot match every command; be more specific than wildcards alone";if(t.startsWith(":"))return"Colon rules need an executable before `:` (e.g. `aws:*s3 rm*`)";const r=Ei(t);if(void 0!==r){const{executablePattern:e,argsPattern:t}=r;if(ki(e)&&(0===t.length||ki(t)))return"Rule cannot match every command; narrow the executable or argument pattern"}return null}(r)||[t.trim(),Si(t).trim(),Ii(t).trim()].some((e=>function(e,t){const r=Ei(e);if(void 0!==r){const{executablePattern:e,argsPattern:o}=r,n=t.indexOf(" "),s=-1===n?t:t.slice(0,n),i=-1===n?"":t.slice(n+1).trim();if(xi(e,s)&&xi(o,i))return!0}return e.includes("*")?xi(e,t):t===e||t.startsWith(`${e} `)}(r,e))))}function Ti({matchForms:e,blockedCommands:t}){const r=t.map((e=>e.trim())).filter((e=>e.length>0));if(0===r.length)return;const o=e.map((e=>e.trim())).filter((e=>e.length>0)),n=o.length>0?o:[""];for(const e of r)if(n.some((t=>Ri({rule:e,command:t}))))return e}function Ai(e){return`Denied: this command was blocked by administrator policy (denylist rule: ${e}) and was not executed. It cannot be approved from this conversation; only a user can run it manually outside the agent. You may continue working on the task.`}function Mi({command:e,parsingResult:t,blockedCommands:r}){if(0===r.length)return;if(t.parsingFailed||0===t.executableCommands.length)return"Denied: this command could not be conclusively analyzed against your team's administrator command denylist, so it was blocked (fail-closed) and was not executed. It cannot be approved from this conversation; only a user can run it manually outside the agent. You may continue working on the task.";const o=Ti({matchForms:_i({command:e,parsingResult:t}),blockedCommands:r});return void 0===o?void 0:Ai(o)}var Di=r("../utils/dist/lru-cache.js");const Oi=["Desktop","Documents","Downloads","Music","Movies","Pictures","Library",".Trash"],Ni="/Volumes";function $i(e){const t=e.replace(/\/{2,}/g,"/");return t.length>1&&t.endsWith("/")?t.slice(0,-1):t}function Fi(e,t){if("darwin"!==t.platform)return[];const r=$i(e),o=r.toLowerCase(),n=$i(t.homeDirectory),s="/"===r?1:r.split("/").length;return[...Oi.map((e=>`${n}/${e}`)),Ni].filter((e=>{return(t=e.toLowerCase())!==(r=o)&&t.startsWith(r.endsWith("/")?r:`${r}/`);var t,r})).map((e=>{const t=e.split("/").slice(s).join("/");return`${"/"===r?"":r}/${t}`}))}var ji=r("node:util"),Li=r("../../node_modules/.pnpm/iconv-lite@0.7.0/node_modules/iconv-lite/lib/index.js"),Ui=r("../../node_modules/.pnpm/jschardet@3.1.4/node_modules/jschardet/index.js");function Bi(e){let t=1,r=0;for(;;){const o=e.indexOf("\n",r);if(-1===o)return t;t++,r=o+1}}const Wi="utf8",Hi="utf8bom",qi="latin1",zi={"windows-1250":"cp1250","windows-1251":"cp1251","windows-1252":"cp1252","windows-1253":"cp1253","windows-1254":"cp1254","windows-1255":"cp1255","windows-1256":"cp1256","windows-1257":"cp1257","windows-1258":"cp1258","iso-8859-1":"iso88591","iso-8859-2":"iso88592","iso-8859-5":"iso88595","iso-8859-6":"iso88596","iso-8859-7":"iso88597","iso-8859-8":"iso88598","iso-8859-9":"iso88599","iso-8859-15":"iso885915","iso-8859-16":"iso885916",shift_jis:"shiftjis","euc-jp":"eucjp","euc-kr":"euckr","iso-2022-jp":"iso2022jp","iso-2022-kr":"iso2022kr",gb2312:"gb2312",gbk:"gbk",gb18030:"gb18030",big5:"big5","big5-hkscs":"big5hkscs","koi8-r":"koi8r","koi8-u":"koi8u",ibm855:"cp855",ibm866:"cp866",maccyrillic:"maccyrillic","utf-16le":"utf16le","utf-16be":"utf16be","utf-32le":"utf32le","utf-32be":"utf32be",johab:"johab",cp949:"cp949",cp932:"cp932"};function Gi(e){return zi[e]||e}function Vi(e){return e.startsWith("\ufeff")?e.slice(1):e}function Ji(e){const t=e.toLowerCase();return"latin-1"===t?qi:"utf-8"===t?Wi:"utf-8-bom"===t||"utf-8 bom"===t?Hi:t}function Ki(e){const t=[],r=[];let o=0;for(let n=e.indexOf("\n");-1!==n;n=e.indexOf("\n",o)){const s=13===e.charCodeAt(n-1);t.push(e.slice(o,s?n-1:n)),r.push(s?"\r\n":"\n"),o=n+1}return t.push(e.slice(o)),r.push(""),{lines:t,ends:r}}var Zi;!function(e){e.CRLF="CRLF",e.LF="LF"}(Zi||(Zi={}));const Xi=[".mp4",".webm",".mov",".avi",".mkv",".wmv",".flv",".m4v"],Qi=new Set(Xi),Yi=new ji.TextDecoder("utf-8",{fatal:!0}),ea=new ji.TextDecoder("latin1"),ta=Buffer.from([239,187,191]),ra={utf16le:Buffer.from([255,254]),utf16be:Buffer.from([254,255]),utf32le:Buffer.from([255,254,0,0]),utf32be:Buffer.from([0,0,254,255])},oa=8192,na=new Map,sa=new Set([".png",".jpg",".jpeg",".gif",".webp",".ico",".bmp",".svg",".pdf",".zip",".tar",".gz",".exe",".dll",".so",".dylib",".bin",...Xi]),ia=/\.(png|jpg|jpeg|gif|webp|ico|bmp|svg)$/i;function aa(e){const t=e.toLowerCase(),r=t.lastIndexOf(".");return-1===r?"":t.substring(r)}function ca(e){const t=aa(e);return Qi.has(t)}function la(e){const t=aa(e);return{encoding:"binary",lineEnding:Zi.LF,isBinaryFile:!0,isImageFile:ia.test(t),isVideoFile:Qi.has(t)}}async function ua(e,t){const r=await(0,Os.readFile)(e),o=pa(r);if(o.isBinaryFile)throw new Error("Binary file cannot be decoded as text");const n=na.get(e);let s;s=t||n||o.encoding;const{text:i,encoding:a}=ka(r,s),c=Vi(i);var l;return ba(e,a===Wi&&(l=r).length>=ta.length&&l[0]===ta[0]&&l[1]===ta[1]&&l[2]===ta[2]?Hi:a),o.lineEnding===Zi.CRLF?c.replaceAll("\r\n","\n"):c}async function da(e,t,r,o){let n;try{n=r?await async function(e,t){try{return await ha(e)}catch{}const r=aa(e);if(sa.has(r))return la(e);try{return await async function(e){const t=new Map;let r=0;for await(const o of ya(e)){if(r>=100)break;try{const e=await ha(o);if(!e.isBinaryFile){const r=`${e.encoding}:${e.lineEnding}`,o=t.get(r);if(o){if(o.count++,o.count>=3)return o.format}else t.set(r,{format:e,count:1})}r++}catch(e){}}let o;for(const e of t.values())(!o||e.count>o.count)&&(o=e);return o?o.format:va()}(t)}catch{return va()}}(e,r):await ha(e)}catch{const t=aa(e);n=sa.has(t)?la(e):va()}const s=na.get(e);let i;if(!n.isBinaryFile){let t;t=Ji(o||s||n.encoding);const r=t===Hi||t===Wi&&!o&&await Ea(e,ta),a=ra[Gi(t)];r?i=ta:a&&await Ea(e,a)&&(i=a),n={...n,encoding:r?Hi:t},ba(e,n.encoding)}const a=Bi(t),c=t.includes("\r\n")?void 0:await async function(e,t){if(t.isBinaryFile)return;let r;try{const t=await(0,Os.stat)(e);if(!t.isFile()||t.size>jt)return;r=await(0,Os.readFile)(e)}catch{return}if(!r.includes(13))return;const o=Vi(ka(r,t.encoding).text);return function(e){let t=!1,r=!1;for(let o=e.indexOf("\n");-1!==o;o=e.indexOf("\n",o+1))if(13===e.charCodeAt(o-1)?t=!0:r=!0,t&&r)return!0;return!1}(o)?o:void 0}(e,n);if(void 0!==c?t=function({content:e,existing:t,defaultEnding:r}){const o=Ki(t),n=Ki(e),s=function({before:e,after:t}){const r=new Int32Array(t.length).fill(-1);let o=0;for(;o<e.length&&o<t.length&&e[o]===t[o];)r[o]=o,o++;let n=0;for(;n<e.length-o&&n<t.length-o&&e[e.length-1-n]===t[t.length-1-n];)r[t.length-1-n]=e.length-1-n,n++;const s=e.length-o-n,i=t.length-o-n;if(s>0&&i>0&&(s+1)*(i+1)<=4e6){const n=i+1,a=new Uint16Array((s+1)*n);for(let r=s-1;r>=0;r--)for(let s=i-1;s>=0;s--)a[r*n+s]=e[o+r]===t[o+s]?a[(r+1)*n+s+1]+1:Math.max(a[(r+1)*n+s],a[r*n+s+1]);for(let c=0,l=0;c<s&&l<i;)e[o+c]===t[o+l]?(r[o+l]=o+c,c++,l++):a[(c+1)*n+l]>=a[c*n+l+1]?c++:l++}let a=-1,c=-1;for(let o=0;o<=t.length;o++){const n=o===t.length?e.length:r[o];if(-1!==n){if(n-a==o-c)for(let e=1;e<o-c;e++)r[c+e]=a+e;a=n,c=o}}return r}({before:o.lines,after:n.lines});let i=r,a="";for(let e=0;e<n.lines.length;e++){const t=s[e];let r=n.ends[e];"\n"===r&&(r=-1!==t&&""!==o.ends[t]?o.ends[t]:i),""!==r&&(i=r),a+=n.lines[e]+r}return a}({content:t,existing:c,defaultEnding:n.lineEnding===Zi.CRLF?"\r\n":"\n"}):n.lineEnding===Zi.CRLF&&(t=t.replace(/(?<!\r)\n/g,"\r\n")),"binary"===n.encoding){const e=function(e){const t=e.trim().replace(/\s/g,"");if(t.length>50&&/^[A-Za-z0-9+/]*={0,2}$/.test(t))try{const e=Buffer.from(t,"base64");if(e.length>0){const r=Math.floor(.5*t.length);if(e.length>=r)return e}}catch{}return Buffer.from(e,"latin1")}(t);return{lines:a,buffer:e,format:n}}const l=Li.encode(i?Vi(t):t,n.encoding===Hi?Wi:n.encoding,{defaultEncoding:Wi});return{lines:a,buffer:i?Buffer.concat([i,l]):l,format:n}}async function ha(e){const t=pa((r=await wa(e)).length===oa?function(e){for(let t=e.length-1;t>=Math.max(0,e.length-3);t--){const r=e[t];if(r<128)return e;if(r>=192){const o=r>=240?4:r>=224?3:2;return e.length-t<o?e.subarray(0,t):e}}return e}(r):r);var r;return t.isBinaryFile?{...t,isVideoFile:ca(e)}:{...t,isVideoFile:!1}}function pa(e){if(0===e.length)return va();const t=function(e){if(e.length<4)return null;if(255===e[0]&&254===e[1]&&(0!==e[2]||0!==e[3]))return"UTF-16LE";if(254===e[0]&&255===e[1])return"UTF-16BE";let t=0,r=0;const o=Math.min(50,Math.floor(e.length/2));for(let n=0;n<2*o&&!(n+1>=e.length);n+=2){if(0===e[n+1]){const r=e[n];(r>=32&&r<=126||9===r||10===r||13===r)&&t++}if(0===e[n]){const t=e[n+1];(t>=32&&t<=126||9===t||10===t||13===t)&&r++}}return t>.8*o?"UTF-16LE":r>.8*o?"UTF-16BE":null}(e)??function(e){if(e.length<8)return null;if(0===e[0]&&0===e[1]&&254===e[2]&&255===e[3])return"UTF-32BE";if(255===e[0]&&254===e[1]&&0===e[2]&&0===e[3])return"UTF-32LE";let t=0,r=0;const o=Math.min(50,Math.floor(e.length/4));for(let n=0;n<4*o&&!(n+3>=e.length);n+=4){if(0===e[n]&&0===e[n+1]&&0===e[n+2]){const r=e[n+3];(r>=32&&r<=126||9===r||10===r||13===r)&&t++}if(0===e[n+1]&&0===e[n+2]&&0===e[n+3]){const t=e[n];(t>=32&&t<=126||9===t||10===t||13===t)&&r++}}return t>.8*o?"UTF-32BE":r>.8*o?"UTF-32LE":null}(e);if(t)return{encoding:t,lineEnding:ma(Li.decode(e.subarray(0,oa),Gi(Ji(t)))),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1};if(!function(e){const t=Math.min(oa,e.length);if(0===t)return!0;for(let r=0;r<t;r++)if(0===e[r])return!1;let r=0;for(let o=0;o<t;o++){const t=e[o];t<32&&9!==t&&10!==t&&13!==t&&r++}return r/t*100<5}(e))return{encoding:"binary",lineEnding:Zi.LF,isBinaryFile:!0,isImageFile:(r=e,!(r.length<4)&&(r.length>=8&&137===r[0]&&80===r[1]&&78===r[2]&&71===r[3]&&13===r[4]&&10===r[5]&&26===r[6]&&10===r[7]||255===r[0]&&216===r[1]&&255===r[2]||r.length>=12&&82===r[0]&&73===r[1]&&70===r[2]&&70===r[3]&&87===r[8]&&69===r[9]&&66===r[10]&&80===r[11]||r.length>=6&&71===r[0]&&73===r[1]&&70===r[2]&&56===r[3]&&(55===r[4]||57===r[4])&&97===r[5])),isVideoFile:!1};var r;if((0,o.isUtf8)(e)&&(!e.includes(27)||!(0,o.isAscii)(e)))return{encoding:"UTF-8",lineEnding:fa(e),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1};const n=Ui.detect(e);let s=n.confidence>.7?n.encoding:"utf-8";return"ascii"===s&&(s="utf-8"),{encoding:s??"utf-8",lineEnding:fa(e),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1}}function fa(e){let t=0,r=0;for(let o=0;o<e.length;o++)10===e[o]&&(o>0&&13===e[o-1]?t++:r++);return ga(t,r)}function ma(e){const t=e.match(/\n/g)?.length??0,r=e.match(/\r\n/g)?.length??0;return ga(r,t-r)}function ga(e,t){return 0===e&&0===t?Zi.LF:e/(e+t)*100>=5?Zi.CRLF:Zi.LF}async function wa(e){const t=await(0,Os.open)(e,"r");try{const e=Buffer.allocUnsafe(oa),{bytesRead:r}=await t.read(e,0,oa,0);return e.subarray(0,r)}finally{await t.close()}}async function*ya(e){const t=new Set(["node_modules",".git",".svn",".hg","dist","build","out",".next",".cache","coverage","__pycache__",".venv","venv",".turbo"]);try{const r=await(0,Os.readdir)(e,{withFileTypes:!0});for(const o of r){if(o.name.startsWith(".")&&".gitignore"!==o.name)continue;const r=(0,s.join)(e,o.name);o.isDirectory()?t.has(o.name)||(yield*ya(r)):o.isFile()&&(yield r)}}catch(e){return}}function va(){return{encoding:Wi,lineEnding:"win32"===process.platform?Zi.CRLF:Zi.LF,isBinaryFile:!1,isImageFile:!1,isVideoFile:!1}}function ba(e,t){if(na.has(e)&&na.delete(e),na.set(e,t),na.size<=100)return;const r=na.keys().next().value;void 0!==r&&na.delete(r)}function Sa(e){try{return{text:Yi.decode(e),encoding:Wi}}catch{return{text:ea.decode(e),encoding:qi}}}function ka(e,t){const r=Ji(t);if(r===Wi||r===Hi||"ascii"===r){const t=Sa(e);return r===Hi&&t.encoding===Wi?{text:t.text,encoding:Hi}:t}if(r===qi)return{text:ea.decode(e),encoding:qi};try{const t=Gi(r);if(Li.encodingExists(t))return{text:Li.decode(e,t),encoding:r}}catch{}return Sa(e)}async function Ea(e,t){try{return(await wa(e)).subarray(0,t.length).equals(t)}catch{return!1}}var Ca=r("../../node_modules/.pnpm/ignore@7.0.5/node_modules/ignore/index.js"),xa=r("../../node_modules/.pnpm/picomatch@4.0.5/node_modules/picomatch/index.js");class _a{constructor({ttlMs:e,now:t=Date.now}){this.entries=new Map,this.ttlMs="function"==typeof e?e:_a.validated(e),this.now=t}static validated(e){if(!Number.isFinite(e)||e<=0)throw new Error(`TTL cache requires a positive ttlMs, got ${e}`);return()=>e}get(e){const t=this.entries.get(e);if(void 0!==t){if(!(t.expiresAtMs<=this.now()))return t.value;this.entries.delete(e)}}has(e){const t=this.entries.get(e);return!(void 0===t||t.expiresAtMs<=this.now()&&(this.entries.delete(e),1))}set(e,t){this.entries.set(e,{value:t,expiresAtMs:this.now()+this.ttlMs()})}delete(e){return this.entries.delete(e)}clear(){this.entries.clear()}}var Pa=r("node:string_decoder");var Ia=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var 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 Ra(e){if(e.aborted)return{aborted:Promise.resolve("aborted"),[Symbol.dispose](){}};let t=()=>{};const r=new Promise((e=>{t=()=>e("aborted")}));return e.addEventListener("abort",t,{once:!0}),{aborted:r,[Symbol.dispose](){e.removeEventListener("abort",t)}}}function Ta(e,{root:t,searchPaths:r=[],includeGlobs:o=[],excludeGlobs:s=[],caseSensitive:i=!1,cursorIgnoreFiles:a=[],sandboxPolicy:c={type:"insecure_none"},noIgnoreVcs:l=!1,followSymlinks:u=!1,source:d="ripwalk"}){const h=["--files","--hidden","--no-require-git","--no-config","--color=never"],p=function(e=process.env){const t=e.CURSOR_RIPWALK_THREADS?.trim();if(void 0!==t&&""!==t){const e=Number(t);if(Number.isInteger(e)&&e>=0)return 0===e?void 0:e}return Math.min(2,(0,n.availableParallelism)())}();void 0!==p&&h.push("--threads",String(p)),u&&h.push("--follow"),l&&h.push("--no-ignore-vcs"),i&&h.push("--case-sensitive");for(const e of a)h.push("--cursor-ignore",e);for(const e of o)h.push("--iglob",e);for(const e of s)h.push("--iglob",`!${e}`);r.length>0&&h.push("--",...r);let f,m=!1;const g=new Promise((e=>{f=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,Fs.spawnInSandbox)((0,Fs.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(i.catch((()=>{})),!n.stdout)throw new Error("No stdout from ripgrep process");const a=Ra(e.signal);return{stdout:n.stdout,processExit:i,stderr:()=>Buffer.concat(s).toString(),aborted:a.aborted,[Symbol.dispose](){a[Symbol.dispose](),n.kill()}}}(e,h,t,c),!1);let n=0;const s=async function*(e){const t=new Pa.StringDecoder("utf8");let r="";for await(const o of e){r+=t.write(o);const e=r.split("\n");r=e.pop()??"",e.length>0&&(yield e)}r+=t.end(),r&&(yield[r])}(o.stdout)[Symbol.asyncIterator]();e:for(;;){const t=await Promise.race([s.next(),o.aborted]);if("aborted"===t){m=!0,f(!0);break}if(t.done)break;for(const r of t.value){if(e.signal.aborted){m=!0,f(!0);break e}n++,yield r}}if(n>0);else if(!m){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}`:""}`)}}m||f(!1)}catch(e){r.error=e,r.hasError=!0}finally{Ia(r)}}(),didTimeout:g}}var Aa=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var 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});let Ma;function Da({root:e,searchPaths:t=[],includeGlobs:r=[],excludeGlobs:o=[],caseSensitive:n=!1,cursorIgnoreFiles:s=[],sandboxPolicy:i={type:"insecure_none"},noIgnoreVcs:a=!1,followSymlinks:c=!1}){return JSON.stringify({root:e,searchPaths:t,includeGlobs:r,excludeGlobs:o,caseSensitive:n,cursorIgnoreFiles:s,sandboxPolicy:i,noIgnoreVcs:a,followSymlinks:c})}class Oa{constructor(e=()=>function(e=process.env){if(void 0!==Ma)return Ma;const t=e.CURSOR_RIPWALK_CACHE_TTL_MS?.trim();if(void 0!==t&&""!==t){const e=Number(t);if(Number.isFinite(e)&&e>0)return e}return 2e4}()){this.cache=new _a({ttlMs:e})}clear(){this.cache.clear()}delete(e){this.cache.delete(Da(e))}walk(e,t){const r=Da(t);let o,n=!1,s=!1;const i=new Promise((e=>{o=e})),a=e=>{s||(s=!0,o(e))};return{lines:async function*(){const o=this.cache.get(r);if(void 0!==o){const t={stack:[],error:void 0,hasError:!1};try{const s=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var 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,Ra(e.signal),!1),i=await Promise.race([o.linesPromise.then((e=>({type:"lines",lines:e})),(e=>({type:"error",error:e}))),s.aborted.then((()=>({type:"aborted"})))]);if("aborted"===i.type)return n=!0,void a(!0);if("lines"===i.type)return a(!1),void(yield*i.lines);this.cache.get(r)===o&&this.cache.delete(r)}catch(e){t.error=e,t.hasError=!0}finally{Aa(t)}}let s,i;const c={linesPromise:new Promise(((e,t)=>{s=e,i=t}))};c.linesPromise.catch((()=>{})),this.cache.set(r,c);const l=[];let u,d=!1;try{const r=Ta(e,t);for await(const e of r.lines)l.push(e),yield e;if(await r.didTimeout)return n=!0,u=new Error("Ripwalk aborted before cacheable result was available"),void a(!0);d=!0}catch(e){throw u=e,e}finally{d?s?.(l):(this.cache.get(r)===c&&this.cache.delete(r),i?.(u??new Error("Ripwalk terminated before cacheable result was available"))),n||a(!1)}}.bind(this)(),didTimeout:i}}}const Na=[{stage:"prod",gitHost:"origin.cursor.com",gitCdnHost:"gitcdn.origin.cursor.com",rawUserContentHost:"raw.cursorusercontent.com",apiHost:"api.origin.cursor.com",internalHost:"origin-prod.internal.cursor.com"},{stage:"staging",gitHost:"origin-staging.cursor.com",gitCdnHost:"gitcdn.origin-staging.cursor.com",rawUserContentHost:"raw.staging.cursorusercontent.com",apiHost:"api.origin-staging.cursor.com",internalHost:"origin-staging.internal.cursor.com"},{stage:"test",gitHost:"origin-test.cursor.com",gitCdnHost:"gitcdn.origin-test.cursor.com",rawUserContentHost:"raw.test.cursorusercontent.com",apiHost:"api.origin-test.cursor.com",internalHost:"origin-test.internal.cursor.com"}];function $a(e){return/^origin(-[a-z0-9]+)?\.cursor\.com$/i.test(e)}new Map(Na.map((e=>[e.gitHost,e.apiHost]))),new Map(Na.map((e=>[e.gitHost,e.gitCdnHost]))),new Map(Na.map((e=>[e.gitHost,e.rawUserContentHost]))),new Map(Na.map((e=>[e.apiHost,e.gitHost]))),new Map(Na.map((e=>[e.apiHost,e.internalHost]))),new Map,function(e){const t=Na.find((t=>t.stage===e));if(void 0===t)throw new Error(`unknown Origin stage: ${e}`);return t}("prod").gitHost;const Fa=new Map;function ja(e){if(void 0===e)return;if(Fa.has(e))return Fa.get(e);const t=function(e){const t=e?function(e){let t=e.trim();if(""!==t){t.startsWith("git@")?t=`https://${t.slice(4).replace(":","/")}`:/^[a-z][a-z0-9+.-]*:\/\//i.test(t)&&!/^https?:\/\//i.test(t)?t=t.replace(/^[a-z][a-z0-9+.-]*:\/\//i,"https://"):/^https?:\/\//i.test(t)||(t=`https://${t}`);try{return new URL(t)}catch{return}}}(e):void 0;if(void 0===t||!$a(t.hostname))return;const r=function(e){let t=e.length;for(;t>0&&47===e.charCodeAt(t-1);)t--;const r=e.slice(0,t).replace(/\.git$/i,"");return r&&"/"!==r?r.startsWith("/")?r:`/${r}`:""}(t.pathname).split("/").filter(Boolean),o=3===r.length&&"git"===r[0]?.toLowerCase(),n=2===r.length&&"git"!==r[0]?.toLowerCase();if(!o&&!n)return;const s=o?r[1]:r[0],i=o?r[2]:r[1];return s&&i?Object.freeze({hostname:t.hostname,owner:s,name:i}):void 0}(e);return Fa.size>=16384&&Fa.clear(),Fa.set(e,t),t}function La(e){return void 0!==function(e){const t=ja(e);return void 0===t?void 0:{owner:t.owner,name:t.name}}(e)}new Set(["github.com","www.github.com"]),new RegExp("^tmp-[0-9a-f]{16}$");const Ua=new WeakMap;function Ba(e,t,r){const o=performance.now();let n=Ua.get(t);void 0===n&&(n=new Map,Ua.set(t,n));const s=n.get(r);if(void 0!==s&&o-s.startedAt<5e3)return s.root;for(const[e,t]of n)o-t.startedAt>=5e3&&n.delete(e);const i=async function(e,t,r){try{return(await t.exec(e,r,["rev-parse","--show-toplevel"],{caller:"findGitRoot"})).stdout.trim()}catch{return null}}(e,t,r);return n.set(r,{startedAt:o,root:i}),i}async function Wa(e,t,r){try{return(await t.exec(e,r,["config","--get","remote.origin.url"],{caller:"getGitRemoteUrl"})).stdout.trim()}catch{return}}function Ha(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}}const qa=["**/node_modules/**","**/.git/**","**/.turbo/**","**/.next/**","**/.cache/**","**/.pnpm/**","**/.yarn/**","**/dist/**","**/build/**","**/out/**","**/target/**","**/.vscode/**","**/.idea/**","**/venv/**","**/__pycache__/**","**/logs/**","**/tmp/**","**/temp/**"];function za(e,t){return Fi(e,t).map((t=>`/${s.posix.relative(e,t)}`))}const Ga=[".gitignore",".cursorignore"],Va=new Map,Ja=new Map;function Ka(e,t,r,o){if(e.set(r,o),e.size>t){const t=e.keys().next().value;void 0!==t&&e.delete(t)}return o}function Za(e){const t=Va.get(e);return void 0!==t?t:Ka(Va,2048,e,function(e){let t=e.trim();t.startsWith("git@")&&(t=`https://${t.slice(4).replace(":","/")}`),/^[a-z][a-z0-9+.-]*:\/\//i.test(t)&&!/^https?:\/\//i.test(t)&&(t=t.replace(/^[a-z][a-z0-9+.-]*:\/\//i,"https://")),/^https?:\/\//i.test(t)||(t=`https://${t}`);try{const e=new URL(t),r=e.pathname.replace(/\/+$/,"").replace(/\.git$/i,"").replace(/\/+$/,"");return e.hostname+r}catch{return t=t.replace(/^https?:\/\//i,""),t=t.replace(/[?#].*$/,""),t=t.replace(/\/+$/,""),t=t.replace(/\.git$/i,""),t=t.replace(/\/+$/,""),t}}(e).toLowerCase())}async function Xa(e){if(!(0,s.isAbsolute)(e))return null;const t=await(0,Gs.DN)(e);return null===t?null:t}async function Qa(e){return e.getShellSandboxIgnoreMapping?e.getShellSandboxIgnoreMapping():e.getCursorIgnoreMapping()}(0,Xs.J)((function(){Va.clear(),Ja.clear()}));class Ya{constructor(e,t,r){this.disposeRequested=!1,this.ignoreServicePromise=rc.init((0,ce.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,t){return this.ignoreServicePromise.then((r=>r.isCursorIgnored(e,t)))}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()))}getShellSandboxIgnoreMapping(){return this.ignoreServicePromise.then((e=>e.getShellSandboxIgnoreMapping()))}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)))}dispose(){this.disposeRequested||(this.disposeRequested=!0,this.ignoreServicePromise.then((e=>{e.dispose()})).catch((()=>{})))}}const ec=Math.min(8,Math.max(1,Math.floor(n.default.availableParallelism()/2)));class tc{constructor(e){this.maxLookups=e,this.instances=new Map,this.lookups=0}get(e,t){this.lookups>=this.maxLookups&&this.clear(),this.lookups++;let r=this.instances.get(e);return void 0===r&&(r=Ca().add(t),this.instances.set(e,r)),r}delete(e){this.instances.delete(e)}clear(){this.instances.clear(),this.lookups=0}}class rc{constructor(e,t,r,o,n,s){this.gitExecutor=e,this.gitIgnoreMapping=t,this.cursorIgnoreMapping=r,this.teamSettingsService=o,this.rootDirectories=n,this.scanEnvironment=s,this.gitIgnoreCache=new Di.q({max:2e3}),this.cursorIgnoreCache=new Di.q({max:2e3}),this.gitRootCache=new Di.q({max:1e4}),this.gitRemoteUrlCache=new Di.q({max:200}),this.hasGitDirCache=new Di.q({max:1e3}),this.gitParsedIgnoreCache=new tc(1e4),this.cursorParsedIgnoreCache=new tc(1e4),this.unwalkedFolders=n.flatMap((e=>Fi(e,s)))}static getRipwalkCache(){return rc.ripwalkCache??=new Oa,rc.ripwalkCache}hasNoWorkspaceFolders(){return 0===Object.keys(this.gitIgnoreMapping).length&&0===Object.keys(this.cursorIgnoreMapping).length}async resolveLookupRoot(e){return await(0,Gs.DN)(e)??(0,Gs.o1)(e)}static async init(e,t,r,o,s={platform:process.platform,homeDirectory:n.default.homedir()}){const i={...s,homeDirectory:await(0,Gs.DN)(s.homeDirectory)??s.homeDirectory},a=await(0,Ht.PH)(r,(async e=>{const t=await(0,Gs.DN)(e);return null===t?(console.warn(`[IgnoreService] Cannot resolve workspace root, using as-is: ${e}`),e):t})),c={},l={},u=(await(0,Ht.PH)(a,(async r=>{const o=await Ba(e,t,r);return null!==o&&Fi(o,i).length>0?r:o}))).filter((e=>null!==e));return u.length>0&&await Promise.all([rc.initializeIgnoreMapping(u,".gitignore",c,i),rc.initializeIgnoreMapping(a,".cursorignore",l,i)]),new rc(t,c,l,o,a,i)}static async preloadHierarchy(e,t,r,o){let n=(0,Gs.o1)(e);const i=(0,s.parse)(n).root;for(;n!==i;){if(o?.has(n)){const e=(0,s.dirname)(n);if(e===n)break;n=e;continue}void 0===r[n]&&await rc.handleHierarchyIgnore(n,t,r),o?.add(n);const e=(0,s.dirname)(n);if(e===n)break;n=e}}static async handleHierarchyIgnore(e,t,r){const o=(0,s.join)(e,t);try{await(0,Os.access)(o,Os.default.constants.F_OK);const t=await ua(o),n=rc.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,o){try{const n=rc.deduplicateRootDirectories(e),i=await rc.promiseQueue.enqueueList(n,(e=>rc.findFilesWithRipgrep(e,t,o))),a=Array.from(i.values()).flat();await Promise.all(a.map((async e=>{try{const t=await ua(e),o=rc.parseIgnoreRules(t),n=(0,s.dirname)(e);r[n]=o}catch(r){console.error(`Error processing ${t} file at ${e}:`,r)}})));const c=new Set;for(const e of n)await rc.preloadHierarchy(e,t,r,c)}catch(e){console.error(`Error initializing ignore mapping for ${t}:`,e)}}static async findFilesWithRipgrep(e,t,r){const o=(0,ce.q6)(),n=[],i={root:e,includeGlobs:Ga.map((e=>`**/${e}`)),excludeGlobs:[...qa,...za(e,r)],source:"ignore_scan"},a=rc.getRipwalkCache().walk(o,i);for await(const r of a.lines)(0,s.basename)(r)===t&&n.push((0,s.join)(e,r));return n}async handleManualLookupWhenNoWorkspaceDirs(e,t,r){const o={};let n=(0,s.dirname)(e);const i=(0,s.parse)(n).root;for(;;){let e=r?.get(n);if(void 0===e){try{e=rc.parseIgnoreRules(await ua((0,s.join)(n,t)))}catch{e=[]}r?.set(n,e)}if(e.length>0&&(o[n]=e),n===i)break;n=(0,s.dirname)(n)}return this.testIgnored(e,o,((e,t)=>Ca().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,t){return this.checkCursorIgnored(e,t)}async checkGitIgnored(e){if(this.hasNoWorkspaceFolders())return this.handleManualLookupWhenNoWorkspaceDirs(e,".gitignore");const t=this.gitIgnoreCache.get(e);if(void 0!==t)return t;await this.populateHierarchyIfNeeded(e,".gitignore",this.gitIgnoreMapping);const r=this.checkIgnored(e,this.gitIgnoreMapping,this.gitParsedIgnoreCache);return this.gitIgnoreCache.set(e,r),r}async checkCursorIgnored(e,t){if(this.hasNoWorkspaceFolders())return this.handleManualLookupWhenNoWorkspaceDirs(e,".cursorignore",t);const r=this.cursorIgnoreCache.get(e);if(void 0!==r)return r;await this.populateHierarchyIfNeeded(e,".cursorignore",this.cursorIgnoreMapping);const o=this.checkIgnored(e,this.cursorIgnoreMapping,this.cursorParsedIgnoreCache);return this.cursorIgnoreCache.set(e,o),o}isInUnwalkedFolder(e){const t="darwin"===this.scanEnvironment.platform,r=t?e.toLowerCase():e;return this.unwalkedFolders.some((e=>(0,Gs.ZU)({basePath:t?e.toLowerCase():e,targetPath:r})))}async populateHierarchyIfNeeded(e,t,r){let o=(0,s.dirname)((0,Gs.o1)(e));const n=[],i=(0,s.parse)(o).root;for(;o!==i;){const e=this.isInUnwalkedFolder(o);if(!e&&this.rootDirectories.some((e=>(0,Gs.ZU)({basePath:e,targetPath:o})))){o=(0,s.dirname)(o);continue}if(void 0===r[o])n.push(o);else if(!e)break;const t=(0,s.dirname)(o);if(t===o)break;o=t}n.length>0&&(await rc.promiseQueue.enqueueList(n,(e=>rc.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,Gs.ZU)({basePath:o,targetPath:e}))continue;const t=(0,s.relative)(o,e);if(""===t)continue;const i=r(o,n),a=(0,Gs.oL)(t),c=i.test(a);if(c.ignored&&!c.unignored)return!0;const l=i.test(`${a}/`);if(l.ignored&&!l.unignored)return!0}return!1}checkIgnored(e,t,r){return this.testIgnored(e,t,((e,t)=>r.get(e,t)))}async listCursorIgnoreFilesByRoot(e){const t=await this.resolveLookupRoot(e),r=[];for(const[e,o]of Object.entries(this.cursorIgnoreMapping)){if(0===o.length)continue;if(!(0,Gs.ZU)({basePath:t,targetPath:e}))continue;const n=(0,s.join)(e,".cursorignore");try{await(0,Os.access)(n),r.push(n)}catch{}}return r}async getCursorIgnoreMapping(){return{...this.cursorIgnoreMapping}}async getShellSandboxIgnoreMapping(){const e={...this.cursorIgnoreMapping};for(const t of this.rootDirectories){const r=await this.getRepoBlockExcludeGlobs(t);if(0===r.length)continue;const o=e[t];e[t]=o?[...o,...r]:r}return e}async getGitIgnoreMapping(){return{...this.gitIgnoreMapping}}static deduplicateRootDirectories(e){const t=[...e.map((e=>(0,Gs.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()}dispose(){this.gitIgnoreCache=new Di.q({max:1}),this.cursorIgnoreCache=new Di.q({max:1}),this.gitRootCache=new Di.q({max:1}),this.gitRemoteUrlCache=new Di.q({max:1}),this.hasGitDirCache=new Di.q({max:1}),this.gitParsedIgnoreCache.clear(),this.cursorParsedIgnoreCache.clear(),this.gitRepoMappingPromise=void 0}async handleCursorIgnoreCreated(e){const t=(0,s.dirname)(e),r=await ua(e),o=rc.parseIgnoreRules(r);this.cursorIgnoreMapping[t]=o,this.cursorParsedIgnoreCache.delete(t),this.cursorIgnoreCache.clear()}async handleCursorIgnoreChanged(e){const t=(0,s.dirname)(e),r=await ua(e),o=rc.parseIgnoreRules(r);this.cursorIgnoreMapping[t]=o,this.cursorParsedIgnoreCache.delete(t),this.cursorIgnoreCache.clear()}handleCursorIgnoreDeleted(e){const t=(0,s.dirname)(e);this.cursorIgnoreMapping[t]=[],this.cursorParsedIgnoreCache.delete(t),this.cursorIgnoreCache.clear()}async findGitRootsForFile(e){const t=(0,Gs.o1)(e),r=this.gitRootCache.get(t);if(void 0!==r)return r;const o=[],n=[],i=[];let a=t;const c=(0,s.parse)(a).root;for(;a!==c;){n.push(a),void 0===this.hasGitDirCache.get(a)&&i.push(a);const e=(0,s.dirname)(a);if(e===a)break;a=e}if(i.length>0){const e=i.map((e=>(0,Os.access)((0,s.join)(e,".git"),Os.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.teamSettingsService?.getTeamRepos());if(!t)return!1;const r=t.repos??[],o=t.disableLocalExecAllowlistEnforcement?[]:t.allowedRepos??[];if(0===r.length&&0===o.length)return!1;const n=await this.findGitRootsForFile(e);if(0===n.length)return this.checkNonRepoPathBlockedByAllowlist(e,o);let i=0===o.length,a=!1;for(const t of n){let n;if(this.gitRemoteUrlCache.has(t)?n=this.gitRemoteUrlCache.get(t):(n=await Wa((0,ce.q6)(),this.gitExecutor,t),void 0!==n&&this.gitRemoteUrlCache.set(t,n)),void 0===n)continue;const c=n,l=(0,s.relative)(t,e)||".";for(const e of r)if(this.doesRepoUrlMatch(e.url,c))for(const t of e.patterns||[])if(this.matchGlob(t.pattern,l))return!0;o.length>0&&!a&&(a=!0,i=o.some((e=>this.doesRepoUrlMatch(e.url,c)&&(e.patterns||[]).some((e=>this.matchGlob(e.pattern,l))))))}return!i}async checkNonRepoPathBlockedByAllowlist(e,t){if(0===t.length)return!1;const r=await this.getCursorDataDir();if((0,Gs.ZU)({basePath:r,targetPath:e}))return!1;const o=this.getWorkspaceRelativePath(e);for(const e of t)if(this.isWildcardUrl(e.url)){if((e.patterns||[]).some((e=>this.matchGlob(e.pattern,o))))return!1}else if(this.isPathPatternUrl(e.url)&&this.matchGlob(e.url,o))return!1;return!0}isWildcardUrl(e){return"*"===e.trim()}isPathPatternUrl(e){return!(e.includes("://")||e.includes("github.com")||e.includes("gitlab.com")||e.includes("bitbucket.org")||e.includes("@"))}getWorkspaceRelativePath(e){let t;for(const r of this.rootDirectories)(0,Gs.ZU)({basePath:r,targetPath:e})&&(void 0===t||r.length>t.length)&&(t=r);return void 0!==t?(0,Gs.oL)((0,s.relative)(t,e)):(0,Gs.oL)(e)}getCursorDataDir(){return this.cursorDataDirPromise??=(async()=>{const e=(0,s.join)(n.default.homedir(),".cursor");return await(0,Gs.DN)(e)??e})(),this.cursorDataDirPromise}doesRepoUrlMatch(e,t){return e.includes("*")?"*"===e.trim()||this.matchRepoUrlGlob(Za(e),Za(t)):Za(e)===Za(t)}matchGlob(e,t){const r=e.trim();return!("."!==t&&""!==t||"**"!==r&&"**/*"!==r)||function(e){const t=Ja.get(e);if(void 0!==t)return t;let r;try{const t=xa(e,{dot:!0});r=r=>{try{return t(r)}catch{return e===r}}}catch{r=t=>e===t}return Ka(Ja,2048,e,r)}(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,i]of o){if(void 0===i)continue;const o=this.normalizePathForComparison(e),a=this.normalizePathForComparison(r);let c=!1,l="";if(a.startsWith(o)?(c=!0,l=""):o.startsWith(a)&&(c=!0,l=(0,s.relative)(r,e)),!c)continue;const u=t.repos.filter((e=>this.doesRepoUrlMatch(e.url,i)));if(0!==u.length)for(const e of u)for(const t of e.patterns||[]){const e=t.pattern.trim();if(!e)continue;let r;r=l?(0,s.join)(l,e).replace(/\\/g,"/"):e,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,ce.q6)();for(const e of this.rootDirectories){const n=(0,Gs.o1)(e);try{await(0,Os.access)((0,s.join)(n,".git"),Os.default.constants.F_OK),t.includes(n)||t.push(n)}catch{}let i=(0,s.dirname)(n);const a=(0,s.parse)(i).root;for(;i!==a&&""!==i;){try{await(0,Os.access)((0,s.join)(i,".git"),Os.default.constants.F_OK),t.includes(i)||t.push(i)}catch{}const e=(0,s.dirname)(i);if(e===i)break;i=e}try{const e={root:n,includeGlobs:["**/.git/config"],excludeGlobs:[...r,...za(n,this.scanEnvironment)],noIgnoreVcs:!0,source:"ignore_scan"},i=rc.getRipwalkCache().walk(o,e);for await(const e of i.lines){const r=(0,s.join)(n,e),o=(0,s.dirname)(r),i=(0,s.dirname)(o);t.includes(i)||t.push(i)}}catch{}}return await Promise.all(t.map((async t=>{try{const r=await Wa(o,this.gitExecutor,t);e.set(t,r)}catch{e.set(t,void 0)}}))),e}}rc.promiseQueue=new Ht.TJ({max:ec});const oc="agent-tools",nc=51380224,sc=new(r("node:async_hooks").AsyncLocalStorage);function ic(e,t){return sc.run(e,t)}var ac=r("../proto/dist/generated/agent/v1/utils_pb.js"),cc=r("../utils/dist/safe-spawn-cwd.js"),lc=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},uc=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 dc=(0,m.h)("local-exec:shell-core"),hc="win32"===process.platform,pc=["CURSOR_CONVERSATION_ID","CURSOR_REQUEST_ID","CURSOR_AGENT_STORE_FILES_DIR","CURSOR_AGENT_STORE_SHARED_PATHS"];function fc(e){return`'${e.replace(/'/g,"'\\''")}'`}const mc=["eval-cursorbench","cursorbench","sand-eval","eval-harness"];function gc(e){return mc.some((t=>e.includes(t)))?(0,Ts.createHash)("sha256").update(e).digest("hex"):e}function wc(e,t){return e[t]??process.env[t]}const yc=/^[A-Za-z_][A-Za-z0-9_]*$/,vc=/CURSOR_SANDBOX/i;function bc(e){return yc.test(e)&&!vc.test(e)}function Sc(e,t){const r=void 0===e?[]:[...e];return r.includes(t)||r.push(t),r}function kc(e){let t=0,r=0;const o=e.length;for(;r<o;){const o=e.indexOf(10,r);if(-1===o)return t;t+=1,r=o+1}return t}class Ec extends Error{constructor(e){super(`working directory does not exist: ${e}; the command did not run`),this.name="WorkingDirectoryMissingError"}}class Cc{constructor(e,t,r,o={}){this.executor=e,this.workspacePath=t,this.projectDir=r,this.options=o,this.conversationExecutors=new Map}executorFor(e){if(!e)return this.executor;let t=this.conversationExecutors.get(e);return void 0===t&&(t=this.executor.clone(this.workspacePath),this.conversationExecutors.set(e,t)),t}async*execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{lc(r,(0,i.VI)(e.withName("ShellCoreExecutor.execute")),!1);const o=performance.now(),n=this.executorFor(t.conversationId),a=t.workingDirectory||await n.getCwd(),c=(0,Gs.o1)(a,this.workspacePath);if(!(0,cc.$f)(c)&&!await async function(e){try{return(await(0,Os.stat)(e)).isDirectory()}catch(e){const t=e.code;if("ENOENT"===t||"ENOTDIR"===t)return!1;throw e}}(c)){if(c!==(0,Gs.o1)(await n.getCwd(),this.workspacePath))throw new Ec(c);return yield{type:"stderr",data:`The shell's working directory no longer exists: ${c}. The command did not run. Re-run it with working_directory set to an existing directory.\n`},void(yield{type:"exit",code:1,aborted:!1,localExecutionTimeMs:Math.round(performance.now()-o)})}let l,u,d=0,h=0,p=!1,f=!1,m=!1;t.fileOutputThresholdBytes&&this.projectDir&&(l={buffer:"",lineCount:0,size:0,threshold:Number(t.fileOutputThresholdBytes)});const g=t.signal,w={CURSOR_AGENT:"1"};t.conversationId&&(w.CURSOR_CONVERSATION_ID=(0,As.sh)(t.conversationId)),t.requestId&&(w.CURSOR_REQUEST_ID=t.requestId),this.projectDir&&(w.AGENT_TRANSCRIPTS=s.default.join(this.projectDir,As.O2));const y=this.options.extraEnvProvider?.(e,t);void 0!==y&&Object.assign(w,y);const v=t.requestScopedEnv??{};for(const[e,t]of Object.entries(v))void 0!==t&&bc(e)&&(w[e]=t);const b=w.CURSOR_REQUEST_ID;void 0!==b&&(w.CURSOR_REQUEST_ID=gc(b)),function(e,t){const r=Object.keys(t).filter((e=>bc(e)&&!pc.includes(e))),o=`builtin unset ${[...pc,...r].join(" ")} 2>/dev/null || true`,n=[];for(const t of pc){const r=wc(e,t);void 0!==r&&n.push(`builtin export ${t}=${fc(r)}`)}for(const e of r){const r=t[e];void 0!==r&&n.push(`builtin export ${e}=${fc(r)}`)}const s=e.__CURSOR_SANDBOX_ENV_RESTORE?.trim(),i=process.env.__CURSOR_SANDBOX_ENV_RESTORE?.trim();e.__CURSOR_SANDBOX_ENV_RESTORE=[o,i,s,...n].filter((e=>void 0!==e&&""!==e)).join("; ")}(w,v),void 0!==w.__CURSOR_SANDBOX_ENV_RESTORE&&(w.__CURSOR_SANDBOX_ENV_RESTORE=function(e,t){let r=e;for(const e of t){if(null==e||0===e.length)continue;const t=gc(e);t!==e&&(r=r.split(e).join(t))}return r}(w.__CURSOR_SANDBOX_ENV_RESTORE,[t.requestId,b,v.CURSOR_REQUEST_ID,process.env.CURSOR_REQUEST_ID]));const S=function(e,t){const r=wc(t,"CURSOR_AGENT_STORE_FILES_DIR"),o=function(e){if(void 0===e)return[];try{const t=JSON.parse(e);if("object"!=typeof t||null===t)return[];const r=[];for(const e of Object.values(t))"object"==typeof e&&null!==e&&"path"in e&&"readOnly"in e&&"string"==typeof e.path&&"boolean"==typeof e.readOnly&&r.push({path:e.path,readOnly:e.readOnly});return r}catch{return[]}}(wc(t,"CURSOR_AGENT_STORE_SHARED_PATHS"));if(void 0===r&&0===o.length)return e;const n=e?.perUser,s=e?.perRepo??e?.perUser??e?.teamAdmin;if("workspace_readwrite"!==s?.type&&"workspace_readonly"!==s?.type)return e;const i=n?.type===s.type?{...n}:{type:s.type};var a;void 0!==r&&(a=r,"workspace_readwrite"!==i.type?i.additionalReadonlyPaths=Sc(i.additionalReadonlyPaths,a):i.additionalReadwritePaths=Sc(i.additionalReadwritePaths,a));for(const e of o)e.readOnly||"workspace_readwrite"!==i.type?i.additionalReadonlyPaths=Sc(i.additionalReadonlyPaths,e.path):i.additionalReadwritePaths=Sc(i.additionalReadwritePaths,e.path);return{...e,perUser:i}}(t.sandboxPolicy,w),k=(0,Fs.CG)(S??Fs.BM);S&&(yield{type:"start",sandboxed:"workspace_readonly"===k||"workspace_readwrite"===k}),t.askpassConfig&&!hc&&(w.SUDO_ASKPASS=t.askpassConfig.helperPath,w.CURSOR_ASKPASS_SOCKET=t.askpassConfig.socketPath,w.CURSOR_ASKPASS_SECRET=t.askpassConfig.secret);let E=0,C="";for await(const r of n.execute(e,t.command,{signal:g,workingDirectory:c,env:w,sandboxPolicy:S,sandboxWorkspaceRoot:this.workspacePath,pipeStdin:t.pipeStdin??!1,keepBackgroundJobs:this.options.keepBackgroundJobs??!1,bufferOutputEvents:this.options.shellOutputBackpressureOptions?.bufferOutputEvents,outputLimiterOptions:this.options.shellOutputBackpressureOptions?.outputLimiterOptions,powershellUtf8Console:this.options.powershellUtf8Console,powershellUtf8ChildEnv:this.options.powershellUtf8ChildEnv})){E=0,C="";let e=!1,t=!1;if("stdout"===r.type||"stderr"===r.type){const o="stdout"===r.type?p:f,n=void 0===l||!0===l.truncated;if(!o||!n){E=r.data.length;const n="stdout"===r.type?d:h,i=!o&&n+E<=Ks,a=void 0!==l&&!0!==l.truncated&&l.size+E<=nc;if("stdout"===r.type?e=i:t=i,(i||a)&&(C=r.data.toString()),void 0!==l&&l.size+E>nc)l.truncated=!0;else if(a&&void 0!==l)if(l.size+=E,l.lineCount+=kc(r.data),l.file)l.file.write(C);else if(l.buffer+=C,l.size>l.threshold){const e=s.default.join(this.projectDir,oc);l.path=s.default.join(e,`${(0,Ts.randomUUID)()}.txt`);try{await(0,Os.mkdir)(e,{recursive:!0}),l.file=(0,$s.createWriteStream)(l.path),l.file.on("error",(e=>{u??=e})),l.file.write(l.buffer)}catch(e){u??=e instanceof Error?e:new Error(String(e)),l.truncated=!0}l.buffer=""}}}switch(r.type){case"stdout":e?(d+=E,yield{type:"stdout",data:C}):p||(p=!0,yield{type:"stdout_trimmed"});break;case"suppressed_output":m||(m=!0,yield{type:"stdout",data:Fs.Ls});break;case"stderr":t?(h+=E,yield{type:"stderr",data:C}):f||(f=!0,yield{type:"stderr_trimmed"});break;case"exit":{const e=Math.max(0,Math.round(performance.now()-o));let t;if(l?.file){if(l.truncated){const e=`\n... (output truncated at ${l.size} bytes) ...\n`;l.file.write(e),l.size+=e.length,l.lineCount+=Bi(e)-1}const e=await new Promise((e=>l.file.end(e)));u??=e??void 0,u?await(0,Os.rm)(l.path,{force:!0}):t=new ac.pV({filePath:l.path,sizeBytes:BigInt(l.size),lineCount:BigInt(l.lineCount)})}u&&void 0!==l?.path&&(yield{type:"stderr",data:`\nThe full output could not be saved to ${l.path}: ${u.message}\n`}),yield{type:"exit",code:r.code,signal:r.signal,aborted:r.aborted,outputLocation:t,localExecutionTimeMs:e};break}case"stdin_ready":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{uc(r)}}async getCwd(e){return this.executorFor(e).getCwd()}getWorkspacePath(){if(!this.workspacePath)throw new Error("Workspace path is not configured");return this.workspacePath}}class xc{constructor(e,t){this.innerExecutor=e,this.shellManager=t}async*execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{lc(r,(0,i.VI)(e.withName("ManagedShellCoreExecutor.execute")),!1),dc.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{uc(r)}}async getCwd(e){return this.innerExecutor.getCwd(e)}getWorkspacePath(){return this.innerExecutor.getWorkspacePath()}}class _c{constructor(e,t){this.innerExecutor=e,this.askpassConfig=t}async*execute(e,t){const r={...t,askpassConfig:t.askpassConfig??this.askpassConfig};yield*this.innerExecutor.execute(e,r)}async getCwd(e){return this.innerExecutor.getCwd(e)}getWorkspacePath(){return this.innerExecutor.getWorkspacePath()}}async function Pc(e,t){switch(e.type){case"needsApproval":return t.onNeedsApproval(e.approvalReason,e.approvalDetails);case"userRejected":return t.onUserRejected(e.reason);case"cursorIgnore":return t.onPermissionDenied("Blocked by cursor ignore");case"permissionsConfig":return t.onPermissionDenied("Blocked by permissions configuration",{isReadonly:e.isReadonly});case"cursorFiles":return t.onPermissionDenied("Blocked by cursor files protection");case"adminBlock":return t.onPermissionDenied("Blocked by admin repository block");case"adminCommandDenylist":return t.onPermissionDenied(Ai(e.pattern));case"unsafeResolution":return t.onPermissionDenied(e.message);default:{const t=e;throw new Error(`Unhandled block reason type: ${JSON.stringify(t)}`)}}}function Ic(e){switch(e.type){case"userRejected":return e.reason;case"unsafeResolution":return e.message;case"adminCommandDenylist":return Ai(e.pattern);case"needsApproval":case"cursorIgnore":case"adminBlock":case"permissionsConfig":case"cursorFiles":return"Command is not allowed";default:{const t=e;return`Command is not allowed (${JSON.stringify(t)})`}}}function Rc(e,t,r){return"permissionsConfig"===r.type?{case:"permissionDenied",value:new yr.jn({command:e,workingDirectory:t,error:"Command blocked by permissions configuration",isReadonly:r.isReadonly??!1})}:{case:"rejected",value:new yr.pZ({command:e,workingDirectory:t,reason:Ic(r)})}}var Tc=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 Ac=(0,m.h)("local-exec:background-shell");function Mc(e,t,r){return new gr.Lt({result:Rc(e,t,r)})}class Dc{constructor(e,t){this.id=e,this.abortController=t,this.disposed=!1,this.completed=!1,this.completionListeners=[]}abort(){this.abortController.abort()}dispose(){this.disposed||(this.disposed=!0,this.abortController.signal.aborted||this.abortController.abort())}get signal(){return this.abortController.signal}isDisposed(){return this.disposed}onComplete(e){this.completed&&this.completion?e(this.completion):this.completionListeners.push(e)}markCompleted(e){if(this.completed)return;this.completed=!0,this.completion=e;const t=[...this.completionListeners];this.completionListeners=[];for(const r of t)r(e)}}async function Oc(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,signal:o.value.signal,aborted:o.value.aborted,outputPath:o.value.outputLocation?.filePath})}catch(e){}finally{e.markCompleted(r??{code:null,aborted:e.signal.aborted})}}function Nc(e){e().catch((()=>{}))}const $c=65536;class Fc{constructor(e){if(this.args=e,this.carryover="",this.matchedOccurrences=0,this.emittedNotifications=0,this.finished=!1,this.startedAtMs=Date.now(),this.limit=e.config.notificationLimit??100,e.config.pattern.length>500)throw new Error("Output notification pattern exceeds 500 characters");this.regex=zs.L3.compile(e.config.pattern,zs.L3.MULTILINE)}observe(e){if(this.finished||this.matchedOccurrences>=this.limit||0===e.length)return;if(e.length>$c){for(let t=0;t<e.length&&this.matchedOccurrences<this.limit;t+=$c)this.observe(e.slice(t,t+$c));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(),0===this.matchedOccurrences&&this.recordWatchOutcome("silent",{silent_ms:Date.now()-this.startedAtMs}))}queueMatch(e){if(this.matchedOccurrences>=this.limit)return;this.matchedOccurrences+=1;const t=this.matchedOccurrences,r=function(e,t){return e.length<=5e3?`${t}: ${e}`:`${t} is ${e.length} characters; omitted from notification detail.`}(e,1===t?"Matched text":"Latest match");return 1===t?(this.emitNotification({startOccurrence:t,endOccurrence:t,count:1,matchedTextDetail:r}),this.recordWatchOutcome("matched",{first_match_ms:Date.now()-this.startedAtMs}),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.enqueue({conversationId:this.args.conversationId,id:s,source:"shell",payload:{taskId:s,...void 0!==this.args.toolCallId?{toolCallId:this.args.toolCallId}:{},kind:"shell",status:"success",title:(i=t,i.length<=500?i:`${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.enqueue({conversationId:this.args.conversationId,id:t,source:"shell",payload:{taskId:t,...void 0!==this.args.toolCallId?{toolCallId:this.args.toolCallId}:{},kind:"shell",status:"success",title:`Notification limit reached (${this.limit})`,detail:`Shell output matched /${e}/ ${this.limit} times and has reached the notification limit. No further notifications will be sent for this pattern. To continue monitoring, read the output file directly at the output path.`,outputPath:this.args.outputPath,reason:"task_progress"}}),this.recordWatchOutcome("limit_reached")}recordWatchOutcome(e,t){void 0!==this.args.ctx&&Ac.info(this.args.ctx,"agent.shell_output_notification_match",{event:"agent.shell_output_notification_match",outcome:e,shell_id:this.args.shellId,conversation_id:this.args.conversationId,tool_call_id:this.args.toolCallId,limit:this.limit,...t})}}class jc{constructor(e,t,r){this.innerFactory=e,this.projectDir=t,this.backgroundWorkRegistry=r}async spawn(e,t){const r=this.createObserver(e.ctx,e.shellId,e.conversationId,e.toolCallId,e.outputNotification);if(!r)return this.innerFactory.spawn(e,t);try{return await this.innerFactory.spawn(e,this.createObservingExecutor(t,r))}catch(e){throw r.finish(),e}}async adopt(e){const t=this.createObserver(e.ctx,e.shellId,void 0,e.toolCallId,e.outputNotification);if(!t)return this.innerFactory.adopt(e);e.initialOutput.length>0&&t.observe(e.initialOutput);try{return await this.innerFactory.adopt({...e,eventIterator:this.createObservingIterator(e.eventIterator,t)})}catch(e){throw t.finish(),e}}createObserver(e,t,r,o,n){if(!this.backgroundWorkRegistry||!n)return;if(0===n.pattern.trim().length)return;const i=s.join(this.projectDir,"terminals",`${t}.txt`);try{return new Fc({shellId:t,outputPath:i,config:n,conversationId:r??oe,toolCallId:o,registry:this.backgroundWorkRegistry,ctx:e})}catch(r){return void(void 0!==e&&Ac.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 Lc{async spawn(e,t){const r=new AbortController,o=new Dc(e.shellId,r),n=t.execute(e.ctx,{command:e.command,workingDirectory:e.workingDirectory,signal:r.signal,toolCallId:e.toolCallId,conversationId:e.conversationId,requestId:e.requestId,secretScopeId:e.secretScopeId,sandboxPolicy:e.sandboxPolicy,pipeStdin:e.enableWriteShellStdinTool,showElapsedTime:!0})[Symbol.asyncIterator]();try{for(let e=await 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){if(e instanceof Fs.SandboxUnsupportedError||e instanceof Ec)throw e}return Nc((()=>Oc(o,n))),o}async adopt(e){const t=new Dc(e.shellId,e.abortController);return t.stdin=e.stdin,t.pid=e.pid,Nc((()=>Oc(t,e.eventIterator))),t}}function Uc(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`}function Bc(e){const t=String(e.runningForMs).padEnd(9," "),r=e.status.padEnd(9," ");let o="---\n";return void 0!==e.pid&&0!==e.pid&&(o+=`pid: ${e.pid}\n`),o+=`cwd: ${Uc(e.cwd)}\n`,o+=`command: ${Uc(e.command)}\n`,void 0!==e.title&&e.title.trim().length>0&&(o+=`title: ${Uc(e.title)}\n`),o+=`status: ${r}\n`,o+=`started_at: ${e.startedAt}\n`,o+=`running_for_ms: ${t}\n`,o+="---\n",o}function Wc(e){return`\n[${e} truncated by cursor: the command wrote more than 1048576 characters to ${e}; only the first 1048576 were captured and the rest was dropped from this file]\n`}class Hc{constructor(e,t){this.innerFactory=e,this.projectDir=t}async spawn(e,t){const r=s.join(this.projectDir,"terminals");await(0,Os.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 a,c,l,u=!1,d=!1,h=!1,p=!1;const f=Date.now(),m=new Date(f).toISOString();let g,w="running",y=!1,v=Promise.resolve();const b=async e=>{if(c)try{await c.write(e)}catch(e){}},S=t.shellId,k=s.join(r,`${S}.txt`),E=async()=>{if(!a)return;const e=Date.now()-f,r=Bc({pid:g,cwd:t.workingDirectory,command:t.command,title:t.description,status:w,startedAt:m,runningForMs:e});try{await a.write(r,0,"utf8")}catch(e){}},C=()=>(v=v.then(E).catch((()=>{})),v),x=()=>{void 0!==l&&(clearInterval(l),l=void 0)},_=async e=>{if(p)return;p=!0,g=e;const r=Date.now()-f,o=Bc({pid:e,cwd:t.workingDirectory,command:t.command,title:t.description,status:w,startedAt:m,runningForMs:r});await(0,Os.writeFile)(k,o,"utf8"),l=setInterval((()=>{C()}),5e3)},P=async()=>{a||(a=await $s.promises.open(k,"r+")),c||(c=await $s.promises.open(k,"a"))},I=async(e,t)=>{if(!y){if(y=!0,x(),p||await _(),await P(),void 0!==t){const e=Date.now()-f,r=`\n---\n${t}\n`+(i.showElapsedTime?`elapsed_ms: ${e}\n`:"")+`ended_at: ${(new Date).toISOString()}\n---\n`;await b(r)}w=e,await C()}};try{for await(const r of n(e,i)){if("stdout"===r.type)p||(await _(),await P()),await b(r.data);else if("stderr"===r.type)p||(await _(),await P()),await b(r.data);else if("stdout_trimmed"!==r.type||d)if("stderr_trimmed"!==r.type||h)if("stdin_ready"!==r.type||u)"exit"===r.type&&await I(r.aborted?"aborted":0===r.code?"succeeded":"failed",`exit_code: ${r.code??"unknown"}`);else{u=!0,p||(await _(r.pid),await P());const e=r.stdin;if(e&&!0!==t.suppressStdinLogging){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`;b(`[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))}}}else h=!0,p||await _(),await P(),await b(Wc("stderr"));else d=!0,p||await _(),await P(),await b(Wc("stdout"));yield r}if(!y){const e=i.signal?.aborted??!1;await I(e?"aborted":"failed")}}catch(e){const t=i.signal?.aborted??!1,r=Uc(e instanceof Error?e.message:"Unknown error");if(await I(t?"aborted":"failed",t?void 0:`error: ${r}`),!t)throw e}finally{if(x(),await v,a)try{await a.close()}catch{}if(c)try{await c.close()}catch{}}}}}async adopt(e){const t=s.join(this.projectDir,"terminals");await(0,Os.mkdir)(t,{recursive:!0});const r=s.join(t,`${e.shellId}.txt`),o=e.startTime,n=new Date(o).toISOString();let i="running";const a=Date.now()-o,c=Bc({pid:e.pid,cwd:e.workingDirectory,command:e.command,title:e.description,status:i,startedAt:n,runningForMs:a})+(e.initialOutput??"");await(0,Os.writeFile)(r,c,"utf8");const l=await $s.promises.open(r,"r+");let u;try{u=await $s.promises.open(r,"a")}catch(e){throw await l.close(),e}let d=!1,h=!1,p=!1,f=!1,m=Promise.resolve();const g=async()=>{const t=Date.now()-o,r=Bc({pid:e.pid,cwd:e.workingDirectory,command:e.command,title:e.description,status:i,startedAt:n,runningForMs:t});try{await l.write(r,0,"utf8")}catch{}},w=()=>(m=m.then(g).catch((()=>{})),m);let y=setInterval((()=>{w()}),5e3);const v=()=>{void 0!==y&&(clearInterval(y),y=void 0)},b=async()=>{if(!d){d=!0,v(),await m;try{await l.close()}catch{}try{await u.close()}catch{}}},S=async e=>{try{await u.write(e)}catch(e){}},k=async(t,r)=>{if(!h){if(h=!0,v(),void 0!==r){const t=Date.now()-o,n=`\n---\n${r}\n`+(e.showElapsedTime?`elapsed_ms: ${t}\n`:"")+`ended_at: ${(new Date).toISOString()}\n---\n`;await S(n)}i=t,await w()}},E={next:async()=>{try{const t=await e.eventIterator.next();if(t.done){if(!h){const t=e.abortController.signal.aborted;await k(t?"aborted":"failed")}}else{const e=t.value;"stdout"===e.type||"stderr"===e.type?await S(e.data):"stdout_trimmed"!==e.type||p?"stderr_trimmed"!==e.type||f?"exit"===e.type&&(await k(e.aborted?"aborted":0===e.code?"succeeded":"failed",`exit_code: ${e.code??"unknown"}`),await b()):(f=!0,await S(Wc("stderr"))):(p=!0,await S(Wc("stdout")))}return t.done&&await b(),t}catch(t){const r=e.abortController.signal.aborted;throw await k(r?"aborted":"failed"),await b(),t}},return:async()=>{if(!h){const t=e.abortController.signal.aborted;await k(t?"aborted":"failed")}return await b(),e.eventIterator.return?e.eventIterator.return():{done:!0,value:void 0}}};return this.innerFactory.adopt({...e,eventIterator:E})}}class qc{constructor(e,t){this.factory=e,this.backgroundWorkRegistry=t,this.runningShells=new Map,this.nextShellId=1e3+Math.floor(999e3*Math.random())}registerShellWork(e,t){const r=String(e.id);this.backgroundWorkRegistry?.upsertWork({id:r,kind:"shell",state:"running",metadata:re(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,o,n){if(!this.backgroundWorkRegistry)return;const s=n.aborted?"aborted":0===n.code?"success":"error",i=function(e){if(!e.aborted)return void 0!==e.signal?`signal=${e.signal}`:null!==e.code&&0!==e.code?`exit_code=${e.code}`:void 0}(n),a=String(e);this.backgroundWorkRegistry.enqueue({conversationId:r??oe,id:a,source:"shell",payload:{taskId:a,...void 0!==t?{toolCallId:t}:{},kind:"shell",status:s,title:o,...i?{detail:i}:{},...n.outputPath?{outputPath:n.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.toolCallId,e.conversationId,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),e.onCleanup?.()})),t.onComplete?.((r=>{this.enqueueShellCompletion(t.id,e.toolCallId,void 0,e.description||e.command,r),this.cleanupShell(t.id),e.onCleanup?.()})),{shellId:t.id,pid:e.pid}}generateShellId(){for(let e=0;e<=998999;e++){this.nextShellId>999999&&(this.nextShellId=1e3);const e=this.nextShellId;if(this.nextShellId+=1,!this.runningShells.has(e))return e}throw new Error("No available background shell id in range")}abort(e){const t=this.runningShells.get(e);return!!t&&(t.abort(),this.runningShells.delete(e),this.clearShellWork(e),!0)}isRunning(e){return this.runningShells.has(e)}dispose(){for(const[e,t]of this.runningShells)t.dispose(),this.clearShellWork(e);this.runningShells.clear()}async writeStdin(e,t){const r=this.runningShells.get(e);if(!r)throw new Error("Shell not found");if(!r.stdin)throw new Error("Shell stdin not available");const 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 zc{constructor(e,t){this.inner=e,this.ownerConversationId=t}enqueue(e){this.inner.enqueue({...e,conversationId:this.ownerConversationId})}enqueueCompletion(e){this.enqueue({conversationId:this.ownerConversationId,id:e.taskId,source:e.kind,payload:e})}pull(e){return this.inner.pull(e)}ack(e){return this.inner.ack(e)}nack(e,t){this.inner.nack(e,t)}suppress(e,t){this.inner.suppress(e,t)}upsertWork(e){this.inner.upsertWork(e)}clearWork(e){return this.inner.clearWork(e)}abortWork(e){return this.inner.abortWork(e)}hasRunningWork(e){return this.inner.hasRunningWork(e)}abortAllWork(e){return this.inner.abortAllWork(e)}listWork(e){return this.inner.listWork(e)}drainCompletions(){return this.inner.drainCompletions()}hasPendingCompletions(e){return this.inner.hasPendingCompletions(e)}markAwaitedCompletion(e){this.inner.suppress(this.ownerConversationId,e)}}class Gc{constructor(e,t,r,o,n,s,i){this.permissionsService=e,this.coreExecutor=t,this.ignoreService=r;const a=s&&void 0!==i?new zc(s,i):s,c=n??function(e){const t=new Lc;return new Hc(t,e)}(o),l=new jc(c,o,a);this.backgroundShellManager=new qc(l,a)}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,i.VI)(e.withName("LocalBackgroundShellExecutor.execute")),!1);const o=t.command,n=t.sandboxPolicy?yi(t.sandboxPolicy):void 0,s=t.workingDirectory||await this.coreExecutor.getCwd(t.conversationId),a=(0,Gs.o1)(s),c=new yr.HO(qs(o).structured),l=Mi({command:o,parsingResult:c,blockedCommands:t.adminCommandDenylist});if(void 0!==l)return new gr.Lt({result:{case:"rejected",value:new yr.pZ({command:o,workingDirectory:a,reason:l})}});let u=n;if(Ac.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:c.executableCommands.length,classifierCommandCount:t.classifierResult?.commands.length??0,commandLength:o.length}),t.skipApproval){const r=await this.permissionsService.shouldEnforceShellInvariantBlocks(e,{workingDirectory:a,skipUnsafeWorkingDirectoryBlock:!0,command:o,parsingResult:c,toolCallId:t.toolCallId},n);if("block"===r.kind)return Ac.info(e,"Background shell: invariant blocked command",{toolCallId:t.toolCallId,blockReasonType:r.reason.type,skipApproval:t.skipApproval}),Mc(o,a,r.reason);Ac.info(e,"Background shell: skipped local approval",{toolCallId:t.toolCallId,requestedPolicyType:n?.type??"undefined"})}else{const r=await this.permissionsService.shouldBlockShellCommand(e,o,{workingDirectory:a,timeout:0,parsingResult:c,toolCallId:t.toolCallId,classifierResult:t.classifierResult,smartModeApprovalReason:t.smartModeApproval?.reason,smartModeApprovalRequestId:t.smartModeApproval?.requestId,hookApprovalRequirement:Dr(t)},n);if("block"===r.kind)return Ac.info(e,"Background shell: approval gate blocked command",{toolCallId:t.toolCallId,blockReasonType:r.reason.type,hasSmartModeApproval:void 0!==t.smartModeApproval,skipApproval:t.skipApproval}),Mc(o,a,r.reason);u=r.policy,Ac.info(e,"Background shell: approval gate allowed command",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,effectivePolicyType:u.type})}if(ii()&&(u=hi(o,c),"insecure_none"!==u.type)){const e=await Qa(this.ignoreService);u={...u,ignoreMapping:e}}try{const r=this.backgroundShellManager.generateShellId(),n=u?{perRepo:u}:void 0,s={ctx:e,command:o,workingDirectory:a,toolCallId:t.toolCallId,conversationId:t.conversationId,requestId:t.requestId,secretScopeId:t.secretScopeId,sandboxPolicy:n,shellId:r,enableWriteShellStdinTool:t.enableWriteShellStdinTool,suppressStdinLogging:t.suppressStdinLogging,description:t.description,outputNotification:t.outputNotification},i=await this.backgroundShellManager.spawn(s,this.coreExecutor);return new gr.Lt({result:{case:"success",value:new gr.Po({shellId:r,command:o,workingDirectory:a,pid:i.pid})}})}catch(r){if(r instanceof Fs.SandboxUnsupportedError){const n=u?.type??"unknown";return Ac.debug(e,"Background shell: sandbox policy unsupported on this host",{toolCallId:t.toolCallId,policyType:n,reason:r.reason}),new gr.Lt({result:{case:"sandboxUnsupported",value:new yr.rI({command:o,workingDirectory:a,sandboxPolicyType:n,reason:r.reason??r.message,isReadonly:"workspace_readonly"===n})}})}return new gr.Lt({result:{case:"error",value:new gr.Of({command:o,workingDirectory:a,error:r instanceof Error?r.message:"Unknown error"})}})}}catch(e){r.error=e,r.hasError=!0}finally{Tc(r)}}writeStdin(e,t){return this.backgroundShellManager.writeStdin(e,t)}}var Vc=r("../../node_modules/.pnpm/minimatch@10.2.5/node_modules/minimatch/dist/esm/index.js");const Jc={log:()=>{},increment:()=>{},distribution:()=>{},captureException:()=>{}},Kc=Io.object({command:Io.string().optional(),args:Io.array(Io.string()).optional(),env:Io.record(Io.string(),Io.string()).optional(),url:Io.string().optional(),headers:Io.record(Io.string(),Io.string()).optional(),cwd:Io.string().optional(),envFile:Io.string().optional(),auth:Io.object({CLIENT_ID:Io.string(),CLIENT_SECRET:Io.string().optional(),scopes:Io.array(Io.string()).optional()}).optional(),enabledTools:Io.array(Io.string()).optional(),placement:Io.enum(["server","client"]).optional(),tls:Io.object({caBundle:Io.string().trim().min(1).max(131072)}).optional()}),Zc=Io.object({mcpServers:Io.record(Io.string(),Kc).optional()}),Xc=Io.enum(["canvas"]),Qc=Io.array(Xc).transform((e=>[...new Set(e)].sort()));class Yc extends Error{constructor(e,t){super(`Invalid Claude Code plugin identifier "${t}": ${e}`),this.raw=t,this.name="CCPluginIdentifierError"}}function el(e){const t=e.trim();if(!t)throw new Yc("Empty identifier",e);const r=/^[a-zA-Z0-9_-]+$/,o=t.indexOf("@");if(o!==t.lastIndexOf("@"))throw new Yc("Plugin identifier cannot contain multiple @ symbols",e);if(-1===o){if(!r.test(t))throw new Yc("Plugin name must contain only alphanumeric characters, dashes, and underscores",e);if(t.length>100)throw new Yc("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 Yc("Missing plugin name before @",e);if(!s)throw new Yc("Missing source after @",e);if(!r.test(n))throw new Yc("Plugin name must contain only alphanumeric characters, dashes, and underscores",e);if(n.length>100)throw new Yc("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 Yc("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 Yc("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 Yc("Missing Git URL after 'url:'",e);try{new URL(t)}catch{throw new Yc("Invalid Git URL format",e)}return{name:n,sourceType:"url",gitUrl:t,raw:e}}const i=s.indexOf("#");let a,c;if(-1!==i?(a=s.slice(0,i).trim(),c=s.slice(i+1).trim()):a=s,!a)throw new Yc("Missing marketplace name",e);if(!r.test(a))throw new Yc("Marketplace name must contain only alphanumeric characters, dashes, and underscores",e);return{name:n,sourceType:"marketplace",marketplace:a,version:c,raw:e}}function tl(e){if("claude-plugin"===e.source)return e.sourceInfo.raw;if("user-local"===e.source)return`user-local:${e.sourceInfo.name}`;if("extension"===e.source){const t=e.sourceInfo;return`extension:${t.extensionId}:${t.localPath}`}const t=e.sourceInfo;return`${t.name}-${t.version}`}function rl(e){return e.sourceInfo.name}function ol(e){switch(e.source){case"claude-plugin":case"cursor-first-party":case"cursor-third-party":return e.sourceInfo.marketplace;default:return}}function nl(e){switch(e.source){case"cursor-first-party":case"cursor-third-party":return e.sourceInfo.pluginDbId;default:return}}function sl(e){switch(e.source){case"cursor-first-party":case"cursor-third-party":return e.sourceInfo.marketplaceDbId;default:return}}const il=new Set(["CREDENTIAL","CREDENTIALS","KEY","PASSPHRASE","PASSWORD","SECRET","TOKEN"]);function al(e){return function(e){return e.replace(/([a-z\d])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/[^a-z\d]+/gi,"_").toUpperCase().split("_").filter((e=>e.length>0))}(e).some((e=>il.has(e)))}const cl=/\$\{(?:env:([A-Z][A-Z0-9_]*)|([A-Z][A-Z0-9_]*)(?::-([^}]*))?)\}/g,ll=new Set(["CURSOR_PLUGIN_ROOT","CLAUDE_PLUGIN_ROOT"]),ul=new Set(["api","aws","db","dd","gcp","http","https","id","mcp","ssl","tls","uri","url"]);function dl(e){return e.split("_").filter((e=>e.length>0)).map((e=>{const t=e.toLowerCase();return ul.has(t)?e.toUpperCase():e.charAt(0).toUpperCase()+t.slice(1)})).join(" ")}function hl(e,t){if("string"!=typeof e){if(Array.isArray(e))for(const r of e)hl(r,t);else if(null!==e&&"object"==typeof e)for(const r of Object.values(e))hl(r,t)}else for(const[,r,o,n]of e.matchAll(cl)){const e=r??o;if(void 0===e||ll.has(e)||t.has(e))continue;const s=void 0===r?`\${${e}}`:`\${env:${e}}`;t.set(e,{reference:s,defaultValue:n})}}function pl(e){if(void 0===e?.mcpServers)return;const t=new Map;if(hl(e.mcpServers,t),0===t.size)return;const r={};for(const e of[...t.keys()].sort()){const{reference:o,defaultValue:n}=t.get(e);r[e]={type:"string",title:dl(e),description:void 0===n||0===n.length?`Referenced as \`${o}\` in this plugin's MCP configuration.`:`Referenced as \`${o}\` in this plugin's MCP configuration. Defaults to \`${n}\` when left blank.`,...al(e)?{writeOnly:!0}:{}}}return{type:"object",properties:r}}var fl=r("../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/ajv.js");const ml=new Set(["https://agent-plugins.org/schemas/1.0.0/plugin.schema.json","https://agent-plugins.org/schemas/1.0.0/mcp.schema.json"]),gl=/^v?(\d+\.\d+(?:\.\d+)?)$/;function wl(e){if("object"!=typeof e||null===e||Array.isArray(e))return;const t=e.$schema;return"string"==typeof t&&t.length>0?t:void 0}function yl(e){let t;try{t=new URL(e).pathname.split("/")}catch{t=e.split("/")}for(const e of t){const t=gl.exec(e);if(null!==t)return t[1]}}function vl(e){return void 0===e?{kind:"absent"}:ml.has(e)?{kind:"supported",id:e,version:yl(e)??e}:{kind:"unsupported",id:e}}const bl=10485760,Sl=/^[a-z0-9]([a-z0-9.-]*[a-z0-9])?$/,kl=[".cursor-plugin/plugin.json",".claude-plugin/plugin.json","plugin.json"],El=[".cursor-plugin",".claude-plugin"],Cl=[".cursor-plugin/marketplace.json",".claude-plugin/marketplace.json"],xl=Io.object({source:Io.literal("github"),repo:Io.string().regex(/^[^/]+\/[^/]+$/,"Must be in owner/repo format"),ref:Io.string().optional(),sha:Io.string().length(40,"SHA must be 40 characters").regex(/^[a-f0-9]+$/,"SHA must be hexadecimal").optional()}),_l=Io.object({source:Io.literal("url"),url:Io.string().url().endsWith(".git","URL must end with .git"),ref:Io.string().optional(),sha:Io.string().length(40,"SHA must be 40 characters").regex(/^[a-f0-9]+$/,"SHA must be hexadecimal").optional()}),Pl=Io.object({source:Io.literal("git-subdir"),url:Io.string().url().endsWith(".git","URL must end with .git"),path:Io.string().min(1),ref:Io.string().optional(),sha:Io.string().length(40,"SHA must be 40 characters").regex(/^[a-f0-9]+$/,"SHA must be hexadecimal").optional()}),Il=Io.union([Io.string(),xl,_l,Pl]),Rl=/^(\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?|never)$/,Tl='Must be a semver version (X.Y.Z) or "never"',Al=Io.object({cursor:Io.string().regex(Rl,Tl).optional(),sand:Io.string().regex(Rl,Tl).optional()}),Ml=Io.object({name:Io.string().min(1,"Author name is required"),email:Io.string().email().optional()}),Dl=Io.enum(["string","number","integer","boolean","object","array","null"]),Ol=Io.union([Dl,Io.array(Dl).nonempty().superRefine(((e,t)=>{new Set(e).size!==e.length&&t.addIssue({code:Io.ZodIssueCode.custom,message:"Schema type arrays must not contain duplicates"})}))]);function Nl(e,t){if(void 0!==e.required)if(void 0===e.properties)for(const r of e.required)t.addIssue({code:Io.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:Io.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:Io.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:Io.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:Io.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:Io.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:Io.ZodIssueCode.custom,message:"minProperties must be less than or equal to maxProperties",path:["minProperties"]})}const $l=Io.lazy((()=>Io.object({type:Ol.optional(),title:Io.string().optional(),description:Io.string().optional(),format:Io.string().optional(),writeOnly:Io.boolean().optional(),default:Io.unknown().optional(),enum:Io.array(Io.any()).nonempty().optional(),const:Io.unknown().optional(),properties:Io.record(Io.string(),$l).optional(),required:Io.array(Io.string()).optional(),additionalProperties:Io.union([Io.boolean(),$l]).optional(),items:Io.union([$l,Io.array($l)]).optional(),minLength:Io.number().int().nonnegative().optional(),maxLength:Io.number().int().nonnegative().optional(),minimum:Io.number().optional(),maximum:Io.number().optional(),exclusiveMinimum:Io.number().optional(),exclusiveMaximum:Io.number().optional(),multipleOf:Io.number().positive().optional(),minItems:Io.number().int().nonnegative().optional(),maxItems:Io.number().int().nonnegative().optional(),uniqueItems:Io.boolean().optional(),minProperties:Io.number().int().nonnegative().optional(),maxProperties:Io.number().int().nonnegative().optional()}).strict().superRefine(Nl)));function Fl(e){const t=$l.superRefine(((e,t)=>{"object"!==e.type&&t.addIssue({code:Io.ZodIssueCode.custom,message:'Plugin variable schemas must declare type "object"',path:["type"]})})).safeParse(e);return t.success?{success:!0,data:t.data}:{success:!1,error:t.error}}const jl=Io.unknown().superRefine(((e,t)=>{const r=Fl(e);if(!r.success)for(const e of r.error.issues)t.addIssue(e)})).transform((e=>e)),Ll=(Io.object({name:Io.string().min(1).transform((e=>e.toLowerCase())).refine((e=>Sl.test(e)),"Name must be kebab-case (lowercase alphanumeric with hyphens and periods)"),displayName:Io.string().optional(),source:Il,description:Io.string().optional(),version:Io.string().optional(),author:Ml.optional(),publisher:Io.string().min(1).optional(),homepage:Io.string().url().optional(),repository:Io.string().url().optional(),license:Io.string().optional(),keywords:Io.array(Io.string()).optional(),capabilities:Qc.optional(),logo:Io.string().optional(),category:Io.string().optional(),tags:Io.array(Io.string()).optional(),minClientVersions:Al.optional(),strict:Io.boolean().default(!0),commands:Io.union([Io.string(),Io.array(Io.string())]).optional(),agents:Io.union([Io.string(),Io.array(Io.string())]).optional(),skills:Io.union([Io.string(),Io.array(Io.string())]).optional(),rules:Io.union([Io.string(),Io.array(Io.string())]).optional(),hooks:Io.union([Io.string(),Io.record(Io.string(),Io.unknown())]).optional(),variables:jl.optional(),mcpServers:Io.union([Io.string(),Io.record(Io.string(),Io.unknown()),Io.array(Io.union([Io.string(),Io.record(Io.string(),Io.unknown())]))]).optional()}),Io.object({description:Io.string().optional(),version:Io.string().optional(),pluginRoot:Io.string().optional()}),Io.object({name:Io.string().min(1).regex(Sl,"Name must be kebab-case (lowercase alphanumeric with hyphens and periods)"),displayName:Io.string().optional(),description:Io.string().optional(),version:Io.string().optional(),author:Ml.optional(),publisher:Io.string().min(1).optional(),homepage:Io.string().url().optional(),repository:Io.string().url().optional(),license:Io.string().optional(),logo:Io.string().optional(),keywords:Io.array(Io.string()).optional(),capabilities:Qc.optional(),minClientVersions:Al.optional(),commands:Io.union([Io.string(),Io.array(Io.string())]).optional(),agents:Io.union([Io.string(),Io.array(Io.string())]).optional(),skills:Io.union([Io.string(),Io.array(Io.string())]).optional(),rules:Io.union([Io.string(),Io.array(Io.string())]).optional(),hooks:Io.union([Io.string(),Io.record(Io.string(),Io.unknown())]).optional(),variables:jl.optional(),mcpServers:Io.union([Io.string(),Io.record(Io.string(),Io.unknown()),Io.array(Io.union([Io.string(),Io.record(Io.string(),Io.unknown())]))]).optional()}));function Ul(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Bl(e){return e.trim().toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")}function Wl(e,t){if(Ul(e)&&"string"==typeof e.name){const t=Bl(e.name);if(t.length>0)return t}return function(e){const t=void 0!==e.repoName?Bl(e.repoName):"";return t.length>0?t:`cursor-marketplace-${e.fallbackId??(0,Ts.randomUUID)()}`}(t)}function Hl(e){if(Ul(e)&&Ul(e.owner)){const t="string"==typeof e.owner.name&&e.owner.name.trim().length>0?e.owner.name:"Unknown",r="string"==typeof e.owner.email&&e.owner.email.trim().length>0?e.owner.email:void 0;return{name:t,...void 0!==r?{email:r}:{}}}return{name:"Unknown"}}function ql(e){return"string"==typeof e?e:void 0}function zl(e){if(!Array.isArray(e))return;const t=e.filter((e=>"string"==typeof e));return t.length>0?t:void 0}function Gl(e){return"string"==typeof e?e:zl(e)}function Vl(e){if(!Ul(e)||!Ul(e.metadata))return;const t={description:ql(e.metadata.description),version:ql(e.metadata.version),pluginRoot:ql(e.metadata.pluginRoot)};return void 0!==t.description||void 0!==t.version||void 0!==t.pluginRoot?t:void 0}function Jl(e){if(!Ul(e))return;const t=ql(e.name);if(void 0===t||0===t.length)return;const r=ql(e.email);return{name:t,...void 0!==r?{email:r}:{}}}function Kl(e){if("string"==typeof e||Ul(e))return e;if(Array.isArray(e)){const t=e.filter((e=>"string"==typeof e||Ul(e)));return t.length>0?t:void 0}}function Zl(e){if("string"==typeof e||Ul(e))return e}function Xl(e){if(void 0===e)return;const t=Fl(e);return t.success?t.data:void 0}function Ql(e,t={}){if(e.length>bl)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(!Ul(r))return{success:!1,error:"Invalid marketplace manifest: expected a JSON object"};const o=[],n=[],i=new Set;return(Array.isArray(r.plugins)?r.plugins:[]).forEach(((e,t)=>{const r=function(e,t){if(!Ul(e))return{skippedEntry:{index:t,error:`Plugin entry at index ${t} is not an object`}};const r="string"==typeof(o=e.source)?o:Ul(o)?"github"===o.source&&"string"==typeof o.repo&&o.repo.length>0?{source:"github",repo:o.repo,ref:ql(o.ref),sha:ql(o.sha)}:("url"===o.source||void 0===o.source)&&"string"==typeof o.url&&o.url.length>0?{source:"url",url:o.url,ref:ql(o.ref),sha:ql(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:ql(o.ref),sha:ql(o.sha)}:"string"==typeof o.repo&&o.repo.length>0?{source:"github",repo:o.repo,ref:ql(o.ref),sha:ql(o.sha)}:void 0:void 0;var o;if(void 0===r){const r=ql(e.name);return{skippedEntry:{index:t,...void 0!==r&&r.length>0?{name:r}:{},error:`Plugin entry at index ${t} has no usable source`}}}const n=("string"==typeof e.name?Bl(e.name):"")||function(e){if("string"==typeof e){const t=Bl((0,s.basename)(e));return t.length>0?t:void 0}if("github"===e.source){const t=Bl(e.repo.split("/").at(-1)??"");return t.length>0?t:void 0}if("git-subdir"===e.source){const t=Bl((0,s.basename)(e.path));return t.length>0?t:void 0}let t=e.url;try{t=new URL(e.url).pathname}catch{}for(;t.endsWith("/");)t=t.slice(0,-1);t.toLowerCase().endsWith(".git")&&(t=t.slice(0,-4));const r=Bl((0,s.basename)(t));return r.length>0?r:void 0}(r);if(void 0===n)return{skippedEntry:{index:t,error:`Plugin entry at index ${t} has no usable name`}};const i=Qc.safeParse(e.capabilities);if(void 0!==e.capabilities&&!i.success)return{skippedEntry:{index:t,name:n,error:`Plugin entry at index ${t} has invalid capabilities: ${i.error.issues.map((e=>`${e.path.join(".")}: ${e.message}`)).join(", ")}`}};const a=i.success?i.data:void 0,c=function(e){const t=Al.safeParse(e);if(t.success&&(void 0!==t.data.cursor||void 0!==t.data.sand))return t.data}(e.minClientVersions);return{entry:{name:n,displayName:ql(e.displayName),source:r,description:ql(e.description),version:ql(e.version),author:Jl(e.author),publisher:ql(e.publisher),homepage:ql(e.homepage),repository:ql(e.repository),license:ql(e.license),keywords:zl(e.keywords),logo:ql(e.logo),category:ql(e.category),tags:zl(e.tags),strict:"boolean"!=typeof e.strict||e.strict,commands:Gl(e.commands),agents:Gl(e.agents),skills:Gl(e.skills),rules:Gl(e.rules),hooks:Zl(e.hooks),variables:Xl(e.variables),mcpServers:Kl(e.mcpServers),...void 0!==a&&{capabilities:a},...void 0!==c&&{minClientVersions:c}}}}(e,t);"skippedEntry"in r?n.push(r.skippedEntry):i.has(r.entry.name)?n.push({index:t,name:r.entry.name,error:`Duplicate plugin name "${r.entry.name}" at index ${t}`}):(i.add(r.entry.name),o.push(r.entry))})),{success:!0,data:{name:Wl(r,t),owner:Hl(r),description:ql(r.description),plugins:o,metadata:Vl(r),skippedPluginEntries:n}}}function Yl(e){if(e.length>bl)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=vl(wl(t)),o=Ll.safeParse(t);return o.success?{success:!0,data:o.data,..."unsupported"===r.kind&&{unrecognizedSchemaId:r.id}}:{success:!1,error:`Invalid plugin manifest: ${o.error.issues.map((e=>`${e.path.join(".")}: ${e.message}`)).join(", ")}`,details:o.error}}function eu(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 tu(e){return!e.includes("..")&&!(0,s.isAbsolute)(e)&&!e.includes("://")}function ru(e,t){if((e.disabledEnvironments??[]).includes(t))return!1;const r=e.environments??[];return 0===r.length||r.includes(t)}new fl.Ajv({allErrors:!0,strict:!1,validateSchema:!0});var ou=r("../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/main.js");const nu=/\$\{(?:env:([A-Za-z_][A-Za-z0-9_]*)|([^:}]+)(?::-([^}]*))?)\}/g;function su(e,t){return iu(e,"function"==typeof t?t:function(e){const t=new Map(Object.entries(e).map((([e,t])=>[e.toLowerCase(),t])));return r=>e[r]??t.get(r.toLowerCase())}(t))}function iu(e,t){if("string"==typeof e)return e.replace(nu,((e,r,o,n)=>{if(void 0!==r)return t(r)??e;const s=t(o);return void 0!==s?s:void 0!==n?n:e}));if(Array.isArray(e))return e.map((e=>iu(e,t)));if(null!==e&&"object"==typeof e){const r={};for(const[o,n]of Object.entries(e))r[o]=iu(n,t);return r}return e}function au(e,t){return e.replace(/\$\{CLAUDE_PLUGIN_ROOT\}/g,(()=>t)).replace(/\$\{CURSOR_PLUGIN_ROOT\}/g,(()=>t))}const cu=[".mcp.json","mcp.json"],lu=new Set(["author","owner","source","metadata"].map((e=>e.toLowerCase())));function uu(e,t){if(!function(e){return lu.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 du(e){return"object"==typeof e&&null!==e&&("command"in e||"url"in e)}function hu(e){const t=void 0!==e&&e.length>0?e.replace(/\/+$/,""):void 0;return cu.map((e=>void 0!==t?`${t}/${e}`:e))}function pu(e,t,r){if(!e.mcpServers)return e;const o={};for(const[r,n]of Object.entries(e.mcpServers)){const e={...n};if("string"==typeof n.command&&(e.command=au(n.command,t)),Array.isArray(n.args)&&(e.args=n.args.map((e=>"string"==typeof e?au(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?au(o,t):o;e.env=r}"string"==typeof n.cwd&&(e.cwd=au(n.cwd,t)),o[r]=e}return function(e,t){const r=t?.cloudAgentEnvLookup,o=t?.configuredVariables;if(void 0!==r)return su(e,r);const n=new Map(Object.keys(o??{}).map((e=>[e.toLowerCase(),e])));return su(e,(e=>{const t=process.env[e];if(void 0!==t)return t;const r=void 0!==o&&Object.hasOwn(o,e)?e:n.get(e.toLowerCase()),s=void 0!==r?o?.[r]:void 0;return null!=s?"string"==typeof s?s:String(s):void 0}))}({...e,mcpServers:o},r)}function fu(e,t,r){try{const o=(0,ou.qg)(e),n=wl(o);if(void 0!==n){const e=r?.log??Jc;"unsupported"===vl(n).kind?e.log("debug",`mcp.json declares an unrecognized $schema, loading anyway: ${n}`):function(e,t){if(void 0===e||void 0===t)return!1;const r=yl(e),o=yl(t);return void 0!==r&&void 0!==o&&r!==o}(r?.pluginSchemaId,n)&&e.log("debug",`mcp.json $schema ${n} disagrees with plugin.json $schema ${r?.pluginSchemaId}, loading anyway`)}const s=Zc.safeParse(o),i=!0===r?.skipExpansion;if(s.success&&s.data.mcpServers&&Object.keys(s.data.mcpServers).length>0)return i?s.data:pu(s.data,t,r);const a={};for(const[e,t]of Object.entries(o))"mcpServers"!==e&&!uu(e,t)&&du(t)&&(a[e]=t);if(Object.keys(a).length>0){const e=Zc.safeParse({mcpServers:a});if(e.success)return i?e.data:pu(e.data,t,r)}return null}catch{return null}}function mu(e,t,r){for(const[o,n]of Object.entries(t))e.mcpServers[o]=n,e.mcpServerSourcePaths[o]=r}async function gu(e,t,r,o={}){const n=o.toSourcePath??(e=>e),s=o.installPathForExpansion??"",i=o.fallbackFileNames??cu,a=o.manifestPrecedence??"override",c={},l={};for(const t of i){const r=await e(t);if(null===r)continue;const i=fu(r,s,o.parserOptions);if(i?.mcpServers)for(const[e,r]of Object.entries(i.mcpServers))void 0===c[e]&&(c[e]=r,l[e]=n(t))}if(void 0!==t){const i=await async function(e,t,r={}){const o=r.toSourcePath??(e=>e),n=r.installPathForExpansion??"",s={mcpServers:{},mcpServerSourcePaths:{}},i=async e=>{const i=e.replace(/^\.\//,"");if(!tu(i))return;const a=await t(i);if(null===a)return;const c=fu(a,n,r.parserOptions);c?.mcpServers&&Object.keys(c.mcpServers).length>0&&mu(s,c.mcpServers,o(i))},a=e=>{const t=fu(JSON.stringify(e),n,r.parserOptions);t?.mcpServers&&Object.keys(t.mcpServers).length>0&&mu(s,t.mcpServers,r.manifestSourcePath??"manifest")};if("string"==typeof e)await i(e);else if(Array.isArray(e))for(const t of e)"string"==typeof t?await i(t):"object"==typeof t&&null!==t&&a(t);else"object"==typeof e&&null!==e&&a(e);return s}(t,e,{toSourcePath:n,manifestSourcePath:r,installPathForExpansion:s,parserOptions:o.parserOptions});for(const[e,t]of Object.entries(i.mcpServers))"fill"===a&&void 0!==c[e]||(c[e]=t,l[e]=i.mcpServerSourcePaths[e])}return 0===Object.keys(c).length?null:{mcpServers:c,...Object.keys(l).length>0&&{mcpServerSourcePaths:l}}}function wu(e,t,r,o,n,s){const i=[],a=e.mcpServers;if(!a)return i;for(const[e,c]of Object.entries(a)){const a=c,l=`plugin-${o}-${e}`,u=e;a.url?i.push({identifier:l,name:u,marketplace:t,marketplaceId:r,pluginName:o,pluginId:n,pluginSource:s,type:"streamableHttp",url:a.url,headers:a.headers,auth:a.auth,tls:a.tls,enabledTools:a.enabledTools,placement:a.placement,projectManaged:!1,pluginManaged:!0}):a.command&&i.push({identifier:l,name:u,marketplace:t,marketplaceId:r,pluginName:o,pluginId:n,pluginSource:s,type:"stdio",command:a.command,args:a.args??[],env:a.env??{},cwd:a.cwd,envFile:a.envFile,enabledTools:a.enabledTools,projectManaged:!1,pluginManaged:!0})}return i}var yu=r("node:stream"),vu=r("node:stream/promises"),bu=r("node:zlib"),Su=r("../../node_modules/.pnpm/tar@7.5.21/node_modules/tar/dist/esm/index.min.js");const ku=".cache-complete";function Eu(e){return Wt(e)}function Cu(e){const{parent:t,name:r}=e;return t.startsWith("\\\\")||/^[A-Za-z]:\\/.test(t)?s.win32.join(t,r):/^[A-Za-z]:\//.test(t)||t.startsWith("//")&&!t.startsWith("//?/")?`${t.replace(/\/+$/,"")}/${r}`:(0,s.join)(t,r)}function xu(e,t){return function(e,t,r,o){const n=[t,r];return void 0!==o&&n.push(o),e.startsWith("\\\\")||/^[A-Za-z]:\\/.test(e)?s.win32.join(e,...n):/^[A-Za-z]:\//.test(e)||e.startsWith("//")&&!e.startsWith("//?/")?[e.replace(/\/+$/,""),...n].join("/"):(0,s.join)(e,...n)}(e,t.marketplaceSlug.replace(/[^a-zA-Z0-9_-]/g,"_"),t.pluginId.replace(/[^a-zA-Z0-9_-]/g,"_"),void 0!==t.version?Eu(t.version):void 0)}class _u{constructor(e,t){const r=e??process.env.HOME??"";this.cacheRoot=t?.cacheRoot??(0,s.join)(r,".cursor","plugins/cache")}getCacheDir(e){return xu(this.cacheRoot,e)}async isCached(e){const t=this.getCacheDir(e);try{const e=Cu({parent:t,name:ku});return(await(0,Os.stat)(e)).isFile()}catch{return!1}}async extractToCache(e){const t=this.getCacheDir(e);await(0,Os.mkdir)(t,{recursive:!0});const r=yu.Readable.from(e.tarball);return await(0,vu.pipeline)(r,(0,bu.createGunzip)(),(0,Su.o6)({cwd:t,strip:1})),await this.markCacheComplete(e),t}async listCachedVersions(e){const t=xu(this.cacheRoot,e);try{return(await(0,Os.readdir)(t,{withFileTypes:!0})).filter((e=>e.isDirectory())).map((e=>e.name))}catch{return[]}}async removeVersion(e){const t=this.getCacheDir(e);try{await(0,Os.rm)(t,{recursive:!0,force:!0})}catch{}}async removeAllVersions(e){const t=xu(this.cacheRoot,e);await(0,Os.rm)(t,{recursive:!0,force:!0})}async pruneOldVersions(e){const t=await this.listCachedVersions({marketplaceSlug:e.marketplaceSlug,pluginId:e.pluginId}),r=new Set(e.keepVersions.map((e=>Eu(e))));for(const o of t)r.has(o)||await this.removeVersion({marketplaceSlug:e.marketplaceSlug,pluginId:e.pluginId,version:o})}async markCacheComplete(e){const t=this.getCacheDir(e);await(0,Os.writeFile)(Cu({parent:t,name:ku}),"")}}function Pu(e,t){const r=e.releaseTag??t;if(e.releaseRepo&&e.releaseAsset&&r)return{kind:"release",releaseRepo:e.releaseRepo,releaseAsset:e.releaseAsset,releaseTag:r}}var Iu=r("node:child_process");const Ru=[["safe.bareRepository","explicit"]],Tu=[["core.fsmonitor","false"],["core.hooksPath",n.devNull],["core.attributesFile",n.devNull]];function Au(e){const t={...process.env,...e.spawnerEnv,LC_ALL:"en_US.UTF-8",LANG:"en_US.UTF-8",GIT_PAGER:"cat",...e.optionsEnv};return void 0!==e.command?t.VSCODE_GIT_COMMAND=e.command:delete t.VSCODE_GIT_COMMAND,function(e,t){const r=function(e){const t=e.GIT_CONFIG_COUNT;if(void 0===t||""===t)return 0;const r=Number.parseInt(t,10);return!Number.isFinite(r)||r<0?0:r}(e),o={...e},n=new Set;for(let e=0;e<r;e++){const r=o[`GIT_CONFIG_KEY_${e}`];for(const[s,i]of t)r===s&&(o[`GIT_CONFIG_VALUE_${e}`]=i,n.add(s))}let s=r;for(const[e,r]of t)n.has(e)||(o[`GIT_CONFIG_KEY_${s}`]=e,o[`GIT_CONFIG_VALUE_${s}`]=r,s++);return s!==r&&(o.GIT_CONFIG_COUNT=String(s)),o}(t,function(e){const t="allow-hooks"===e?Tu.filter((([e])=>"core.hooksPath"!==e)):Tu;return[...Ru,...t]}(e.repoConfigExecution??"block"))}const Mu=(0,ji.promisify)(Iu.execFile),Du=new Set(["-c","-C","--git-dir","--work-tree","--namespace","--super-prefix","--config-env","--attr-source"]),Ou=new Set(["diff","show","blame","log","whatchanged"]);function Nu(e){for(let t=0;t<e.length;t++){const r=e[t];if(Du.has(r))t++;else if(!r.startsWith("-"))return t}return-1}function $u(e){const t=Nu(e);return-1===t?void 0:e[t]}function Fu(e){const t=Nu(e);if(-1===t||!Ou.has(e[t]))return e.slice();const r=[...e.slice(0,t+1),"--no-ext-diff","--no-textconv"];for(let o=t+1;o<e.length;o++){const t=e[o];"--ext-diff"!==t&&"--no-ext-diff"!==t&&"--textconv"!==t&&"--no-textconv"!==t&&r.push(t)}return r}function ju(e,t){return Au({command:$u(e),optionsEnv:t})}async function Lu(e,t,r){const{env:o,encoding:n="utf8",...s}=r??{},i=Fu(t),a=await Mu(e,i,{...s,encoding:n,env:ju(i,o)});return{stdout:a.stdout,stderr:a.stderr}}function Uu(e,t,r){const{env:o,...n}=r??{},s=Fu(t);return(0,Iu.spawn)(e,s,{...n,env:ju(s,o)})}function Bu(){const e=["-c","credential.interactive=false","-c","core.fsmonitor=false"];return"win32"===process.platform&&e.push("-c","core.longpaths=true"),e}function Wu(e){return"function"==typeof e?e():e}async function Hu(e,t){const r=function(e){const t={...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:void 0,VSCODE_GIT_ASKPASS_NODE:void 0,VSCODE_GIT_ASKPASS_MAIN:void 0,VSCODE_GIT_ASKPASS_EXTRA_ARGS:void 0,GCM_INTERACTIVE:"Never"};if(t.GIT_CONFIG_NOSYSTEM=void 0,!0===e?.sshBatchMode){const e=process.env.GIT_SSH_COMMAND?.trim()||"ssh";t.GIT_SSH_COMMAND=`${e} -oBatchMode=yes`}if(void 0!==e?.extraGitConfig){const r=Object.entries(e.extraGitConfig).flatMap((([e,t])=>Array.isArray(t)?t.map((t=>[e,t])):[[e,t]]));t.GIT_CONFIG_COUNT=String(r.length);for(const[e,[o,n]]of r.entries())t[`GIT_CONFIG_KEY_${e}`]=o,t[`GIT_CONFIG_VALUE_${e}`]=n}return{cwd:e?.cwd,env:t}}({cwd:t?.cwd,sshBatchMode:t?.sshBatchMode,extraGitConfig:t?.extraGitConfig});return Lu("git",[...Bu(),...e],{...r,...void 0!==t?.timeoutMs&&{timeout:t.timeoutMs,killSignal:"SIGTERM"}})}const qu=/^[0-9a-f]{7,40}$/i,zu=/^[0-9a-f]{40}$/i;function Gu(e){if(void 0===e||""===e)return;const t=e.split(/\r?\n/).map((e=>{const[t,r]=e.split("\t");if(t&&r&&/^[0-9a-f]{40}$/i.test(t))return{sha:t,refName:r}})).filter((e=>void 0!==e));return 0!==t.length?t.find((e=>e.refName.endsWith("^{}")))?.sha??t[0].sha:void 0}async function Vu(e,t,r){const o=t.trim();if(zu.test(o))return{fullSha:o.toLowerCase()};if(qu.test(o)){try{const t=await async function(e,t,r){const{stdout:o}=await Hu(["ls-remote",e,`refs/heads/${t}`,`refs/tags/${t}`,`refs/tags/${t}^{}`],{sshBatchMode:r?.sshBatchMode,extraGitConfig:r?.extraGitConfig,timeoutMs:r?.timeoutMs});return Gu(o)?.toLowerCase()}(e,o,r);if(t)return{fullSha:t}}catch{}return{fullSha:o.toLowerCase()}}let n;try{if("HEAD"===o.toUpperCase()){const t=await Hu(["ls-remote","--symref",e,"HEAD"],{sshBatchMode:r?.sshBatchMode,extraGitConfig:r?.extraGitConfig,timeoutMs:r?.timeoutMs}),o=Gu(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=(await Hu(["ls-remote",e,o],{sshBatchMode:r?.sshBatchMode,extraGitConfig:r?.extraGitConfig,timeoutMs:r?.timeoutMs})).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=Gu(n);if(!s)throw new Error(`git ls-remote did not return a resolvable commit for ref "${o}" (${e})`);return{fullSha:s.toLowerCase()}}const Ju=Cl.map((e=>e.split("/")[0]));let Ku;function Zu(e){let t=e.trim().replaceAll("\\","/");for(;t.startsWith("./");)t=t.slice(2);return t=t.replace(/\/+$/,""),""===t||"."===t||t.startsWith("/")||/^[a-zA-Z]:/.test(t)||t.split("/").some((e=>""===e||"."===e||".."===e))?null:t}function Xu(e){const t=[];for(const r of e){const e=Zu(r);if(null===e)return"all";t.push(e)}return t}async function Qu(e,t){const r="all"===e?"all":Xu(e),o=t&&"all"!==r&&await(process.env.CURSOR_DISABLE_SPARSE_PLUGIN_CLONES?Promise.resolve(!1):(Ku??=(async()=>{try{const{stdout:e}=await Hu(["--version"]),t=function(e){const t=/git version (\d+)\.(\d+)/.exec(e);return t?{major:Number(t[1]),minor:Number(t[2])}:null}(e);return null!==t&&(t.major>2||2===t.major&&t.minor>=28)}catch{return!1}})(),Ku));return{materialize:r,sparse:o,sparseDirs:o?(n=r,[...new Set([...Ju,...n])]):[]};var n}function Yu(e){return e.toLowerCase().includes("filtering not recognized by server")}async function ed(e,t,r){await Hu(["sparse-checkout","set","--cone","--",...t],{...r,cwd:e})}async function td(e){try{await(0,Os.access)((0,s.join)(e,".git","info","sparse-checkout"))}catch{return!1}try{const{stdout:t}=await Hu(["config","--bool","--get","core.sparseCheckout"],{cwd:e});return"true"===t.trim()}catch{return!1}}async function rd(e,t,r){if("all"!==t&&0===t.length)return;if(!await td(e))return;const o={...r,cwd:e,sshBatchMode:!0};if("all"===t)return void await Hu(["sparse-checkout","disable"],o);const n=Xu(t);"all"!==n?await Hu(["sparse-checkout","add","--",...n],o):await Hu(["sparse-checkout","disable"],o)}(0,Xs.J)((function(){Ku=void 0}));const od=/\.git$/i,nd=new Set(["account","dashboard"]);function sd(e){return e.replace(od,"")}function id(e){let t;try{t=decodeURIComponent(e)}catch{return}return t.length>0&&!t.includes("/")?t:void 0}function ad(e){const t=e.toLowerCase();return"github.com"===t||t.endsWith(".github.com")}function cd(e){return e.toLowerCase().split(".").includes("gitlab")}function ld(e){const t=e.toLowerCase();return"bitbucket.org"===t||"www.bitbucket.org"===t}function ud(e){const t=e.toLowerCase();return cd(e)?"GitLab":t.includes("bitbucket")?"Bitbucket":t.includes("gitea")||t.includes("codeberg")?"Gitea/Codeberg":t.includes("azure")&&t.includes("dev")?"Azure DevOps":null}function dd(e){return ad(e)?"github":cd(e)?"gitlab":ld(e)?"bitbucket":function(e){const t=e.toLowerCase();return"dev.azure.com"===t||"www.dev.azure.com"===t}(e)?"azure_devops":"generic"}function hd(e){let t;try{const r=e.startsWith("git@")?`ssh://${e.replace(":","/")}`:e;t=new URL(r.includes("://")?r:`https://${r}`)}catch{return null}const r=t.hostname;let o=t.pathname.split("/").filter(Boolean);$a(r)&&"git"===o[0]?.toLowerCase()&&(o=o.slice(1)),o.length>=3&&"scm"===o[0].toLowerCase()&&(o=o.slice(1));const n=function(e){const t=e[0],r=e[1];if(!t||!r)return;const o=sd(r);return o?{owner:t,repo:o,hasSubpath:e.length>2}:void 0}(o);return void 0===n?null:{provider:dd(r),owner:n.owner,repo:n.repo,host:r}}function pd(e){const t=fd(e);if(null===t)return!1;const r=t.pathname.split("/").filter(Boolean);return r.length>=3&&"scm"===r[0].toLowerCase()}function fd(e){try{const t=e.startsWith("git@")?`ssh://${e.replace(":","/")}`:e;return new URL(t.includes("://")?t:`https://${t}`)}catch{return null}}function md(e){const t=e.trim();if(""===t)return{error:"URL cannot be empty"};const r=hd(t);if(null===r)return{error:"Invalid URL format. Expected: github.com/owner/repo or gitlab.com/namespace/repo"};if(cd(r.host)){const e=fd(t),r=null===e?void 0:function(e){const t=e.indexOf("-"),r=-1!==t,o=r?e.slice(0,t):[...e];if(o.length<2||o.some((e=>0===e.length)))return;const n=sd(o[o.length-1]);return n?(o[o.length-1]=n,{repositorySegments:o,hasSpecialRouteSeparator:r}):void 0}(e.pathname.split("/").filter(Boolean));if(null===e||void 0===r)return{error:"Invalid GitLab repository URL format. Expected: https://gitlab.com/namespace/repo"};const o=e.host.replace(/^www\./i,"");return{url:`https://${o}/${r.repositorySegments.join("/")}`,owner:r.repositorySegments[0],repo:r.repositorySegments[r.repositorySegments.length-1],host:o,provider:"gitlab"}}if("bitbucket"===r.provider){const e=function(e){const t=fd(e.trim());if(null!==t&&ld(t.hostname))return function(e){const t=e[0],r=e[1];if(void 0===t||void 0===r)return;const o=id(t),n=id(r);if(void 0===o||void 0===n||nd.has(o.toLowerCase()))return;const s=sd(n);return s?{workspace:encodeURIComponent(o),repo:encodeURIComponent(s),hasSubpath:e.length>2}:void 0}(function(e){const t=e.pathname.split("/");return""===t[0]&&t.shift(),""===t[t.length-1]&&t.pop(),t}(t))}(t);if(void 0===e)return{error:"Invalid Bitbucket repository URL format. Expected: https://bitbucket.org/{workspace}/{repo}"};const o=r.host.replace(/^www\./i,"");return{url:`https://${o}/${e.workspace}/${e.repo}`,owner:e.workspace,repo:e.repo,host:o,provider:"bitbucket"}}if("azure_devops"===r.provider){const e=fd(t),o=null===e?void 0:function(e){const t=e.findIndex((e=>"_git"===e.toLowerCase()));if(t<1||t>2)return;const r=e[0],o=e[t+1];if(!r||!o)return;const n=sd(o);if(!n)return;const s=2===t?e[1]:n;return s?{organization:r,project:s,repo:n,hasSubpath:e.length>t+2}:void 0}(e.pathname.split("/").filter(Boolean));if(null===e||void 0===o)return{error:"Invalid Azure DevOps repository URL format. Expected: https://dev.azure.com/{organization}/{project}/_git/{repo}"};const n=r.host.replace(/^www\./i,"");return{url:`https://${n}/${o.organization}/${o.project}/_git/${o.repo}`,owner:o.organization,repo:o.repo,host:n,provider:"azure_devops",project:o.project}}if(function(e){switch(e.provider){case"github":return!0;case"generic":return!$a(e.host)&&null===ud(e.host);case"gitlab":case"bitbucket":case"azure_devops":return!1;default:return e.provider,!1}}(r)){const e=wd(r.host.replace(/^www\./i,""));return{url:`https://${e}/${pd(t)?"scm/":""}${r.owner}/${r.repo}`,owner:r.owner,repo:r.repo,host:e,provider:"github"}}const o=ud(r.host);return{error:"Only GitHub, GitLab, Bitbucket, and Azure DevOps URLs are currently supported."+(null!==o?` ${o} is not supported yet.`:"")}}function gd(e){const t=md(e);if("error"in t)return null;switch(t.provider){case"github":return`git@${t.host}:${t.owner}/${t.repo}.git`;case"gitlab":return function(e){let t;try{t=new URL(e.url).pathname.replace(/^\//,"").replace(/\.git$/i,"")}catch{return null}if(0===t.length)return null;return`git@${e.host.replace(/:\d+$/,"")}:${t}.git`}(t);case"bitbucket":case"azure_devops":return null;default:return t.provider,null}}function wd(e){return ad(e)?"github.com":e}function yd(e){return!e.operatingSystems||0===e.operatingSystems.length||e.operatingSystems.includes(function(){const e=(0,n.platform)();return"win32"===e?"Windows":"darwin"===e?"Macintosh":"Linux"}())}function vd(e){return/[\n\r:#[\]{}&*!|>'"%@`]/.test(e)||e.startsWith(" ")||e.endsWith(" ")?`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:e}function bd(e,t){const r=(0,s.resolve)(e),o=(0,s.resolve)(e,t),n=(0,s.relative)(r,o);if(n.startsWith("..")||(0,s.isAbsolute)(n))throw new Error(`Invalid subPath: path traversal not allowed (${JSON.stringify(t)})`);return o}const Sd=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 kd(e){const t=Wt(e).replace(/[. ]+$/g,"");return""===t||"."===t||".."===t?"_":Sd.has(t.toLowerCase())?`_${t}`:t}const Ed=18e5,Cd=6e5,xd={recursive:!0,force:!0,maxRetries:3},_d=["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"],Pd=["enotempty: directory not empty, rename","/_staging/"],Id=["upload-pack: not our ref","server does not allow request for unadvertised object"];function Rd(e){const t=String(e).toLowerCase().replaceAll("\\","/");return _d.some((e=>t.includes(e)))?"user_git_access":Pd.every((e=>t.includes(e)))?"local_cache_race":Id.some((e=>t.includes(e)))?"stale_pinned_ref":"infrastructure"}function Td(e){return"object"==typeof e&&null!==e&&(!0===e.killed||Td(e.cause))}function Ad(e){return Td(e)?"killed_by_budget":Rd(e)}function Md(e){const t=md(e);if(!("error"in t)&&"gitlab"===t.provider){let r;try{r=new URL(t.url).pathname.replace(/^\//,"")}catch{throw new Error(`Invalid git URL: ${e}`)}const o=r.split("/").filter(Boolean).map((e=>e.toLowerCase()));if(o.length<2)throw new Error(`Invalid git URL: ${e}`);return{host:t.host.toLowerCase(),pathSegments:o}}const r=hd(e);if(null===r)throw new Error(`Invalid git URL: ${e}`);return{host:wd(r.host.replace(/^www\./i,"")).toLowerCase(),pathSegments:[r.owner.toLowerCase(),r.repo.toLowerCase()]}}const Dd=new Map;class Od{constructor(e,t){this.cacheRoot=e,this.options=t,this.manifestCache=new Map}get sparsePluginClones(){return this.options?.sparsePluginClones??!1}remoteTimeoutMs(){return this.sparsePluginClones?Ed:void 0}localTimeoutMs(){return this.sparsePluginClones?Cd:void 0}lsRemoteTimeoutMs(){return this.sparsePluginClones?3e4:void 0}async cloneResolvedRef(e,t,r,o){const n={cwd:e,sshBatchMode:o?.sshBatchMode,extraGitConfig:{...Wu(this.options?.extraGitConfig),"safe.directory":e}},{sparse:s,sparseDirs:i}=await Qu(o?.materialize??"all",this.sparsePluginClones);await Hu(["init"],{...n,timeoutMs:this.localTimeoutMs()}),s&&await ed(e,i,{sshBatchMode:o?.sshBatchMode,extraGitConfig:Wu(this.options?.extraGitConfig),timeoutMs:this.localTimeoutMs()});const{stderr:a}=await Hu(["fetch","--depth","1",...s?["--filter=blob:none"]:[],t,r],{...n,timeoutMs:this.remoteTimeoutMs()});return await Hu(["checkout","FETCH_HEAD"],{...n,timeoutMs:this.remoteTimeoutMs()}),{strategy:s?"sparse":"full",filterIgnoredByServer:s&&Yu(a??"")}}async createStagingDir(){const e=(0,s.join)(this.cacheRoot,"_staging",(0,Ts.randomUUID)());return await(0,Os.mkdir)(e,{recursive:!0}),e}async moveToCanonicalDir(e,t){return await(0,Os.mkdir)((0,s.dirname)(t),{recursive:!0}),await(0,Os.rm)(t,xd),await(0,Os.rename)(e,t),t}async cleanStaleStagingDirs(){const e=(0,s.join)(this.cacheRoot,"_staging");try{const t=await(0,Os.readdir)(e,{withFileTypes:!0}),r=Date.now();await Promise.all(t.filter((e=>e.isDirectory())).map((async t=>{try{const o=(0,s.join)(e,t.name),n=await(0,Os.stat)(o);r-n.mtimeMs>Od.STALE_STAGING_THRESHOLD_MS&&await(0,Os.rm)(o,xd)}catch{}})))}catch{}}getLegacyCloneDir(e,t){return(0,s.join)(this.cacheRoot,kd(e),kd(t))}getCanonicalCloneDir(e,t){const{host:r,pathSegments:o}=Md(e);return(0,s.join)(this.cacheRoot,kd(r),...o.map(kd),kd(t))}getCanonicalRepoRootDir(e){const{host:t,pathSegments:r}=Md(e);return(0,s.join)(this.cacheRoot,kd(t),...r.map(kd))}async pruneSiblingCloneDirs(e,t,r){const o=this.getCanonicalRepoRootDir(e),n=kd(t);try{const e=await(0,Os.readdir)(o,{withFileTypes:!0});await Promise.all(e.filter((e=>e.isDirectory()&&e.name!==n)).map((e=>(0,Os.rm)((0,s.join)(o,e.name),xd))))}catch{}if(void 0!==r)try{await(0,Os.rm)(r,xd)}catch{}}async ensureCloned(e,t,r,o=Jc,n){const s=this.serializedOnRepo(this.getCanonicalRepoRootDir(t),(()=>this.ensureClonedImpl(e,t,r,o,n?.materialize??"all")));return this.sparsePluginClones?s:(0,Ht.wj)(s,3e4,`ensureCloned timed out after 30000ms for ${t} @ ${r}`)}async ensureMaterialized(e,t,r=Jc){const o=this.serializedOnRepo((0,s.dirname)(e),(async()=>{const o=performance.now();try{await rd(e,t,{extraGitConfig:Wu(this.options?.extraGitConfig),timeoutMs:this.remoteTimeoutMs()}),r.increment("marketplace_cache_manager.ensure_materialized.success",1),r.distribution("marketplace_cache_manager.ensure_materialized.duration",performance.now()-o)}catch(n){throw r.log("error","Failed to materialize plugin directories in sparse marketplace clone",{clonePath:e,spec:"all"===t?"all":t.join(","),error:String(n),errorCategory:Ad(n)}),r.increment("marketplace_cache_manager.ensure_materialized.error",1,{error_category:Ad(n)}),r.distribution("marketplace_cache_manager.ensure_materialized.duration",performance.now()-o,{outcome:"error"}),n}}));return this.sparsePluginClones?o:(0,Ht.wj)(o,3e4,`ensureMaterialized timed out after 30000ms for ${e}`)}async serializedOnRepo(e,t){const r=`${this.cacheRoot}:${e}`,o=(Dd.get(r)??Promise.resolve()).catch((()=>{})).then(t);Dd.set(r,o);try{return await o}finally{Dd.get(r)===o&&Dd.delete(r)}}async ensureClonedImpl(e,t,r,o,n){o.log("info",`MarketplaceCacheManager: Ensuring cloned ${e} at ${t}@${r}`,{marketplaceId:e,gitUrl:t,ref:r});const s=r.trim();let i,a=t.startsWith("git@")||t.startsWith("ssh://")?null:gd(t);if(null!==a)try{i=(await Vu(a,s,{sshBatchMode:!0,extraGitConfig:Wu(this.options?.extraGitConfig),timeoutMs:this.lsRemoteTimeoutMs()})).fullSha}catch(e){if(this.sparsePluginClones&&Td(e))throw e;o.log("debug","Failed to resolve remote ref using SSH URL, falling back to HTTPS",{gitUrl:t,ref:r,error:String(e),errorCategory:Rd(e)}),a=null,i=(await Vu(t,s,{extraGitConfig:Wu(this.options?.extraGitConfig),timeoutMs:this.lsRemoteTimeoutMs()})).fullSha}else i=(await Vu(t,s,{extraGitConfig:Wu(this.options?.extraGitConfig),timeoutMs:this.lsRemoteTimeoutMs()})).fullSha;const c=this.getCanonicalCloneDir(t,i),l=this.getLegacyCloneDir(e,s);o.log("info",`MarketplaceCacheManager: Resolved clone directory for ${e} at ${t}@${r} to ${c}`,{marketplaceId:e,resolvedRef:i,originalRef:s});const u=performance.now(),d=(e,t)=>{o.increment(`marketplace_cache_manager.ensure_cloned.${e}`,1,t),o.distribution(`marketplace_cache_manager.ensure_cloned.${e}.duration`,performance.now()-u,t)};if(await this.isCloneComplete(c)){await this.pruneSiblingCloneDirs(t,i,l);const e=await td(c);return e&&await rd(c,n,{extraGitConfig:Wu(this.options?.extraGitConfig),timeoutMs:this.remoteTimeoutMs()}),d("cache_hit",{strategy:e?"sparse":"full"}),c}return o.increment("marketplace_cache_manager.ensure_cloned.cache_miss",1),this.cloneViaStaging(c,t,a,i,l,r,o,d,n)}async cloneViaStaging(e,t,r,o,n,s,i,a,c){await this.cleanStaleStagingDirs();const l=await this.createStagingDir();i.log("info",`MarketplaceCacheManager: Cloning ${t}@${s} into staging directory: ${l}`,{gitUrl:t,ref:s,cloneDir:e});const u=this.sparsePluginClones?setInterval((()=>{const e=new Date;(0,Os.utimes)(l,e,e).catch((()=>{}))}),Od.STAGING_HEARTBEAT_INTERVAL_MS):void 0;u?.unref?.();try{let u;if(null!==r)try{u=await this.cloneResolvedRef(l,r,o,{sshBatchMode:!0,materialize:c})}catch(e){if(this.sparsePluginClones&&Td(e))throw e;i.log("debug","Falling back to HTTPS clone due to SSH clone failure",{gitUrl:t,ref:s,error:String(e),errorCategory:Ad(e)}),await(0,Os.rm)(l,xd),await(0,Os.mkdir)(l,{recursive:!0}),u=await this.cloneResolvedRef(l,t,o,{materialize:c})}else u=await this.cloneResolvedRef(l,t,o,{materialize:c});u.filterIgnoredByServer&&(i.log("warn","Server ignored --filter=blob:none; sparse clone downloaded a full pack",{gitUrl:t,ref:s}),i.increment("marketplace_cache_manager.ensure_cloned.filter_ignored_by_server",1));const d=await this.moveToCanonicalDir(l,e);return await this.pruneSiblingCloneDirs(t,o,n),a("cache_write_success",{strategy:u.strategy}),d}catch(e){const r=Ad(e);throw a("error",{error_category:r}),i.log("error","Failed to clone marketplace repository via staging clone",{gitUrl:t,ref:s,error:String(e),errorCategory:r}),i.captureException(e,{error_type:"clone_marketplace_repository",error_category:r}),e}finally{void 0!==u&&clearInterval(u);try{await(0,Os.rm)(l,xd)}catch{}}}async isCloneComplete(e){try{if(!(await(0,Os.stat)(e)).isDirectory())return!1;const t=await(0,Os.readdir)(e);if(!t.includes(".git"))return!1;if(t.length>1)return!0;try{return(await(0,Os.stat)((0,s.join)(e,".git","info","sparse-checkout"))).isFile()}catch{return!1}}catch{return!1}}getPluginDir(e,t){return bd(e,t)}async copyPluginToDir(e,t){await(0,Os.mkdir)(t,{recursive:!0}),await(0,Os.cp)(e,t,{recursive:!0,verbatimSymlinks:!0})}async readManifest(e,t={}){const r=function(e,t){return JSON.stringify({clonePath:e,repoName:t.repoName??null,fallbackId:t.fallbackId??null})}(e,t);if(this.manifestCache.has(r))return this.manifestCache.get(r)??null;const o=await async function(e,t={}){for(const r of Cl){const o=(0,s.join)(e,r);let n;try{n=await(0,Os.readFile)(o,"utf-8")}catch{continue}const i=Ql(n,t);if(i.success)return i.data}return null}(e,t);return this.manifestCache.set(r,o),o}async resolvePluginPath(e,t){const r=await this.readManifest(e);if(!r)return null;const o=r.plugins.find((e=>e.name===t.toLowerCase()));if(!o)return null;const n=eu(o.source,r.metadata?.pluginRoot);return n&&tu(n)?n:null}async discoverPlugins(e){const t=await this.readManifest(e);return t?function(e){const t=[],r=function(e,t){const r=[];for(const o of e){const e=o.source;if("string"!=typeof e)switch(e.source){case"github":r.push({entry:o,kind:"external-github",externalUrl:`https://github.com/${e.repo}.git`,externalRef:e.ref,externalSha:e.sha,effectiveRef:e.sha??e.ref});break;case"url":r.push({entry:o,kind:"external-url",externalUrl:e.url,externalRef:e.ref,externalSha:e.sha,effectiveRef:e.sha??e.ref});break;case"git-subdir":r.push({entry:o,kind:"external-git-subdir",externalUrl:e.url,externalRef:e.ref,externalSha:e.sha,effectiveRef:e.sha??e.ref,subdirPath:e.path})}else{const n=eu(e,t);null!==n?r.push({entry:o,kind:"local",localPath:n}):r.push({entry:o,kind:"unresolvable",rawSource:e})}}return r}(e.plugins,e.metadata?.pluginRoot);for(const e of r){const{name:r,displayName:o,description:n,version:s}=e.entry,i={name:r,displayName:o,description:n,version:s};switch(e.kind){case"local":tu(e.localPath)&&t.push({...i,sourceType:"local",gitPath:e.localPath});break;case"external-github":t.push({...i,sourceType:"github",gitUrl:e.externalUrl,gitRef:e.externalRef,sha:e.externalSha});break;case"external-url":t.push({...i,sourceType:"url",gitUrl:e.externalUrl,gitRef:e.externalRef,sha:e.externalSha});break;case"external-git-subdir":t.push({...i,sourceType:"git-subdir",gitUrl:e.externalUrl,gitRef:e.externalRef,sha:e.externalSha,subdirPath:e.subdirPath})}}return t}(t):[]}}Od.STALE_STAGING_THRESHOLD_MS=3e5,Od.STAGING_HEARTBEAT_INTERVAL_MS=6e4;const Nd=(0,ji.debuglog)("cursor-plugins");function $d(e){const t=e.name?.trim();return void 0!==t&&t.length>0?t:e.pluginId}function Fd(e,t){return void 0!==e?.marketplace?e.marketplace:void 0!==e?.marketplaceId?(t??[]).find((t=>void 0!==t.id&&String(t.id)===String(e.marketplaceId))):void 0}function jd(e,t){const r=t?.distributionGitUrl?.trim();return r?t?.gitUrl&&!Kd(e,t.gitUrl)?e:r:e}function Ld(e){return e?.distributionGitUrl?.trim()||e?.gitUrl}function Ud(e,t){if(e.pinnedGitRef)return e.pinnedGitRef;if(e.plugin?.gitRef)return e.plugin.gitRef;const r=Fd(e.plugin,t),o=e.plugin?.gitUrl,n=r?.gitUrl;return o&&n&&o!==n||!r?.gitRef?"main":r.gitRef}const Bd="backend-git://";function Wd(e,t,r){const o=r?`#${encodeURIComponent(r)}`:"";return`${Bd}${encodeURIComponent(e)}@${encodeURIComponent(t)}${o}`}function Hd(e){if(!e.startsWith(Bd))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}}const qd="backend-release://";function zd(e){const t=e.tag?`@${encodeURIComponent(e.tag)}`:"";return`${qd}${encodeURIComponent(e.repo)}#${encodeURIComponent(e.asset)}${t}`}function Gd(e){if(!e.startsWith(qd))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 Vd=/^[0-9a-f]{7,40}$/i;function Jd(e){let t;try{t=Md(e)}catch{return null}return`${t.host}\0${t.pathSegments.join("\0")}`}function Kd(e,t){if(e.trim()===t.trim())return!0;const r=Jd(e),o=Jd(t);return null!==r&&r===o}const Zd=104857600;async function Xd(e,t,r,o,i,a){const c=await async function(e){const{repo:t,asset:r,tag:o}=e,{apiBase:n,ownerRepo:s,host:i}=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),a="github.com"===i&&void 0!==e.githubToken&&e.githubToken.length>0?{Authorization:`token ${e.githubToken}`}:{},c=o?`${n}/repos/${s}/releases/tags/${encodeURIComponent(o)}`:`${n}/repos/${s}/releases/latest`,l=await fetch(c,{headers:{Accept:"application/vnd.github.v3+json","User-Agent":"CursorPluginInstaller",...a}});if(!l.ok)throw new Error(`Failed to fetch release from ${c}: ${l.status} ${l.statusText}`);const u=await l.json(),d=u.assets.find((e=>e.name===r));if(!d){const e=u.assets.map((e=>e.name)).join(", ");throw new Error(`Release asset "${r}" not found. Available assets: ${e}`)}if(d.size>Zd)throw new Error(`Release asset "${r}" exceeds maximum size of 104857600 bytes (actual: ${d.size})`);const h=new URL(d.browser_download_url);if("https:"!==h.protocol||!Qd(h.hostname,i))throw new Error(`Refusing to download release asset from untrusted host: ${h.hostname}`);const p=await fetch(d.browser_download_url,{headers:{"User-Agent":"CursorPluginInstaller",Accept:"application/octet-stream",...a}});if(!p.ok)throw new Error(`Failed to download release asset: ${p.status} ${p.statusText}`);if(p.url){const e=new URL(p.url);if("https:"!==e.protocol||!Qd(e.hostname,i))throw new Error(`Refusing to download release asset: redirected to untrusted host: ${e.hostname}`)}const f=Buffer.from(await p.arrayBuffer());if(f.byteLength>Zd)throw new Error(`Release asset "${r}" actual download size exceeds maximum of 104857600 bytes (actual: ${f.byteLength})`);if(e.expectedSha256){const t=(0,Ts.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:i,githubToken:a}),l=c.byteLength;await(0,Os.mkdir)(o,{recursive:!0});const u=await(0,Os.mkdtemp)((0,s.join)((0,n.tmpdir)(),"release-asset-")),d=(0,s.join)(u,"asset.tar.gz"),h=(0,s.join)(u,"extracted");try{await(0,Os.writeFile)(d,c),await(0,Os.mkdir)(h,{recursive:!0});let e=0,t=0;await Su.x({file:d,cwd:h,onReadEntry:r=>{if(t++,t>5e4)throw new Error("Release archive contains too many files (>50000).");if(e+=r.size,e>524288e3)throw new Error("Release archive uncompressed size exceeds maximum of 524288000 bytes.");if(l>0&&e/l>100)throw new Error("Release archive has suspicious compression ratio (>100x).")}});const r=await(0,Os.readdir)(h,{withFileTypes:!0}),n=r.filter((e=>e.isDirectory())),i=r.filter((e=>e.isFile()));let a=h;if(1===n.length&&0===i.length){const e=(0,s.join)(h,n[0].name);(await(0,Os.readdir)(e)).some((e=>El.includes(e)))&&(a=e)}const u=await(0,Os.readdir)(a);await Promise.all(u.map((e=>(0,Os.cp)((0,s.join)(a,e),(0,s.join)(o,e),{recursive:!0,verbatimSymlinks:!0}))))}finally{await(0,Os.rm)(u,{recursive:!0,force:!0}).catch((()=>{}))}}function Qd(e,t){return!(e!==t&&!e.endsWith(".githubusercontent.com"))||("github.com"===t?"github.com"===e:e.endsWith(`.${t}`))}class Yd{constructor(e,t,r,o,n){this.getEffectiveUserPlugins=e;const s="string"==typeof t||void 0===t?{marketplaceCacheRoot:t,pluginLogger:r,marketplaceCacheOptions:o,listOptions:n}:t,i=s.marketplaceCacheOptions??o;this.pluginLogger=s.pluginLogger??r??Jc,this.extraGitConfig=s.extraGitConfig,this.awaitAuthReady=s.awaitAuthReady,this.githubToken=s.githubToken,this.sparsePluginClones=s.sparsePluginClones??!1,this.marketplaceCache=s.marketplaceCacheRoot?new Od(s.marketplaceCacheRoot,{...i,extraGitConfig:i?.extraGitConfig??s.extraGitConfig,sparsePluginClones:this.sparsePluginClones}):void 0;const a=s.listOptions??n;this.allowedMarketplaceNames=a?.allowedMarketplaceNames?new Set(a.allowedMarketplaceNames):void 0,this.enableInlinePlugins=a?.enableInlinePlugins??!1}isMarketplaceAllowed(e){return void 0===this.allowedMarketplaceNames||void 0!==e?.name&&this.allowedMarketplaceNames.has(e.name)}async listEnabledPlugins(e,t){const r=await this.getEffectiveUserPlugins(),o=r.plugins??[],n=r.marketplaces??[],s=[],i=[],a=new Map,c=async(e,t)=>{const r=`${e}\0${t}`;let o=a.get(r);if(!o){const n=Wu(this.extraGitConfig),s=this.sparsePluginClones?3e4:void 0,i=e.startsWith("git@")||e.startsWith("ssh://")?null:gd(e),c=async(e,r)=>{const o={};return r&&(o.sshBatchMode=!0),void 0!==n&&(o.extraGitConfig=n),void 0!==s&&(o.timeoutMs=s),(Object.keys(o).length>0?await Vu(e,t,o):await Vu(e,t)).fullSha};if(null!==i)try{o=await c(i,!0)}catch(t){if(this.sparsePluginClones&&Td(t))throw t;o=await c(e,!1)}else o=await c(e,!1);a.set(r,o)}return o},l=async e=>{const{preferredGitUrl:t,sourceGitUrl:r,gitRef:o,pluginId:n}=e;if(t!==r){void 0!==this.awaitAuthReady&&await this.awaitAuthReady();const e=`${t}\0${o}`,s=!a.has(e);let i;s&&this.pluginLogger.increment("marketplace.origin_distribution.fetch",1);try{i={sha:await c(t,o),gitUrl:t}}catch(e){s&&this.pluginLogger.increment("marketplace.origin_distribution.fetch.error",1),this.pluginLogger.captureException(e,{error_type:"distribution_url_fallback"}),this.pluginLogger.log("warn",`Distribution mirror ${t}@${o} unavailable (not synced yet or unreachable); falling back to source ${r}`,{pluginId:n,preferredGitUrl:t,sourceGitUrl:r,gitRef:o,error:String(e)})}if(void 0!==i){if(s)try{this.pluginLogger.log("info",`Resolved plugin ${n} from Origin distribution mirror ${t}@${o}`,{pluginId:n,preferredGitUrl:t,gitRef:o})}catch{}return i}}return{sha:await c(r,o),gitUrl:r}};for(const e of o){if(!e.isEnabled||!e.plugin?.name)continue;const t=e.plugin,r=Fd(t,n);if(!this.isMarketplaceAllowed(r)){this.pluginLogger.log("info",`Skipping plugin ${t.name} because marketplace ${r?.name??"<none>"} is not allowed`,{pluginId:t.name,marketplaceName:r?.name,allowedMarketplaceNames:void 0!==this.allowedMarketplaceNames?Array.from(this.allowedMarketplaceNames):void 0});continue}const o=$d({name:t.name,pluginId:void 0!==t.id?String(t.id):t.name??""}),a=o;if(!t.gitUrl){if(!this.enableInlinePlugins){this.pluginLogger.log("info",`Skipping plugin ${o} without gitUrl (enableInlinePlugins=false)`,{pluginId:a});continue}const n=e.inlineContentJson;if(!n){this.pluginLogger.log("info",`Skipping DB-inline plugin ${o}: no inline content provided`,{pluginId:a});continue}const i=(0,Ts.createHash)("sha256").update(`${t.id??"0"}:${t.updatedAt??"0"}`).digest("hex").slice(0,40),c=r?.name?{id:void 0!==r.id?`${r.name}-${r.id}`:`${r.name}-inline`,name:r.name}:void 0;this.pluginLogger.log("info",`BackendMarketplaceClient: Adding DB-inline plugin: ${a}`,{pluginId:a,marketplaceId:c?.id??"unknown",version:i}),s.push({pluginId:a,pluginDbId:void 0!==t.id?String(t.id):void 0,configuredVariables:e.configuredVariables,isTeamRequired:e.isTeamRequired,name:o,version:i,downloadUrl:`inline://${t.id??a}`,marketplaceDbId:void 0!==r?.id?String(r.id):void 0,marketplace:c,inlineContentJson:n});continue}const c=t.gitUrl,u=jd(c,r),d=Ud(e,n),h=Pu(t,d),p=r?.gitRef??d;let f,m,g=u;try{if(void 0!==h)f=`release/${h.releaseTag}`;else{const e=await l({preferredGitUrl:u,sourceGitUrl:c,gitRef:d,pluginId:a});f=e.sha,g=e.gitUrl}}catch(e){this.pluginLogger.captureException(e,{error_type:"resolve_version_sha"}),this.pluginLogger.log("error",`Failed to resolve version for plugin ${o}@${d}, skipping plugin`,{pluginId:a,ref:d,error:String(e)});const n=e instanceof Error?e.message:String(e);i.push({pluginName:o,pluginId:a,pluginDbId:void 0!==t.id?String(t.id):void 0,marketplaceName:r?.name,errorMessage:n,errorType:/timed?\s*out/i.test(n)?"timeout":"clone"});continue}m=void 0!==h?zd({repo:h.releaseRepo,asset:h.releaseAsset,tag:h.releaseTag}):Wd(g,d,t.gitPath??void 0);const w=Ld(r);let y=w,v=r?.gitUrl,b=p;if(r?.gitUrl&&w){const e=Kd(c,r.gitUrl),t=e?g:w,n=e?c:r.gitUrl,s=e?d:p;v=n;try{const e=await l({preferredGitUrl:t,sourceGitUrl:n,gitRef:s,pluginId:a});b=e.sha,y=e.gitUrl}catch(e){this.pluginLogger.captureException(e,{error_type:"resolve_marketplace_cache_ref"}),this.pluginLogger.log("warn",`Failed to resolve marketplace cache ref for plugin ${o} from ${t}@${s}, falling back to raw ref`,{pluginId:a,cacheRepoUrl:t,cacheRef:s,error:String(e)}),y=n}}const S=r?.name?{id:void 0!==r.id?`${r.name}-${r.id}`:`${r.name}-${encodeURIComponent(r.gitUrl??"project")}`,name:r.name,...y&&{gitUrl:y,gitRef:b}}:void 0,k=void 0!==h||g===c&&y===v?void 0:{downloadUrl:Wd(c,d,t.gitPath??void 0),marketplaceGitUrl:v};this.pluginLogger.log("info",`BackendMarketplaceClient: Adding enabled plugin: ${a} from ${b} at ${t.gitPath}`,{pluginId:a,marketplaceId:S?.id??"unknown",gitPath:t.gitPath??void 0,gitRef:b}),s.push({pluginId:a,pluginDbId:void 0!==t.id?String(t.id):void 0,configuredVariables:e.configuredVariables,isTeamRequired:e.isTeamRequired,name:o,version:f,downloadUrl:m,marketplaceDbId:void 0!==r?.id?String(r.id):void 0,marketplace:S,gitPath:t.gitPath??void 0,isOriginBacked:void 0===h&&g!==c||void 0,originSourceFallback:k})}return{plugins:s,listFailures:i}}isDirectInstallSameFetch(e){const t=e.marketplace;if(!t?.gitUrl||!t.gitRef)return!1;const r=Hd(e.downloadUrl);return!(!r||!Kd(r.gitUrl,t.gitUrl)||r.ref!==t.gitRef&&e.version!==t.gitRef)}async installPlugin(e,t){if(e.inlineContentJson)await async function(e){const{targetDir:t,inlineContentJson:r,pluginName:o}=e,n=JSON.parse(r);await(0,Os.mkdir)(t,{recursive:!0});const i={};if(n.rules&&n.rules.length>0){const e=(0,s.join)(t,"rules");await(0,Os.mkdir)(e,{recursive:!0});const r=[];for(const t of n.rules){if(!t.content)continue;if(!1===t.isActive)continue;const o=`${Wt(t.name)}.md`,n=[];n.push(`description: ${vd(t.name)}`),t.globs&&t.globs.length>0&&n.push(`globs: ${vd(t.globs.join(", "))}`),n.push(`alwaysApply: ${!0===t.isRequired}`);const i=`---\n${n.join("\n")}\n---\n\n`;await(0,Os.writeFile)((0,s.join)(e,o),i+t.content,"utf-8"),r.push(`rules/${o}`)}r.length>0&&(i.rules=r)}if(n.commands&&n.commands.length>0){const e=(0,s.join)(t,"commands");await(0,Os.mkdir)(e,{recursive:!0});const r=[];for(const t of n.commands){if(!t.content)continue;if(!1===t.isActive)continue;const o=`${Wt(t.name)}.md`,n=t.description?`---\ndescription: ${vd(t.description)}\n---\n\n`:"";await(0,Os.writeFile)((0,s.join)(e,o),n+t.content,"utf-8"),r.push(`commands/${o}`)}r.length>0&&(i.commands=r)}if(n.hooks&&n.hooks.length>0){const e=(0,s.join)(t,"hooks");await(0,Os.mkdir)(e,{recursive:!0});const r={};for(const e of n.hooks){const t=e.hookStep;t&&!1!==e.isActive&&yd(e)&&(r[t]||(r[t]=[]),"prompt"===e.hookType?r[t].push({type:"prompt",prompt:e.promptContent??"",...e.promptModel?{model:e.promptModel}:{}}):r[t].push({type:"command",command:e.scriptContent??""}))}await(0,Os.writeFile)((0,s.join)(e,"hooks.json"),JSON.stringify({version:1,hooks:r},null,2),"utf-8")}if(n.mcpServers&&n.mcpServers.length>0){const e={};for(const t of n.mcpServers)t.config&&(e[t.name]=t.config);Object.keys(e).length>0&&await(0,Os.writeFile)((0,s.join)(t,".mcp.json"),JSON.stringify({mcpServers:e},null,2),"utf-8")}const a={name:o,...i},c=(0,s.join)(t,".cursor-plugin");await(0,Os.mkdir)(c,{recursive:!0}),await(0,Os.writeFile)((0,s.join)(c,"plugin.json"),JSON.stringify(a,null,2),"utf-8")}({targetDir:t,inlineContentJson:e.inlineContentJson,pluginName:e.name});else{e.isOriginBacked&&void 0!==this.awaitAuthReady&&await this.awaitAuthReady();try{return void await this.installFromEntryUrls(e,t)}catch(r){const o=function(e){const t=e.originSourceFallback;if(void 0===t)return;let r=e.marketplace;if(void 0!==r)if(void 0!==t.marketplaceGitUrl)r={...r,gitUrl:t.marketplaceGitUrl};else{const{gitUrl:e,gitRef:t,...o}=r;r=o}return{...e,downloadUrl:t.downloadUrl,marketplace:r,isOriginBacked:void 0,originSourceFallback:void 0}}(e);if(void 0===o)throw r;this.pluginLogger.captureException(r,{error_type:"install_plugin_from_origin_distribution"}),this.pluginLogger.log("warn",`Failed to install plugin ${e.name} from the Origin distribution mirror, falling back to the source repo`,{pluginId:e.pluginId,version:e.version,sourceDownloadUrl:o.downloadUrl,sourceMarketplaceGitUrl:o.marketplace?.gitUrl,error:String(r)}),this.pluginLogger.increment("marketplace.origin_distribution.install.source_fallback",1),await(0,Os.rm)(t,{recursive:!0,force:!0});try{await this.installFromEntryUrls(o,t)}catch(e){throw this.pluginLogger.increment("marketplace.origin_distribution.install.source_fallback.error",1),e}}}}async installFromEntryUrls(e,t){if(null===Gd(e.downloadUrl))try{if(await this.tryInstallFromMarketplaceCache(e,t))return void this.emitOriginLoadIfApplicable(e)}catch(t){if(this.pluginLogger.captureException(t,{error_type:"install_plugin_from_marketplace_cache"}),this.sparsePluginClones&&this.isDirectInstallSameFetch(e)&&Td(t))throw this.pluginLogger.log("warn",`Failed to install plugin ${e.name} from marketplace cache; skipping direct install fallback because it would repeat the identical fetch`,{pluginId:e.pluginId,version:e.version,error:String(t)}),t;this.pluginLogger.log("warn",`Failed to install plugin ${e.name} from marketplace cache, falling back to direct install`,{pluginId:e.pluginId,version:e.version,error:String(t)})}await async function(e,t,r=Jc,o,i){const a=i?.sparsePluginClones??!1,c=a?Ed:void 0,l=Gd(e.downloadUrl);if(l){if(e.gitPath){const r=await(0,Os.mkdtemp)((0,s.join)((0,n.tmpdir)(),"release-plugin-"));try{await Xd(l.repo,l.asset,l.tag,r,i?.expectedReleaseAssetSha256,i?.githubToken);const o=bd(r,e.gitPath);await(0,Os.mkdir)(t,{recursive:!0}),await(0,Os.cp)(o,t,{recursive:!0,verbatimSymlinks:!0})}finally{await(0,Os.rm)(r,{recursive:!0,force:!0}).catch((()=>{}))}}else await Xd(l.repo,l.asset,l.tag,t,i?.expectedReleaseAssetSha256,i?.githubToken);return}const u=Hd(e.downloadUrl);if(!u)throw new Error(`Invalid download URL format for plugin ${e.pluginId}: ${e.downloadUrl}`);const d=await(0,Os.mkdtemp)((0,s.join)((0,n.tmpdir)(),"backend-plugin-"));try{let n;if(await async function(e,t,r,o=Jc,n,s="all",i=!1){const a=performance.now(),c=Vd.test(t),l="HEAD"===t.toUpperCase(),u={...n,"safe.directory":r},d=i?Ed:void 0,h=i?Cd:void 0,{sparse:p,sparseDirs:f}=await Qu(s,i),m=p?["--filter=blob:none","--sparse"]:[],g=!!p||void 0,w=async e=>{p&&await ed(r,f,{extraGitConfig:u,timeoutMs:e,sshBatchMode:!0})},y=async(e,o)=>{let n="";return l?(({stderr:n}=await Hu(["clone","--depth","1",...m,e,r],{extraGitConfig:u,timeoutMs:d,sshBatchMode:o})),await w(d)):c?(await Hu(["init"],{cwd:r,extraGitConfig:u,timeoutMs:h}),await Hu(["remote","add","origin",e],{cwd:r,extraGitConfig:u,timeoutMs:h}),await w(h),({stderr:n}=await Hu(["fetch","--depth","1",...p?["--filter=blob:none"]:[],"origin",t],{cwd:r,extraGitConfig:u,timeoutMs:d,sshBatchMode:o})),await Hu(["checkout","FETCH_HEAD"],{cwd:r,extraGitConfig:u,timeoutMs:d,sshBatchMode:o})):(({stderr:n}=await Hu(["clone","--depth","1","--branch",t,...m,e,r],{extraGitConfig:u,timeoutMs:d,sshBatchMode:o})),await w(d)),n},v=e.startsWith("git@")||e.startsWith("ssh://")?null:gd(e);let b="";if(null!==v)try{b=await y(v,!0)}catch(t){if(i&&Td(t))throw t;await(0,Os.rm)(r,{recursive:!0,force:!0}),await(0,Os.mkdir)(r,{recursive:!0}),b=await y(e,g)}else b=await y(e,g);p&&Yu(b)&&(o.log("warn",`shallowClone: server ignored --filter=blob:none for ${e}; sparse clone downloaded a full pack`),o.increment("backend_marketplace_client.shallow_clone.filter_ignored_by_server",1));const S=(performance.now()-a).toFixed(1);Nd("shallowClone %s@%s completed in %sms",e,t,S),o.log("info",`shallowClone ${e}@${t} completed in ${S}ms (${p?"sparse":"full"})`)}(u.gitUrl,u.ref,d,r,o,u.gitPath?Xu([u.gitPath]):[],a),u.gitPath)n=bd(d,u.gitPath);else{const t=await async function(e,t){for(const r of Cl){const o=(0,s.join)(e,r);let n;try{n=await(0,Os.readFile)(o,"utf-8")}catch{continue}const i=Ql(n);if(!i.success)return{type:"manifest-unresolved",reason:`Invalid marketplace manifest at ${r}: ${i.error}`};const a=i.data,c=a.plugins.find((e=>e.name===t.toLowerCase()));if(!c)return{type:"manifest-unresolved",reason:`Plugin ${JSON.stringify(t)} not found in ${r}`};if("string"!=typeof c.source&&"git-subdir"===c.source.source)return{type:"manifest-unresolved",reason:`Plugin ${JSON.stringify(t)} uses unsupported git-subdir source`};const l=eu(c.source,a.metadata?.pluginRoot);return l&&tu(l)?{type:"resolved",gitPath:l}:{type:"manifest-unresolved",reason:`Plugin ${JSON.stringify(t)} has unresolved or unsafe source path`}}return{type:"no-manifest"}}(d,e.name);if("resolved"===t.type)await rd(d,Xu([t.gitPath]),{extraGitConfig:o,timeoutMs:c}),n=bd(d,t.gitPath);else{if("manifest-unresolved"===t.type)throw new Error(`Unable to install plugin ${JSON.stringify(e.name)} without gitPath: ${t.reason}`);await rd(d,"all",{extraGitConfig:o,timeoutMs:c}),n=d}}await(0,Os.mkdir)(t,{recursive:!0}),await(0,Os.cp)(n,t,{recursive:!0,verbatimSymlinks:!0})}finally{await(0,Os.rm)(d,{recursive:!0,force:!0}).catch((()=>{}))}}(e,t,this.pluginLogger,Wu(this.extraGitConfig),{githubToken:this.githubToken,sparsePluginClones:this.sparsePluginClones}),this.emitOriginLoadIfApplicable(e)}emitOriginLoadIfApplicable(e){if(e.isOriginBacked)try{this.pluginLogger.increment("marketplace.origin_distribution.load",1),this.pluginLogger.log("info",`Loaded plugin ${e.pluginId} from Origin distribution (fetch complete)`,{pluginId:e.pluginId})}catch{}}async prewarmMarketplaceClones(e){const t=this.marketplaceCache;if(!t)return;const r=new Map;for(const t of e){const e=t.marketplace;if(!e?.gitUrl)continue;const o=e.gitRef??"main",n=`${e.id}\0${e.gitUrl}\0${o}`;let s=r.get(n);void 0===s&&(s={marketplaceId:e.id,gitUrl:e.gitUrl,gitRef:o,gitPaths:[]},r.set(n,s)),t.gitPath&&s.gitPaths.push(t.gitPath)}for(const e of r.values()){const r=Xu(e.gitPaths),o=performance.now();try{await t.ensureCloned(e.marketplaceId,e.gitUrl,e.gitRef,this.pluginLogger,{materialize:r}),this.pluginLogger.log("info",`Prewarmed marketplace clone ${e.gitUrl}@${e.gitRef} for ${e.gitPaths.length} plugin directories`,{marketplaceId:e.marketplaceId,gitUrl:e.gitUrl,gitRef:e.gitRef,requestedDirs:e.gitPaths.length,materialize:"all"===r?"all":r.length}),this.pluginLogger.increment("marketplace_cache_manager.prewarm.success",1,{materialize:"all"===r?"all":"dirs"})}catch(t){this.pluginLogger.captureException(t,{error_type:"prewarm_marketplace_clone"}),this.pluginLogger.log("warn",`Failed to prewarm marketplace clone ${e.gitUrl}@${e.gitRef}; falling back to per-plugin materialization`,{marketplaceId:e.marketplaceId,gitUrl:e.gitUrl,gitRef:e.gitRef,error:String(t)}),this.pluginLogger.increment("marketplace_cache_manager.prewarm.error",1)}this.pluginLogger.distribution("marketplace_cache_manager.prewarm.duration",performance.now()-o)}}async tryInstallFromMarketplaceCache(e,t){const r=this.marketplaceCache,o=e.marketplace;if(!r||!o||!o.gitUrl)return this.pluginLogger.log("info","No marketplace cache or marketplace metadata, skipping cache check",{pluginId:e.pluginId,name:e.name,version:e.version,marketplaceId:e.marketplace?.id}),!1;const n=await r.ensureCloned(o.id,o.gitUrl,o.gitRef??"main",this.pluginLogger,{materialize:e.gitPath?Xu([e.gitPath]):[]}),s=e.gitPath??await r.resolvePluginPath(n,e.name);if(!s)return this.pluginLogger.log("info","No git path found for plugin, skipping cache check",{pluginId:e.pluginId,name:e.name,version:e.version,marketplaceId:e.marketplace?.id}),!1;void 0===e.gitPath&&await r.ensureMaterialized(n,Xu([s]),this.pluginLogger);const i=r.getPluginDir(n,s);return await r.copyPluginToDir(i,t),!0}async discoverMarketplacePlugins(e,t,r){const o=this.marketplaceCache;if(!o)throw new Error("discoverMarketplacePlugins requires a MarketplaceCacheManager (marketplaceCacheRoot)");const n=await o.ensureCloned(e,t,r,this.pluginLogger,{materialize:[]});return o.discoverPlugins(n)}}function eh(e,t,r,o,n){return new Yd(e,t,r,o,n)}var th=r("node:url"),rh=r("../../node_modules/.pnpm/gray-matter@4.0.3/node_modules/gray-matter/index.js");const oh=()=>({});function nh(e,t){return rh(e,{...t,engines:{...t?.engines,js:oh,javascript:oh}})}function sh(e,t,r){return rh.stringify({content:e,data:{}},t,r)}function ih(e){return e.replace(/\\/g,"/").replace(/\/+$/,"")||"/"}function ah(e,t,r,o){const n=e?.plugins;if(!n||"object"!=typeof n)return[];const s=t?.enabledPlugins??{},i={};r?.enabledPlugins&&Object.assign(i,r.enabledPlugins);const a=void 0!==o?ih(o):void 0,c=new Set,l=[];for(const[e,t]of Object.entries(n)){if(!Array.isArray(t)||0===t.length)continue;if(void 0!==a&&!1===i[e])continue;let r;void 0!==a&&(r=t.find((t=>!("project"!==t.scope&&"local"!==t.scope||!t.projectPath)&&(ih(t.projectPath)===a&&!0===i[e])))),r||!0!==s[e]||(r=t.find((e=>"user"===e.scope))),r?.installPath&&!c.has(e)&&(l.push({pluginId:e,installPath:r.installPath}),c.add(e))}return l}var ch=r("../../node_modules/.pnpm/js-yaml@4.3.1/node_modules/js-yaml/dist/js-yaml.mjs");const lh=[".md",".mdc",".markdown"],uh=[...lh,".txt"],dh=/^---\s*\n([\s\S]*?)\n---/;function hh(e){return e.trim().toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9.-]/g,"")}function ph(e){const t=e.match(dh);if(!t)return{};try{const e=ch.Ay.load(t[1],{schema:ch.Ay.JSON_SCHEMA});if(!e||"object"!=typeof e)return{};const r=null!==e.metadata&&"object"==typeof e.metadata?e.metadata:void 0,o=fh(e.environments??r?.environments);return{disabledEnvironments:fh(e["disabled-environments"]??r?.disabledEnvironments),environments:o,name:"string"==typeof e.name?e.name:void 0,description:"string"==typeof e.description?e.description:void 0}}catch{const e=t[1],r=e.match(/^name:\s*(.+)$/m),o=e.match(/^description:\s*(.+)$/m);return r||o?{name:r?r[1].trim():void 0,description:o?o[1].trim():void 0}:{}}}function fh(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 mh(e){return hh((0,s.basename)(e).replace(/\.(md|mdc|markdown|txt)$/i,""))}function gh(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 wh{constructor(e){this.fetcher=e}async discoverComponents(e={}){const t=e.basePath??"",r=t?`${t}/`:"",o=e.manifest;let n;try{n=await this.fetcher.listDirectory(t)}catch{n=[]}const s=new Set(n.filter((e=>"dir"===e.type)).map((e=>e.name.toLowerCase()))),i=cu.filter((e=>n.some((t=>"file"===t.type&&t.name===e)))),a=n.some((e=>"file"===e.type&&"SKILL.md"===e.name)),[c,l,u,d,h,p,f]=await Promise.all([a&&void 0===o?.skills?this.discoverRootSkill(r):Promise.resolve(null),void 0!==o?.skills?this.discoverFromManifestPaths(r,o.skills,!0,lh):s.has("skills")?this.discoverSkills(`${r}skills`):Promise.resolve([]),void 0!==o?.agents?this.discoverFromManifestPaths(r,o.agents,!1,lh):s.has("agents")?this.discoverMarkdownComponents(`${r}agents`,lh):Promise.resolve([]),void 0!==o?.hooks?this.discoverHooksFromManifest(r,o.hooks):s.has("hooks")?this.discoverHooksFromJson(`${r}hooks/hooks.json`):Promise.resolve([]),void 0!==o?.commands?this.discoverFromManifestPaths(r,o.commands,!1,uh):s.has("commands")?this.discoverMarkdownComponents(`${r}commands`,uh):Promise.resolve([]),void 0!==o?.rules?this.discoverFromManifestPaths(r,o.rules,!1,lh):s.has("rules")?this.discoverMarkdownComponents(`${r}rules`,lh):Promise.resolve([]),this.discoverMcpServers(r,o?.mcpServers,i)]);return{skills:gh(c?[c,...l]:l),agents:gh(u),hooks:d,commands:gh(h),rules:gh(p),mcpServers:f.servers,mcpVariables:f.variables,mcpConfigs:f.configs}}async discoverHooksFromJson(e){try{if(!await this.fetcher.fileExists(e))return[];const{content:t}=await this.fetcher.fetchFile(e),r=JSON.parse(t);return!r.hooks||"object"!=typeof r.hooks||Array.isArray(r.hooks)?[]:Object.keys(r.hooks).map((t=>({name:hh(t),path:e,description:`Hook: ${t}`})))}catch{return[]}}async discoverHooksFromManifest(e,t){if("string"==typeof t){if(!tu(t))return[];const r=`${e}${t.replace(/^\.\//,"")}`;return r.endsWith(".json")?this.discoverHooksFromJson(r):this.discoverHooksFromJson(`${r}/hooks.json`)}const r=t.hooks??t;return!r||"object"!=typeof r||Array.isArray(r)?[]:Object.keys(r).map((e=>({name:hh(e),path:"manifest",description:`Hook: ${e}`})))}async discoverFromManifestPaths(e,t,r=!1,o=lh){if("string"==typeof t){if(!tu(t))return[];const n=`${e}${t.replace(/^\.\//,"")}`.replace(/\/$/,"");return r?this.discoverSkills(n):this.discoverMarkdownComponents(n,o)}const n=[];for(const o of t)try{if(!tu(o))continue;const t=`${e}${o.replace(/^\.\//,"")}`;if(r){const e=t.endsWith("SKILL.md")?t:`${t.replace(/\/$/,"")}/SKILL.md`;if(!await this.fetcher.fileExists(e)){const e=t.replace(/\/$/,""),r=await this.discoverSkills(e);n.push(...r);continue}let r=mh(t.endsWith("SKILL.md")?t.slice(0,-8).replace(/\/$/,""):t);const{content:o}=await this.fetcher.fetchFile(e),s=ph(o);if(r=s.name??r,r){const t={disabledEnvironments:s.disabledEnvironments,environments:s.environments,name:hh(r),path:e};void 0!==s.description&&(t.description=s.description),n.push(t)}}else{if(!await this.fetcher.fileExists(t))continue;let e=mh(t);const{content:r}=await this.fetcher.fetchFile(t),o=ph(r);e=o.name??e;const s=o.description;if(e){const r={name:hh(e),path:t};void 0!==s&&(r.description=s),n.push(r)}}}catch{}return n}async discoverMarkdownComponents(e,t=lh,r=new Set){let o;try{o=await this.fetcher.listDirectory(e,r)}catch{return[]}const n=o.filter((e=>"file"===e.type&&t.some((t=>e.name.endsWith(t))))),s=o.filter((e=>"dir"===e.type)),[i,a]=await Promise.all([Promise.all(n.map((async e=>{try{let t=mh(e.name);const{content:r}=await this.fetcher.fetchFile(e.path),o=ph(r);t=o.name?hh(o.name):t;const n=o.description;if(!t)return null;const s={name:t,path:e.path};return void 0!==n&&(s.description=n),s}catch{return null}}))),Promise.all(s.map((e=>this.discoverMarkdownComponents(e.path,t,r))))]);return[...i.filter((e=>null!==e)),...a.flat()]}async discoverRootSkill(e){try{const t=`${e}SKILL.md`;let r=hh((0,s.basename)(e.replace(/[\\/]+$/,"")));const{content:o}=await this.fetcher.fetchFile(t),n=ph(o);if(r=n.name?hh(n.name):r,!r)return null;const i={disabledEnvironments:n.disabledEnvironments,environments:n.environments,name:r,path:t};return void 0!==n.description&&(i.description=n.description),i}catch{return null}}async discoverSkills(e){let t;try{t=await this.fetcher.listDirectory(e)}catch{return[]}const r=t.filter((e=>"dir"===e.type));return(await Promise.all(r.map((async e=>{try{const t=`${e.path}/SKILL.md`;if(!await this.fetcher.fileExists(t))return null;const{content:r}=await this.fetcher.fetchFile(t),o=ph(r),n=o.name?hh(o.name):hh(e.name);if(!n)return null;const s={disabledEnvironments:o.disabledEnvironments,environments:o.environments,name:n,path:t};return void 0!==o.description&&(s.description=o.description),s}catch{return null}})))).filter((e=>null!==e))}async discoverMcpServers(e,t,r){const o=new Map,n=async t=>{const r=o.get(t);if(void 0!==r)return r;const n=this.fetcher.fetchFile(`${e}${t}`).then((({content:e})=>e)).catch((()=>null));return o.set(t,n),n},s=async o=>gu(n,t,void 0!==t?"manifest":void 0,{fallbackFileNames:r,manifestPrecedence:o,toSourcePath:t=>`${e}${t}`,parserOptions:{skipExpansion:!0}}),i=await s("fill");if(void 0===i?.mcpServers)return{servers:[],variables:void 0,configs:void 0};const a=void 0===t?i:await s("override"),c=a?.mcpServers??i.mcpServers,l={};for(const[e,t]of Object.entries(c))l[e]=t;return{servers:Object.keys(i.mcpServers).map((e=>({name:hh(e),path:i.mcpServerSourcePaths?.[e]??"manifest"}))),variables:pl(a??i),configs:l}}}function yh(e){const t=e??process.env.HOME??"";return(0,s.join)(t,".claude")}async function vh(e){const t={enabledPlugins:{}};let r=!1;const o=(0,s.join)(e,".claude","settings.json");try{const e=await(0,Os.readFile)(o,"utf-8"),n=JSON.parse(e);n.enabledPlugins&&(Object.assign(t.enabledPlugins,n.enabledPlugins),r=!0)}catch{}const n=(0,s.join)(e,".claude","settings.local.json");try{const e=await(0,Os.readFile)(n,"utf-8"),o=JSON.parse(e);o.enabledPlugins&&(Object.assign(t.enabledPlugins,o.enabledPlugins),r=!0)}catch{}return r?t:null}async function bh(e){try{return(await(0,Os.lstat)(e)).isSymbolicLink()}catch{return!1}}async function Sh(e){if(await bh(e))throw new Error(`Refusing to read symlink: ${e}`);return(0,Os.readFile)(e,"utf-8")}async function kh(e){if((await(0,Os.stat)(e)).size>10485760)throw new Error(`File ${e} exceeds maximum size of 10485760 bytes`)}function Eh(e){const t=e instanceof Error?e.message:String(e);return/timed?\s*out/i.test(t)?"timeout":/clone|fetch|git/i.test(t)?"clone":/manifest|marketplace\.json/i.test(t)?"manifest":/parse|invalid|malformed/i.test(t)?"parse":/install|download|copy/i.test(t)?"install":"unknown"}async function Ch({installPath:e,logo:t}){const r=t?.trim();if(r&&!(0,s.isAbsolute)(r)&&!r.includes("://"))try{const t=await(0,Os.realpath)(e),o=bd(t,r),n=await(0,Os.realpath)(o);if(bd(t,n),!(await(0,Os.stat)(n)).isFile())return;return await kh(n),(0,th.pathToFileURL)(n).href}catch{return}}function xh(e){const t={};return void 0!==e.version&&(t.version=e.version),void 0!==e.homepage&&(t.homepage=e.homepage),void 0!==e.repository&&(t.repository=e.repository),t}function _h(e){return void 0!==e.version||void 0!==e.homepage||void 0!==e.repository}function Ph(e,t){return xh({version:e.version??t?.version,homepage:e.homepage??t?.homepage,repository:e.repository??t?.repository})}async function Ih(e,t,r){let o;for(const n of kl){const i=(0,s.join)(e,n);let a;try{if(await bh(i))continue;if(!(await(0,Os.stat)(i)).isFile())continue;await kh(i),a=await Sh(i)}catch{continue}const c=Yl(a);if(!c.success)continue;const l=c.data,u=l.commands,d=l.agents,h=l.skills,p=l.rules,f=l.hooks,m=l.mcpServers,g=void 0!==u||void 0!==d||void 0!==h||void 0!==p||void 0!==f||void 0!==m,w="string"==typeof l.displayName?l.displayName:void 0,y="string"==typeof l.description?l.description:void 0,v=l.author?.name,b=await Ch({installPath:e,logo:l.logo}),S=xh(l),k=l.variables,E=l.capabilities,C=void 0!==w||void 0!==y||void 0!==v||void 0!==b||void 0!==k||void 0!==E;if(!g&&!C&&!_h(S))continue;if(!g&&!C){o=o?{...o,fields:Ph(o.fields,S)}:{fields:S,path:i,relPath:n,unrecognizedSchemaId:c.unrecognizedSchemaId};continue}void 0!==c.unrecognizedSchemaId&&r.log("debug",`${t}: ${n} declares an unrecognized $schema, loading anyway: ${c.unrecognizedSchemaId}`);const x=Ph(S,o?.fields);return{manifestFilePath:i,...g&&{manifestOptions:{commands:u,agents:d,skills:h,rules:p,hooks:f,mcpServers:m}},...(C||_h(x))&&{metadata:{displayName:w,description:y,authorName:v,logoUrl:b,...x,variables:k,capabilities:E}}}}if(void 0!==o)return void 0!==o.unrecognizedSchemaId&&r.log("debug",`${t}: ${o.relPath} declares an unrecognized $schema, loading anyway: ${o.unrecognizedSchemaId}`),{manifestFilePath:o.path,metadata:o.fields}}async function Rh(e,t){const r=function(e,t){const r=new Map,o=(0,s.resolve)(e),n=(0,s.resolve)(t?.symlinkTargetRoot??o),i=(0,Os.realpath)(n).catch((()=>n));function a(e){const t=(0,s.resolve)(e);try{return bd(o,t)}catch{throw new Error(`Path escapes plugin directory: ${e}`)}}async function c(e){const t=a(e),r=await i,o=await(0,Os.realpath)(t);try{return bd(r,o)}catch{throw new Error(`Path escapes plugin directory via symlink: ${e}`)}}return{async listDirectory(t,r){const o=a(t?(0,s.join)(e,t):e);try{const e=await c(o);if(r?.has(e))return[];r?.add(e);const n=await(0,Os.readdir)(e,{withFileTypes:!0}),i=[];for(const e of n){const r=(0,s.join)(o,e.name);let n=e.isDirectory()?"dir":"file";if(e.isSymbolicLink())try{const e=await c(r);n=(await(0,Os.stat)(e)).isDirectory()?"dir":"file"}catch{continue}i.push({name:e.name,type:n,path:t?`${t}/${e.name}`:e.name})}return i}catch{return[]}},async fetchFile(t){const o=r.get(t);if(void 0!==o)return{content:o};const n=a((0,s.join)(e,t)),i=await c(n);await kh(i);const l=await(0,Os.readFile)(i,"utf-8");return r.set(t,l),{content:l}},async fileExists(t){try{const r=a((0,s.join)(e,t)),o=await c(r);return(await(0,Os.stat)(o)).isFile()}catch{return!1}}}}(e),o=new wh(r),n=await o.discoverComponents({manifest:t}),[i,a,c,l]=await Promise.all([Th(r,n.skills,e),Mh(r,n.agents,e),Dh(r,n.commands,e),Ah(r,n.rules,e)]);return{skills:i,agents:a,commands:c,rules:l}}async function Th(e,t,r){const o=[];for(const n of t)try{const{content:t}=await e.fetchFile(n.path),s=Nh({content:au(t,r),relativePath:n.path});s&&o.push(s)}catch{}return o}async function Ah(e,t,r){const o=[];for(const n of t)try{const{content:t}=await e.fetchFile(n.path),s=Nh({content:au(t,r),relativePath:n.path});s&&o.push({...s,name:n.name})}catch{}return o}async function Mh(e,t,r){const o=[];for(const n of t)try{const{content:t}=await e.fetchFile(n.path),s=$h({content:au(t,r),relativePath:n.path});s&&o.push(s)}catch{}return o}async function Dh(e,t,r){const o=[];for(const n of t)try{const{content:t}=await e.fetchFile(n.path),s=Fh({content:au(t,r),relativePath:n.path});s&&o.push(s)}catch{}return o}function Oh(e){if("string"==typeof e){const t=function(e){const t=[];let r=0,o=0;for(let n=0;n<e.length;n++){const s=e[n];if("{"===s)o++;else if("}"===s&&o>0)o--;else if(","===s&&0===o){const o=e.slice(r,n).trim();o&&t.push(o),r=n+1}}if(o>0){for(const o of e.slice(r).split(",")){const e=o.trim();e&&t.push(e)}return t}const n=e.slice(r).trim();return n&&t.push(n),t}(e);return t.length>0?t:void 0}if(Array.isArray(e)){const t=e.filter((e=>"string"==typeof e)).map((e=>e.trim())).filter(Boolean);return t.length>0?t:void 0}}function Nh({content:e,relativePath:t}){try{const r=nh(e),o=t.replace(/\\/g,"/"),n=o.split("/").filter((e=>e.length>0)),s=n.length>=2?n[n.length-2]:void 0,i=n[n.length-1]??o,a=s??i.replace(/\.md$/i,""),c="string"==typeof r.data.name?r.data.name.trim():void 0,l=fh(r.data.environments??r.data.metadata?.environments),u=fh(r.data["disabled-environments"]??r.data.metadata?.disabledEnvironments);return{path:t,name:c&&c.length>0?c:a,description:"string"==typeof r.data.description?r.data.description:void 0,globs:Oh(r.data.globs),alwaysApply:!0===r.data.alwaysApply,content:e,environments:l,disabledEnvironments:u}}catch{return null}}function $h({content:e,relativePath:t}){try{const o=nh(e),n=o.content.trim();if(!n)return null;let i;"string"==typeof o.data.tools?i=o.data.tools.split(",").map((e=>e.trim())).filter(Boolean):Array.isArray(o.data.tools)&&(i=o.data.tools.map((e=>"string"==typeof e?e.trim():String(e))).filter(Boolean));const a=o.data.permissionMode??o.data.permissionmode,c=(0,s.basename)(t);return{path:t,name:"string"==typeof o.data.name?o.data.name:(0,s.basename)(c,(0,s.extname)(c)).replace(/[\s_]+/g,"-"),description:"string"==typeof o.data.description?o.data.description:void 0,tools:i,model:"string"==typeof o.data.model?o.data.model:"inherit",prompt:n,permissionMode:(r=a,"readonly"===(r??"").trim().toLowerCase()?"readonly":"default")}}catch{return null}var r}function Fh({content:e,relativePath:t}){try{const r=nh(e);let o;const n=r.data["argument-hint"];"string"==typeof n?o=n:Array.isArray(n)&&(o=`[${n.join(" ")}]`);const i=(0,s.basename)(t);return{path:t,name:"string"==typeof r.data.name?r.data.name:(0,s.basename)(i,(0,s.extname)(i)),description:"string"==typeof r.data.description?r.data.description:void 0,argumentHint:o,content:r.content.trim()}}catch{return null}}function jh(e){if(void 0!==e)return{configuredVariables:e.configuredVariables}}async function Lh(e,t,r){const o=r??jh(t);return async function(e,t={}){const r=t.toSourcePath??(e=>e);let o,n,s;for(const t of kl){const i=await e(t);if(null===i)continue;let a;try{a=JSON.parse(i)}catch{continue}s=wl(a);const c=Yl(i);if(c.success){void 0!==c.data.mcpServers&&(o=c.data.mcpServers,n=r(t));break}}return gu(e,o,n,void 0===s?t:{...t,parserOptions:{...t.parserOptions,pluginSchemaId:s}})}(function(e){return async t=>{if(!tu(t))return null;const r=(0,s.join)(e,t);try{return await bh(r)?null:(await(0,Os.stat)(r)).isFile()?(await kh(r),await Sh(r)):null}catch{return null}}}(e),{fallbackFileNames:hu(),manifestPrecedence:"override",toSourcePath:t=>(0,s.join)(e,t),installPathForExpansion:e,parserOptions:o})}async function Uh(e,t,r){const o=await Lh(e,void 0,{log:r});if(o)return o;for(const o of Cl){const n=(0,s.join)(e,o);try{if(!(await(0,Os.stat)(n)).isFile())continue;const o=await(0,Os.readFile)(n,"utf-8"),i=JSON.parse(o).plugins;if(!Array.isArray(i))continue;const a=t.name,c=i.find((e=>e.name===a));if(!c?.mcpServers?.length)continue;for(const t of c.mcpServers){const o=t.replace(/^\.\//,"");if(!tu(o))continue;const n=(0,s.join)(e,o);try{await kh(n);const t=fu(await Sh(n),e,{log:r});if(t?.mcpServers&&Object.keys(t.mcpServers).length>0){const e=Object.fromEntries(Object.keys(t.mcpServers).map((e=>[e,n])));return{...t,mcpServerSourcePaths:e}}}catch{}}return null}catch{}}return null}function Bh(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?{...e,command:au(e.command,t)}:"prompt"in e&&"string"==typeof e.prompt?{...e,prompt:au(e.prompt,t)}:e)));return{...e,hooks:r}}async function Wh(e,t,r,o){if("object"==typeof r){const n=Hh(r,t);return n&&"config"in n?{config:Bh(n.config,e),...void 0!==o&&{sourcePath:o}}:n}let n,i,a;if("string"==typeof r){const t=r.replace(/^\.\//,"");if(!tu(t))return;n=t.endsWith(".json")?(0,s.join)(e,t):(0,s.join)(e,t,"hooks.json")}else n=(0,s.join)(e,"hooks","hooks.json");try{if(await bh(n))return;if(!(await(0,Os.stat)(n)).isFile())return}catch{return}try{await kh(n),i=await(0,Os.readFile)(n,"utf-8")}catch{return}try{a=JSON.parse(i)}catch{return{error:{source:"claude-plugin",message:`Plugin ${t} ${n}: invalid JSON`}}}const c=Hh(a,t);return c&&"config"in c?{config:Bh(c.config,e),sourcePath:n}:c}function Hh(e,t){const r=function(e){if(!Se(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(Se(t)){if("hooks"in t&&Array.isArray(t.hooks))return"claude-code";if("command"in t||"prompt"in t||"type"in t)return"cursor"}}return"unknown"}(e);if("cursor"===r){const r=e,o=ut(r);return o.isValid?{config:r}:{error:{source:"claude-plugin",message:`Plugin ${t} hooks: ${o.errors.join("; ")}`}}}if("claude-code"===r){const r=e,o=r?.hooks;if(!o||0===Object.keys(o).length)return;const n=Pe(o),s=ut(n);return s.isValid?{config:n}:{error:{source:"claude-plugin",message:`Plugin ${t} hooks: ${s.errors.join("; ")}`}}}}async function qh(e,t,r,o){const n=o?.log??Jc,s=await Ih(e,t,n),i={...jh(r)??(o?.configuredVariables?{configuredVariables:o.configuredVariables}:void 0),log:n},[a,c,l]=await Promise.all([Rh(e,s?.manifestOptions),Lh(e,r,i),Wh(e,t,s?.manifestOptions?.hooks,s?.manifestFilePath)]);return{...a,...void 0!==s?.metadata?.displayName&&{displayName:s.metadata.displayName},...void 0!==s?.metadata?.description&&{description:s.metadata.description},...void 0!==s?.metadata?.authorName&&{authorName:s.metadata.authorName},...void 0!==s?.metadata?.logoUrl&&{logoUrl:s.metadata.logoUrl},...void 0!==s?.metadata?.version&&{version:s.metadata.version},...void 0!==s?.metadata?.homepage&&{homepage:s.metadata.homepage},...void 0!==s?.metadata?.repository&&{repository:s.metadata.repository},variablesSchema:s?.metadata?.variables,mcpConfig:c,capabilities:s?.metadata?.capabilities??[],hooks:l}}async function zh(e,t,r){const o=r?.log??Jc,n=await Ih(e,t.raw,o),[s,i,a]=await Promise.all([Rh(e,n?.manifestOptions),Uh(e,t,o),Wh(e,t.raw,n?.manifestOptions?.hooks,n?.manifestFilePath)]);return{identifier:{source:"claude-plugin",sourceInfo:t},installPath:e,...void 0!==n?.metadata?.displayName&&{displayName:n.metadata.displayName},...void 0!==n?.metadata?.description&&{description:n.metadata.description},...void 0!==n?.metadata?.authorName&&{authorName:n.metadata.authorName},...void 0!==n?.metadata?.logoUrl&&{logoUrl:n.metadata.logoUrl},...void 0!==n?.metadata?.version&&{version:n.metadata.version},...void 0!==n?.metadata?.homepage&&{homepage:n.metadata.homepage},...void 0!==n?.metadata?.repository&&{repository:n.metadata.repository},...s,mcpConfig:i??void 0,capabilities:n?.metadata?.capabilities??[],hooks:a}}async function Gh(e,t,r,o){const n=`${r.name}@${r.version}`,{displayName:s,description:i,authorName:a,logoUrl:c,version:l,homepage:u,repository:d,variablesSchema:h,skills:p,rules:f,agents:m,commands:g,mcpConfig:w,capabilities:y,hooks:v}=await qh(e,n,r,{log:o?.log});return{identifier:{source:t,sourceInfo:r},installPath:e,...void 0!==s&&{displayName:s},...void 0!==i&&{description:i},...void 0!==a&&{authorName:a},...void 0!==c&&{logoUrl:c},...void 0!==l&&{version:l},...void 0!==u&&{homepage:u},...void 0!==d&&{repository:d},variablesSchema:h,skills:p,rules:f,agents:m,commands:g,mcpConfig:w??void 0,capabilities:y,hooks:v}}async function Vh(e,t,r={}){const o=r.log??Jc,n=performance.now(),i=await async function(e){const t=yh(e),r=(0,s.join)(t,"plugins","installed_plugins.json");try{const e=await(0,Os.readFile)(r,"utf-8");return JSON.parse(e)}catch(e){return e.code,null}}(r.userHomeDir);if(!i?.plugins)return o.log("info",`loadAllEnabledPlugins: no installed plugins metadata found (${(performance.now()-n).toFixed(1)}ms)`),[];const a=await async function(e){const t=yh(e),r=(0,s.join)(t,"settings.json");try{const e=await(0,Os.readFile)(r,"utf-8");return JSON.parse(e)}catch(e){return e.code,null}}(r.userHomeDir),c=function(e){if(void 0===e)return[];const t="string"==typeof e?[e]:e,r=new Set,o=[];for(const e of t){if(!e)continue;const t=(0,s.resolve)(e);r.has(t)||(r.add(t),o.push(t))}return o}(e),l=function(e,t,r){if(0===r.length)return ah(e,t,null,void 0);const o=new Set;for(const{settings:e}of r)for(const[t,r]of Object.entries(e?.enabledPlugins??{}))!1===r&&o.add(t);const n=new Set,s=[];for(const{workspacePath:i,settings:a}of r){const r=ah(e,t,a,i);for(const e of r)n.has(e.pluginId)||o.has(e.pluginId)||(n.add(e.pluginId),s.push(e))}return s}(i,a,await(0,Ht.PH)(c,(async e=>({workspacePath:e,settings:await vh(e)})),{max:8})),u=[],d=r.onError;for(const{pluginId:e,installPath:t}of l)try{const r=performance.now(),n=el(e),s=await zh(t,n,{log:o});u.push(s),o.log("info",`loadClaudePlugin ${e} loaded in ${(performance.now()-r).toFixed(1)}ms`)}catch(t){const r=t instanceof Error?t:new Error(String(t));if(d)try{d(el(e),r)}catch{d({name:e.split("@")[0]??e,sourceType:"marketplace",marketplace:"unknown",raw:e},r)}}return o.log("info",`loadAllEnabledPlugins completed in ${(performance.now()-n).toFixed(1)}ms (${l.length} resolved, ${u.length} loaded)`),u}Error;async function Jh(e){const t=e.log??Jc,r=performance.now(),{client:o,userId:n,teamId:s,onCursorError:i,pruneOldVersions:a,pluginFilter:c,onPluginsListed:l}=e,u=[],d=e.cacheManager??new _u(e.userHomeDir),h=performance.now();let p;try{p=await o.listEnabledPlugins(n,s)}catch(e){return t.captureException(e,{error_type:"list_enabled_plugins"}),t.increment("marketplace.source_unavailable",1),t.log("error",`marketplace listEnabledPlugins failed after ${(performance.now()-h).toFixed(1)}ms; treating source as unavailable: ${e instanceof Error?e.message:String(e)}`),{plugins:[],failures:[],sourceUnavailable:!0}}t.log("info",`marketplace listEnabledPlugins completed in ${(performance.now()-h).toFixed(1)}ms (${p.plugins.length} plugins)`),l&&await l(p.plugins);const f=[];if(p.listFailures){u.push(...p.listFailures);for(const e of p.listFailures)f.push({identifier:{source:e.marketplaceName&&"cursor-public"!==e.marketplaceName?"cursor-third-party":"cursor-first-party",sourceInfo:{name:e.pluginName,version:"",...void 0!==e.pluginDbId&&{pluginDbId:e.pluginDbId},marketplace:e.marketplaceName}},installPath:"",loadError:e.errorMessage,skills:[],rules:[],agents:[],commands:[],capabilities:[]})}const m=new Map;for(const e of p.plugins)if(!c||c(e))try{const r=e.marketplace?.name;if(!r){const t=new Error(`Plugin ${e.name} has no marketplace metadata — cannot determine cache path`);u.push({pluginName:e.name,pluginId:e.pluginId,marketplaceName:void 0,errorMessage:t.message,errorType:"manifest"}),i&&i(e,t);continue}const n=`${r}/${e.pluginId}`;let s,a=m.get(n);if(a||(a={slug:r,pluginId:e.pluginId,versions:[]},m.set(n,a)),a.versions.push(e.version),await d.isCached({marketplaceSlug:r,pluginId:e.pluginId,version:e.version}))s=d.getCacheDir({marketplaceSlug:r,pluginId:e.pluginId,version:e.version}),t.log("info",`loadFromMarketplaceSource: Found cached plugin: ${e.pluginId} at ${s}`,{marketplaceSlug:r,pluginId:e.pluginId,gitRef:e.version,marketplaceId:e.marketplace?.id});else{const n=d.getCacheDir({marketplaceSlug:r,pluginId:e.pluginId,version:e.version});t.log("info",`loadFromMarketplaceSource: Plugin missing from cache, installing: ${e.pluginId} at ${n}`,{marketplaceSlug:r,pluginId:e.pluginId,gitRef:e.version,marketplaceId:e.marketplace?.id}),await(0,Os.mkdir)(n,{recursive:!0});try{await o.installPlugin(e,n),await d.markCacheComplete({marketplaceSlug:r,pluginId:e.pluginId,version:e.version})}catch(e){try{await(0,Os.rm)(n,{recursive:!0,force:!0})}catch{}throw e}s=n}const c=e.marketplace?.name,l=void 0!==c&&"cursor-public"!==c&&c.length>0?"cursor-third-party":"cursor-first-party",h={name:e.name,version:e.version,pluginDbId:e.pluginDbId,configuredVariables:e.configuredVariables,marketplace:c,marketplaceDbId:e.marketplaceDbId,isTeamRequired:e.isTeamRequired},p=await Gh(s,l,h,{log:t});f.push(p);try{await d.pruneOldVersions({marketplaceSlug:r,pluginId:e.pluginId,keepVersions:[e.version]})}catch{}}catch(r){t.captureException(r,{error_type:"load_plugin_from_marketplace"});const o=r instanceof Error?r:new Error(String(r));u.push({pluginName:e.name,pluginId:e.pluginId,marketplaceName:e.marketplace?.name,errorMessage:o.message,errorType:Eh(o)});const n=e.marketplace?.name,s=void 0!==n&&"cursor-public"!==n&&n.length>0;f.push({identifier:{source:s?"cursor-third-party":"cursor-first-party",sourceInfo:{name:e.name,version:e.version,pluginDbId:e.pluginDbId,marketplace:n,marketplaceDbId:e.marketplaceDbId,isTeamRequired:e.isTeamRequired}},installPath:"",loadError:o.message||"Plugin load failed",skills:[],rules:[],agents:[],commands:[],capabilities:[]}),i&&i(e,o)}if(a)for(const{slug:e,pluginId:t,versions:r}of m.values())try{await d.pruneOldVersions({marketplaceSlug:e,pluginId:t,keepVersions:r})}catch{}return t.log("info",`loadFromMarketplaceSource completed in ${(performance.now()-r).toFixed(1)}ms (${f.length} plugins loaded, ${u.length} failures)`),{plugins:f,failures:u,sourceUnavailable:!1}}function Kh(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 Zh(e){return Kh(e)??`path:${e.installPath}`}function Xh(e,t={}){return{...e,model:t.stripModel?void 0:e.model,tools:t.stripTools?void 0:e.tools}}function Qh(e,t){const r=[];for(const n of e){const e=tl(n.identifier),i=`plugin:${e}`,a=rl(n.identifier),c=ol(n.identifier),l=nl(n.identifier),u=sl(n.identifier);for(const d of t(n)){const t=(0,s.join)(n.installPath,d.path),{type:h,globs:p,description:f}=(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:h,globs:p,description:f,pluginIdentifier:e,gitRemoteOrigin:i,plugin:a,marketplace:c,pluginId:l,marketplaceId:u,environments:d.environments,disabledEnvironments:d.disabledEnvironments})}}var o;return r}(0,s.join)((0,n.homedir)(),".claude","plugins","marketplaces");const Yh=Io.object({path:Io.string(),name:Io.string().optional(),description:Io.string().optional(),globs:Io.array(Io.string()).optional(),alwaysApply:Io.boolean().optional(),content:Io.string(),environments:Io.array(Io.string()).optional(),disabledEnvironments:Io.array(Io.string()).optional()}),ep=Yh.extend({name:Io.string()}),tp=Io.object({path:Io.string(),name:Io.string(),description:Io.string().optional(),tools:Io.array(Io.string()).optional(),model:Io.string().optional(),prompt:Io.string(),permissionMode:Io.enum(["default","readonly"]).optional()}),rp=Io.object({path:Io.string(),name:Io.string(),description:Io.string().optional(),argumentHint:Io.string().optional(),content:Io.string()}),op=Io.custom((e=>"object"==typeof e&&null!==e&&"object"==typeof e.hooks&&null!==e.hooks)),np=Io.object({config:op,sourcePath:Io.string().optional()}),sp=Io.custom((e=>"object"==typeof e&&null!==e));function ip(e){const t=e.trim();if(!t)return!1;if(t.startsWith("git@"))return/^git@[a-zA-Z0-9.-]+:[a-zA-Z0-9._~\-/]+(?:\.git)?$/.test(t);try{const e=new URL(t);return"https:"===e.protocol&&""===e.username&&""===e.password&&""===e.search&&""===e.hash}catch{return!1}}Io.object({schemaVersion:Io.number().int(),displayName:Io.string().optional(),description:Io.string().optional(),authorName:Io.string().optional(),skills:Io.array(Yh),rules:Io.array(ep),agents:Io.array(tp),commands:Io.array(rp),mcpConfig:Zc.extend({mcpServerSourcePaths:Io.record(Io.string(),Io.string()).optional()}).optional(),hooks:np.optional(),hooksError:Io.string().optional(),capabilities:Io.array(Io.string()),variablesSchema:sp.optional()}),Error;class ap extends Error{constructor(e){super(e),this.name="SettingsParseError"}}function cp(e){return 65279===e.charCodeAt(0)?e.slice(1):e}async function lp(e){try{return cp(await(0,Os.readFile)(function(e){return(0,s.join)(e,".cursor","settings.json")}(e),"utf-8"))}catch(e){if(function(e){return e instanceof Error&&"code"in e}(e)&&("ENOENT"===e.code||"ENOTDIR"===e.code))return;throw e}}async function up(e){const t=await lp(e);return void 0===t?[]:function(e){const t=function(e){const t=cp(e);if(0===t.trim().length)return{};const r=[],o=(0,ou.qg)(t,r,{allowTrailingComma:!0});if(r.length>0){const e=r.slice(0,3).map((e=>`${(0,ou._n)(e.error)} at offset ${e.offset}`)).join("; ");throw new ap(`.cursor/settings.json contains syntax errors: ${e}`)}if("object"!=typeof o||null===o||Array.isArray(o))return{};const n=o;return void 0===n.plugins||"object"==typeof n.plugins&&null!==n.plugins&&!Array.isArray(n.plugins)?n:{}}(e);return t.plugins?Object.entries(t.plugins).filter((([,e])=>!0===e.enabled)).filter((([,e])=>!e.gitUrl||ip(e.gitUrl))).map((([e,t])=>({key:e,entry:t}))):[]}(t)}function dp(e){const t=e.indexOf("/");return-1===t?{name:e}:{name:e.slice(t+1),marketplaceName:e.slice(0,t)}}var hp=r("../proto/dist/generated/agent/v1/agent_skills_pb.js"),pp=r("../proto/dist/generated/agent/v1/cursor_rules_pb.js");const fp=(0,ji.debuglog)("agent-skills-catalog-cache");function mp(e){return(0,Ts.createHash)("sha256").update(JSON.stringify({v:1,...e})).digest("hex")}async function gp(e){try{return(await(0,Os.stat)(e)).mtimeMs}catch{return}}const wp={configDir:".cursor",subdir:"skills-cursor",thirdParty:!1,builtin:!0},yp=[{configDir:".cursor",subdir:"skills",thirdParty:!1,builtin:!1},{configDir:".claude",subdir:"skills",thirdParty:!0,builtin:!1},{configDir:".codex",subdir:"skills",thirdParty:!0,builtin:!1},{configDir:".grok",subdir:"skills",thirdParty:!0,builtin:!1},{configDir:".agents",subdir:"skills",thirdParty:!1,builtin:!1},wp],vp=(new Set(yp.map((e=>e.configDir))),new Set(["imagegen","openai-docs","opneai-docs","plugin-creator","skill-creator","skill-installer"]));function bp(e){const t=e.replace(/\\/g,"/").split("/").filter(Boolean);if(function(e){const t=e.findIndex(((t,r)=>function(e,t){return yp.some((r=>r.configDir===e&&r.subdir===t))}(t,e[r+1])));return-1!==t&&e.slice(t+2).some((e=>e.startsWith(".")))}(t))return!0;const r=t.lastIndexOf(".codex");if(-1===r||"skills"!==t[r+1])return!1;const o=t.at(-1),n="SKILL.md"===o?t.at(-2):o;return void 0!==n&&vp.has(n)}function Sp(e){return{dirPath:(0,s.join)(e,wp.configDir,wp.subdir),scope:"builtin",source:"builtin"}}function kp(e){return yp.filter((t=>!t.builtin&&(e||!t.thirdParty)))}function Ep(e,t){return kp(t).map((t=>({dirPath:(0,s.join)(e,t.configDir,t.subdir),scope:"project",source:"workspace"})))}function Cp(e,t){return kp(t).map((t=>({dirPath:(0,s.join)(e,t.configDir,t.subdir),scope:"user",source:"user"})))}var xp=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var 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 _p(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}const Pp=yp.map((({configDir:e,subdir:t,thirdParty:r})=>({pattern:new RegExp(`[/\\\\]${_p(e)}[/\\\\]${_p(t)}[/\\\\]`,"i"),requiresThirdParty:r}))),Ip=/[/\\]\.cursor[/\\]rules[/\\]/i,Rp=[{pattern:/[/\\]\.cursor[/\\]agents[/\\]/i,requiresThirdParty:!1},{pattern:/[/\\]\.claude[/\\]agents[/\\]/i,requiresThirdParty:!0}],Tp=new Set(["AGENTS.md","CLAUDE.md","CLAUDE.local.md"]);function Ap(e,t){const r=e.replace(/\\/g,"/"),o=(0,s.basename)(r);if(Tp.has(o))return"AGENTS.md"===o||t&&("CLAUDE.md"===o||"CLAUDE.local.md"===o)?"markdown":void 0;if(Ip.test(r)&&o.endsWith(".mdc"))return"rules";if("SKILL.md"===o)for(const{pattern:e,requiresThirdParty:o}of Pp)if(e.test(r)){if(o&&!t)continue;return"skills"}if(o.endsWith(".md"))for(const{pattern:e,requiresThirdParty:o}of Rp)if(e.test(r)){if(o&&!t)continue;return"agents"}}class Mp{constructor(e,t,r,o){this.root=e,this.gitExecutor=t,this.userHomeDirectory=r,this.getThirdPartyExtensibilityEnabled=o}static getRipwalkCache(){return Mp.ripwalkCache??=new Oa,Mp.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,i.VI)(e.withName("NestedExtensibilityService.discover")),!1),o={rules:[],skills:[],markdown:[],agents:[]},n=(0,s.resolve)(this.root),a=(0,s.resolve)(this.userHomeDirectory);if(n===a||Fi(n,{platform:process.platform,homeDirectory:a}).length>0)return r.span.setAttribute("nested_extensibility.rules",0),r.span.setAttribute("nested_extensibility.skills",0),r.span.setAttribute("nested_extensibility.markdown",0),r.span.setAttribute("nested_extensibility.agents",0),o;if(!await Ba(e,this.gitExecutor,(0,s.resolve)(this.root)))return r.span.setAttribute("nested_extensibility.rules",0),r.span.setAttribute("nested_extensibility.skills",0),r.span.setAttribute("nested_extensibility.markdown",0),r.span.setAttribute("nested_extensibility.agents",0),o;const c=this.getThirdPartyExtensibilityEnabled(),l=this.buildIncludeGlobs(c),u={root:this.root,includeGlobs:l,excludeGlobs:qa,followSymlinks:!0,source:"nested_extensibility"},d={rules:[],skills:[],markdown:[],agents:[]},h=Mp.getRipwalkCache();try{const e=h.walk(r.ctx,u);try{for await(const t of e.lines){const e=Ap(t,c);e&&d[e].push((0,s.resolve)(this.root,t))}}finally{h.delete(u)}}catch{}return r.span.setAttribute("nested_extensibility.rules",d.rules.length),r.span.setAttribute("nested_extensibility.skills",d.skills.length),r.span.setAttribute("nested_extensibility.markdown",d.markdown.length),r.span.setAttribute("nested_extensibility.agents",d.agents.length),d}catch(e){t.error=e,t.hasError=!0}finally{xp(t)}}buildIncludeGlobs(e){const t=["*/**/.cursor/**","*/**/.agents/**","*/**/AGENTS.md"];return e&&t.push("*/**/.claude/**","*/**/.codex/**","*/**/.grok/**","*/**/CLAUDE.md","*/**/CLAUDE.local.md"),t}}const Dp=new Set(["node_modules","__pycache__","dist","build"]);async function Op({rootDir:e,includeFile:t,maxDepth:r=10,containmentRootDir:o}){const n=[],i=[{dir:e,depth:0}],a=new Set,c=void 0!==o?await(0,Os.realpath)(o):null,l=e=>{if(null===c)return!0;const t=(0,s.relative)(c,e);return""===t||!t.startsWith("..")&&!(0,s.isAbsolute)(t)};for(;i.length>0;){const e=i.pop();if(void 0===e)continue;const{dir:o,depth:c}=e;if(c>r)continue;try{const e=await(0,Os.realpath)(o);if(!l(e))continue;if(a.has(e))continue;a.add(e)}catch{continue}const d=await(0,Os.readdir)(o,{withFileTypes:!0,encoding:"utf8"}).catch((()=>null));if(null!==d)for(const e of d){const r=(0,s.join)(o,e.name);let a=e.isDirectory(),l=e.isFile();if(e.isSymbolicLink())try{const e=await(0,Os.stat)(r);a=e.isDirectory(),l=e.isFile()}catch{continue}if(a){if((u=e.name).startsWith(".")||Dp.has(u))continue;i.push({dir:r,depth:c+1})}else l&&t(e.name)&&n.push(r)}}var u;return n.sort(((e,t)=>e.localeCompare(t))),n}const Np={agentStoreSkillsDirs:[],userHomeDirectory:""};function $p(e){const t=e.replace(/\\/g,"/");return t.endsWith("/")?t.slice(0,-1):t}function Fp(e,t){const r=$p(t.userHomeDirectory),o=e.replace(/\\/g,"/");if(r.length>0)for(const e of t.agentStoreSkillsDirs){const t=$p(e);if(t.length>0&&o.startsWith(`${t}/`))return{key:`${r}::skills/${o.slice(t.length+1)}`,inAgentStore:!0}}return{key:jp(e),inAgentStore:!1}}function jp(e){const t=e.replace(/\\/g,"/"),r=t.toLowerCase(),o=r.indexOf("/.cursor/"),n=r.indexOf("/.claude/"),s=r.indexOf("/.codex/"),i=r.indexOf("/.grok/"),a=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+7)}`:-1!==a?`${t.slice(0,a)}::${t.slice(a+9)}`:e}function Lp(e,t){const r=new Map,o=[];for(const n of e){const{key:e,inAgentStore:s}=Fp(n.fullPath,t),i=r.get(e);void 0!==i?s&&!o[i].inAgentStore&&(o[i]={item:n,inAgentStore:s}):(r.set(e,o.length),o.push({item:n,inAgentStore:s}))}return o.map((e=>e.item))}var Up=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},Bp=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,m.h)("local-exec:cursor-rules"),Hp=102400;function qp(e){return"AGENTS.md"===e||"CLAUDE.md"===e||"CLAUDE.local.md"===e}function zp(e){return"/"===e||"\\"===e}function Gp(e){return e.split(/[\\/]+/).filter((e=>e.length>0)).length}async function Vp(e){return await Op({rootDir:e,includeFile:e=>"SKILL.md"===e})}async function Jp(e){let t;try{t=await ua(e)}catch(t){return{skillFilePath:e,error:u(t)}}try{return{skillFilePath:e,content:t,parsed:nh(t)}}catch(t){return{skillFilePath:e,error:d(t)}}}async function Kp(e){const t=await Js(e);return{...await Jp(e),realSkillFilePath:t}}function Zp(e){return Yp(e.data?.environments??e.data?.metadata?.environments)??[]}function Xp(e){return Yp(e.data?.["disabled-environments"]??e.data?.metadata?.disabledEnvironments)??[]}function Qp(e){return Yp(e.data?.metadata?.scopedTo??e.data?.["metadata.scopedTo"])??[]}function Yp(e){if(Array.isArray(e)){const t=e.filter((e=>"string"==typeof e&&e.length>0));return 0===t.length?void 0:t}if("string"==typeof e){const t=e.split(",").map((e=>e.trim())).filter((e=>e.length>0));return 0===t.length?void 0:t}}function ef(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 tf(e){return e.slice(0,1536)}function rf(e){return!0===e.data?.alwaysApply}function of(e){return!0===e.data?.["disable-model-invocation"]}function nf({skillFilePath:e,content:t,parsed:r}){const o=function(e){return function(e){const t=(e.matter??"").trim(),r=e.language?.toLowerCase();return t.length>0&&"js"!==r&&"javascript"!==r?`---\n${t}\n---`:sh("",e.data??{}).trim()}(e)}(r),n=function({fullPath:e,name:t,description:r,body:o}){const n=[],s=function(e){const t=e.replace(/\\/g,"/").split("/"),r=t[t.length-1]??"";return"SKILL.md"===r&&t.length>=2?t[t.length-2]??"":r}(e);s.length>64&&n.push(`Name is ${f(s.length)} characters; the limit is 64. Rename the skill's folder.`),p.test(s)||n.push('Name should be lowercase letters and numbers joined by single hyphens, like "pdf-helper". Rename the skill\'s folder.'),void 0!==t&&t!==s&&n.push(`Frontmatter name ${JSON.stringify(t)} doesn't match the folder name ${JSON.stringify(s)}, which is the name the skill goes by. Make them the same.`);const i=r?.trim().length??0;i>1024&&n.push(`Description is ${f(i)} characters; the limit is ${f(1024)}.`);const a=Math.round(o.length/4);return a>5e3&&n.push(`Body is about ${f(a)} tokens; the recommended limit is ${f(5e3)}. Move details into reference files that SKILL.md links to.`),n}({fullPath:e,name:"string"==typeof r.data?.name?r.data.name:void 0,description:"string"==typeof r.data?.description?r.data.description:void 0,body:r.content});if(rf(r))return new pp.DX({fullPath:e,content:t,frontmatter:o,type:new pp.f5({type:{case:"global",value:new pp.i9}}),environments:Zp(r),disabledEnvironments:Xp(r),scopedTo:Qp(r),warnings:n});const s="string"==typeof r.data?.description?tf(r.data.description):void 0,i=h(s,of(r));return i?new pp.DX({fullPath:e,parseError:i,frontmatter:o,scopedTo:Qp(r),type:new pp.f5({type:{case:"agentFetched",value:new pp.Xo}})}):new pp.DX({fullPath:e,content:t,frontmatter:o,type:new pp.f5({type:{case:"agentFetched",value:new pp.Xo({description:s})}}),environments:Zp(r),disabledEnvironments:Xp(r),scopedTo:Qp(r),warnings:n})}function sf({skillFilePath:e,content:t,parsed:r}){const o="string"==typeof r.data?.description?tf(r.data.description):"",n=Oh(r.data?.paths??r.data?.globs),s=of(r);return new hp.N({fullPath:e,content:t,description:o,globs:n??[],parseError:h(o,s),environments:Zp(r),disabledEnvironments:Xp(r),scopedTo:Qp(r),disableModelInvocation:s})}function af({rules:e,agentSkills:t,skillFilePath:r,errorMessage:o}){e.push(function({skillFilePath:e,errorMessage:t}){return new pp.DX({fullPath:e,parseError:t,type:new pp.f5({type:{case:"agentFetched",value:new pp.Xo}})})}({skillFilePath:r,errorMessage:o})),t.push(function({skillFilePath:e,errorMessage:t}){return new hp.N({fullPath:e,parseError:t})}({skillFilePath:r,errorMessage:o}))}function cf(e,t,r){if("error"in t)return e.realSkillFilePathsByFullPath.set(t.skillFilePath,t.realSkillFilePath),void af({rules:e.rules,agentSkills:e.agentSkills,skillFilePath:t.skillFilePath,errorMessage:t.error});ef(t.parsed,r)||(e.realSkillFilePathsByFullPath.set(t.skillFilePath,t.realSkillFilePath),e.rules.push(nf(t)),rf(t.parsed)||e.agentSkills.push(sf(t)))}const lf=(0,ji.debuglog)("cursor-rules-service");function uf(){return{rules:[],agentSkills:[],realSkillFilePathsByFullPath:new Map}}function df(e){return t=>(lf("%s: %O",e,t),uf())}function hf(e,t){return mp({kind:"agent-store",surface:e,roots:[...t].sort()})}function pf(e,t){const r=t.replace(/\\/g,"/").replace(/\/+$/,"");return""!==r&&e.replace(/\\/g,"/").startsWith(`${r}/`)}function ff(e){const t=e.trim();return"true"===t||"false"!==t&&(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t)}function mf(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(),c=ff(n),l=`${i}.${o}`;""===n?(s[l]=[],a=l):"metadata.environments"===l||"metadata.disabledEnvironments"===l||"metadata.scopedTo"===l?(s[l]=String(c).split(",").map((e=>e.trim())).filter(Boolean),a=null):(s[l]=c,a=null);continue}i=null,a=null;const n=t.indexOf(":");if(-1===n)continue;const c=t.slice(0,n).trim(),l=t.slice(n+1).trim();if(""===l&&"metadata"===c){i=c;continue}if("globs"===c&&""===l){s.globs=[],a="globs";continue}const u=ff(l);s[c]="metadata.environments"!==c&&"metadata.disabledEnvironments"!==c&&"metadata.scopedTo"!==c?u:String(u).split(",").map((e=>e.trim())).filter(Boolean)}return{frontmatter:s,rawFrontmatter:`---\n${o}\n---`,body:n}}class gf{constructor(e,t){this.cursorRulesServices=e,this.getAgentStoreSkillsContext=t,this.onChangeCallbacks=new Set}async getAllCursorRules(e){const t={stack:[],error:void 0,hasError:!1};try{const r=Up(t,(0,i.VI)(e.withName("MergedCursorRulesService.getAllCursorRules")),!1),o=this.cursorRulesServices.map((e=>e.getAllCursorRules(r.ctx).catch((e=>((0,ji.debuglog)("Failed to load cursor rules from service:",e),[])))));return Lp((await Promise.all(o)).flat(),this.getAgentStoreSkillsContext())}catch(e){t.error=e,t.hasError=!0}finally{Bp(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()}),gf.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()}}gf.CHANGE_COALESCE_MS=1e3;class wf{constructor(e,t,r,o,a,c,l,u){this.gitExecutor=t,this.rootDirectory=r,this.loadNestedRules=o,this.getThirdPartyExtensibilityEnabled=a,this.loadTraceId=void 0,this.onChangeCallbacks=new Set,this.nestedExtensibilityService=new Mp(r,t,(0,n.homedir)(),a),this.ignoreService=l??new Ya(t,void 0,[this.rootDirectory]);const d=performance.now();if(this._rules=this.load(e,u).then((t=>{try{Wp.info(e,"LocalCursorRulesService load completed",{durationMs:Math.round(performance.now()-d),ruleCount:t.length})}catch{}return t})).catch((e=>((0,ji.debuglog)("Failed to load cursor rules:",e),[]))),c){const e=[".cursor/rules/**/*.mdc","AGENTS.md","CLAUDE.md","CLAUDE.local.md",".cursorrules",".cursorignore"];this.unsubscribeWatcher=c.subscribe(this.rootDirectory,e,(e=>{const t={stack:[],error:void 0,hasError:!1};try{const r=(0,ce.q6)(),o=Up(t,(0,i.VI)(r.withName("LocalCursorRulesService.fileWatcher.subscribe")),!1);if(".cursorignore"===(0,s.basename)(e))return wf.getRipwalkCache().clear(),void this.reload(o.ctx);this.reloadAtPath(o.ctx,e)}catch(e){t.error=e,t.hasError=!0}finally{Bp(t)}}))}}reload(e){this._rules=this.load(e).catch((e=>((0,ji.debuglog)("Failed to load cursor rules:",e),[])));for(const e of this.onChangeCallbacks)e()}static getRipwalkCache(){return wf.ripwalkCache??=new Oa,wf.ripwalkCache}reloadAtPath(e,t){const r={stack:[],error:void 0,hasError:!1};try{const o=Up(r,(0,i.VI)(e.withName("LocalCursorRulesService.reloadAtPath")),!1);if(qp((0,s.basename)(t)))return void this.reload(o.ctx);const n=this._rules;this._rules=(async()=>{const e=(await n).filter((e=>e.fullPath!==t));const r=(await this.readRulesAtPath(o.ctx,t)).map((e=>this.toCursorRule(e)));return[...e,...r]})().catch((e=>((0,ji.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{Bp(r)}}isRuleMarkdownFile(e){return qp(e)}async readRulesAtPath(e,t){const r={stack:[],error:void 0,hasError:!1};try{const o=Up(r,(0,i.VI)(e.withName("LocalCursorRulesService.readRulesAtPath")),!1),n=(0,s.basename)(t);if(".cursorrules"===n){const e=(0,s.resolve)(this.rootDirectory),t=await Ba(o.ctx,this.gitExecutor,e)||e,r=await this.loadCursorRulesRule(o.ctx,t);return r?[r]:[]}if(n.endsWith(".mdc"))try{const e=mf(await ua(t));if(e)return[{filename:(0,s.basename)(t,".mdc"),path:t,frontmatter:e.frontmatter,rawFrontmatter:e.rawFrontmatter,body:e.body}]}catch{}else if(this.isRuleMarkdownFile(n))try{return await this.loadRulesFromMarkdownFile(o.ctx,(0,s.dirname)(t),n)}catch{}return[]}catch(e){r.error=e,r.hasError=!0}finally{Bp(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=Up(r,(0,i.VI)(e.withName("LocalCursorRulesService.load")),!1);this.loadTraceId=o.span.spanContext().traceId;const n=(0,s.resolve)(this.rootDirectory),a=await Ba(o.ctx,this.gitExecutor,n)||n,c=this.loadCursorRulesRule(o.ctx,a).then((e=>e?[e]:[])),l=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 h=(await Promise.all([c,l,u,d])).flat(),p=new Map;for(const e of h)p.set(e.path,e);const f=[...p.values()];return(await async function(e){const t=e.filter((e=>qp((0,s.basename)(e.fullPath))));if(t.length<=1)return[...e];const r=await(0,Ht.PH)(t,(e=>async function(e){try{const t=await(0,Os.stat)(e,{bigint:!0});if(0n!==t.ino)return`ino:${String(t.dev)}:${String(t.ino)}`}catch{}return await Js(e)}(e.fullPath)),{max:16}),o=t.map(((e,t)=>({item:e,identity:r[t],dir:(0,s.dirname)(e.fullPath),content:e.content.trim()}))).sort(((e,t)=>{const r=Gp(e.dir)-Gp(t.dir);if(0!==r)return r;const o="AGENTS.md"===(0,s.basename)(e.item.fullPath);return o===("AGENTS.md"===(0,s.basename)(t.item.fullPath))?0:o?-1:1})),n=[];for(const e of o)n.some((t=>{return((r=t.dir)===(o=e.dir)||!!o.startsWith(r)&&(zp(r.at(-1))||zp(o[r.length])))&&(t.identity===e.identity||t.content===e.content);var r,o}))||n.push(e);const i=new Set(n.map((e=>e.item)));return e.filter((e=>!qp((0,s.basename)(e.fullPath))||i.has(e)))}(f.map((e=>({fullPath:e.path,content:e.body,rule:e}))))).map((e=>this.toCursorRule(e.rule)))}catch(e){r.error=e,r.hasError=!0}finally{Bp(r)}}async loadCursorRulesRule(e,t){const r={stack:[],error:void 0,hasError:!1};try{Up(r,(0,i.VI)(e.withName("LocalCursorRulesService.loadCursorrules")),!1);try{const e=(0,s.join)(t,".cursorrules");if((await(0,Os.stat)(e)).isFile())return{filename:".cursorrules",path:e,frontmatter:{alwaysApply:!0},body:await ua(e)}}catch{}return null}catch(e){r.error=e,r.hasError=!0}finally{Bp(r)}}async getAllCursorRules(e){const t={stack:[],error:void 0,hasError:!1};try{return Up(t,(0,i.VI)(e.withName("LocalCursorRulesService.getAllCursorRules")),!1).span.setAttribute("cacheTraceId",this.loadTraceId??"undefined"),await this._rules}catch(e){t.error=e,t.hasError=!0}finally{Bp(t)}}toCursorRule(e){return function(e){let t;if(!0===e.frontmatter.alwaysApply)t={case:"global",value:new pp.i9};else{const r=Oh(e.frontmatter.globs);t=r&&r.length>0?{case:"fileGlobbed",value:new pp.uT({globs:r})}:"string"==typeof e.frontmatter.description&&e.frontmatter.description.trim().length>0?{case:"agentFetched",value:new pp.Xo({description:tf(e.frontmatter.description)})}:{case:"manuallyAttached",value:new pp._u}}const r=e.frontmatter["metadata.environments"],o=Array.isArray(r)?r:[],n=e.frontmatter["metadata.disabledEnvironments"],s=Array.isArray(n)?n:[],i=e.frontmatter["metadata.scopedTo"],a=Array.isArray(i)?i:[];return new pp.DX({fullPath:e.path,content:e.body,type:new pp.f5({type:t}),environments:o,disabledEnvironments:s,scopedTo:a,frontmatter:e.rawFrontmatter??""})}({path:e.path,body:e.body,frontmatter:e.frontmatter,rawFrontmatter:e.rawFrontmatter})}async loadRulesFromDirAndAncestors(e,t){const r={stack:[],error:void 0,hasError:!1};try{const o=Up(r,(0,i.VI)(e.withName("LocalCursorRulesService.loadRulesFromDirAndAncestors")),!1),n=[];let a=t;const c=this.getThirdPartyExtensibilityEnabled();for(;;){const e=(0,s.join)(a,".cursor","rules"),t=a;n.push((async()=>await this.dirIsDirectory(o.ctx,e)?this.loadRulesFromDirectory(o.ctx,t):[])());const r=[];c&&r.push("CLAUDE.md","CLAUDE.local.md"),r.push("AGENTS.md");for(const e of r)n.push(this.loadRulesFromMarkdownFile(o.ctx,a,e));const i=(0,s.dirname)(a);if(i===a)break;a=i}const l=(await Promise.all(n)).flat();return o.span.setAttribute("rules",l.length),l}catch(e){r.error=e,r.hasError=!0}finally{Bp(r)}}async loadRulesFromMarkdownFile(e,t,r){const o={stack:[],error:void 0,hasError:!1};try{Up(o,(0,i.VI)(e.withName("LocalCursorRulesService.loadRulesFromMarkdownFile")),!1).span.setAttribute("filename",r);try{const e=(0,s.join)(t,r);if(await this.isCursorIgnored(e))return[];if((await(0,Os.stat)(e)).isFile()){const t=await ua(e),o=Buffer.byteLength(t,"utf8")>Hp?function({content:e,filename:t}){const r=Buffer.from(e,"utf8");let o=Hp;for(;128==(192&r.readUInt8(o));)o--;const n=`[truncated: ${t} is ${Math.round(r.length/1024)} KB; only the first 100 KB is included]`;return`${r.subarray(0,o).toString("utf8")}\n\n${n}`}({content:t,filename:r}):t;return[{filename:(0,s.basename)(e,".md"),path:e,frontmatter:{alwaysApply:!0},body:o}]}}catch{}return[]}catch(e){o.error=e,o.hasError=!0}finally{Bp(o)}}async isCursorIgnored(e){try{const t=await Xa((0,s.resolve)(this.rootDirectory,e));return null===t||await this.ignoreService.isCursorIgnored(t)}catch{return!1}}async parseNestedRuleFiles(e,t){const r={stack:[],error:void 0,hasError:!1};try{const o=Up(r,(0,i.VI)(e.withName("LocalCursorRulesService.parseNestedRuleFiles")),!1),n=(await Promise.all(t.map((async e=>{try{const t=mf(await ua(e));if(t)return{filename:(0,s.basename)(e,".mdc"),path:e,frontmatter:t.frontmatter,rawFrontmatter:t.rawFrontmatter,body:t.body}}catch{}})))).filter((e=>void 0!==e));return o.span.setAttribute("ruleFiles",n.length),n}catch(e){r.error=e,r.hasError=!0}finally{Bp(r)}}async parseNestedMarkdownFiles(e,t){const r={stack:[],error:void 0,hasError:!1};try{const o=Up(r,(0,i.VI)(e.withName("LocalCursorRulesService.parseNestedMarkdownFiles")),!1),n=(await Promise.all(t.map((async e=>{try{const t=(0,s.basename)(e);if(!this.isRuleMarkdownFile(t))return[];const r=(0,s.dirname)(e);return await this.loadRulesFromMarkdownFile(o.ctx,r,t)}catch{}return[]})))).flat();return o.span.setAttribute("markdownFiles",n.length),n}catch(e){r.error=e,r.hasError=!0}finally{Bp(r)}}async loadRulesFromDirectory(e,t){const r={stack:[],error:void 0,hasError:!1};try{const o=Up(r,(0,i.VI)(e.withName("LocalCursorRulesService.loadRulesFromDirectory")),!1),n=[];try{(0,s.join)(t,".cursorignore");const e={root:(0,s.join)(t,".cursor","rules"),includeGlobs:["**/*.mdc"],followSymlinks:!0,source:"cursor_rules"},r=wf.getRipwalkCache().walk(o.ctx,e);for await(const t of r.lines){const r=(0,s.join)(e.root,t);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{Bp(r)}}async dirIsDirectory(e,t){const r={stack:[],error:void 0,hasError:!1};try{Up(r,(0,i.VI)(e.withName("LocalCursorRulesService.dirIsDirectory")),!1);try{return(await(0,Os.stat)(t)).isDirectory()}catch{return!1}}catch(e){r.error=e,r.hasError=!0}finally{Bp(r)}}}class yf{constructor(e,t,r,o,n,s,i=()=>!0,a=Promise.resolve(),c="ide",l,u=()=>[],d){if(this.workspacePaths=t,this.userHomeDirectory=r,this.gitExecutor=o,this.initialBuiltinSkillsSyncPromise=a,this.agentStoreLoadRequestedWhileInFlight=!1,this.agentStoreLoadGeneration=0,this.watchersByFolder=new Map,this.onChangeCallbacks=new Set,this.reloadRequestedDuringSeed=!1,this.surface=c,this.getAgentStoreSkillRoots=u,this.fileWatcher=s,this.getThirdPartyExtensibilityEnabled=i,this.catalogCache=d,this.workspaceCatalogKey=mp({kind:"workspace",surface:c,loadNestedSkills:n,thirdPartyExtensibility:i(),workspacePaths:[...t].sort(),userHomeDirectory:r}),void 0!==l&&l.length!==t.length)throw new Error(`initialNestedExtensibilityResults length (${l.length}) must match workspacePaths length (${t.length})`);this.nestedExtensibilityEntries=n?t.map((e=>new Mp(e,o,r,i))):[],this.foldersToWatch=this.computeFoldersToWatch();const h=performance.now();let p=!1,f=!1,m=!1;const g=this.loadAll(e,l).then((t=>{try{Wp.info(e,"AgentSkillsCursorRulesService load completed",{durationMs:Math.round(performance.now()-h),ruleCount:t.rules.length,skillCount:t.agentSkills.length,servedFromCache:p})}catch{}return t})).catch((e=>(f=!0,df("Failed to load Agent Skills")(e))));if(void 0===this.catalogCache)this._loaded=g;else{const t=this.readCatalog(this.workspaceCatalogKey).then((r=>(m=!0,this._loaded!==t?this._loaded:(f&&this.closeSeedWindow(e),void 0===r?g:(p=!0,r)))));this.seededLoaded=t,this._loaded=t,g.then((r=>{this._loaded===t?f?m&&this.closeSeedWindow(e):(this._loaded=g,p&&this.notifyChanged(),this.persistCatalog(this.workspaceCatalogKey,r),this.closeSeedWindow(e)):this.seededLoaded=void 0}))}this.refreshAgentStoreSkills(),this.setupWatchers(this.foldersToWatch)}closeSeedWindow(e){this.seededLoaded=void 0,this.reloadRequestedDuringSeed&&(this.reloadRequestedDuringSeed=!1,this.reload(e))}async readCatalog(e){if(void 0!==this.catalogCache)try{const t=await this.catalogCache.read(e);return void 0===t?void 0:await async function(e){if(!function(e){if("object"!=typeof e||null===e)return!1;const t=e;return 1===t.version&&Array.isArray(t.rules)&&Array.isArray(t.agentSkills)&&Array.isArray(t.realSkillFilePathsByFullPath)&&t.realSkillFilePathsByFullPath.every((e=>Array.isArray(e)&&2===e.length&&"string"==typeof e[0]&&"string"==typeof e[1]))&&"object"==typeof t.fileMtimesMs&&null!==t.fileMtimesMs&&Object.values(t.fileMtimesMs).every((e=>"number"==typeof e&&Number.isFinite(e)))}(e))return;const t=new Map;if(await Promise.all(e.realSkillFilePathsByFullPath.map((async([r,o])=>{const n=e.fileMtimesMs[o];void 0!==n&&await gp(r)===n&&t.set(r,o)}))),0===t.size)return;const r=e=>void 0!==e&&t.has(e);try{return{rules:e.rules.map((e=>pp.DX.fromJson(e,{ignoreUnknownFields:!0}))).filter((e=>r(e.fullPath))),agentSkills:e.agentSkills.map((e=>hp.N.fromJson(e,{ignoreUnknownFields:!0}))).filter((e=>r(e.fullPath))),realSkillFilePathsByFullPath:t}}catch(e){return void fp("snapshot failed to decode: %O",e)}}(t)}catch(e){return void lf("Failed to read the skills catalog cache: %O",e)}}persistCatalog(e,t){const r=this.catalogCache;void 0!==r&&async function(e){const t=new Set(e.realSkillFilePathsByFullPath.values()),r={};return await Promise.all(Array.from(t,(async e=>{const t=await gp(e);void 0!==t&&(r[e]=t)}))),{version:1,rules:e.rules.map((e=>e.toJson())),agentSkills:e.agentSkills.map((e=>e.toJson())),realSkillFilePathsByFullPath:Array.from(e.realSkillFilePathsByFullPath),fileMtimesMs:r}}(t).then((t=>r.write(e,t))).catch((e=>{lf("Failed to persist the skills catalog cache: %O",e)}))}computeFoldersToWatch(){const e=this.getThirdPartyExtensibilityEnabled(),t=new Set;for(const r of this.workspacePaths){t.add((0,s.join)(r,".cursor","rules"));for(const o of Ep(r,e))t.add(o.dirPath)}for(const r of Cp(this.userHomeDirectory,e))t.add(r.dirPath);for(const e of this.getAgentStoreSkillRoots())t.add(e);return t.add(Sp(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,ce.q6)(),o=Up(t,(0,i.VI)(r.withName("AgentSkillsCursorRulesService.fileWatcher.subscribe")),!1);this.reloadAtPath(o.ctx,e)}catch(e){t.error=e,t.hasError=!0}finally{Bp(t)}}));this.watchersByFolder.set(r,e)}}removeWatchers(e){for(const t of e){const e=this.watchersByFolder.get(t);e&&(e(),this.watchersByFolder.delete(t))}}async getAllCursorRules(e){const[t]=await Promise.all([this._loaded,this.awaitAgentStoreSeed()]);return this.withAgentStoreSkills(t).rules}async awaitAgentStoreSeed(){void 0!==this.agentStoreSeedInFlight&&await(0,Ht.wj)(this.agentStoreSeedInFlight,250,"Agent Store skills cache read timed out").catch((()=>{}))}reload(e){this.syncWatchers(),this.seededLoaded=void 0,this.reloadRequestedDuringSeed=!1;const t=this.loadAll(e),r=t.catch(df("Failed to load Agent Skills"));this._loaded=r,t.then((e=>{this._loaded===r&&this.persistCatalog(this.workspaceCatalogKey,e)}),(()=>{})),this.refreshAgentStoreSkills(),this.notifyChanged()}reloadSkillRoots(){try{this.syncWatchers()}finally{this.refreshAgentStoreSkills()}}async agentStoreSkillsSettled(){for(let e=this.agentStoreWalk;void 0!==e;e=this.agentStoreWalk)await e}syncWatchers(){const e=this.computeFoldersToWatch(),t=new Set(this.foldersToWatch),r=new Set(e);this.removeWatchers(this.foldersToWatch.filter((e=>!r.has(e)))),this.setupWatchers(e.filter((e=>!t.has(e)))),this.foldersToWatch=e}isPrunedByExtensibilityScan(e){const t=e.replace(/\\/g,"/");for(const e of this.foldersToWatch){const r=e.replace(/\\/g,"/");if(t.startsWith(`${r}/`))return t.slice(r.length+1).split("/").slice(0,-1).some((e=>e.startsWith(".")))}return!1}reloadAtPath(e,t){const r={stack:[],error:void 0,hasError:!1};try{const o=Up(r,(0,i.VI)(e.withName("AgentSkillsCursorRulesService.reloadAtPath")),!1),n=t.endsWith("SKILL.md")?t:(0,s.join)(t,"SKILL.md");if(void 0!==this.seededLoaded&&this._loaded===this.seededLoaded&&!this.getAgentStoreSkillRoots().some((e=>pf(n,e))))return void(this.reloadRequestedDuringSeed=!0);if(this.getAgentStoreSkillRoots().some((e=>pf(n,e))))return void this.refreshAgentStoreSkills();if(this.foldersToWatch.some((e=>""===(0,s.relative)(e,t))))return void this.reload(o.ctx);const a=this._loaded,c=(async()=>{const e=await a,{realSkillFilePathsByFullPath:t}=e,r=function(e,t){const r=new Map(e.realSkillFilePathsByFullPath);for(const e of t)r.delete(e);return{rules:e.rules.filter((e=>!t.has(e.fullPath))),agentSkills:e.agentSkills.filter((e=>!t.has(e.fullPath))),realSkillFilePathsByFullPath:r}}(e,new Set([n]));if(bp(n)||this.isPrunedByExtensibilityScan(n))return r;const s=t.get(n);if(void 0===s){try{await(0,Os.stat)(n)}catch{return r}return await this.loadAll(o.ctx)}let i;try{i=await(0,Os.realpath)(n)}catch{return await this.loadAll(o.ctx)}if(i!==s)return await this.loadAll(o.ctx);try{return cf(r,{...await async function(e){const t=await ua(e);return{skillFilePath:e,content:t,parsed:nh(t)}}(n),realSkillFilePath:i},this.surface),r}catch{return await this.loadAll(o.ctx)}})().catch(df("Failed to load Agent Skills at path"));this._loaded=c,this.notifyChanged()}catch(e){r.error=e,r.hasError=!0}finally{Bp(r)}}async getAllAgentSkills(e){const[t]=await Promise.all([this._loaded,this.awaitAgentStoreSeed()]);return this.withAgentStoreSkills(t).agentSkills}withAgentStoreSkills(e){const t=this.settledAgentStoreSkills?.loaded;if(void 0===t||0===t.realSkillFilePathsByFullPath.size)return e;const r=new Set(e.realSkillFilePathsByFullPath.values()),o={rules:[...e.rules],agentSkills:[...e.agentSkills],realSkillFilePathsByFullPath:new Map(e.realSkillFilePathsByFullPath)},n=new Set;for(const[e,s]of t.realSkillFilePathsByFullPath)o.realSkillFilePathsByFullPath.has(e)||r.has(s)?n.add(e):o.realSkillFilePathsByFullPath.set(e,s);for(const e of t.rules)n.has(e.fullPath)||o.rules.push(e);for(const e of t.agentSkills)n.has(e.fullPath)||o.agentSkills.push(e);return o}refreshAgentStoreSkills(){const e=this.getAgentStoreSkillRoots().filter((e=>""!==e.trim())),t=++this.agentStoreLoadGeneration;var r,o;if(void 0===this.settledAgentStoreSkills||(r=this.settledAgentStoreSkills.roots,o=e,r.length===o.length&&r.every(((e,t)=>e===o[t])))||(this.settledAgentStoreSkills=void 0,this.notifyChanged()),0!==e.length){if(void 0===this.settledAgentStoreSkills){const r=this.seedAgentStoreSkills(e,t).finally((()=>{this.agentStoreSeedInFlight===r&&(this.agentStoreSeedInFlight=void 0)}));this.agentStoreSeedInFlight=r}void 0===this.agentStoreWalk?this.agentStoreWalk=(0,Ht.wj)(this.loadAgentStoreSkills(e),3e4,"Agent Store skills walk timed out").then((r=>{t===this.agentStoreLoadGeneration&&(this.settledAgentStoreSkills={roots:e,loaded:r},this.notifyChanged(),(r.rules.length>0||r.agentSkills.length>0)&&this.persistCatalog(hf(this.surface,e),r))}),(e=>{lf("Failed to load Agent Store skills: %O",e)})).finally((()=>{this.agentStoreWalk=void 0,this.agentStoreLoadRequestedWhileInFlight&&(this.agentStoreLoadRequestedWhileInFlight=!1,this.refreshAgentStoreSkills())})):this.agentStoreLoadRequestedWhileInFlight=!0}}async seedAgentStoreSkills(e,t){const r=await this.readCatalog(hf(this.surface,e));void 0!==r&&t===this.agentStoreLoadGeneration&&void 0===this.settledAgentStoreSkills&&(this.settledAgentStoreSkills={roots:e,loaded:r},this.notifyChanged())}async loadAgentStoreSkills(e){const t=uf(),r=(await Promise.all(e.map((e=>Vp(e))))).flat().filter((e=>!bp(e))),o=await Promise.all(r.map((e=>Kp(e)))),n=new Set;for(const e of o)n.has(e.realSkillFilePath)||(n.add(e.realSkillFilePath),cf(t,e,this.surface));return t}notifyChanged(){for(const e of Array.from(this.onChangeCallbacks))e()}onDidChangeSkills(e){return this.onDidChangeRules(e)}onDidChangeRules(e){return this.onChangeCallbacks.add(e),()=>{this.onChangeCallbacks.delete(e)}}dispose(){for(const e of this.watchersByFolder.values())e();this.watchersByFolder.clear()}async loadAll(e,t){const r={stack:[],error:void 0,hasError:!1};try{const o=Up(r,(0,i.VI)(e.withName("AgentSkillsCursorRulesService.loadAll")),!1);await this.initialBuiltinSkillsSyncPromise;const n=[],s=[],a=new Map,c=Promise.all(this.nestedExtensibilityEntries.map(((e,r)=>(t?.[r]??e.discover(o.ctx)).catch((e=>{lf("Failed to discover nested agent skills: %O",e)}))))),l=new Set(this.getAgentStoreSkillRoots()),u=await Promise.all(this.foldersToWatch.filter((e=>!l.has(e))).map((async e=>{const t=(await Vp(e)).filter((e=>!bp(e)));return Promise.all(t.map((e=>Kp(e))))}))),d=new Set;for(const e of u)for(const t of e)if(!d.has(t.realSkillFilePath))if(d.add(t.realSkillFilePath),"error"in t)a.set(t.skillFilePath,t.realSkillFilePath),af({rules:n,agentSkills:s,skillFilePath:t.skillFilePath,errorMessage:t.error});else{if(ef(t.parsed,this.surface))continue;a.set(t.skillFilePath,t.realSkillFilePath),n.push(nf(t)),rf(t.parsed)||s.push(sf(t))}const h=(await c).flatMap((e=>e?.skills??[])).filter((e=>!bp(e))),p=await Promise.all(h.map((e=>Js(e)))),f=[];for(const[e,t]of h.entries()){const r=p[e];d.has(r)||(d.add(r),f.push(t))}const m=await Promise.all(f.map((e=>Kp(e))));for(const e of m)if("error"in e)a.set(e.skillFilePath,e.realSkillFilePath),af({rules:n,agentSkills:s,skillFilePath:e.skillFilePath,errorMessage:e.error});else{if(ef(e.parsed,this.surface))continue;a.set(e.skillFilePath,e.realSkillFilePath),n.push(nf(e)),rf(e.parsed)||s.push(sf(e))}return o.span.setAttribute("agent_skills.total",n.length),o.span.setAttribute("agent_skills_proto.total",s.length),{rules:n,agentSkills:s,realSkillFilePathsByFullPath:a}}catch(e){r.error=e,r.hasError=!0}finally{Bp(r)}}}function vf(e){let t;switch(e.type){case"global":t=new pp.f5({type:{case:"global",value:new pp.i9}});break;case"fileGlobbed":t=new pp.f5({type:{case:"fileGlobbed",value:new pp.uT({globs:e.globs??[]})}});break;case"agentFetched":t=new pp.f5({type:{case:"agentFetched",value:new pp.Xo({description:tf(e.description??"")})}});break;case"manuallyAttached":t=new pp.f5({type:{case:"manuallyAttached",value:new pp._u}});break;default:e.type,t=new pp.f5({type:{case:"manuallyAttached",value:new pp._u}})}return new pp.DX({fullPath:e.fullPath,content:e.content,type:t,gitRemoteOrigin:e.gitRemoteOrigin,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId,environments:e.environments??[],disabledEnvironments:e.disabledEnvironments??[],scopedTo:[]})}class bf{constructor(e,t,r,o){this.getImportSettings=t,this.pluginsService=o,this._rules=Promise.resolve([]),this._agentSkills=Promise.resolve([]),this._lastLoaded={rules:[],agentSkills:[]},this._loadGeneration=0,this.onChangeCallbacks=new Set,this.currentImportSettings=this.getImportSettings();const n=performance.now();this.startLoad(e,!1,(t=>{try{Wp.info(e,"CursorPluginsAgentSkillsService load completed",{durationMs:Math.round(performance.now()-n),ruleCount:t.rules.length,skillCount:t.agentSkills.length})}catch{}}))}startLoad(e,t,r){const o=++this._loadGeneration,n=this.loadAll(e,t).catch((e=>((0,ji.debuglog)("cursor-plugins-agent-skills")("Failed to load Cursor Plugins Agent Skills: %s",e instanceof Error?e.message:String(e)),{rules:[],agentSkills:[]}))).then((e=>(o===this._loadGeneration&&(this._lastLoaded=e,r?.(e)),e))),s=()=>(n.then((e=>{o===this._loadGeneration&&(this._rules=Promise.resolve(e.rules),this._agentSkills=Promise.resolve(e.agentSkills),this.notifyChange())})),this._lastLoaded),i=void 0!==this._overBudgetLoad?Promise.resolve(s()):(0,Ht.wj)(n,5e3,"Cursor plugin load did not finish within the rules wait budget").catch((t=>(Wp.warn(e,"Serving rules without plugin primitives while plugins load",{error:t instanceof Error?t.message:String(t),waitMs:5e3}),this._overBudgetLoad=n,n.then((()=>{this._overBudgetLoad===n&&(this._overBudgetLoad=void 0)})),s())));this._rules=i.then((e=>e.rules)),this._agentSkills=i.then((e=>e.agentSkills))}notifyChange(){for(const e of Array.from(this.onChangeCallbacks))e()}async getAllCursorRules(e){return await this._rules}async getAllAgentSkills(e){return await this._agentSkills}reload(e){const t=this.getImportSettings();this.currentImportSettings=t,this.startLoad(e,!0),this.notifyChange()}onDidChangeRules(e){return this.onChangeCallbacks.add(e),()=>{this.onChangeCallbacks.delete(e)}}onDidChangeSkills(e){return this.onDidChangeRules(e)}dispose(){this.onChangeCallbacks.clear()}async loadAll(e,t=!1){const r={stack:[],error:void 0,hasError:!1};try{const o=Up(r,(0,i.VI)(e.withName("CursorPluginsAgentSkillsService.loadAll")),!1),n=[],a=[];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 Qh(e,(e=>e.skills))}(e),i=function(e){return Qh(e,(e=>e.rules))}(e);for(const e of[...r,...i])n.push(vf(e));for(const t of e){const e=`plugin:${tl(t.identifier)}`,r=rl(t.identifier),o=ol(t.identifier),n=nl(t.identifier),i=sl(t.identifier);for(const c of t.skills){if(!0===c.alwaysApply)continue;let l=!1;if(c.content?.includes("disable-model-invocation"))try{l=!0===nh(c.content).data?.["disable-model-invocation"]}catch{}a.push(new hp.N({fullPath:(0,s.join)(t.installPath,c.path),content:c.content,description:tf(c.description??""),environments:c.environments??[],disabledEnvironments:c.disabledEnvironments??[],gitRemoteOrigin:e,plugin:r,marketplace:o,pluginId:n,marketplaceId:i,disableModelInvocation:l}))}}}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",a.length),{rules:n,agentSkills:a}}catch(e){r.error=e,r.hasError=!0}finally{Bp(r)}}}const Sf=(0,ji.debuglog)("local-subagents");class kf{async getAllSubagents(){return[]}async reload(){return[]}}function Ef(e){return"true"===(e??"").trim().toLowerCase()}function Cf(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,c=Ef(n["force-default-model"]),l="true"===(n.readonly??"").trim().toLowerCase()?io.b$.READONLY:io.b$.DEFAULT,u=Ef(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:c,prompt:o,permissionMode:l,isBackground:u}}function xf(e){const t=(0,s.extname)(e).toLowerCase();return".md"===t||".mdc"===t||".markdown"===t}function _f(e){return(0,s.basename)(e,(0,s.extname)(e)).replace(/[\s_]+/g,"-")}async function Pf(e,t){return await Op({rootDir:e,includeFile:xf,containmentRootDir:t})}class If{constructor(e,t,r="workspace",o=!1){this.workspacePath=e,this.cursorAgentsSource=r,this.allowExternalAgentSymlinks=o,this.getThirdPartyExtensibilityEnabled=t??(()=>!0),this.subagents=this.load().catch((e=>(Sf("Failed to load subagents: %o",e),[])))}async getAllSubagents(){return this.subagents}async reload(){return this.subagents=this.load().catch((e=>(Sf("Failed to load subagents: %o",e),[]))),await this.subagents}computeAgentsDirs(){const e=(0,s.resolve)(this.workspacePath),t=[{dirPath:(0,s.join)(e,".cursor","agents"),source:this.cursorAgentsSource}];return this.getThirdPartyExtensibilityEnabled()&&(t.push({dirPath:(0,s.join)(e,".claude","agents"),source:"claude"}),t.push({dirPath:(0,s.join)(e,".grok","agents"),source:"grok"})),t}async load(){const e=this.computeAgentsDirs(),t=[];for(const{dirPath:r,source:o}of e){const e=await Pf(r,this.allowExternalAgentSymlinks?void 0:this.workspacePath);for(const r of e){const e=(0,s.basename)(r);try{if(!(await(0,Os.stat)(r)).isFile())continue}catch(e){Sf("Skipping subagent file %s due to stat error: %o",r,e);continue}try{const n=Cf(await ua(r));if(!n)continue;t.push(new io.zz({fullPath:r,name:n.name||_f(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){Sf("Failed to parse subagent file %s: %o",r,e)}}}return t}}const Rf=new Set(["claude-code-tutor"]);class Tf{constructor(e){this.subagentsServices=e}async getAllSubagents(){const e=await Promise.all(this.subagentsServices.map((e=>e.getAllSubagents().catch((e=>(Sf("Failed to load subagents from merged service: %o",e),[])))))),t=new Map;for(const r of e)for(const e of r)Rf.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 Af{constructor(e,t){this.getSettings=e,this.pluginsService=t,this._subagentsCache=[],this._loadId=0,this._loadPromise=null,this._loadedOnce=!1,this.runLoadInBackground()}async getAllSubagents(){return this._loadPromise&&await this._loadPromise,this._loadedOnce||await this.reload(),[...this._subagentsCache]}async reload(){return this.runLoadInBackground(!0),this._loadPromise&&await this._loadPromise,this._subagentsCache}runLoadInBackground(e=!1){const t=++this._loadId;this._loadPromise=this.load(e).then((e=>{t===this._loadId&&(this._subagentsCache=e,this._loadedOnce=!0)})).catch((e=>{t===this._loadId&&(Sf("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}){const r=[];for(const o of e){const e=rl(o.identifier),n=ol(o.identifier),i=nl(o.identifier),a=sl(o.identifier);for(const c of o.agents){const l=Xh(c,t),u=(0,s.join)(o.installPath,l.path);r.push({name:l.name,description:l.description??"",prompt:l.prompt,fullPath:u,permissionMode:"readonly"===l.permissionMode?"readonly":"default",plugin:e,marketplace:n,pluginId:i,marketplaceId:a})}}return r}(r,{stripModel:!0,stripTools:!0});for(const e of o){const r="readonly"===e.permissionMode?io.b$.READONLY:io.b$.DEFAULT;t.push(new io.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 Mf=r("../proto/dist/generated/agent/v1/computer_use_tool_pb.js"),Df=r("node:readline");Error,r("node:timers/promises");var Of=r("../utils/dist/workload-spawn.js");const Nf=Iu.execFile;function $f(e,t,r){return new Promise(((o,n)=>{r?.signal?.throwIfAborted();const s={timeout:r?.timeoutMs??3e4,env:r?.env?{...process.env,...r.env}:void 0,signal:r?.signal};(0,Of.D9)(Nf,e,t.map(String),{...s,encoding:"utf8"},((e,t)=>{e?n(e):o(t)}))}))}Mf.w3.UNSPECIFIED,Mf.w3.LEFT,Mf.w3.MIDDLE,Mf.w3.RIGHT,Mf.w3.BACK,Mf.w3.FORWARD,Mf.Dh.UNSPECIFIED,Mf.Dh.UP,Mf.Dh.DOWN,Mf.Dh.LEFT,Mf.Dh.RIGHT;const Ff=(0,ji.promisify)(Iu.execFile);function jf(e,t,r,o){const n=function(e={}){const t=e.displayWidth??1920,r=e.displayHeight??1200,o=e.apiWidth??1280;return{width:o,height:Math.round(o*r/t)}}({displayWidth:e,displayHeight:t,apiWidth:r});return{display:{width:e,height:t},api:{width:n.width,height:o??n.height}}}async function Lf(e){const{stdout:t}=await(0,Of.D9)(Ff,"xrandr",["--display",e],{timeout:5e3,encoding:"utf8"}),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:jf(r.width,r.height),resolutionString:`${r.width}x${r.height}`}}Mf.w3.UNSPECIFIED,Mf.w3.LEFT,Mf.w3.MIDDLE,Mf.w3.RIGHT,Mf.w3.BACK,Mf.w3.FORWARD,Mf.Dh.UNSPECIFIED,Mf.Dh.UP,Mf.Dh.DOWN,Mf.Dh.LEFT,Mf.Dh.RIGHT,Mf.Z8.NATIVE_X11,Mf.Z8.XDOTOOL,(0,g.v5)("computer_use.session.duration_ms",{description:"Duration of computer-use session in milliseconds"}),(0,g.v5)("computer_use.session.action_count",{description:"Number of actions executed in a computer-use session"}),(0,g.Pu)("computer_use.session.result",{description:"Result status of computer-use session",labelNames:["outcome"]}),(0,g.Pu)("computer_use.session.action_kind",{description:"Requested computer-use actions by bounded kind",labelNames:["kind"]}),(0,m.h)("computer-use"),Math.floor(35927136),["Skip changes that cannot affect what runs in any deployed environment:","- documentation-only changes (Markdown, docs sites, code comments, changelogs)","- formatting, lint, or typo fixes with no behavior change","- test-only changes (test files, fixtures, snapshots)","Monitor everything else, including dependency bumps, configuration, and infrastructure changes."].join("\n"),Error,(0,g.Pu)("computer_use.desktop_lease.check",{description:"Desktop lease action-gate outcomes",labelNames:["outcome","reason"]});var Uf=r("../proto/dist/runtime/compact.js");Uf.HL;var Bf=(0,Uf.QT)(qt.proto3,"agent.v1.","CursorType",[[0,"UNSPECIFIED"],[1,"ARROW"],[2,"POINTER"],[3,"TEXT"],[4,"WAIT"],[5,"CROSSHAIR"],[6,"MOVE"],[7,"RESIZE_NS"],[8,"RESIZE_EW"],[9,"RESIZE_NWSE"],[10,"RESIZE_NESW"],[11,"NOT_ALLOWED"],[12,"GRAB"],[13,"GRABBING"]],1);qt.proto3,qt.proto3,qt.proto3,qt.proto3;class Wf{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 Hf={left_ptr:Bf.ARROW,arrow:Bf.ARROW,default:Bf.ARROW,top_left_arrow:Bf.ARROW,hand:Bf.POINTER,hand1:Bf.POINTER,hand2:Bf.POINTER,pointer:Bf.POINTER,pointing_hand:Bf.POINTER,xterm:Bf.TEXT,ibeam:Bf.TEXT,text:Bf.TEXT,watch:Bf.WAIT,wait:Bf.WAIT,progress:Bf.WAIT,left_ptr_watch:Bf.WAIT,crosshair:Bf.CROSSHAIR,cross:Bf.CROSSHAIR,tcross:Bf.CROSSHAIR,move:Bf.MOVE,fleur:Bf.MOVE,size_all:Bf.MOVE,sb_v_double_arrow:Bf.RESIZE_NS,v_double_arrow:Bf.RESIZE_NS,ns_resize:Bf.RESIZE_NS,row_resize:Bf.RESIZE_NS,top_side:Bf.RESIZE_NS,bottom_side:Bf.RESIZE_NS,sb_h_double_arrow:Bf.RESIZE_EW,h_double_arrow:Bf.RESIZE_EW,ew_resize:Bf.RESIZE_EW,col_resize:Bf.RESIZE_EW,left_side:Bf.RESIZE_EW,right_side:Bf.RESIZE_EW,top_left_corner:Bf.RESIZE_NWSE,bottom_right_corner:Bf.RESIZE_NWSE,nwse_resize:Bf.RESIZE_NWSE,size_fdiag:Bf.RESIZE_NWSE,top_right_corner:Bf.RESIZE_NESW,bottom_left_corner:Bf.RESIZE_NESW,nesw_resize:Bf.RESIZE_NESW,size_bdiag:Bf.RESIZE_NESW,not_allowed:Bf.NOT_ALLOWED,no_drop:Bf.NOT_ALLOWED,forbidden:Bf.NOT_ALLOWED,circle:Bf.NOT_ALLOWED,grab:Bf.GRAB,openhand:Bf.GRAB,grabbing:Bf.GRABBING,closedhand:Bf.GRABBING};class qf{constructor(e){this.events=[],this.recordingStartTime=0,this.lastKnownPosition={x:0,y:0},this.isRunning=!1,this.pending=Promise.resolve();const t=e.displayNum??1;this.env={DISPLAY:`:${t}`},this.scaler=new Wf(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=Bf.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 $f("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 $f("xdotool",["getmouselocation","--shell"],{env:this.env})).match(/CURSOR=(\S+)/i);if(e){const t=e[1].toLowerCase();return Hf[t]??Bf.ARROW}try{const e=await $f("xprop",["-root","_XSERVER_CURSOR"],{env:this.env,timeoutMs:500});for(const[t,r]of Object.entries(Hf))if(e.toLowerCase().includes(t))return r}catch{}return Bf.ARROW}catch{return Bf.ARROW}}getExpectedPositionAfterAction(e,t){const r=e.action;if(!r)return t;switch(r.case){case"mouseMove":{const e=r.value.coordinate;if(e)return{x:e.x,y:e.y};break}case"click":{const e=r.value.coordinate;if(e)return{x:e.x,y:e.y};break}case"drag":{const e=r.value.path;if(e.length>0){const t=e[e.length-1];return{x:t.x,y:t.y}}break}case"scroll":{const e=r.value.coordinate;if(e)return{x:e.x,y:e.y};break}}return t}}(0,m.h)("computer-use-lazy");var zf=r("node:net");class Gf extends Error{constructor(e){super(e),this.name="MacRPCProtocolError"}}const Vf=Io.object({rpcSocketPath:Io.string().min(1).optional(),appControlSocketPath:Io.string().min(1).optional()}).passthrough(),Jf=Io.object({data:Io.string(),mimeType:Io.string().min(1)}).strip(),Kf=Io.object({message:Io.string(),screenshot:Jf.optional(),screenshotBefore:Jf.optional(),structuredContent:Io.unknown().optional(),isError:Io.boolean()}).strip(),Zf=Io.object({accessibilityTrusted:Io.boolean(),screenRecordingGranted:Io.boolean()}).strip(),Xf=Io.union([Io.object({id:Io.number().int(),result:Kf,ok:Io.never().optional(),error:Io.never().optional(),errorCode:Io.never().optional(),permissionStatus:Io.never().optional(),sessionId:Io.never().optional()}).strip(),Io.object({id:Io.number().int(),sessionId:Io.string().min(1),ok:Io.literal(!0).optional(),result:Io.never().optional(),error:Io.never().optional(),errorCode:Io.never().optional(),permissionStatus:Io.never().optional()}).strip(),Io.object({id:Io.number().int(),ok:Io.literal(!0),result:Io.never().optional(),error:Io.never().optional(),errorCode:Io.never().optional(),permissionStatus:Io.never().optional(),sessionId:Io.never().optional()}).strip(),Io.object({id:Io.number().int().nullable().optional(),error:Io.string().min(1),errorCode:Io.string().min(1).optional(),result:Io.never().optional(),ok:Io.never().optional(),permissionStatus:Io.never().optional(),sessionId:Io.never().optional()}).strip(),Io.object({id:Io.number().int(),permissionStatus:Zf,result:Io.never().optional(),ok:Io.never().optional(),error:Io.never().optional(),errorCode:Io.never().optional(),sessionId:Io.never().optional()}).strip()]);function Qf(e,t){try{return JSON.parse(e)}catch{throw new Gf(`local-cua ${t} is not valid JSON`)}}const Yf={responseMaxBytes:33554432,parseServiceState(e){const t=Vf.safeParse(Qf(e,"service state")),r=t.success?t.data.rpcSocketPath??t.data.appControlSocketPath:void 0;if(!t.success||void 0===r)throw new Gf("local-cua service state is malformed");return{...t.data,rpcSocketPath:r}},parseResponse({line:e,expectedID:t}){const r=Xf.safeParse(Qf(e.toString("utf8"),"RPC response"));if(!r.success)throw new Gf("local-cua RPC response is malformed");if(void 0!==r.data.id&&null!==r.data.id&&r.data.id!==t)throw new Gf("local-cua RPC response ID did not match");return r.data}};class em extends Error{constructor(e,t){super(e),this.name="MacComputerUseRPCError",this.code=t?.code,this.userFacing=!0===t?.userFacing,this.tool=t?.tool}}function tm(e){return"object"==typeof e&&null!==e&&"code"in e&&"string"==typeof e.code?e.code:e instanceof Error?rm(e.message)?e.name:e.message.length>0?`${e.name}: ${e.message}`:e.name:"unknown"}function rm(e){return!!e.includes(n.homedir())||e.includes("node_modules")||e.includes("Application Support")||/\.wasm\b/.test(e)||/(?:^|[\s'`"])(?:\/|\.{1,2}\/|[A-Za-z]:[\\/]|\\\\)/.test(e)}class om{constructor(e){this.mode=e}static isInstalled(){return!!(0,$s.existsSync)(om.serviceExecutablePath())||(0,$s.existsSync)(om.serviceStatePath())}screenshot(e){return this.callTool(e,"computer_use_screenshot",{})}click(e,t){return this.callTool(e,"computer_use_click",{method:"coordinate",...void 0!==t.coordinate&&{x:t.coordinate.x,y:t.coordinate.y},button:t.button,count:t.count,modifier_keys:t.modifierKeys})}scroll(e,t){return this.callTool(e,"computer_use_scroll",{x:t.coordinate?.x,y:t.coordinate?.y,direction:t.direction,amount:t.amount,modifier_keys:t.modifierKeys})}move(e,t){return this.callTool(e,"computer_use_mouse_move",{x:t.x,y:t.y})}mouseButton(e,t){return this.callTool(e,"computer_use_mouse_button",{button:t.button,action:t.action})}drag(e,t){return this.callTool(e,"computer_use_drag",{button:t.button,path:t.path,modifier_keys:t.modifierKeys})}typeText(e,t){return this.callTool(e,"computer_use_typing",{value:t})}pressKey(e,t){return this.callTool(e,"computer_use_press_key",{key:t.key,hold_duration_ms:t.holdDurationMs})}checkPermissions(e){return this.callTool(e,"computer_use_check_permissions",{})}async startControl(e){if("remote"!==this.mode||void 0!==this.activeSessionId)return;om.throwIfAborted(e.signal);const t=(0,Ts.randomUUID)(),r=await this.sendWithRelaunchRetry(e,(()=>({id:om.requestID,method:"control/start",requestID:t,mode:this.mode})),"control/start");if(void 0!==r.error)throw om.rpcError(r);if(void 0===r.sessionId)throw new em("local-cua control/start returned no session");this.activeSessionId=r.sessionId}async releaseControl(e){const t=this.activeSessionId;if(void 0!==t){this.activeSessionId=void 0;try{const e=await om.readServiceState();if(void 0===e)return;const r=await om.sendOnce(om.socketPathFrom(e),{id:om.requestID,method:"control/release",requestID:(0,Ts.randomUUID)(),mode:this.mode,sessionId:t},om.defaultCallTimeoutMs);if(void 0!==r.error)throw om.rpcError(r)}catch(t){om.logger.warn(e,"local-cua control release failed",{error:tm(t)})}}}async callTool(e,t,r){om.throwIfAborted(e.signal);const o=om.defaultCallTimeoutMs,n=await this.sendWithRelaunchRetry(e,(()=>{const e=Date.now()/1e3,n=this.activeSessionId;return{id:om.requestID,method:"tools/call",requestID:(0,Ts.randomUUID)(),name:t,arguments:r,timeoutSeconds:o/1e3,startedAtEpochSeconds:e,deadlineEpochSeconds:e+o/1e3,mode:this.mode,...void 0!==n&&{sessionId:n}}}),t);if(void 0!==n.error)throw om.rpcError(n,t);const s=n.result;if(void 0===s)throw new em(`local-cua tool ${t} returned no result`,{tool:t});if(s.isError){const e=s.message.trim();throw new em(e.length>0?e:`local-cua tool ${t} reported an error`,{tool:t,userFacing:e.length>0})}return s}async sendWithRelaunchRetry(e,t,r){const o=om.defaultCallTimeoutMs,n=await this.ensureSocketPath(e);om.throwIfAborted(e.signal);try{return await om.sendOnce(n,t(),o,e.signal)}catch(n){if(!om.isPreDeliveryConnectionError(n))throw n;om.logger.warn(e,"local-cua callTool failed; relaunching and retrying",{tool:r,error:om.spawnErrorCode(n)});const s=await this.ensureSocketPath(e,!0);return om.throwIfAborted(e.signal),void 0!==this.activeSessionId&&(this.activeSessionId=void 0,await this.startControl(e)),await om.sendOnce(s,t(),o,e.signal)}}static rpcError(e,t){return new em(e.error,{code:e.errorCode,userFacing:!0,tool:t})}async ensureSocketPath(e,t=!1){if(om.throwIfAborted(e.signal),!t){const e=await om.readServiceState();if(e)return om.socketPathFrom(e)}await this.launchAndWait(e);const r=await om.readServiceState();if(!r)throw new em("local-cua sidecar did not publish service.json after launch");return om.socketPathFrom(r)}async launchAndWait(e){const t=om.serviceAppPath();om.logger.info(e,"launching local-cua sidecar",om.sidecarLaunchLogFields(t)),"1"===process.env[om.directLaunchEnv]?await om.spawnSidecarProcess(e,om.serviceExecutablePath(),[],{detached:!0}):await om.spawnSidecarProcess(e,"/usr/bin/open",["-g",t]);const r=Date.now()+om.launchReadyTimeoutMs;for(;Date.now()<r;){om.throwIfAborted(e.signal);const t=await om.readServiceState();if(t)try{if("ok"in await om.sendOnce(om.socketPathFrom(t),{id:om.requestID,method:"ping"},2e3,e.signal))return}catch{}await(0,Ht.cb)(om.launchPollIntervalMs)}throw new em("local-cua sidecar did not become ready in time")}static isPreDeliveryConnectionError(e){const t=tm(e);return"ENOENT"===t||"ECONNREFUSED"===t}static appSupportDirectory(){const e=process.env[om.appSupportOverrideEnv];return e&&e.length>0?e:s.join(n.homedir(),"Library","Application Support",om.appSupportFolder)}static serviceStatePath(){return s.join(om.appSupportDirectory(),"service.json")}static serviceAppPath(){const e=process.env[om.serviceAppOverrideEnv];return e&&e.length>0?e:s.join(n.homedir(),".cursor","cursor-computer-use",`${om.serviceAppBundleName}.app`)}static sidecarLaunchLogFields(e){const t=`${om.serviceAppBundleName}.app`;return{appName:s.basename(e)===t?t:"custom",appPathHash:(0,Ts.createHash)("sha256").update(e).digest("hex"),usingOverride:Boolean(process.env[om.serviceAppOverrideEnv])}}static spawnErrorCode(e){return tm(e)}static socketError(e){const t=tm(e);return new em(`local-cua RPC connection failed: ${t}`,{code:t})}static serviceExecutablePath(){return s.join(om.serviceAppPath(),"Contents","MacOS","CUCursorService")}static spawnSidecarProcess(e,t,r,o){return new Promise(((n,s)=>{const i=(0,Iu.spawn)(t,[...r],{detached:!0===o?.detached,stdio:"ignore"}),a=e=>{s(new em(`local-cua sidecar launch failed: ${om.spawnErrorCode(e)}`))};i.once("error",a),i.once("spawn",(()=>{i.removeListener("error",a),i.on("error",(t=>{om.logger.warn(e,"local-cua sidecar process error after launch",{error:om.spawnErrorCode(t)})})),i.unref(),n()}))}))}static async readServiceState(){try{const e=await(0,Os.readFile)(om.serviceStatePath(),"utf8");return Yf.parseServiceState(e)}catch(e){if(e instanceof Error&&"code"in e&&"ENOENT"===e.code)return;if(e instanceof Gf)return;throw new em("local-cua service state could not be read")}}static socketPathFrom(e){return e.rpcSocketPath}static abortError(e){return e.reason instanceof Error?e.reason:new em("local-cua RPC aborted")}static throwIfAborted(e){if(e.aborted)throw om.abortError(e)}static sendOnce(e,t,r,o){return o?.aborted?Promise.reject(om.abortError(o)):new Promise(((n,s)=>{let i=!1,a=[],c=0,l=!1;const u=(0,zf.createConnection)({path:e}),d=e=>{i||(i=!0,clearTimeout(p),o?.removeEventListener("abort",h),u.destroy(),e())},h=()=>{d((()=>s(void 0===o?new em("local-cua RPC aborted"):om.abortError(o))))},p=setTimeout((()=>{d((()=>s(new em(`local-cua RPC timed out after ${r}ms`))))}),r);o?.addEventListener("abort",h,{once:!0}),o?.aborted?h():(u.on("connect",(()=>{u.write(`${JSON.stringify(t)}\n`,(e=>{null==e?l=!0:d((()=>s(om.socketError(e))))}))})),u.on("data",(e=>{const t=e.indexOf(10),r=c+(t<0?e.length:t);if(r>Yf.responseMaxBytes)return void d((()=>s(new em("local-cua RPC response exceeded the size limit"))));if(t<0)return a.push(e),void(c+=e.length);a.push(e.subarray(0,t));const o=Buffer.concat(a,r);a=[],c=0;try{const e=Yf.parseResponse({line:o,expectedID:om.requestID});d((()=>n(e)))}catch(e){d((()=>s(e)))}})),u.on("error",(e=>{d(l?()=>s(new em("local-cua RPC connection failed after request delivery")):()=>s(om.socketError(e)))})),u.on("close",(()=>{const e=c>0?"local-cua RPC response ended without a newline":l?"local-cua RPC connection closed after request delivery":"local-cua RPC connection closed";d((()=>s(new em(e))))})))}))}}let nm;function sm(){if(void 0===nm){const e=async function(){const[{createJimp:e},{default:t},{default:o},{default:n,msBmp:s},{default:i},{default:a},{methods:c}]=await Promise.all([Promise.all([r.e(731),r.e(250)]).then(r.bind(r,"../../node_modules/.pnpm/@jimp+core@1.6.0/node_modules/@jimp/core/dist/esm/index.js")),r.e(690).then(r.bind(r,"../../node_modules/.pnpm/@jimp+js-png@1.6.0/node_modules/@jimp/js-png/dist/esm/index.js")),r.e(831).then(r.bind(r,"../../node_modules/.pnpm/@jimp+js-jpeg@1.6.0/node_modules/@jimp/js-jpeg/dist/esm/index.js")),Promise.all([r.e(731),r.e(284)]).then(r.bind(r,"../../node_modules/.pnpm/@jimp+js-bmp@1.6.0/node_modules/@jimp/js-bmp/dist/esm/index.js")),r.e(295).then(r.bind(r,"../../node_modules/.pnpm/@jimp+js-gif@1.6.0/node_modules/@jimp/js-gif/dist/esm/index.js")),r.e(181).then(r.bind(r,"../../node_modules/.pnpm/@jimp+js-tiff@1.6.0/node_modules/@jimp/js-tiff/dist/esm/index.js")),r.e(162).then(r.bind(r,"../../node_modules/.pnpm/@jimp+plugin-resize@1.6.0/node_modules/@jimp/plugin-resize/dist/esm/index.js"))]);return e({formats:[t,o,n,s,i,a],plugins:[c]})}().catch((t=>{throw nm===e&&(nm=void 0),t}));nm=e}return nm}om.logger=(0,m.h)("local-cua:rpc"),om.serviceAppBundleName="Cursor Computer Use",om.appSupportFolder="cursor-computer-use",om.appSupportOverrideEnv="CUA_APP_SUPPORT_DIR",om.serviceAppOverrideEnv="CUA_SERVICE_APP",om.directLaunchEnv="CUA_DIRECT_LAUNCH",om.defaultCallTimeoutMs=45e3,om.launchReadyTimeoutMs=8e3,om.launchPollIntervalMs=200,om.requestID=1;var im=r("node:module");const am="mac-webp-runtime.cjs";let cm,lm;function um(){return cm??=(()=>{const e=Error.prepareStackTrace;try{Error.prepareStackTrace=(e,t)=>t;const e=(new Error).stack,t=Array.isArray(e)?e[0]?.getFileName():void 0;return function(){const e=im,t=e.createRequire??e.default?.createRequire;if("function"!=typeof t)throw new Error("node:module createRequire is unavailable");return t}()("string"==typeof t&&t.length>0?t:(0,s.join)(process.cwd(),"package.json"))}finally{Error.prepareStackTrace=e}})(),cm}function dm(){const e=globalThis.__MAC_WEBP_IMPORT__;return"function"==typeof e?e:(lm??=function(){const e=[],t=new Set,r=r=>{t.has(r)||(t.add(r),e.push(r))};for(const e of function(){const e=Error.prepareStackTrace;try{Error.prepareStackTrace=(e,t)=>t;const e=(new Error).stack;if(!Array.isArray(e))return[];const t=[];for(const r of e){const e=r.getFileName();"string"==typeof e&&e.length>0&&t.push(e)}return t}finally{Error.prepareStackTrace=e}}()){const t=(0,s.dirname)((o=e).startsWith("file:")?(0,th.fileURLToPath)(o):o);r((0,s.join)(t,am)),r((0,s.join)(t,"..","..","src","computer-use",am))}var o;"string"==typeof process.argv[1]&&process.argv[1].length>0&&r((0,s.join)((0,s.dirname)(process.argv[1]),am)),r((0,s.join)(process.cwd(),"src","computer-use",am)),r((0,s.join)(process.cwd(),"computer-use",am));try{const e=(0,s.dirname)(um().resolve("@anysphere/local-exec/package.json"));r((0,s.join)(e,"src","computer-use",am)),r((0,s.join)(e,"dist","computer-use",am))}catch{}for(const t of e)try{const e=um()(t);if("function"==typeof e.importFile)return e.importFile.bind(e)}catch{}throw new Error("mac-webp runtime importer was not found next to the bundle")}(),lm)}function hm(...e){return t=["@jsquash","webp",...e].join("/"),um().resolve(t);var t}async function pm(...e){return await(t=(0,th.pathToFileURL)(hm(...e)).href,dm()(t));var t}const fm=e=>{let t;return()=>{if(void 0===t){const r=e();r.catch((()=>{t===r&&(t=void 0)})),t=r}return t}},mm=(fm((async()=>{const e=await pm("decode.js");return await e.init({wasmBinary:await $s.promises.readFile(hm("codec","dec","webp_dec.wasm"))}),e})),fm((async()=>{const[e,t,r]=await Promise.all([pm("utils.js"),pm("meta.js"),pm("codec","enc","webp_enc.js")]);return{module:await e.initEmscriptenModule(r.default,void 0,{wasmBinary:await $s.promises.readFile(hm("codec","enc","webp_enc.wasm"))}),defaultOptions:t.defaultOptions}}))),gm="image/png",wm={async normalize(e){if(e.mimeType!==gm)throw new Error(`Mac screenshot must be ${gm}, received ${e.mimeType}`);const t=await sm(),r=await t.read(Buffer.from(e.data,"base64"));return(await(o={data:r.bitmap.data,width:r.bitmap.width,height:r.bitmap.height},(async e=>{const{module:t,defaultOptions:r}=await mm(),o=new Uint8ClampedArray(e.data.buffer,e.data.byteOffset,e.data.byteLength);return Buffer.from(t.encode(o,e.width,e.height,{...r,lossless:1,exact:1}))})(o))).toString("base64");var o}};class ym{constructor({ctx:e,actions:t,sidecar:r}){this.startTime=Date.now(),this.geometryPrimed=!1,this.actionCount=0,this.hasCompletedActuation=!1,this.staleAfterWait=!1,this.ctx=e,this.actions=t,this.sidecar=r}async execute(){const e=this.actions.some((e=>ym.isInputAction(e.action.case)));try{this.throwIfAborted(),e&&await this.sidecar.startControl(this.ctx);for(const e of this.actions){this.throwIfAborted();const t=e.action;if(void 0===t.case)throw new Error("Computer use action case is undefined");switch(this.actionCount+=1,t.case){case"screenshot":case"cursorPosition":await this.captureScreen();break;case"click":void 0!==t.value.coordinate&&await this.ensureGeometryCached(),this.recordActuation(await this.sidecar.click(this.ctx,{coordinate:t.value.coordinate,button:ym.mouseButtonName(t.value.button),count:t.value.count>0?t.value.count:1,modifierKeys:t.value.modifierKeys}),t.value.coordinate);break;case"scroll":void 0!==t.value.coordinate&&await this.ensureGeometryCached(),this.recordActuation(await this.sidecar.scroll(this.ctx,{coordinate:t.value.coordinate,direction:ym.scrollDirectionName(t.value.direction),amount:t.value.amount>0?t.value.amount:3,modifierKeys:t.value.modifierKeys}),t.value.coordinate);break;case"mouseMove":if(void 0===t.value.coordinate)throw new Error("MouseMoveAction requires coordinate");await this.ensureGeometryCached(),this.recordActuation(await this.sidecar.move(this.ctx,{x:t.value.coordinate.x,y:t.value.coordinate.y}),t.value.coordinate);break;case"mouseDown":this.recordActuation(await this.sidecar.mouseButton(this.ctx,{button:ym.mouseButtonName(t.value.button),action:"down"}));break;case"mouseUp":this.recordActuation(await this.sidecar.mouseButton(this.ctx,{button:ym.mouseButtonName(t.value.button),action:"up"}));break;case"drag":{const e=t.value.path.map((e=>({x:e.x,y:e.y})));await this.ensureGeometryCached(),this.recordActuation(await this.sidecar.drag(this.ctx,{button:ym.mouseButtonName(t.value.button),path:e,modifierKeys:t.value.modifierKeys}),e.at(-1));break}case"type":this.recordActuation(await this.sidecar.typeText(this.ctx,t.value.text));break;case"key":if(t.value.stroke===Mf.EB.DOWN||t.value.stroke===Mf.EB.UP)throw new Error("Held keys (KeyAction.stroke DOWN/UP) are not supported by the macOS computer-use sidecar; use hold_duration_ms");this.recordActuation(await this.sidecar.pressKey(this.ctx,{key:t.value.key,holdDurationMs:t.value.holdDurationMs}));break;case"wait":await this.delay(Math.max(0,t.value.durationMs)),this.staleAfterWait=!0;break;default:{const e=t;throw new Error(`Unknown computer use action: ${JSON.stringify(e)}`)}}}this.throwIfAborted(),(void 0===this.screenshot||this.staleAfterWait)&&await this.captureScreen(),this.throwIfAborted();const t=await this.normalizeRetainedScreenshots();return t.screenshotFailed&&!this.hasCompletedActuation?this.screenshotUnavailableResult(t.failureReason):(this.throwIfAborted(),new Mf.ks({result:{case:"success",value:new Mf.Wd({actionCount:this.actionCount,durationMs:Date.now()-this.startTime,screenshot:t.screenshot,cursorPosition:this.cursor,log:t.screenshotFailed?"Screenshot unavailable":void 0})}}))}catch(e){return this.ctx.signal.aborted?this.abortedResult():this.errorResult(e)}finally{e&&await this.sidecar.releaseControl(this.ctx)}}static isInputAction(e){switch(e){case"click":case"scroll":case"mouseMove":case"mouseDown":case"mouseUp":case"drag":case"type":case"key":return!0;default:return!1}}async captureScreen(){const e=await this.sidecar.screenshot(this.ctx);this.screenshot=e.screenshot,this.cursor=ym.cursorFromResult(e)??this.cursor,this.geometryPrimed=!0,this.staleAfterWait=!1}async ensureGeometryCached(){this.geometryPrimed||await this.captureScreen()}recordActuation(e,t){this.screenshot=e.screenshot,this.hasCompletedActuation=!0,this.staleAfterWait=!1,void 0!==e.screenshot&&(this.geometryPrimed=!0),this.cursor=ym.cursorFromResult(e)??ym.coordinateFromPoint(t)??this.cursor}async errorResult(e){let t;if(ym.logger.error(this.ctx,"local-cua execute failed",void 0,{error:tm(e)}),!function(e){return e instanceof em&&("computer_use_screenshot"===e.tool||"permission_required"===e.code)}(e))try{const e=await this.sidecar.screenshot(this.ctx);t=(await this.normalizeScreenshot(e.screenshot,"error")).data}catch(e){ym.logger.warn(this.ctx,"local-cua error screenshot capture failed",{error:tm(e)})}const r=function(e){if(e instanceof em&&e.userFacing&&e.message.trim().length>0&&!rm(e.message))return e.message.trim()}(e);return new Mf.ks({result:{case:"error",value:new Mf.Jb({error:void 0===r?"Computer use failed":`Computer use failed: ${r}`,actionCount:this.actionCount,durationMs:Date.now()-this.startTime,screenshot:t})}})}screenshotUnavailableResult(e){return new Mf.ks({result:{case:"error",value:new Mf.Jb({error:"Screenshot unavailable",actionCount:this.actionCount,durationMs:Date.now()-this.startTime,log:e})}})}abortedResult(){return new Mf.ks({result:{case:"error",value:new Mf.Jb({error:"Computer use aborted",actionCount:this.actionCount,durationMs:Date.now()-this.startTime})}})}static mouseButtonName(e){return ym.mouseButtonNames[e]??"left"}static scrollDirectionName(e){return ym.scrollDirectionNames[e]??"down"}async normalizeRetainedScreenshots(){const e=await this.normalizeScreenshot(this.screenshot,"post-action");return{screenshot:e.data,screenshotFailed:void 0===this.screenshot||e.failed,failureReason:void 0===this.screenshot?"sidecar returned no image":e.reason}}async normalizeScreenshot(e,t){if(void 0===e)return{failed:!1};try{return{data:await wm.normalize(e),failed:!1}}catch(r){const o=tm(r);return ym.logger.error(this.ctx,"local-cua screenshot conversion failed",void 0,{frame:t,error:o}),"image/png"===e.mimeType&&e.data.length>0?{data:e.data,failed:!1}:{failed:!0,reason:o}}}static coordinateFromPoint(e){if(void 0!==e&&Number.isFinite(e.x)&&Number.isFinite(e.y))return new Mf.xp({x:Math.round(e.x),y:Math.round(e.y)})}static cursorFromResult(e){const t=e.structuredContent;if("object"!=typeof t||null===t||!("cursor"in t))return;const r=t.cursor;return"object"==typeof r&&null!==r&&"x"in r&&"y"in r&&"number"==typeof r.x&&"number"==typeof r.y&&Number.isFinite(r.x)&&Number.isFinite(r.y)?new Mf.xp({x:Math.round(r.x),y:Math.round(r.y)}):void 0}throwIfAborted(){if(this.ctx.signal.aborted)throw this.ctx.signal.reason??new Error("Computer use aborted")}delay(e){return this.throwIfAborted(),new Promise(((t,r)=>{const o=()=>{clearTimeout(n),r(this.ctx.signal.reason??new Error("Computer use aborted"))},n=setTimeout((()=>{this.ctx.signal.removeEventListener("abort",o),t()}),e);this.ctx.signal.addEventListener("abort",o,{once:!0}),this.ctx.signal.aborted&&o()}))}}var vm;ym.logger=(0,m.h)("local-cua:actions"),ym.mouseButtonNames={[Mf.w3.UNSPECIFIED]:"left",[Mf.w3.LEFT]:"left",[Mf.w3.RIGHT]:"right",[Mf.w3.MIDDLE]:"middle",[Mf.w3.BACK]:"left",[Mf.w3.FORWARD]:"left"},ym.scrollDirectionNames={[Mf.Dh.UNSPECIFIED]:"down",[Mf.Dh.UP]:"up",[Mf.Dh.DOWN]:"down",[Mf.Dh.LEFT]:"left",[Mf.Dh.RIGHT]:"right"},s.default.join("Contents","MacOS","CUCursorService"),function(e){e.Write="write",e.Read="read",e.Shell="shell",e.Delete="delete",e.Mcp="mcp"}(vm||(vm={}));var bm=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var 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 Sm{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,i.VI)(e.withName("LocalDeleteExecutor.execute")),!1);const o=t.path;if(""===o.trim())return new wr.Pi({result:{case:"error",value:new wr.GU({path:o,error:Vs})}});const n=(0,Gs.o1)(o,this.workspacePath),a=await this.permissionsService.shouldBlockWrite(e,n,"");if(a){const e=await Pc(a,{onNeedsApproval:async(e,t)=>null,onUserRejected:e=>new wr.Pi({result:{case:"rejected",value:new wr.iq({path:n,reason:e||""})}}),onPermissionDenied:(e,t)=>new wr.Pi({result:{case:"permissionDenied",value:new wr.QG({path:n,clientVisibleError:e,isReadonly:t?.isReadonly??!1})}})});if(null!==e)return e}const c=await async function(e,t){const r=await(0,Os.realpath)((0,s.dirname)(e)).catch((()=>{}));if(void 0===r)return e;if(void 0!==t){const o=await(0,Os.realpath)(t).catch((()=>{}));if(void 0!==o&&(0,Gs.BJ)(r,o))return(0,s.resolve)(t,(0,s.relative)(o,r),(0,s.basename)(e))}return(0,s.join)(r,(0,s.basename)(e))}(n,this.workspacePath),l=await this.pendingDecisionProvider.requestApproval({type:vm.Delete,details:{path:c},toolCallId:t.toolCallId});if(!l.approved)return new wr.Pi({result:{case:"rejected",value:new wr.iq({path:n,reason:l.reason||""})}});let u;try{u=await(0,Os.stat)(n)}catch(e){return"ENOENT"===e.code?new wr.Pi({result:{case:"fileNotFound",value:new wr.n0({path:n})}}):new wr.Pi({result:{case:"error",value:new wr.GU({path:n,error:e.message})}})}if(!u.isFile()){const e=u.isDirectory()?"directory":"other";return new wr.Pi({result:{case:"notFile",value:new wr.LX({path:n,actualType:e})}})}const d=u.size;let h;if(d<=Zs)try{h=await ua(n)}catch{}const p=h??"",f=await(0,Os.stat)(n).catch((()=>{}));if(f?.dev!==u.dev||f.ino!==u.ino)return new wr.Pi({result:{case:"error",value:new wr.GU({path:n,error:"File changed while deleting; nothing was removed"})}});try{await(0,Os.unlink)(n)}catch(e){return"EACCES"===e.code?new wr.Pi({result:{case:"permissionDenied",value:new wr.QG({path:n,clientVisibleError:"Permission denied"})}}):"EBUSY"===e.code?new wr.Pi({result:{case:"fileBusy",value:new wr.vX({path:n})}}):new wr.Pi({result:{case:"error",value:new wr.GU({path:n,error:e.message})}})}if(this.fileChangeTracker&&void 0!==h){const e=t.toolCallId?{toolCallId:t.toolCallId}:void 0;await this.fileChangeTracker.trackChange(n,h,void 0,e)}return this.onDeleteForAiTracking&&this.onDeleteForAiTracking({path:n}).catch((()=>{})),new wr.Pi({result:{case:"success",value:new wr.fl({path:n,deletedFile:n,fileSize:BigInt(d),prevContent:p})}})}catch(e){r.error=e,r.hasError=!0}finally{bm(r)}}}class km{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===kt));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 Jn.I0({serverIdentifier:kt,serverName:kt,instructions:`User-defined tools for this session (server "${kt}"). 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 Em extends km{constructor(e,t){super(e,t),this.observableInner=e}onDidChange(e){return this.observableInner.onDidChange(e)}}var Cm=r("../proto/dist/generated/agent/v1/fetch_exec_pb.js"),xm=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 _m{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,i.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 Cm.uN({result:{case:"success",value:new Cm.Uk({url:o,content:t,statusCode:e.status,contentType:r})}})}catch(e){return new Cm.uN({result:{case:"error",value:new Cm.fk({url:o,error:e.message})}})}}catch(e){r.error=e,r.hasError=!0}finally{xm(r)}}}class Pm{constructor(e){this.workspacePath=e,this.changes=new Map,this.listeners=new Set}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}notify(e){for(const t of this.listeners)t(e)}async trackChange(e,t,r,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,Os.unlink)(e):(void 0!==t.before&&void 0===t.after||void 0!==t.before&&void 0!==t.after)&&await async function(e,t,r,o){const{buffer:n}=await da(e,t,r,o);await(0,Os.writeFile)(e,n)}(e,t.before,this.workspacePath)}catch{}finally{this.changes.delete(e),this.notify(t)}}async rejectAll(){const e=Array.from(this.changes.keys());await Promise.all(e.map((e=>this.reject(e))))}clear(){const e=this.changes.values().next().value;this.changes.clear(),this.notify(e)}get size(){return this.changes.size}dispose(){this.changes.clear(),this.listeners.clear()}}var Im=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 Rm{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,i.VI)(e.withName("LocalGitExecutor.exec"),{attributes:{"git.cwd":t,"git.args":r,"git.caller":o?.caller}}),!1);const{stdout:s,stderr:a}=await Lu("git",r,{cwd:t,timeout:o?.timeout});return{exitCode:0,stdout:s.toString(),stderr:a.toString()}}catch(e){n.error=e,n.hasError=!0}finally{Im(n)}}}var Tm=r("../proto/dist/generated/agent/v1/grep_exec_pb.js");const Am=-(2**31),Mm=2**31-1;function Dm(e){return Number.isNaN(e)?0:e<Am?Am:e>Mm?Mm:e}function Om(e){if("number"==typeof e&&Number.isFinite(e)&&!(e<0))return Dm(Math.trunc(e))}class Nm{constructor(){this.lineEnd=0,this.nextStart=0}}function $m(e,t,r){const o=e.length;if(t>=o)return!1;const n=e.indexOf("\n",t);if(-1!==n){const o=n>t&&13===e.charCodeAt(n-1);return r.lineEnd=o?n-1:n,r.nextStart=n+1,!0}return r.lineEnd=o,r.nextStart=o,!0}var Fm=r("../mcp-core/dist/index.js"),jm=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 Lm extends Error{constructor(e){super(`MCP server "${e}" is disabled`),this.name="McpServerDisabledError"}}class Um extends Error{constructor(e){super(`MCP server "${e}" has not been approved`),this.serverName=e,this.name="McpServerNotApprovedError"}}class Bm{constructor(e){this.disabledService=e}async load(e,t,r,o,n){if(await this.disabledService.isServerDisabled(t))throw new Lm(t);return await n(e,r)}}class Wm{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,i.VI)(e.withName("ServerApprovalMiddleware.load")),!1),!await this.approvalService.isServerApproved(t,r,o))throw new Um(t);return await n(e,r)}catch(e){s.error=e,s.hasError=!0}finally{jm(s)}}}class Hm{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,Ts.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,Os.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,Os.mkdir)(s.default.dirname(this.approvalsPath),{recursive:!0}),await(0,Os.writeFile)(this.approvalsPath,JSON.stringify(e,null,2))}async saveApprovals(e){await this.saveApprovalsToFile(e),this.approvalsPromise=Promise.resolve(e)}}var qm=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},zm=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 Gm{async load(e,t,r,o,n){const s=n(e,r);return new Jm(e,t,s,r)}}function Vm(e){let t;return e.then((e=>{t=e})).catch((()=>{})),t}class Jm{constructor(e,t,r,o){this.serverName=t,this.clientPromise=r,this.config=o,this.clientPromiseTraceId=(0,i.fU)(e)?.spanContext()?.traceId,this.toolsPromise=this.clientPromise.then((async t=>null===t?[]:await t.getTools(e))),this.resourcesPromise=this.clientPromise.then((async t=>null===t?[]:(await t.listResources(e)).resources)),this.promptsPromise=this.clientPromise.then((async t=>null===t?[]:await t.listPrompts(e))),this.toolsPromise.catch((()=>{})),this.resourcesPromise.catch((()=>{})),this.promptsPromise.catch((()=>{}))}async getTools(e){const t={stack:[],error:void 0,hasError:!1};try{const r=qm(t,(0,i.VI)(e.withName("CachedMcpClient.getTools")),!1);r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("cacheTraceId",this.clientPromiseTraceId??"undefined");const o=Vm(this.toolsPromise);return void 0!==o?o:await this.toolsPromise}catch(e){t.error=e,t.hasError=!0}finally{zm(t)}}async callTool(e,t,r,o,n){const s={stack:[],error:void 0,hasError:!1};try{const a=qm(s,(0,i.VI)(e.withName("CachedMcpClient.callTool")),!1),c=await this.getClient(a.ctx);if(null===c)throw new Error("Client is not ready");return c.callTool(a.ctx,t,r,o,n)}catch(e){s.error=e,s.hasError=!0}finally{zm(s)}}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{const r=qm(t,(0,i.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{zm(t)}}async getClient(e){const t={stack:[],error:void 0,hasError:!1};try{const r=qm(t,(0,i.VI)(e.withName("CachedMcpClient.getClient")),!1);return r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("cacheTraceId",this.clientPromiseTraceId??"undefined"),await this.clientPromise}catch(e){t.error=e,t.hasError=!0}finally{zm(t)}}async listResources(e){const t={stack:[],error:void 0,hasError:!1};try{const r=qm(t,(0,i.VI)(e.withName("CachedMcpClient.listResources")),!1);r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("cacheTraceId",this.clientPromiseTraceId??"undefined");const o=Vm(this.resourcesPromise);return void 0!==o?{resources:o}:{resources:await this.resourcesPromise}}catch(e){t.error=e,t.hasError=!0}finally{zm(t)}}async readResource(e,t){const r={stack:[],error:void 0,hasError:!1};try{const o=qm(r,(0,i.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{zm(r)}}async listPrompts(e){const t={stack:[],error:void 0,hasError:!1};try{const r=qm(t,(0,i.VI)(e.withName("CachedMcpClient.listPrompts")),!1);r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("cacheTraceId",this.clientPromiseTraceId??"undefined");const o=Vm(this.promptsPromise);return void 0!==o?o:await this.promptsPromise}catch(e){t.error=e,t.hasError=!0}finally{zm(t)}}async getPrompt(e,t,r){const o={stack:[],error:void 0,hasError:!1};try{const n=qm(o,(0,i.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{zm(o)}}async getState(e){const t={stack:[],error:void 0,hasError:!1};try{const r=qm(t,(0,i.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{zm(t)}}async close(){try{const e=await this.clientPromise;await(e?.close?.())}catch{}}}function Km(e){const t=e;if(!t.resource||"object"!=typeof t.resource)return t.uri?`Resource: ${t.uri}${t.name?` (${t.name})`:""}`:`Unsupported content type "${e.type}": ${JSON.stringify(e)}`;{const e=t.resource;if("string"==typeof e.text)return e.text;if("string"!=typeof e.blob)return`Resource: ${e.uri??"unknown"}${e.name?` (${e.name})`:""}`;try{return Buffer.from(e.blob,"base64").toString("utf8")}catch{return`[Binary resource: ${e.uri??"unknown"}]`}}}function Zm(e){if("object"==typeof e&&null!==e&&!Array.isArray(e)&&0!==Object.keys(e).length)try{return Buffer.byteLength(JSON.stringify(e))<=262144?e:void 0}catch{return}}var Xm=r("zod/v4-mini");const Qm=Xm.object({CLIENT_ID:Xm.string(),CLIENT_SECRET:Xm.optional(Xm.string()),scopes:Xm.optional(Xm.array(Xm.string()))}),Ym=Xm.strictObject({caBundle:Xm.string().check(Xm.trim(),Xm.minLength(1),Xm.maxLength(131072))}),eg=Xm.object({type:Xm.optional(Xm.literal("stdio")),command:Xm.string(),args:Xm.optional(Xm.array(Xm.string())),env:Xm.optional(Xm.record(Xm.string(),Xm.string())),envFile:Xm.optional(Xm.string()),cwd:Xm.optional(Xm.string()),enabledTools:Xm.optional(Xm.array(Xm.string())),startupTimeoutSec:Xm.catch(Xm.optional(Xm.number().check(Xm.positive())),void 0)}),tg=Xm.object({type:Xm.optional(Xm.enum(["http","sse"])),url:Xm.string(),headers:Xm.optional(Xm.record(Xm.string(),Xm.string())),auth:Xm.optional(Qm),tls:Xm.optional(Ym),placement:Xm.optional(Xm.enum(["server","client"])),enabledTools:Xm.optional(Xm.array(Xm.string()))}),rg=Xm.union([eg,tg]),og=Xm.object({mcpServers:Xm.record(Xm.string(),rg)});Error;const ng=/\$\{(?:env:([A-Za-z_][A-Za-z0-9_]*)|([^:}]+)(?::-([^}]*))?)\}/g;function sg(e,t){if("string"==typeof e)return function(e,t){return e.replace(ng,((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=>sg(e,t)));if(null!==e&&"object"==typeof e){const r={};for(const[o,n]of Object.entries(e))r[o]=sg(n,t);return r}return e}async function ig(e,t=e=>process.env[e]){try{const r=await(0,Os.readFile)(e,"utf8"),o=sg((0,ou.qg)(r),t);return og.parse(o)}catch{return{mcpServers:{}}}}var ag=r("../../node_modules/.pnpm/string-argv@0.3.2/node_modules/string-argv/index.js"),cg=r("../constants/dist/mcp.js"),lg=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=d6585ecc3ef25fb368c06a7be3232df8c0e9380e7f3_9fbb579d5110d1faa52af09926f676f7/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js"),ug=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=d6585ecc3ef25fb368c06a7be3232df8c0e9380e7f3_9fbb579d5110d1faa52af09926f676f7/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js"),dg=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=d6585ecc3ef25fb368c06a7be3232df8c0e9380e7f3_9fbb579d5110d1faa52af09926f676f7/node_modules/@modelcontextprotocol/sdk/dist/esm/client/sse.js"),hg=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=d6585ecc3ef25fb368c06a7be3232df8c0e9380e7f3_9fbb579d5110d1faa52af09926f676f7/node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.js"),pg=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=d6585ecc3ef25fb368c06a7be3232df8c0e9380e7f3_9fbb579d5110d1faa52af09926f676f7/node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js"),fg=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=d6585ecc3ef25fb368c06a7be3232df8c0e9380e7f3_9fbb579d5110d1faa52af09926f676f7/node_modules/@modelcontextprotocol/sdk/dist/esm/types.js");function mg(e){return`${typeof e}:${String(e)}`}function gg(e){const t=new Map,r=new Set,o=new Set,n=e=>{for(const t of o)t(e)},s=e=>{t.delete(e),r.delete(e)},i=e.send.bind(e);e.send=(e,o)=>((e=>{if("method"in e)if("tools/call"===e.method&&"id"in e){const r=e.params?.name;"string"==typeof r&&t.set(mg(e.id),r)}else if("notifications/cancelled"===e.method){const o=e.params?.requestId;if("string"!=typeof o&&"number"!=typeof o)return;const n=mg(o);if(!t.has(n))return;if(r.add(n),r.size>64){const e=r.values().next().value;void 0!==e&&s(e)}}})(e),i(e,o));const a=e.onmessage;return e.onmessage=(e,o)=>{(e=>{if("method"in e)return void("notifications/tools/list_changed"===e.method&&n({kind:"tools_list_changed"}));if(!("id"in e))return;const o=e.id;if("string"!=typeof o&&"number"!=typeof o)return;const i=mg(o),a=t.get(i);if(void 0===a)return;const c=r.has(i);if(s(i),!c)return;const l="error"in e||"object"==typeof e.result&&null!==e.result&&"isError"in e.result&&!0===e.result.isError;n({kind:"late_tool_result",toolName:a,isError:l})})(e),a?.(e,o)},{subscribe:e=>(o.add(e),()=>{o.delete(e)})}}function wg(e){const t=Object.entries(e.headers??{}).map((([e,t])=>[e.toLowerCase(),t])).sort((([e],[t])=>e<t?-1:e>t?1:0));return(0,Ts.createHash)("sha256").update(JSON.stringify([e.url,t,e.accessToken??null])).digest("hex")}class yg{constructor(e,t){this.inner=e,this.initializeResult=t,e.onclose=()=>this.onclose?.(),e.onerror=e=>this.onerror?.(e),e.onmessage=e=>this.onmessage?.(e)}get sessionId(){return this.inner.sessionId}setProtocolVersion(e){this.inner.setProtocolVersion(e)}start(){return this.inner.start()}close(){return this.inner.close()}async send(e,t){if((0,fg.vo)(e)&&(0,fg.eK)(e)){const t={jsonrpc:"2.0",id:e.id,result:this.initializeResult};queueMicrotask((()=>this.onmessage?.(t)))}else(0,fg.wU)(e)||await this.inner.send(e,t)}}var vg=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=d6585ecc3ef25fb368c06a7be3232df8c0e9380e7f3_9fbb579d5110d1faa52af09926f676f7/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/ajv-provider.js");const bg=new class{constructor({maxSchemasPerCompiler:e=2048,createCompiler:t=()=>new vg.p}={}){this.compiled=new Map,this.maxSchemasPerCompiler=e,this.createCompiler=t,this.compiler=t()}get compiledSchemaCount(){return this.compiled.size}getValidator(e){let t;return r=>(t??=this.compile(e),t(r))}compile(e){const t=JSON.stringify(e),r=(0,Ts.createHash)("sha256").update(t).digest("base64url"),o=this.compiled.get(r);if(void 0!==o)return o;this.compiled.size>=this.maxSchemasPerCompiler&&(this.compiler=this.createCompiler(),this.compiled.clear());const n=(t.includes('"$id"')?this.createCompiler():this.compiler).getValidator(e);return this.compiled.set(r,n),n}},Sg="mcpStdioStderrTail";function kg(e){if(!(e instanceof Error))return;const t=e[Sg];return"string"==typeof t?t:void 0}var Eg=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},Cg=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 xg=(0,g.Pu)(Fm.fz,{description:"One MCP tools/call dial, split by payload, HTTP, and other dial failures",labelNames:["error_class","error_code","transport"]});function _g(e,t,r){try{xg.increment(e,1,(0,Fm.bIe)({transport:(0,Fm.sfL)(t),...r}))}catch{}}function Pg(e){return void 0===e?"unknown":"url"in e?"http":"stdio"}const Ig=["authorization_code","refresh_token"],Rg=["code"];class Tg{constructor(e){this._identifier=e.identifier,this._redirectUrl=e.redirectUrl,this._serverUrl=e.serverUrl,this._restMcpProviderMetadata=e.restMcpProviderMetadata,this.validateResourceURL=!0===e.restMcpProviderMetadata?.omitResourceIndicator?async()=>{}:(0,cg.U_)(e.serverUrl,e.gtmMcpMatch),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,this.addClientAuthentication=e.addClientAuthentication}get redirectUrl(){return this._redirectUrl}get clientMetadata(){return this._clientMetadata}state(){return this._oauthAttemptId=(0,Ts.randomUUID)(),this._oauthState=function(e,t,r){const o={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(){await(this._prepareForRefresh?.())}async releaseRefreshLeaseOnError(e){await(this._releaseRefreshLeaseOnError?.(e))}async invalidateCredentials(e){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(this._invalidateCredentials?.(e))}redirectToAuthorization(e){(0,Fm.E_S)(e,this._scopes),void 0!==this._serverUrl&&(0,cg.uS)(e,this._serverUrl);for(const[t,r]of Object.entries(this._restMcpProviderMetadata?.authorizationParams??{}))e.searchParams.set(t,r);(!0===this._restMcpProviderMetadata?.omitConsentPrompt||(0,cg.NC)(e))&&(0,cg.TS)(e),this._lastRedirectUrl=e}get lastRedirectUrl(){return this._lastRedirectUrl}async saveCodeVerifier(e){this._codeVerifier=e}codeVerifier(){if(!this._codeVerifier)throw new Error("No code verifier saved");return this._codeVerifier}}async function Ag(e){const{serverName:t,config:r,tokenStorage:o}=e,n=await(0,Fm.Ezk)(r.url,e.fetchImpl),s=(0,cg.OY)({loopbackIpv4:n?.loopbackIpv4,redirectUrl:e.authRedirectUrl}),i=function(e,t){const r=(0,Fm.qFm)(e?.CLIENT_ID);if(void 0!==r)return{client_id:r,...e?.CLIENT_SECRET?{client_secret:e.CLIENT_SECRET}:{},redirect_uris:(0,cg.RJ)(t),grant_types:[...Ig],response_types:[...Rg],token_endpoint_auth_method:"none"}}(r.auth,s),a=function({storedClientInformation:e,staticClientInformation:t}){return t?e&&e.client_id===t.client_id?{...t,...e,client_secret:t.client_secret??e.client_secret,redirect_uris:t.redirect_uris,grant_types:e.grant_types??t.grant_types,response_types:e.response_types??t.response_types,token_endpoint_auth_method:e.token_endpoint_auth_method??t.token_endpoint_auth_method}:t:e}({storedClientInformation:await o.loadClientInformation(),staticClientInformation:i});return new Tg({identifier:t,redirectUrl:s,serverUrl:r.url,restMcpProviderMetadata:n,gtmMcpMatch:e.gtmMcpMatch??{gtmApiOrigin:void 0},clientMetadata:{redirect_uris:(0,cg.RJ)(s),token_endpoint_auth_method:"none",grant_types:[...Ig],response_types:[...Rg],client_name:"Cursor",logo_uri:cg.G$},scopes:r.auth?.scopes,tokens:await o.loadTokens(),clientInformation:a,saveTokens:e=>o.saveTokens(e),prepareForRefresh:()=>o.prepareForRefresh?.()??Promise.resolve(),releaseRefreshLeaseOnError:e=>o.releaseRefreshLeaseOnError?.(e)??Promise.resolve(),invalidateCredentials:o.invalidateCredentials?e=>o.invalidateCredentials(e):void 0,saveClientInformation:e=>o.saveClientInformation(e),addClientAuthentication:o.tokenEndpointAuth?.({clientId:a?.client_id})})}const Mg=new Set;let Dg=!1;function Og(){for(const e of Mg)try{process.kill(e,"SIGKILL")}catch{}}function Ng(e,t){return(0,Fm.Uuy)(e??globalThis.fetch.bind(globalThis),{serverUrl:t})}function $g(e,t,r){const o=(0,Fm.mtU)(e,t),n=r??(globalThis.fetch?globalThis.fetch.bind(globalThis):void 0),s=void 0!==o.cursorAuthHeaderValue&&void 0!==o.cursorAuthOrigin&&void 0!==n?(0,Fm.utF)((()=>o.cursorAuthHeaderValue),o.cursorAuthOrigin,n):n;return{transportHeaders:o.headers,baseFetch:s}}class Fg{constructor(e,t,r){this._callToolLock=Promise.resolve(),this._callToolQueueDepth=0,this._stateEnteredAtMs=Date.now(),this._terminatingSession=!1,this.serverName=e,this.client=t,this.tools=new Fm.B1j,this.stateValue=r.initialState,this._authProvider=r.authProvider,this._authCodeExchange=r.authCodeExchange,this._sessionId=r.sessionId,this._protocolVersion=r.protocolVersion,this._resumedInstructions=r.resumedInstructions,this._sessionlessInitialize=r.sessionlessInitialize,this.config=r.config,this._oauthLifecycleLogger=r.oauthLifecycleLogger,this._stdioChildPid=r.stdioChildPid,this._serverSignals=r.serverSignals,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{return}})();(0,Fm.VDJ)({logger:this._oauthLifecycleLogger,event:"mcp_oauth_state_transition",metadata:{identifier:this.serverName,from:n,to:s,cause:r,serverUrlHost:a,previousStateDurationMs:i,...o}})}static createClient(){return new ug.K({name:"Cursor",version:"1.0.0"},{capabilities:{elicitation:{form:{}}},jsonSchemaValidator:bg})}setupElicitationHandler(){this.client.setRequestHandler(fg.$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,c){const l=new URL(t.url);n=n??cg.tl;const u=await Ag({serverName:e,config:t,tokenStorage:r,authRedirectUrl:n,fetchImpl:s,gtmMcpMatch:c}),d=u.tokens(),h=(0,Fm.mtU)(t.url,o),p=h.headers,f=s??(globalThis.fetch?globalThis.fetch.bind(globalThis):void 0),m=void 0!==h.cursorAuthHeaderValue&&void 0!==h.cursorAuthOrigin&&void 0!==f?(0,Fm.utF)((()=>h.cursorAuthHeaderValue),h.cursorAuthOrigin,f):f,g=e=>void 0===m||void 0===i?m:(0,Fm.jIB)({fetch:m,logger:i.logger,metadata:{...i.metadata,transportType:e}}),w=Fg.createClient(),y=e=>e instanceof lg.D_||(0,Fm.Gpm)(e),v=async t=>{if(!u.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,lg.j2)(u,{serverUrl:l.toString(),authorizationCode:t,...void 0!==m?{fetchFn:m}:{}}),a&&(0,Fm.VDJ)({logger:a,event:"mcp_oauth_callback_completion",metadata:{identifier:e,...(0,Fm.q2e)(l.toString()),...(0,Fm.tBH)(u.tokens(),{expiresInIsFresh:!0})}})},b=r=>{const o=u.lastRedirectUrl?.toString?.()??"",n=new Fg(e,w,{oauthLifecycleLogger:a,initialState:{kind:"requires_authentication",url:o,callback:async e=>{try{await v(e),n.updateState({kind:"ready"})}catch(e){const t=e instanceof Error?e.message:"Authentication failed";throw new Error(`Authentication callback failed: ${t}`)}}},authProvider:u,authCodeExchange:v,sessionId:r,config:t});return n},S=async()=>{const r=new dg.A(l,{authProvider:u,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...p??{}}},fetch:g("sse")});try{return await w.connect(r),new Fg(e,w,{initialState:{kind:"ready"},authProvider:u,authCodeExchange:v,config:t,oauthLifecycleLogger:a})}catch(t){if(await r.close().catch((()=>{})),y(t))return a&&(0,Fm.VDJ)({logger:a,event:"mcp_oauth_state_transition",metadata:{identifier:e,from:"connecting",to:"needsAuth",cause:"connect_auth_error",transport:"sse",refreshTokenPresent:Boolean(d?.refresh_token),...(0,Fm.q2e)(l.toString()),...(0,Fm.X5z)(t)}}),b();throw t}};if("sse"===t.type)return S();const k=new pg.j(l,{authProvider:u,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...p??{}}},fetch:Ng(g("streamableHttp"),l)});try{await w.connect(k);const r=(0,Fm.iog)(t.url)?void 0:function(e,r){const n=r.protocolVersion;if(void 0!==r.sessionId||void 0===n)return;const s=e.getServerCapabilities(),i=e.getServerVersion();if(void 0===s||void 0===i)return;const a=e.getInstructions();return{result:{protocolVersion:n,capabilities:s,serverInfo:i,...void 0===a?{}:{instructions:a}},credentialFingerprint:wg({url:t.url,headers:o,accessToken:u.tokens()?.access_token})}}(w,k);return new Fg(e,w,{initialState:{kind:"ready"},authProvider:u,authCodeExchange:v,sessionId:k.sessionId,protocolVersion:k.protocolVersion,...void 0===r?{}:{sessionlessInitialize:r},config:t,oauthLifecycleLogger:a})}catch(t){if(y(t))return a&&(0,Fm.VDJ)({logger:a,event:"mcp_oauth_state_transition",metadata:{identifier:e,from:"connecting",to:"needsAuth",cause:"connect_auth_error",transport:"streamableHttp",refreshTokenPresent:Boolean(d?.refresh_token),...(0,Fm.q2e)(l.toString()),...(0,Fm.X5z)(t)}}),b(k.sessionId);if((0,Fm.PKk)(t))return S();throw t}}static async fromStreamableHttpWithoutOAuth(e,t,r){const o=Fg.createClient(),n=new pg.j(new URL(t.url),{requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...t.headers}},fetch:r});return await o.connect(n),new Fg(e,o,{initialState:{kind:"ready"},sessionId:n.sessionId,protocolVersion:n.protocolVersion,config:t})}static async fromCachedSession(e,t,r,o,n,s=cg.tl,i,a,c,l){const u=new URL(t.url),d=await Ag({serverName:e,config:t,tokenStorage:o,authRedirectUrl:s,fetchImpl:i,gtmMcpMatch:l}),{transportHeaders:h,baseFetch:p}=$g(t.url,n,i),f=new pg.j(u,{authProvider:d,sessionId:r.sessionId,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...h??{}}},fetch:void 0!==p&&void 0!==a?(0,Fm.jIB)({fetch:p,logger:a.logger,metadata:{...a.metadata,transportType:"streamableHttp"}}):p});f.setProtocolVersion(r.protocolVersion);const m=Fg.createClient();return await m.connect(f),new Fg(e,m,{initialState:{kind:"ready"},authProvider:d,sessionId:f.sessionId,protocolVersion:r.protocolVersion,...void 0===r.instructions?{}:{resumedInstructions:r.instructions},config:t,oauthLifecycleLogger:c})}static async fromSessionlessInitialize(e,t,r,o,n,s=cg.tl,i,a){const c=await Ag({serverName:e,config:t,tokenStorage:o,authRedirectUrl:s,fetchImpl:i,gtmMcpMatch:a});if(wg({url:t.url,headers:n,accessToken:c.tokens()?.access_token})!==r.credentialFingerprint)return;const{transportHeaders:l,baseFetch:u}=$g(t.url,n,i),d=new pg.j(new URL(t.url),{authProvider:c,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...l??{}}},fetch:u}),h=Fg.createClient();return await h.connect(new yg(d,r.result)),new Fg(e,h,{initialState:{kind:"ready"},authProvider:c,sessionlessInitialize:r,config:t})}get sessionId(){return this._sessionId}get protocolVersion(){return this._protocolVersion}get sessionlessInitialize(){return this._sessionlessInitialize}get holdsOAuthAccessToken(){return Boolean(this._authProvider?.tokens()?.access_token)}async openStandaloneStream(){const e=this.client.transport;e instanceof pg.j&&await e.resumeStream("")}static async fromCommand(e,t,r,o,n){const s={stack:[],error:void 0,hasError:!1};try{Eg(s,(0,i.VI)(e.withName("McpSdkClient.fromCommand")),!1);const u=(l=n?.spawn,void 0!==l||"linux"!==process.platform?l:(e,t,r)=>(0,Of.D9)(Iu.spawn,e,t,r)),d=new hg.oQ({command:r.command,args:r.args??[],env:o,cwd:r.cwd,stderr:"pipe",...u&&{spawn:u}}),h=function(e){let t="",r=null===e;return null!==e&&(e.on("data",(e=>{const r=Fm.uOd-t.length;r<=0||(t+=e.toString().slice(0,r))})),e.once("end",(()=>{r=!0}))),{read:()=>(0,Fm.eaG)(t.replace(/\s+/g," ").trim(),{maxLength:Fm.uOd}),waitForFlush:async()=>{r||null===e||await new Promise((t=>{let r;const o=()=>{void 0!==r&&clearTimeout(r),e.off("end",o),t()};r=setTimeout(o,250),r.unref(),e.once("end",o)}))}}}(d.stderr),p=Fg.createClient(),f=n?.connectTimeoutMs??(void 0!==(c=r.startupTimeoutSec)&&Number.isFinite(c)&&c>0?Math.min(1e3*c,3e5):6e4),m=new AbortController,g=p.connect(d,{timeout:f,signal:m.signal});let w;const y=new Promise(((e,r)=>{w=setTimeout((()=>r(new Error(`MCP server connection timed out after ${f}ms: ${t}`))),f)}));try{await Promise.race([g,y])}catch(e){throw m.abort(),g.catch((()=>{})),await d.close().catch((()=>{})),await h.waitForFlush(),function(e,t){if(""===t)return e;const r=e instanceof Error?e:new Error(String(e));return r.message=`${r.message}; stderr: ${t}`,Object.defineProperty(r,Sg,{value:t,enumerable:!1,configurable:!0,writable:!0}),r}(e,h.read())}finally{void 0!==w&&clearTimeout(w)}const v=d.pid??void 0;return"number"==typeof v&&(a=v,Mg.add(a),Dg||(Dg=!0,process.on("exit",Og))),new Fg(t,p,{initialState:{kind:"ready"},config:r,stdioChildPid:v,serverSignals:gg(d)})}catch(e){s.error=e,s.hasError=!0}finally{Cg(s)}var a,c,l}terminateSessionOnClose(e){this._sessionTermination=e}setToolCallRequestOptions(e){this._toolCallRequestOptions=e}failToolCallInFlight(e){const t=this._toolCallInFlight;return void 0!==t&&!t.signal.aborted&&(t.abort(e),!0)}onServerSignal(e){return this._serverSignals?.subscribe(e)??(()=>{})}setToolCallOutputSchemaPassthrough(e){this._toolCallOutputSchemaPassthrough=e}async close(){var e;if(void 0!==this._stdioChildPid&&(e=this._stdioChildPid,Mg.delete(e)),this._terminatingSession)return;const t=this._sessionTermination,r=this.client.transport;if(void 0!==t&&r instanceof pg.j)return this._terminatingSession=!0,void(async()=>{await async function(e,t){const r=await async function(e,t){if(void 0===e.sessionId)return{outcome:"no_session",durationMs:0};const r=Date.now(),o=e.terminateSession();o.catch((()=>{}));try{await(0,Ht.wj)(o,t.timeoutMs)}catch(e){const t=Date.now()-r;return e instanceof Ht.MU?{outcome:"timeout",durationMs:t}:e instanceof pg.b&&void 0!==e.code&&e.code>0?{outcome:"rejected",durationMs:t,httpStatus:e.code,error:e.message}:{outcome:"failed",durationMs:t,error:String(e)}}const n=t.deleteObserver?.lastDeleteStatus;return{outcome:405===n?"unsupported":"terminated",durationMs:Date.now()-r,...void 0!==n?{httpStatus:n}:{}}}(e,t);try{t.onResult?.(r)}catch{}return r}(r,t),await this.client.close()})().catch((()=>{}));await this.client.close()}async getTools(e){const t={stack:[],error:void 0,hasError:!1};try{const r=Eg(t,(0,i.VI)(e.withName("McpSdkClient.getTools")),!1);if(r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("mcp.transport",Pg(this.config)),"requires_authentication"===this.stateValue.kind)return r.span.setAttribute("mcp.tools.requires_authentication",!0),[];let o=0;try{const e=await this.tools.get((async()=>(await(0,Fm.eod)({fetchPage:e=>(o++,this.client.listTools({cursor:e})),itemsOf:e=>e.tools,nextCursorOf:e=>e.nextCursor})).map((e=>({...e,inputSchema:e.inputSchema,outputSchema:e.outputSchema})))));return r.span.setAttribute("mcp.tools.fetched",o>0),r.span.setAttribute("mcp.tools.pages",o),r.span.setAttribute("mcp.tools.count",e.length),e}catch(e){if(r.span.setAttribute("mcp.tools.fetched",o>0),r.span.setAttribute("mcp.tools.pages",o),e instanceof lg.D_&&"ready"===this.stateValue.kind){const t=this.stateValue,r=this._authProvider?.lastRedirectUrl?.toString()??"";this.stateValue={kind:"requires_authentication",url:r,callback:e=>this.completeRuntimeAuthorization(e)},this._logStateTransition(t,this.stateValue,"runtime_unauthorized",{...(0,Fm.X5z)(e)}),this._stateEnteredAtMs=Date.now()}throw e}}catch(e){t.error=e,t.hasError=!0}finally{Cg(t)}}async callTool(e,t,r,o,n){const s={stack:[],error:void 0,hasError:!1};try{const c=Eg(s,(0,i.VI)(e.withName("McpSdkClient.callTool")),!1);c.span.setAttribute("toolName",t),c.span.setAttribute("serverName",this.serverName),c.span.setAttribute("mcp.transport",Pg(this.config));const l=this._callToolLock,u=this._callToolQueueDepth;let d;this._callToolQueueDepth++,this._callToolLock=new Promise((e=>{d=e}));try{{const e={stack:[],error:void 0,hasError:!1};try{const t=Eg(e,(0,i.VI)(c.ctx.withName("McpSdkClient.callTool.lockWait")),!1);t.span.setAttribute("serverName",this.serverName),t.span.setAttribute("mcp.call_tool.queued_ahead",u);const r=performance.now();await l;const o=performance.now()-r;t.span.setAttribute("mcp.call_tool.lock_wait_ms",o),c.span.setAttribute("mcp.call_tool.lock_wait_ms",o),c.span.setAttribute("mcp.call_tool.queued_ahead",u)}catch(t){e.error=t,e.hasError=!0}finally{Cg(e)}}if("requires_authentication"===this.stateValue.kind)throw new lg.D_(`MCP server "${this.serverName}" requires authentication`);this._currentToolCallId=o,this._currentToolName=t,this._currentElicitationProvider=n;const s=new AbortController;this._toolCallInFlight=s;try{const o={stack:[],error:void 0,hasError:!1};try{const n=Eg(o,(0,i.VI)(c.ctx.withName("McpSdkClient.callTool.sdk")),!1);n.span.setAttribute("toolName",t),n.span.setAttribute("serverName",this.serverName);const l=await this.sendToolCall({name:t,arguments:r},s.signal);return n.span.setAttribute("mcp.call_tool.is_error",!0===l.isError),_g(e,this.config,{isError:!0===l.isError}),{content:l.content,isError:!0===l.isError,structuredContent:(a=l.structuredContent,"object"!=typeof a||null===a||Array.isArray(a)?void 0:a),_meta:Zm(l._meta)}}catch(e){o.error=e,o.hasError=!0}finally{Cg(o)}}catch(t){if(_g(e,this.config,{error:t}),t instanceof lg.D_&&"ready"===this.stateValue.kind){const e=this.stateValue,r=this._authProvider?.lastRedirectUrl?.toString()??"";this.stateValue={kind:"requires_authentication",url:r,callback:e=>this.completeRuntimeAuthorization(e)},this._logStateTransition(e,this.stateValue,"runtime_unauthorized",{...(0,Fm.X5z)(t)}),this._stateEnteredAtMs=Date.now()}throw t}finally{this._toolCallInFlight=void 0,this._currentElicitationProvider=void 0,this._currentToolCallId=void 0,this._currentToolName=void 0}}finally{this._callToolQueueDepth--,l.then(d)}}catch(e){s.error=e,s.hasError=!0}finally{Cg(s)}var a}sendToolCall(e,t){const r=this._toolCallRequestOptions?.(e.name),o={...r,signal:void 0===r?.signal?t:AbortSignal.any([r.signal,t])};return!0===this._toolCallOutputSchemaPassthrough?.()?this.client.request({method:"tools/call",params:e},fg.TF,o):this.client.callTool(e,void 0,o)}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{if(Eg(t,(0,i.VI)(e.withName("McpSdkClient.getInstructions")),!1).span.setAttribute("serverName",this.serverName),"requires_authentication"===this.stateValue.kind)return;return this.client.getInstructions()??this._resumedInstructions}catch(e){t.error=e,t.hasError=!0}finally{Cg(t)}}async listResources(e){const t={stack:[],error:void 0,hasError:!1};try{if(Eg(t,(0,i.VI)(e.withName("McpSdkClient.listResources")),!1),"requires_authentication"===this.stateValue.kind)return{resources:[]};const r=this.client.getServerCapabilities();return r?.resources?{resources:await(0,Fm.eod)({fetchPage:e=>this.client.listResources({cursor:e}),itemsOf:e=>e.resources,nextCursorOf:e=>e.nextCursor})}:{resources:[]}}catch(e){t.error=e,t.hasError=!0}finally{Cg(t)}}async readResource(e,t){const r={stack:[],error:void 0,hasError:!1};try{return Eg(r,(0,i.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{Cg(r)}}async listPrompts(e){const t={stack:[],error:void 0,hasError:!1};try{return Eg(t,(0,i.VI)(e.withName("McpSdkClient.listPrompts")),!1),"requires_authentication"===this.stateValue.kind?[]:(this.client.getServerCapabilities()??{prompts:!1}).prompts?(await(0,Fm.eod)({fetchPage:e=>this.client.listPrompts({cursor:e}),itemsOf:e=>e.prompts,nextCursorOf:e=>e.nextCursor})).map((e=>({name:e.name,description:e.description,arguments:e.arguments?.map((e=>({name:e.name,description:e.description,required:e.required})))}))):[]}catch(e){t.error=e,t.hasError=!0}finally{Cg(t)}}async getPrompt(e,t,r){const o={stack:[],error:void 0,hasError:!1};try{return Eg(o,(0,i.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{Cg(o)}}getCurrentToolCallContext(){if(this._currentToolName)return{toolName:this._currentToolName,toolCallId:this._currentToolCallId}}async getState(e){return this.stateValue}async completeRuntimeAuthorization(e){if(!this._authCodeExchange)throw new Error(`MCP server "${this.serverName}" cannot complete authorization: no code exchange is configured for this client.`);try{await this._authCodeExchange(e)}catch(e){const t=e instanceof Error?e.message:"Authentication failed";throw new Error(`Authentication callback failed: ${t}`)}this.updateState({kind:"ready"},"runtime_authorization_completed")}updateState(e,t){const r=this.stateValue;this.stateValue=e,this._logStateTransition(r,e,t??"explicit_update"),this._stateEnteredAtMs=Date.now()}}class jg extends Error{constructor(e,t){super(`MCP server ${e} not found, available servers: ${t.join(", ")}`),this.serverName=e,this.availableServers=t,this.name="McpServerNotFoundError"}}Error,Error;class Lg{constructor(e){this.tools=e}async execute(e,t,r,o){const n=this.tools[e];if(!n)throw new $t(e,Object.keys(this.tools));return n.execute(t,r,o)}getTools(){return Object.entries(this.tools).map((([e,t])=>({...t.definition,name:e})))}}class Ug{async getClients(e){return{}}async getClient(e,t){}async getInstructions(e){return[]}async getToolSet(e){return new Lg({})}async getTools(e){return[]}async getToolsForServers(e,t){return[]}}class Bg{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=Eg(t,(0,i.VI)(e.withName("ManagerMcpLease.getInstructions")),!1);return await this.manager.getInstructions(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{Cg(t)}}async getToolSet(e){const t={stack:[],error:void 0,hasError:!1};try{const r=Eg(t,(0,i.VI)(e.withName("ManagerMcpLease.getToolSet")),!1);return await this.manager.getToolSet(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{Cg(t)}}async getTools(e){const t={stack:[],error:void 0,hasError:!1};try{const r=Eg(t,(0,i.VI)(e.withName("ManagerMcpLease.getTools")),!1);return(await this.getToolSet(r.ctx)).getTools()}catch(e){t.error=e,t.hasError=!0}finally{Cg(t)}}async getToolsForServers(e,t){const r=new Set(t);return(await this.getTools(e)).filter((e=>r.has(e.clientKey)))}onDidChange(e){return{dispose:this.manager.onDidChange((()=>e(void 0)))}}async reconcileSelection(e,t,r){for(const e of t.removed){const t=this.manager.getClient(e);this.manager.deleteClient(e);try{await(t?.close?.())}catch{}}for(const o of t.added){if(this.manager.getClient(o))continue;const t=await r(e,o);this.manager.setClient(o,t)}}}class Wg{constructor(e,t){this.clients=e,this.elicitationFactory=t,this.changeListeners=new Set,this.warnedToolNameCollisions=new Set}onDidChange(e){return this.changeListeners.add(e),()=>{this.changeListeners.delete(e)}}fireDidChange(){for(const e of this.changeListeners)try{e()}catch(e){console.error("Error in McpManager change listener:",e)}}getClients(){return this.clients}getClient(e){return this.clients[e]}setClient(e,t){this.clients[e]=t,this.fireDidChange()}deleteClient(e){delete this.clients[e],this.fireDidChange()}setListingDeadline(e){this.listingDeadlineAt=void 0===e?void 0:performance.now()+e}async closeAllClients(){const e=Object.values(this.clients);await Promise.all(e.map((async e=>{try{await(e.close?.())}catch{}})))}async getToolSet(e){const t={stack:[],error:void 0,hasError:!1};try{const r=Eg(t,(0,i.VI)(e.withName("McpManager.getToolSet")),!1),o=Eg(t,Hg(this.listingDeadlineAt),!1),n=await(0,Ht.PH)(Object.entries(this.clients),(([e,t])=>o.within(t.getTools(r.ctx)).then((r=>(r??[]).map((r=>({...r,clientKey:e,clientName:t.serverName,client:t}))))).catch((()=>[]))),{max:o.concurrency}),s=Array.from(n.values()).flat(),a=new Map;for(const e of s){const t=`${e.clientName}-${e.name}`,r=a.get(t);void 0===r?a.set(t,[e]):r.push(e)}const c={};for(const[e,t]of a){const o=t[0];if(void 0===o)continue;if(t.some((e=>e.clientName!==o.clientName||e.name!==o.name))){if(!this.warnedToolNameCollisions.has(e)){this.warnedToolNameCollisions.add(e);const r=t.map((e=>`${e.clientName}/${e.name}`)).join(", ");console.warn("Colliding MCP tool name; exposing neither:",`${e} (${r})`)}continue}const n=t[t.length-1]?.clientKey,s=t.filter((e=>e.clientKey===n)),i=s[0]??o;s.length>1&&!this.warnedToolNameCollisions.has(e)&&(this.warnedToolNameCollisions.add(e),console.warn("MCP server lists a tool name more than once; using the first:",`${i.clientName}/${i.name}`)),c[e]={definition:{...i,clientKey:i.clientKey,providerIdentifier:i.clientName,toolName:i.name},execute:async(e,t,o)=>{const n=o?.createProvider(i.clientName,i.name,t);return await i.client.callTool(r.ctx,i.name,e,t,n)}}}return new Lg(c)}catch(e){t.error=e,t.hasError=!0}finally{Cg(t)}}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{const r=Eg(t,(0,i.VI)(e.withName("McpManager.getInstructions")),!1),o=Eg(t,Hg(this.listingDeadlineAt),!1),n=await(0,Ht.PH)(Object.entries(this.clients),(([e,t])=>o.within(t.getInstructions(r.ctx)).then((e=>e&&0!==e.trim().length?new Jn.I0({serverName:t.serverName,instructions:e.trim()}):null)).catch((()=>null))),{max:o.concurrency});return Array.from(n.values()).filter((e=>null!==e))}catch(e){t.error=e,t.hasError=!0}finally{Cg(t)}}}function Hg(e){if(void 0===e)return{concurrency:4,within:e=>e,[Symbol.dispose]:()=>{}};let t;const r=new Promise((r=>{t=setTimeout((()=>r(void 0)),Math.max(0,e-performance.now()))}));return{concurrency:Number.POSITIVE_INFINITY,within:e=>Promise.race([e,r]),[Symbol.dispose]:()=>clearTimeout(t)}}function qg(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})}Error;class zg{constructor(e){this.options=e,(0,Fm.VDJ)({logger:e.logger,event:"mcp_oauth_provider_initialized",metadata:this.baseMetadata})}get baseMetadata(){return{identifier:this.options.identifier,...this.options.serverUrl?{serverUrl:(0,Fm.q2e)(this.options.serverUrl)}:{}}}async loadTokens(){const e=await this.options.inner.loadTokens();return(0,Fm.VDJ)({logger:this.options.logger,event:"mcp_oauth_tokens_loaded",level:"debug",metadata:{...this.baseMetadata,...(0,Fm.tBH)(e)}}),e}async saveTokens(e){await this.options.inner.saveTokens(e),(0,Fm.VDJ)({logger:this.options.logger,event:"mcp_oauth_tokens_saved",metadata:{...this.baseMetadata,...(0,Fm.tBH)(e,{expiresInIsFresh:!0})}})}async prepareForRefresh(){(0,Fm.VDJ)({logger:this.options.logger,event:"mcp_oauth_refresh_prepare",metadata:this.baseMetadata}),await(this.options.inner.prepareForRefresh?.())}async releaseRefreshLeaseOnError(e){(0,Fm.VDJ)({logger:this.options.logger,event:"mcp_oauth_refresh_error_release",level:"warn",error:e,metadata:{...this.baseMetadata,...(0,Fm.X5z)(e)}}),await(this.options.inner.releaseRefreshLeaseOnError?.(e))}async loadClientInformation(){const e=await this.options.inner.loadClientInformation();return(0,Fm.VDJ)({logger:this.options.logger,event:"mcp_oauth_client_info_loaded",level:"debug",metadata:{...this.baseMetadata,...(0,Fm.O3I)(e)}}),e}async saveClientInformation(e){await this.options.inner.saveClientInformation(e),(0,Fm.VDJ)({logger:this.options.logger,event:"mcp_oauth_client_info_saved",metadata:{...this.baseMetadata,...(0,Fm.O3I)(e)}})}async invalidateCredentials(e){void 0!==this.options.inner.invalidateCredentials&&((0,Fm.VDJ)({logger:this.options.logger,event:"mcp_oauth_credentials_invalidated",level:"warn",metadata:{...this.baseMetadata,scope:e}}),await this.options.inner.invalidateCredentials(e))}tokenEndpointAuth(e){return this.options.inner.tokenEndpointAuth?.(e)}}class Gg{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 Vg{constructor(e){this.inner=e}async loadTokens(){}async loadClientInformation(){}async saveTokens(e){return this.inner.saveTokens(e)}async saveClientInformation(e){return this.inner.saveClientInformation(e)}async invalidateCredentials(e){await(this.inner.invalidateCredentials?.(e))}}var Jg=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},Kg=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 Zg=(0,m.h)("DefinitionMcpLoader");function Xg(e){const{filePath:t,baseDir:r}=e;return"~"===t||t.startsWith("~/")?s.default.join(n.default.homedir(),t.slice(1)):t.startsWith("./")||"."===t?s.default.resolve(r??process.cwd(),t):t}function Qg(e){return"function"==typeof e.getManagedSlackWorkspaceLists}function Yg(e){return"function"==typeof e.getMcpNetworkControlsConfig}function ew(e){return e?.length??0}function tw(e){if(void 0!==e)return(0,Ts.createHash)("sha256").update((0,Fm.Fmf)(e)).digest("hex")}class rw{constructor(e){this.configPath=e,this.configPromise=ig(e)}clearCache(){this.configPromise=ig(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 ow{constructor(e,t,r=[],o={}){this.source=e,this.tokenStorage=t,this.middlewares=r,this.options=o,this.clientCache=new Map}async load(e,t=!0){const r={stack:[],error:void 0,hasError:!1};try{Jg(r,(0,i.VI)(e.withName("DefinitionMcpLoader.load")),!1),t||(await this.closeAllCachedClients(),this.source.clearCache?.());const o=await this.source.getDefinitions(e,t);await this.evictClientsOnSandboxPolicyChange(e,o);const n={};return await(0,Ht.PH)([...o],(async r=>{try{const o=t?this.clientCache.get(r.identifier):void 0,s=o??await this.loadDefinitionClient(e,r);o||this.clientCache.set(r.identifier,s),n[r.identifier]=s}catch(t){if(this.handleDefinitionLoadError(e,r,t))return;!function(e,t,r){Zg.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),stderrTail:kg(r)})}(e,r,t)}}),{max:this.options.maxConcurrency??Math.max(o.length,1)}),new Wg(n,this.options.elicitationFactory)}catch(e){r.error=e,r.hasError=!0}finally{Kg(r)}}clearClient(e){this.clientCache.delete(e)}clearAllMcpCaches(){this.clientCache.clear()}async evictClientsOnSandboxPolicyChange(e,t){const r=this.middlewares.find(Yg);if(!r)return;let o;try{o=JSON.stringify(await Promise.all([...t].sort(((e,t)=>e.identifier.localeCompare(t.identifier))).map((async e=>{const t=await(r.getMcpNetworkControlsConfig?.((o=e.serverConfig,"url"in o?{url:o.url}:{command:[o.command,...o.args??[]].join(" ")})))??{};var o;return[e.identifier,(0,Fm.Fmf)(t)]}))))}catch{return}const n=this.sandboxPolicyFingerprint;this.sandboxPolicyFingerprint=o,void 0!==n&&n!==o&&(Zg.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,Ht.PH)(e,(async e=>{try{await(e.close?.())}catch{}}),{max:Math.max(e.length,1)})}async loadClient(e,t,r){const o={stack:[],error:void 0,hasError:!1};try{Jg(o,(0,i.VI)(e.withName("DefinitionMcpLoader.loadClient")),!1);const n=await this.source.getDefinitions(e);if(await this.evictClientsOnSandboxPolicyChange(e,n),!r){const e=this.clientCache.get(t);if(e)return e}const s=n.find((e=>e.identifier===t));if(!s)throw new Error(`MCP server "${t}" not found in config`);let a;try{a=await this.loadDefinitionClient(e,s,r)}catch(t){throw this.handleDefinitionLoadError(e,s,t),t}return r||this.clientCache.set(t,a),a}catch(e){o.error=e,o.hasError=!0}finally{Kg(o)}}async loadDefinitionClient(e,t,o){const n=t.authStorageKey??t.identifier,s=new Gg(this.tokenStorage,n),a=qg(e,Zg),c=new zg({inner:s,logger:a,identifier:n,serverUrl:"url"in t.serverConfig?t.serverConfig.url:void 0}),l=o?new Vg(c):c;return async function(e,t,o,n,s={middlewares:[],configPath:""},a){const c={stack:[],error:void 0,hasError:!1};try{const{middlewares:l,configPath:u}=s,d=Jg(c,(0,i.VI)(e.withName("mcp-agent-exec.loadServer")),!1);d.span.setAttribute("serverName",t);let h=async(e,o)=>{const s={stack:[],error:void 0,hasError:!1};try{const c=Jg(s,(0,i.VI)(e.withName("loadServer.next")),!1);c.span.setAttribute("serverName",t);const u=c.ctx;if("command"in o){c.span.setAttribute("kind","command");const e=l.find(Yg);return await async function(e,t,o,n){const s=o.cwd?Xg({filePath:o.cwd}):void 0;let i,a;if(o.args&&o.args.length>0)i=Xg({filePath:o.command,baseDir:s}),a=o.args.map((e=>Xg({filePath:e,baseDir:s})));else{const e=(0,ag.A)(o.command);i=Xg({filePath:e[0],baseDir:s}),a=e.slice(1).map((e=>Xg({filePath:e,baseDir:s})))}const c=o.env??{},{startupTimeoutSec:l}=o,u=await(n?.getMcpNetworkControlsConfig?.({command:[o.command,...o.args??[]].join(" ")})),d=(0,Fm.$HQ)(u);if(void 0!==d){const{buildMcpSandboxPolicy:o}=await Promise.resolve().then(r.bind(r,"../mcp-agent-exec/dist/mcp-sandbox-policy.js")),{SandboxUnsupportedError:n,spawnInSandbox:h}=await Promise.resolve().then(r.bind(r,"../shell-exec/dist/api/index.js")),p=s??process.cwd(),f=await o(d,p);Zg.info(e,function(e){return`Sandboxing local MCP server "${e.serverName}" with network controls: networkControlsEnabled=${String(!0===e.networkControlsConfig?.enabled)}, mcpNetworkMode=${e.networkControlsConfig?.mcpNetworkMode??"unset"}, mcpNetworkAllowlistCount=${ew(e.networkControlsConfig?.mcpNetworkAllowlist)}, mcpNetworkDenylistCount=${ew(e.networkControlsConfig?.mcpNetworkDenylist)}, localAgentNetworkAllowlistCount=${ew(e.networkControlsConfig?.localAgentNetworkAllowlist)}, sandboxPolicyHash=${tw(e.sandboxNetworkControlsConfig)??"none"}`}({serverName:t,networkControlsConfig:u,sandboxNetworkControlsConfig:d}),function(e){return{event:"mcp_stdio_sandbox_policy",serverName:e.serverName,networkControlsEnabled:!0===e.networkControlsConfig?.enabled,mcpNetworkMode:e.networkControlsConfig?.mcpNetworkMode,mcpNetworkAllowlistCount:ew(e.networkControlsConfig?.mcpNetworkAllowlist),mcpNetworkDenylistCount:ew(e.networkControlsConfig?.mcpNetworkDenylist),localAgentNetworkAllowlistCount:ew(e.networkControlsConfig?.localAgentNetworkAllowlist),sandboxPolicyHash:tw(e.sandboxNetworkControlsConfig)}}({serverName:t,networkControlsConfig:u,sandboxNetworkControlsConfig:d}));try{return await Fg.fromCommand(e,t,{command:i,args:a,cwd:s,startupTimeoutSec:l},c,{spawn:(e,t,r)=>h(e,t,r,f)})}catch(e){if(e instanceof n)throw new Fm.c8u(t,e);throw e}}return!0===u?.enabled&&"no_sandbox"===u.mcpNetworkMode&&(!0===u.win32UserExtensionUnsandbox?Zg.info(e,`Starting local MCP server "${t}" without MCP sandboxing`,{event:"mcp_stdio_win32_user_extension_unsandbox",serverName:t}):Zg.info(e,`Starting local MCP server "${t}" without MCP sandboxing`)),Fg.fromCommand(e,t,{command:i,args:a,cwd:s,startupTimeoutSec:l},c)}(u,t,o,e)}if("url"in o){c.span.setAttribute("kind","url");const e=a?.(t);return await async function(e,t,r,o,n,s){const i=qg(e,Zg),a=function(e,t){return{logger:{debug:(t,r)=>Zg.debug(e,t,r),info:(t,r)=>Zg.info(e,t,r),warn:(t,r)=>Zg.warn(e,t,r),error:(t,r,o)=>Zg.error(e,t,r,o)},metadata:{identifier:t,source:"mcp-agent-exec"}}}(e,t),c=void 0!==s&&(0,Fm.DEr)(r.url)?(0,Fm.gD9)(globalThis.fetch.bind(globalThis),{managedSlackWorkspaceLists:()=>s.getManagedSlackWorkspaceLists()}):void 0;return Fg.fromStreamableHttp(t,r,o,r.headers,n,c,a,i)}(u,t,o,n,e,l.find(Qg))}throw new Error(`Invalid server: ${JSON.stringify(o)}`)}catch(e){s.error=e,s.hasError=!0}finally{Kg(s)}};for(const e of l){const r=h;h=async(o,n)=>await e.load(o,t,n,u,r)}return await h(d.ctx,o)}catch(e){c.error=e,c.hasError=!0}finally{Kg(c)}}(e,t.identifier,t.serverConfig,l,{middlewares:this.middlewares,configPath:t.configPath??""},this.options.authRedirectUrlGenerator)}handleDefinitionLoadError(e,t,r){let o=!1;try{o="handled"===this.options.onDefinitionLoadError?.(e,t,r)}catch(r){Zg.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 o||function(e){return e instanceof Lm||e instanceof Um||e instanceof nw}(r)}}class nw extends Error{constructor(e,t,r){super(r??("teamNetworkAllowlist"===t?`MCP server "${e}" is not on the team network allowlist`:`MCP server "${e}" is blocked by team policy`)),this.serverName=e,this.reason=t,this.name="McpServerBlockedError"}}const sw=[1e3,3e3];class iw{constructor(e){this.blockingService=e}async getMcpNetworkControlsConfig(e){return await(this.blockingService.getMcpNetworkControlsConfig?.(e))??{}}async getManagedSlackWorkspaceLists(){return await(this.blockingService.getManagedSlackWorkspaceLists?.())??[]}async load(e,t,r,o,n){const s={command:"command"in r?[r.command,...r.args??[]].join(" "):void 0,url:"url"in r?r.url:void 0},i=await(this.blockingService.getMcpServerBlockInfo?.(s))??{blocked:await this.blockingService.isServerBlocked(s)};if(i.blocked)throw new nw(t,i.reason??"teamPolicy",i.message);for(let o=0;;o++)try{return await n(e,r)}catch(e){if(e instanceof Fm.GSN)throw new nw(t,"teamPolicy",e.message);const r=e instanceof Fm.Uod?sw[o]:void 0;if(void 0===r)throw e;await(0,Ht.cb)(r)}}}class aw extends ow{constructor(e,t,r=[],o,n){super(new rw(e),t,r,{authRedirectUrlGenerator:o,elicitationFactory:n}),this.configPath=e,this.elicitationFactory=n}static init(e,t,r=[]){return new aw(t,e,r)}}function cw(e){return"stdio"===e.type&&e.command?{command:e.command,args:e.args??[],env:e.env,cwd:e.cwd}:"streamableHttp"===e.type&&e.url?{url:e.url,headers:e.headers,auth:e.auth,...void 0!==e.tls?{tls:e.tls}:{},...void 0!==e.placement?{placement:e.placement}:{}}:void 0}r("../mcp-agent-exec/dist/mcp-sandbox-policy.js");class lw{constructor(e){this.mcpAuthPath=e;const t=lw.mcpAuthPromises.get(e);if(t)this.mcpAuthPromise=t;else{const t=this.loadMcpAuth();this.mcpAuthPromise=t,lw.mcpAuthPromises.set(e,t),t.catch((()=>{lw.mcpAuthPromises.get(e)===t&&lw.mcpAuthPromises.delete(e)}))}lw.saveLocks.has(e)||lw.saveLocks.set(e,Promise.resolve())}async loadMcpAuth(){try{const e=await(0,Os.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){const t=await this.mcpAuthPromise;return t[e]?.tokens}async saveTokens(e,t){await this.withSaveLock((async()=>{const r=await this.mcpAuthPromise;r[e]||(r[e]={}),r[e].tokens=t,await this.saveMcpAuth(r)}))}async loadClientInformation(e){const t=await this.mcpAuthPromise;return t[e]?.clientInfo}async withSaveLock(e){const t=lw.saveLocks.get(this.mcpAuthPath)??Promise.resolve();let r;lw.saveLocks.set(this.mcpAuthPath,new Promise((e=>{r=e})));try{return await t,await e()}finally{r()}}async saveClientInformation(e,t){await this.withSaveLock((async()=>{const r=await this.mcpAuthPromise;r[e]||(r[e]={}),r[e].clientInfo=t,await this.saveMcpAuth(r)}))}async 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,Os.mkdir)(s.dirname(this.mcpAuthPath),{recursive:!0}),await(0,Os.writeFile)(this.mcpAuthPath,JSON.stringify(e,null,2))}}lw.mcpAuthPromises=new Map,lw.saveLocks=new Map;const uw=Buffer.from([137,80,78,71,13,10,26,10]),dw=Buffer.from([0,0,0,0,73,69,78,68,174,66,96,130]),hw=e=>1===e||e>=208&&e<=216,pw=e=>192===e||193===e||194===e,fw=e=>e>=195&&e<=207&&196!==e&&200!==e&&204!==e,mw=(e,t)=>({width:Math.max(e?.width??0,t.width),height:Math.max(e?.height??0,t.height)}),gw=(e,t)=>{for(;t<e.length&&0!==e[t];)t+=1+e[t];return t+1},ww=e=>{const t=e.toString("latin1",0,6);return e.subarray(0,uw.length).equals(uw)?"png":t.startsWith("ÿØÿ")?"jpeg":"GIF87a"===t||"GIF89a"===t?"gif":t.startsWith("BM")?"bmp":t.startsWith("II*\0")||t.startsWith("MM\0*")?"tiff":t.startsWith("ID3")?"id3":void 0},yw={0:1,2:3,4:2,6:4},vw=({filter:e,row:t,previous:r,bytesPerPixel:o})=>{if(0!==e)for(let n=0;n<t.length;n++){const s=n>=o?t[n-o]:0,i=r[n];switch(e){case 1:t[n]+=s;break;case 2:t[n]+=i;break;case 3:t[n]+=s+i>>1;break;case 4:{const e=n>=o?r[n-o]:0,a=s+i-e,c=Math.abs(a-s),l=Math.abs(a-i),u=Math.abs(a-e);t[n]+=c<=l&&c<=u?s:l<=u?i:e;break}default:throw new Error(`unknown PNG filter type ${e}`)}}},bw=({row:e,channels:t,columnOf:r,sums:o,counts:n})=>{const s=t<3;for(let i=0,a=0;i<r.length;i++,a+=t){const c=e[a],l=s?c:e[a+1],u=s?c:e[a+2],d=2===t?e[a+1]:4===t?e[a+3]:255,h=4*r[i];o[h]+=c*d,o[h+1]+=l*d,o[h+2]+=u*d,o[h+3]+=d,n[r[i]]++}},Sw=({out:e,outY:t,width:r,sums:o,counts:n})=>{for(let s=0;s<r;s++){const i=4*s,a=o[i+3],c=4*(t*r+s);a>0&&(e[c]=Math.round(o[i]/a),e[c+1]=Math.round(o[i+1]/a),e[c+2]=Math.round(o[i+2]/a),e[c+3]=Math.round(a/n[s]))}o.fill(0),n.fill(0)},kw={0:1,2:3,3:1,4:2,6:4},Ew=[1,2,4,8,16],Cw=[[0,0,8,8],[4,0,8,8],[0,4,4,8],[2,0,4,4],[0,2,2,4],[1,0,2,2],[0,1,1,2]],xw=async e=>{const t=_w(e);if(void 0===t)return;const r=Pw(t);let o=0;const n=yu.Readable.from(t.idat).pipe((0,bu.createInflate)());for await(const e of n)if(o+=e.length,o>=r)return void n.destroy();throw new Error(`PNG pixel data ends after ${o} of ${r} bytes`)},_w=e=>{let t;const r=[];let o=8;for(;o+12<=e.length;){const n=e.readUInt32BE(o),s=e.toString("ascii",o+4,o+8),i=e.subarray(o+8,o+8+n);if("IHDR"===s&&void 0===t&&13===i.length){const e=kw[i[9]];if(void 0===e||!Ew.includes(i[8])||i[12]>1)return;t={width:i.readUInt32BE(0),height:i.readUInt32BE(4),bitsPerPixel:e*i[8],interlaced:1===i[12]}}else if("IDAT"===s)r.push(i);else if("IEND"===s)break;o+=n+12}return void 0===t||0===r.length?void 0:{...t,idat:r}},Pw=({width:e,height:t,bitsPerPixel:r,interlaced:o})=>{const n=(e,t)=>e<=0||t<=0?0:t*(1+Math.ceil(e*r/8));return o?Cw.reduce(((r,[o,s,i,a])=>r+n(Math.ceil((e-o)/i),Math.ceil((t-s)/a))),0):n(e,t)};const Iw=()=>{throw new Error("webp codec not registered: registerWebpCodec() must be called by a Node server before decoding/encoding webp")},Rw=e=>e.length>=12&&"RIFF"===e.toString("ascii",0,4)&&"WEBP"===e.toString("ascii",8,12),Tw=e=>{if(!Rw(e)||e.length<16)return;const t=e.toString("ascii",12,16);if("VP8 "===t){if(e.length<30||157!==e[23]||1!==e[24]||42!==e[25])return;return{width:16383&(e[26]|e[27]<<8),height:16383&(e[28]|e[29]<<8)}}if("VP8L"===t){if(e.length<25||47!==e[20])return;const t=(e[21]|e[22]<<8|e[23]<<16|e[24]<<24)>>>0;return{width:1+(16383&t),height:1+(t>>14&16383)}}if("VP8X"===t){if(e.length<30)return;return{width:1+(e[24]|e[25]<<8|e[26]<<16),height:1+(e[27]|e[28]<<8|e[29]<<16)}}},Aw=e=>Iw().decode(e),Mw=e=>Iw().encode(e),Dw=[{width:1280,height:800},{width:1456,height:840}],Ow=1048576,Nw=e=>new Uint8Array(e.buffer,e.byteOffset,e.byteLength),$w=(e,t,r=1024)=>function(e,t,r=1024){if(e<1||t<1)return{width:e,height:t,needsResize:!1};const o=Math.max(e,t);if(o<=r)return{width:e,height:t,needsResize:!1};const n=Math.min(e,t);if(n<8)return{width:e,height:t,needsResize:!1};let s=r/o,i=Math.max(1,Math.round(e*s)),a=Math.max(1,Math.round(t*s));return(i<8||a<8)&&(s=8/n,i=Math.max(8,Math.round(e*s)),a=Math.max(8,Math.round(t*s))),{width:i,height:a,needsResize:i!==e||a!==t}}(e,t,r),Fw=(e,t,r)=>{e.resize({w:t,h:r})},jw=e=>{if(void 0===e)throw new Error("image dimensions could not be read before decoding");const{width:t,height:r}=e;if(!(t*r<=178956970))throw new Error(`image dimensions ${t}x${r} exceed the 178956970 pixel decode limit`);if(!(Math.max(t,r)<=1e6))throw new Error(`image dimensions ${t}x${r} exceed the 1000000 pixel side limit`)},Lw=(e,t)=>{switch(t){case"tiff":throw new Error("TIFF images are not supported; convert the image to PNG or JPEG");case"id3":throw new Error("images that start with an ID3 tag are not supported");case"jpeg":return;default:jw(((e,t)=>{switch(t){case"png":return(e=>{let t,r=uw.length;for(;r+16<=e.length;)"IHDR"===e.toString("ascii",r+4,r+8)&&(t=mw(t,{width:e.readUInt32BE(r+8),height:e.readUInt32BE(r+12)})),r+=12+e.readUInt32BE(r);return t})(e);case"gif":return(e=>{if(e.length<13)return;const t={width:e.readUInt16LE(6),height:e.readUInt16LE(8)};let r=13+(128&(o=e[10])?3<<1+(7&o):0);for(var o;r<e.length;){const o=r;if(44===e[o]&&o+10<=e.length)return mw(t,{width:e.readUInt16LE(o+5),height:e.readUInt16LE(o+7)});if(33===e[o]&&249===e[o+1])r=o+8;else if(33===e[o]&&254===e[o+1])r=gw(e,o+2);else{if(33!==e[o]||255!==e[o+1])break;r=11===e[o+2]?gw(e,o+14):o+19}}return t})(e);case"bmp":return(e=>e.length<26?void 0:{width:e.readUInt32LE(18),height:Math.abs(e.readInt32LE(22))})(e)}})(e,t))}};const Uw=async(e,t)=>{if(Rw(e))return(async(e,t)=>{const r=Tw(e);if(!0===t?.preserveWebpDimensions&&void 0!==r)return{data:Nw(e),mimeType:"image/webp"};const o=void 0!==r&&Dw.some((e=>e.width===r.width&&e.height===r.height));if(void 0!==r&&(o||!$w(r.width,r.height,1280).needsResize)&&e.length<=Ow)return{data:Nw(e),mimeType:"image/webp"};if("passthrough"===t?.webpWithoutCodec)return{data:Nw(e),mimeType:"image/webp"};jw(r);const n=await Aw(e),s=(await sm()).fromBitmap({data:Buffer.from(n.data),width:n.width,height:n.height});let{width:i,height:a,needsResize:c}=o?{width:s.bitmap.width,height:s.bitmap.height,needsResize:!1}:$w(s.bitmap.width,s.bitmap.height,1280);c&&Fw(s,i,a);let l=await Mw({data:s.bitmap.data,width:s.bitmap.width,height:s.bitmap.height});for(;l.length>Ow&&i>8&&a>8;)i=Math.max(8,Math.round(.8*i)),a=Math.max(8,Math.round(.8*a)),Fw(s,i,a),l=await Mw({data:s.bitmap.data,width:s.bitmap.width,height:s.bitmap.height});return{data:Nw(l),mimeType:"image/webp",reencoded:!0}})(e,t);const r=(e=>{if(e.length<uw.length+25+dw.length||!e.subarray(0,uw.length).equals(uw)||13!==e.readUInt32BE(8)||"IHDR"!==e.toString("ascii",12,16)||!e.subarray(e.length-dw.length).equals(dw))return;const t=e.readUInt32BE(16),r=e.readUInt32BE(20);return t<1||r<1?void 0:{mimeType:"image/png",width:t,height:r}})(o=e)??(e=>{if(e.length<4||255!==e[0]||216!==e[1]||255!==e[e.length-2]||217!==e[e.length-1])return;let t=2;for(;t+4<=e.length;){if(255!==e[t])return;const r=e[t+1];if(255===r){t+=1;continue}if(hw(r)){t+=2;continue}if(218===r||217===r||fw(r))return;const o=e.readUInt16BE(t+2);if(o<2)return;if(pw(r)){if(o<8||t+9>e.length)return;const r=e.readUInt16BE(t+5),n=e.readUInt16BE(t+7);if(n<1||r<1)return;return{mimeType:"image/jpeg",width:n,height:r}}t+=2+o}})(o);var o;if(void 0!==r&&e.length<=Ow&&!$w(r.width,r.height).needsResize)return{data:Nw(e),mimeType:r.mimeType};const n=ww(e);void 0!==n&&Lw(e,n),"png"===n&&await xw(e);const s=await sm(),i=void 0===r?void 0:$w(r.width,r.height),a="image/png"===r?.mimeType&&!0===i?.needsResize?await(async({data:e,width:t,height:r})=>{const o=(e=>{let t;const r=[];let o=8;for(;o+12<=e.length;){const n=e.readUInt32BE(o),s=e.toString("ascii",o+4,o+8),i=e.subarray(o+8,o+8+n);if(i.length!==n)return;if("IHDR"===s){const e=yw[i[9]];if(void 0!==t||13!==n||8!==i[8]||0!==i[12]||void 0===e)return;t={width:i.readUInt32BE(0),height:i.readUInt32BE(4),channels:e}}else if("IDAT"===s)r.push(i);else{if("tRNS"===s)return;if("IEND"===s)break}o+=n+12}return void 0===t||0===r.length?void 0:{...t,idat:r}})(e);if(void 0===o||t>o.width||r>o.height)return;const n=o.width*o.channels,s=new Uint32Array(o.width);for(let e=0;e<o.width;e++)s[e]=Math.floor(e*t/o.width);const i=new Float64Array(4*t),a=new Uint32Array(t),c=Buffer.alloc(t*r*4);let l=new Uint8Array(n),u=new Uint8Array(n),d=-1,h=0,p=0;const f=yu.Readable.from(o.idat).pipe((0,bu.createInflate)());for await(const e of f){let f=0;for(;f<e.length&&p<o.height;){if(d<0){d=e[f++];continue}const m=Math.min(n-h,e.length-f);if(u.set(e.subarray(f,f+m),h),h+=m,f+=m,h<n)continue;vw({filter:d,row:u,previous:l,bytesPerPixel:o.channels}),bw({row:u,channels:o.channels,columnOf:s,sums:i,counts:a});const g=Math.floor(p*r/o.height);p++,p!==o.height&&Math.floor(p*r/o.height)===g||Sw({out:c,outY:g,width:t,sums:i,counts:a}),[l,u]=[u,l],d=-1,h=0}if(p===o.height)break}return p===o.height?{data:c,width:t,height:r}:void 0})({data:e,width:i.width,height:i.height}).catch((()=>{})):void 0,c=void 0===a?await s.read(e):s.fromBitmap(a),l=(e=>{switch(e.mime){case"image/png":default:return"image/png";case"image/bmp":return"image/bmp";case"image/tiff":return"image/tiff";case"image/x-ms-bmp":return"image/x-ms-bmp";case"image/gif":return"image/gif";case"image/jpeg":return"image/jpeg"}})(c),u=!0===t?.convertUnsupportedModelFormatsToPng&&"image/png"!==l&&"image/jpeg"!==l?"image/png":l,{width:d,height:h,needsResize:p}=$w(c.width,c.height);if(void 0===a&&!p&&e.length<=Ow&&u===l)return{data:Nw(e),mimeType:l};let f=d,m=h;p&&Fw(c,f,m);let g=await c.getBuffer(u);for(;g.length>Ow&&f>8&&m>8;)f=Math.max(8,Math.round(.8*f)),m=Math.max(8,Math.round(.8*m)),Fw(c,f,m),g=await c.getBuffer(u);return{data:Nw(g),mimeType:u,reencoded:!0}},Bw=async e=>{const t=Buffer.from(e.buffer,e.byteOffset,e.byteLength),r=ww(t);let o;if(Rw(t))return{kind:"unchecked"};if(void 0===r)return{kind:"unchecked"};{Lw(t,r);const e=await sm();o=async()=>("png"===r&&await xw(t),e.read(t))}try{return await o(),{kind:"decodes"}}catch(e){return{kind:"undecodable",reason:e instanceof Error?e.message:String(e)}}};var Ww=r("../mcp-core/dist/mcp-tool-annotations.js"),Hw=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},qw=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 zw=(0,g.Pu)("mcp.filesystem.divergence",{description:"Divergence detected between MCP lease state and filesystem state",labelNames:["divergence_type","mcp_source","configured_servers","mcp_version"]}),Gw=(0,g.Pu)("mcp.filesystem.sync_check",{description:"MCP filesystem sync check executed",labelNames:["synced","mcp_source","configured_servers","mcp_version"]}),Vw=(0,g.wt)("mcp.filesystem.sync_check.expected_servers",{description:"Number of expected MCP servers at last sync check",labelNames:["mcp_source","mcp_version"]}),Jw=(0,g.wt)("mcp.filesystem.sync_check.actual_servers",{description:"Number of actual MCP servers on disk at last sync check",labelNames:["mcp_source","mcp_version"]}),Kw=(0,g.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"]}),Zw=(0,g.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"]}),Xw=(0,m.h)("McpFileSystemWriter"),Qw="mcpFsStructuredLogOptIn";function Yw(e,t){return t?.includeStructuredLogs?{...e??{},[Qw]:!0}:e}const ey={debug(e,t,r,o){Xw.debug(e,t,Yw(r,o))},info(e,t,r,o){Xw.info(e,t,Yw(r,o))},warn(e,t,r,o){Xw.warn(e,t,Yw(r,o))},error(e,t,r,o,n){Xw.error(e,t,r,Yw(o,n))}},ty="mcps",ry="tools",oy="~staging",ny="~prev",sy="mcp_auth",iy="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.",ay="# >>> CURSOR MANAGED BLOCK >>>",cy="# <<< CURSOR MANAGED BLOCK <<<",ly=["# Ignore everything in .cursor","*","# Un-ignore projects so we can descend to allowlisted subdirs","!projects/","projects/*","!projects/*/","projects/*/*","# MCP tool descriptors, resources, prompts","!projects/*/mcps/","!projects/*/mcps/**","# Agent transcripts for citation","!projects/*/agent-transcripts/","!projects/*/agent-transcripts/**","# Terminal output files","!projects/*/terminals/","!projects/*/terminals/**","# Conversation notes (shared scratchpad)","!projects/*/agent-notes/","!projects/*/agent-notes/**","# Large tool output files","!projects/*/agent-tools/","!projects/*/agent-tools/**","# Plugin cache (rules, skills, agents)","!plugins/","!plugins/**","# Built-in Cursor skills","!skills-cursor/","!skills-cursor/**","# User's personal skills","!skills/","!skills/**","# User's personal slash commands","!commands/","!commands/**","# User's plan files","!plans/","!plans/**","# Subagent state/transcripts","!subagents/","!subagents/**","# User-level cursor rules","!rules/","!rules/**"].join("\n");function uy(e,t,r=15e3){let o;return Promise.race([e.catch((()=>t)),new Promise((e=>{o=setTimeout((()=>e(t)),r)}))]).finally((()=>clearTimeout(o)))}function dy(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_")}function hy(e){if(void 0===e)return;const t=e.trim();return t.length>0?t:void 0}function py(e){switch(e.kind){case"loading":return"initializing";case"requires_authentication":return"needsAuth";case"ready":return"connected";case"error":return"error";default:return"disconnected"}}function fy(e){if(Array.isArray(e))return e.map((e=>fy(e)));if(null!==e&&"object"==typeof e){const t=Object.entries(e).filter((([,e])=>void 0!==e)).sort((([e],[t])=>e<t?-1:e>t?1:0)).map((([e,t])=>[e,fy(t)]));return Object.fromEntries(t)}return e}function my(e){return JSON.stringify(fy(e))}function gy(e){const t=e.map((e=>({value:e,key:my(e)})));return t.sort(((e,t)=>e.key<t.key?-1:e.key>t.key?1:0)),t.map((e=>e.value))}function wy(e){const t=gy(e.tools.map((e=>({name:e.toolName,description:e.description,inputSchema:e.inputSchema,outputSchema:e.outputSchema})))),r=gy(e.resources.map((e=>({uri:e.uri,name:e.name,description:e.description,mimeType:e.mimeType})))),o=gy(e.prompts.map((e=>({name:e.name,description:e.description,arguments:e.arguments}))));return my({id:e.serverIdentifier,name:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId,tools:t,resources:r,prompts:o,instructions:e.instructions,status:e.status})}class yy{constructor(e,t,r){this.cachedFingerprints=new Map,this.disposed=!1,this.hasPendingLeaseChangeEvent=!1,this.lastDivergenceCheckMs=0,this.mcpLease=e,this.projectDir=t,this.debounceMs=r?.debounceMs??100,this.mcpAuthCopyOverrides=r?.mcpAuthCopyOverrides,this.exposeVirtualMcpAuthTool=r?.exposeVirtualMcpAuthTool??!0,this.alwaysExposeVirtualMcpAuthTool=r?.alwaysExposeVirtualMcpAuthTool??!1,this.snapshotProvider=r?.snapshotProvider,this.mcpVersion=r?.mcpVersion??(this.snapshotProvider?"snapshots":"v1"),this.onDidWrite=r?.onDidWrite,this.ctx=this.getContext(r?.loggerBackend),this.startupCleanupPromise=this.cleanupStaleStagingDirs(this.ctx),this.leaseChangeDisposable=this.mcpLease.onDidChange((e=>{ey.info(this.ctx,"Lease change event received",{serverIdentifiers:e?.serverIdentifiers,reason:e?.reason}),this.onLeaseChanged(this.ctx,e)})),ey.info(this.ctx,"Constructor: scheduling initial write"),this.scheduleWrite(this.ctx),this.ensureCursorDirGitignore()}ensureCursorDirGitignore(){(async function(e){const t=(0,s.join)(e,".gitignore"),r=`${ay}\n${ly}\n${cy}\n`;let o;await(0,Os.mkdir)(e,{recursive:!0});try{o=await(0,Os.readFile)(t,"utf-8")}catch(e){if("ENOENT"!==e?.code)throw e}if(void 0===o)return void await(0,Os.writeFile)(t,r);const n=o.indexOf(ay),i=o.indexOf(cy,n+30);if(-1===n||-1===i)await(0,Os.writeFile)(t,r);else{const e=`${o.slice(0,n)}${r}${o.slice(i+30).replace(/^\n/,"")}`;e!==o&&await(0,Os.writeFile)(t,e)}})((0,s.join)((0,n.homedir)(),".cursor")).catch((e=>{ey.warn(this.ctx,"Failed to ensure ~/.cursor/.gitignore",e)}))}async cleanupStaleStagingDirs(e){const t=this.getLogContext(e),r=(0,s.join)(this.projectDir,ty);try{const e=await(0,Os.readdir)(r);await Promise.allSettled(e.filter((e=>e.endsWith(oy))).map((e=>(0,Os.rm)((0,s.join)(r,e),{recursive:!0,force:!0}))))}catch(e){"ENOENT"!==e?.code&&ey.error(t,"Error clearing stale mcps staging dirs",e)}}onLeaseChanged(e,t){if(this.disposed)return;const r=t??{serverIdentifiers:void 0};this.hasPendingLeaseChangeEvent?this.pendingLeaseChangeEvent=function(...e){const[t,r]=e;return e.length<2?t:Rt(r)?{serverIdentifiers:void 0,reason:t?.reason??r?.reason}:void 0===t?r:Rt(t)?{serverIdentifiers:void 0,reason:t.reason??r?.reason}:{serverIdentifiers:[...new Set([...t.serverIdentifiers??[],...r?.serverIdentifiers??[]])],reason:t.reason??r?.reason}}(this.pendingLeaseChangeEvent??{serverIdentifiers:void 0},r):(this.pendingLeaseChangeEvent=r,this.hasPendingLeaseChangeEvent=!0),void 0!==this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout((()=>{this.debounceTimer=void 0;const t=this.takePendingLeaseChangeEvent();this.scheduleWrite(e,t)}),this.debounceMs)}takePendingLeaseChangeEvent(){if(!this.hasPendingLeaseChangeEvent)return;const e=this.pendingLeaseChangeEvent??{serverIdentifiers:void 0};return this.pendingLeaseChangeEvent=void 0,this.hasPendingLeaseChangeEvent=!1,e}scheduleWrite(e,t){const r=this.getLogContext(e);if(this.disposed)return;const o=this.writePromise;this.writePromise=(async()=>{if(o)try{await o}catch(e){ey.error(r,"Error waiting for previous write",e)}this.disposed||(await this.startupCleanupPromise,this.disposed||await this.fetchAndWrite(e,t))})()}getContext(e){let t=(0,ce.q6)();return e&&(t=t.with(m._O,e)),t}getLogContext(e){return e.with(m._O,this.ctx.get(m._O))}getMetricTags(e){return{...e,mcp_version:this.mcpVersion}}getMcpAuthToolDescription(){return hy(this.mcpAuthCopyOverrides?.authToolDescription)??iy}shouldExposeVirtualMcpAuthToolForStatus(e,t){return this.exposeVirtualMcpAuthTool&&Ct(e)&&(this.alwaysExposeVirtualMcpAuthTool||"needsAuth"===t)}getErrorStatusMessage(){return hy(this.mcpAuthCopyOverrides?.errorStatusMessage)??"The MCP server errored. If this server is important for completing the task, concisely inform the user and ask them to check the MCP status in Cursor's Customize page > MCPs; otherwise continue with a different approach."}getNeedsAuthStatusMessage(e){return t=hy(this.mcpAuthCopyOverrides?.needsAuthStatusMessageWithAuthTool)??'The MCP server needs authentication. Authenticate it by calling the `{authToolName}` tool for server "{serverIdentifier}" through your MCP tool-calling interface using an empty arguments object. If this server is important for completing the task, authenticate it first; otherwise continue with a different approach.',r={serverIdentifier:e,authToolName:sy},t.replace(/\{serverIdentifier\}/g,r.serverIdentifier).replace(/\{authToolName\}/g,r.authToolName);var t,r}getNeedsAuthStatusMessageForWrite(e){return this.exposeVirtualMcpAuthTool&&Ct(e)?this.getNeedsAuthStatusMessage(e):hy(this.mcpAuthCopyOverrides?.needsAuthStatusMessageWithoutVirtualTool)??"This MCP server requires authentication before its tools can be used. Open Cursor's Customize page > MCPs, select this server, and use Authenticate/Reopen, or refresh credentials in your MCP configuration (for example mcp.json), then restart this environment. If this server is not required for the task, continue without it."}async getToolsForServers(e,t){if(0===t.length)return[];const r=this.getLogContext(e);try{return await this.mcpLease.getToolsForServers(e,t)}catch(o){ey.warn(r,`getToolsForServers() threw, falling back to filtered getTools(): ${o}`);const n=await this.mcpLease.getTools(e).catch((e=>(ey.warn(r,`getTools() threw during scoped-tool fallback, defaulting to []: ${e}`),[]))),s=new Set(t);return n.filter((e=>s.has(e.clientKey)))}}async fetchClientDataForServer(e,t,r,o){const n=await uy(r.getState(e),{kind:"error"}).then((r=>("error"!==r.kind||"message"in r||ey.warn(e,`getState() timed out for "${t}", defaulting to error`),r))),s="ready"===n.kind||"requires_authentication"===n.kind,[i,a,c]=await Promise.all([s?uy(r.listResources(e),{resources:[]}):Promise.resolve({resources:[]}),s?uy(r.listPrompts(e),[]):Promise.resolve([]),s&&o?.fetchInstructions?uy(r.getInstructions(e),void 0):Promise.resolve(void 0)]);return{clientKey:t,serverName:r.serverName,plugin:r.plugin,marketplace:r.marketplace,pluginId:r.pluginId,marketplaceId:r.marketplaceId,resources:i.resources.map((e=>({...e,serverIdentifier:t,serverName:r.serverName}))),prompts:a.map((e=>({...e,serverIdentifier:t,serverName:r.serverName}))),instructions:c,status:py(n)}}buildServerDataMap(e,t,r){const o=new Map;for(const e of t){const t=xy(e.clientKey);o.set(e.clientKey,{serverIdentifier:e.clientKey,serverName:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId,sanitizedId:t,folderPath:(0,s.join)(this.projectDir,ty,t),tools:[],resources:e.resources,prompts:e.prompts,instructions:e.instructions,status:e.status})}for(const t of e){let e=o.get(t.clientKey);if(!e){const r=xy(t.clientKey);e={serverIdentifier:t.clientKey,serverName:t.providerIdentifier,plugin:t.plugin,marketplace:t.marketplace,pluginId:t.pluginId,marketplaceId:t.marketplaceId,sanitizedId:r,folderPath:(0,s.join)(this.projectDir,ty,r),tools:[],resources:[],prompts:[],instructions:void 0,status:void 0},o.set(t.clientKey,e)}e.tools.push(t)}if(void 0!==r)for(const e of r){const t=e.serverIdentifier?.trim();let r=t?Array.from(o.values()).find((e=>e.serverIdentifier===t)):void 0;if(!r){const t=e.serverName?.trim();r=t?Array.from(o.values()).find((e=>e.serverName===t)):void 0}r&&e.instructions&&(r.instructions=e.instructions)}if(this.exposeVirtualMcpAuthTool)for(const e of o.values())this.shouldExposeVirtualMcpAuthToolForStatus(e.serverIdentifier,e.status)&&(e.tools.some((e=>e.toolName===sy))||e.tools.push({clientKey:(n={serverIdentifier:e.serverIdentifier,serverName:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId,authToolDescription:this.getMcpAuthToolDescription()}).serverIdentifier,providerIdentifier:n.serverName,plugin:n.plugin,marketplace:n.marketplace,pluginId:n.pluginId,marketplaceId:n.marketplaceId,toolName:sy,name:sy,description:n.authToolDescription,inputSchema:{type:"object",properties:{},additionalProperties:!1}}));var n;return o}buildServersToWrite(e,t){const r=[],o=new Set;for(const n of t.values()){const t=n.tools.length>0||n.resources.length>0||n.prompts.length>0||n.instructions,s="error"===n.status||"needsAuth"===n.status||"initializing"===n.status;t||s?o.has(n.sanitizedId)?ey.warn(e,`Skipping server "${n.serverIdentifier}" — sanitizedId "${n.sanitizedId}" collides with another server`):(o.add(n.sanitizedId),r.push(n)):ey.info(e,`Server "${n.serverIdentifier}" excluded from write: tools=${n.tools.length}, resources=${n.resources.length}, prompts=${n.prompts.length}, hasInstructions=${!!n.instructions}, status=${n.status}`)}return r}mergeScopedRefreshWithCachedServerData(e,t){const r=[...t.tools];if(this.shouldExposeVirtualMcpAuthToolForStatus(e.serverIdentifier,e.status)&&!r.some((e=>e.toolName===sy))){const t=e.tools.find((e=>e.toolName===sy));void 0!==t&&r.push(t)}return{...e,...t,tools:r,resources:e.resources,prompts:e.prompts,instructions:e.instructions,status:e.status,plugin:t.plugin??e.plugin,marketplace:t.marketplace??e.marketplace,pluginId:t.pluginId??e.pluginId,marketplaceId:t.marketplaceId??e.marketplaceId}}async refreshServersFromLease(e,t){const r=this.getLogContext(e),o=[...new Set(t.serverIdentifiers??[])];ey.info(r,`fetchAndWrite: refreshing ${o.length} targeted servers`,{serverIdentifiers:o});const n=await this.getToolsForServers(e,o),s=await this.mcpLease.getInstructions(e).catch((e=>(ey.warn(r,`getInstructions() threw during scoped refresh, defaulting to []: ${e}`),[]))),i=await Promise.all(o.map((async t=>{try{const r=await this.mcpLease.getClient(e,t);return void 0===r?{serverIdentifier:t,kind:"missing"}:{serverIdentifier:t,kind:"client",client:r}}catch(e){return ey.warn(r,`getClient("${t}") threw during scoped refresh, preserving cached data: ${e}`),{serverIdentifier:t,kind:"error",error:e}}}))),a=i.filter((e=>"missing"===e.kind)).map((e=>e.serverIdentifier));let c=new Set;if(a.length>0){const t=await this.mcpLease.getClients(e).catch((e=>{ey.warn(r,`getClients() threw while confirming targeted server removal, preserving cached data: ${e}`)}));void 0!==t&&(c=new Set(a.filter((e=>void 0===t[e]))))}const l=await Promise.all(i.filter((e=>"client"===e.kind)).map((({serverIdentifier:t,client:r})=>this.fetchClientDataForServer(e,t,r,{fetchInstructions:!0})))),u=new Map((this.cachedServerData??[]).map((e=>[e.serverIdentifier,e]))),d=this.buildServerDataMap(n,l,s),h=new Set(o),p=new Set(i.filter((e=>"error"===e.kind||"missing"===e.kind&&!c.has(e.serverIdentifier))).map((e=>e.serverIdentifier)));for(const e of o){const t=u.get(e),o=d.get(e);if(void 0===o)c.has(e)?u.delete(e):ey.warn(r,`refreshServersFromLease: preserving cached data for "${e}" because targeted refresh returned no replacement`);else{if(p.has(e)&&void 0!==t){u.set(e,this.mergeScopedRefreshWithCachedServerData(t,o)),ey.warn(r,`refreshServersFromLease: preserving cached metadata for "${e}" because the client was unavailable during targeted refresh`);continue}u.set(e,o)}}const f=new Map(Array.from(u.values()).map((e=>[e.sanitizedId,e.serverIdentifier])));for(const[e,t]of this.cachedFingerprints)if(!h.has(e)&&!u.has(e)){const t=xy(e);f.set(t,e)}const m=this.buildServersToWrite(e,u);await this.writeServerData(e,m,f),this.cachedServerData=m,this.fireOnDidWrite(m)}async fetchAndWrite(e,t){const r={stack:[],error:void 0,hasError:!1};try{Hw(r,(0,i.VI)(e.withName("McpFileSystemWriter.fetchAndWrite")),!1);const o=this.getLogContext(e);try{if(void 0!==this.cachedServerData&&void 0!==t&&!Rt(t)&&[...new Set(t.serverIdentifiers??[])].length>0)return void await this.refreshServersFromLease(e,t);const[r,n,s]=await Promise.all([this.mcpLease.getTools(e).catch((e=>(ey.warn(o,`getTools() threw, defaulting to []: ${e}`),[]))),this.mcpLease.getInstructions(e).catch((()=>[])),this.mcpLease.getClients(e).catch((e=>(ey.warn(o,`getClients() threw, defaulting to {}: ${e}`),{})))]),i=Object.keys(s);ey.info(o,`fetchAndWrite: lease returned ${r.length} tools across ${i.length} clients`);const a=Object.entries(s).map((([t,r])=>this.fetchClientDataForServer(e,t,r))),c=await Promise.all(a),l=this.buildServerDataMap(r,c,n),u=this.buildServersToWrite(e,l),d=new Map(Array.from(l.values()).map((e=>[e.sanitizedId,e.serverIdentifier])));await this.writeServerData(e,u,d),this.cachedServerData=u,this.fireOnDidWrite(u)}catch(e){ey.error(o,"Error fetching/writing MCP state",e)}}catch(e){r.error=e,r.hasError=!0}finally{qw(r)}}fireOnDidWrite(e){if(this.onDidWrite)try{const t=e.map((e=>({serverIdentifier:e.serverIdentifier,folderPath:e.folderPath,tools:e.tools.map((t=>({toolName:t.toolName,definitionPath:(0,s.join)(e.folderPath,ry,`${dy(t.toolName)}.json`)})))})));this.onDidWrite(t)}catch{}}async writeServerData(e,t,r){const o={stack:[],error:void 0,hasError:!1};try{Hw(o,(0,i.VI)(e.withName("McpFileSystemWriter.writeServerData")),!1);const n=this.getLogContext(e),a=(0,s.join)(this.projectDir,ty);await(0,Os.mkdir)(a,{recursive:!0});const c=new Map;for(const e of t)try{c.set(e.serverIdentifier,wy(e))}catch(t){ey.error(n,"Error computing server fingerprint, will force write",t,{serverIdentifier:e.serverIdentifier}),c.set(e.serverIdentifier,`__error_${Date.now()}_${Math.random()}`)}const l=[];for(const e of t){const t=this.cachedFingerprints.get(e.serverIdentifier);t!==c.get(e.serverIdentifier)&&(l.push(e),void 0!==t&&ey.info(n,`Server "${e.serverIdentifier}" fingerprint changed: tools=${e.tools.length}, status=${e.status}`))}for(const e of t)if(!l.includes(e))try{await(0,Os.stat)((0,s.join)(a,e.sanitizedId))}catch{ey.info(n,`Server "${e.serverIdentifier}" directory missing on disk, forcing write`),l.push(e)}const u=new Set;for(const[e]of this.cachedFingerprints)if(!c.has(e)){const t=this.cachedServerData?.find((t=>t.serverIdentifier===e)),o=t?.sanitizedId??xy(e);r.has(o)?(ey.info(n,`Server "${e}" (sanitized="${o}") still in lease but excluded from write, preserving directory`),c.set(e,this.cachedFingerprints.get(e))):(ey.info(n,`Server "${e}" (sanitized="${o}") left the lease, scheduling directory removal`),u.add(o))}const d=void 0===this.cachedServerData;if(d)try{const e=await(0,Os.readdir)(a),t=new Set(e.filter((e=>!e.endsWith(oy)&&!e.endsWith(ny))));for(const r of e)if(r.endsWith(oy))await(0,Os.rm)((0,s.join)(a,r),{recursive:!0,force:!0});else if(r.endsWith(ny)){const e=r.slice(0,-5);if(t.has(e))await(0,Os.rm)((0,s.join)(a,r),{recursive:!0,force:!0});else try{await(0,Os.rename)((0,s.join)(a,r),(0,s.join)(a,e)),t.add(e)}catch{await(0,Os.rm)((0,s.join)(a,r),{recursive:!0,force:!0}).catch((()=>{}))}}for(const e of t)if(r.has(e)){const t=r.get(e);c.has(t)||c.set(t,`__preserved_${e}`)}else u.add(e)}catch(e){ey.error(n,"Error clearing mcps directory",e)}const h=Array.from(u);if(l.length>0||u.size>0){const e=l.map((e=>({serverIdentifier:e.serverIdentifier,sanitizedId:e.sanitizedId,toolCount:e.tools.length})));ey.info(n,`Incremental write: ${l.length} changed, ${u.size} removed, ${t.length-l.length} unchanged`,{changedServerCount:l.length,changedServers:e,removedServerCount:u.size,removedServerSanitizedIds:h,unchangedServerCount:t.length-l.length,totalServerCount:t.length,leaseServerCount:r.size,coldStartReconcile:d,projectDirHash:(0,Ts.createHash)("sha256").update(this.projectDir).digest("hex")},{includeStructuredLogs:!0})}const p=await Promise.allSettled(l.map((t=>this.writeServerAtomic(e,t,a))));for(let t=0;t<l.length;t++){const r=p[t];if("rejected"===r.status){const o=l[t],n=this.cachedFingerprints.get(o.serverIdentifier);void 0!==n?c.set(o.serverIdentifier,n):c.delete(o.serverIdentifier),ey.error(e,"Error writing server directory",r.reason,{serverIdentifier:o.serverIdentifier,sanitizedId:o.sanitizedId},{includeStructuredLogs:!0})}}const f=await Promise.allSettled(h.map((e=>(0,Os.rm)((0,s.join)(a,e),{recursive:!0,force:!0}))));for(let r=0;r<f.length;r++){const o=f[r];if("rejected"===o.status){const n=h[r];ey.error(e,"Error removing server directory",o.reason,{sanitizedId:n,removalIndex:r,removalAttemptCount:f.length,removedServerCount:h.length,removedServerSanitizedIds:h,changedServerCount:l.length,unchangedServerCount:t.length-l.length,totalServerCount:t.length},{includeStructuredLogs:!0})}}this.cachedFingerprints=c}catch(e){o.error=e,o.hasError=!0}finally{qw(o)}}async writeServerAtomic(e,t,r){const o={stack:[],error:void 0,hasError:!1};try{Hw(o,(0,i.VI)(e.withName("McpFileSystemWriter.writeServerAtomic")),!1);const n=`${t.sanitizedId}${oy}`,a=`${t.sanitizedId}${ny}`,c=(0,s.join)(r,n),l=(0,s.join)(r,a),u=(0,s.join)(r,t.sanitizedId);await(0,Os.rm)(c,{recursive:!0,force:!0});try{await(0,Os.rename)(l,u)}catch{await(0,Os.rm)(l,{recursive:!0,force:!0})}await this.writeServerDirectory(e,t,{basePath:r,dirName:n});try{try{await(0,Os.rename)(u,l)}catch{}await(0,Os.rename)(c,u)}catch(r){ey.error(e,"Per-server swap failed",r,{serverIdentifier:t.serverIdentifier,sanitizedId:t.sanitizedId},{includeStructuredLogs:!0});try{await(0,Os.rename)(l,u)}catch{}throw await(0,Os.rm)(c,{recursive:!0,force:!0}),r}await(0,Os.rm)(l,{recursive:!0,force:!0}).catch((()=>{}))}catch(e){o.error=e,o.hasError=!0}finally{qw(o)}}async writeServerDirectory(e,t,r){const o={stack:[],error:void 0,hasError:!1};try{Hw(o,(0,i.VI)(e.withName("McpFileSystemWriter.writeServerDirectory")),!1);const n=(0,s.join)(r.basePath,r.dirName??t.sanitizedId);if(await(0,Os.mkdir)(n,{recursive:!0}),t.tools.length>0){const e=(0,s.join)(n,ry);await(0,Os.mkdir)(e,{recursive:!0});for(const r of t.tools){const t=dy(r.toolName),o=(0,s.join)(e,`${t}.json`),n=Pt(r);await(0,Os.writeFile)(o,JSON.stringify(n,null,2))}}if(t.resources.length>0){const e=(0,s.join)(n,"resources");await(0,Os.mkdir)(e,{recursive:!0});for(const r of t.resources){const t=dy(r.name||r.uri.replace(/[^a-zA-Z0-9_-]/g,"_")),o=(0,s.join)(e,`${t}.json`),n={uri:r.uri,name:r.name,description:r.description,mimeType:r.mimeType};await(0,Os.writeFile)(o,JSON.stringify(n,null,2))}}if(t.prompts.length>0){const e=(0,s.join)(n,"prompts");await(0,Os.mkdir)(e,{recursive:!0});for(const r of t.prompts){const t=dy(r.name),o=(0,s.join)(e,`${t}.json`),n={name:r.name,description:r.description,arguments:r.arguments};await(0,Os.writeFile)(o,JSON.stringify(n,null,2))}}if(t.instructions&&t.instructions.trim().length>0){const e=(0,s.join)(n,"INSTRUCTIONS.md");await(0,Os.writeFile)(e,t.instructions.trim())}if("error"===t.status||"needsAuth"===t.status){const e=(0,s.join)(n,"STATUS.md"),r="error"===t.status?this.getErrorStatusMessage():this.getNeedsAuthStatusMessageForWrite(t.serverIdentifier);await(0,Os.writeFile)(e,r)}const a=(0,s.join)(n,"SERVER_METADATA.json"),c={serverIdentifier:t.serverIdentifier,serverName:t.serverName};await(0,Os.writeFile)(a,JSON.stringify(c,null,2))}catch(e){o.error=e,o.hasError=!0}finally{qw(o)}}async getMcpFileSystemOptions(e,t){const r={stack:[],error:void 0,hasError:!1};try{if(this.disposed)return;Hw(r,(0,i.VI)(e.withName("McpFileSystemWriter.getMcpFileSystemOptions")),!1);const o=this.getLogContext(e),n=await this.ensureWritesSettled(e,t?.timeoutMs);if(this.snapshotProvider&&!n)return this.buildOptionsFromSnapshots(e);this.snapshotProvider&&n&&ey.warn(o,"Snapshot mode write barrier timed out; falling back to cached descriptors",{timeoutMs:t?.timeoutMs},{includeStructuredLogs:!0});const a=(this.cachedServerData??[]).map((e=>{const t=e.tools.map((t=>{const r=dy(t.toolName),o=(0,s.join)(e.folderPath,ry,`${r}.json`);return new Jn.E$({toolName:t.toolName,definitionPath:o,...(0,Ww.hT)(t.annotations)})}));return new Jn.UC({serverIdentifier:e.serverIdentifier,serverName:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginDbId:e.pluginId,marketplaceId:e.marketplaceId,folderPath:e.folderPath,serverUseInstructions:e.instructions,tools:t})}));return this.checkDescriptorsVsFilesystem(e,a,"workbench_lease"),new Jn.Is({enabled:!0,workspaceProjectDir:this.projectDir,mcpDescriptors:a})}catch(e){r.error=e,r.hasError=!0}finally{qw(r)}}async ensureWritesSettled(e,t){const r=this.getLogContext(e),o=void 0!==this.debounceTimer;if(void 0!==this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0,this.scheduleWrite(e,this.takePendingLeaseChangeEvent())),o&&ey.info(r,"getMcpFileSystemOptions force-fired pending debounce"),!this.writePromise)return!1;if(void 0!==t){let e,o=!1;try{await Promise.race([this.writePromise,new Promise((r=>{e=setTimeout((()=>{o=!0,r()}),t)}))])}catch(e){ey.error(r,"Error waiting for pending write to complete",e)}finally{clearTimeout(e)}return o&&ey.warn(r,`getMcpFileSystemOptions timed out after ${t}ms waiting for write; returning stale cache`),o}try{await this.writePromise}catch(e){ey.error(r,"Error waiting for pending write to complete",e)}return!1}async buildOptionsFromSnapshots(e){const t={stack:[],error:void 0,hasError:!1};try{Hw(t,(0,i.VI)(e.withName("McpFileSystemWriter.buildOptionsFromSnapshots")),!1);const r=this.getLogContext(e),o=Date.now(),n=await this.snapshotProvider.getAllSnapshots(e),a=(0,s.join)(this.projectDir,ty),c=n.filter((e=>e.tools.length>0||e.resources.length>0||e.prompts.length>0||void 0!==e.instructions||this.shouldExposeVirtualMcpAuthToolForStatus(e.serverIdentifier,e.status)||"needsAuth"===e.status||"error"===e.status)).map((e=>{const t=xy(e.serverIdentifier),r=(0,s.join)(a,t),o=e.tools.map((e=>{const t=dy(e.name);return new Jn.E$({toolName:e.name,definitionPath:(0,s.join)(r,ry,`${t}.json`),...(0,Ww.hT)(e.annotations)})}));if(this.shouldExposeVirtualMcpAuthToolForStatus(e.serverIdentifier,e.status)&&!e.tools.some((e=>e.name===sy))){const e=dy(sy);o.push(new Jn.E$({toolName:sy,definitionPath:(0,s.join)(r,ry,`${e}.json`)}))}return new Jn.UC({serverIdentifier:e.serverIdentifier,serverName:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginDbId:e.pluginId,marketplaceId:e.marketplaceId,folderPath:r,serverUseInstructions:e.instructions,tools:o})})),l=c.reduce(((e,t)=>e+t.tools.length),0);return ey.info(r,`buildOptionsFromSnapshots completed in ${Date.now()-o}ms: ${n.length} snapshots, ${c.length} descriptors, ${l} tools`),this.checkDescriptorsVsFilesystem(e,c,"snapshot"),new Jn.Is({enabled:!0,workspaceProjectDir:this.projectDir,mcpDescriptors:c})}catch(e){t.error=e,t.hasError=!0}finally{qw(t)}}async waitForPendingWrites(){if(void 0!==this.debounceTimer&&await new Promise((e=>{const t=()=>{void 0===this.debounceTimer?e():setTimeout(t,10)};t()})),this.writePromise)try{await this.writePromise}catch{}}getCachedServerData(){return this.cachedServerData}checkDescriptorsVsFilesystem(e,t,r){const o=this.getLogContext(e),n=Date.now();n-this.lastDivergenceCheckMs<yy.DIVERGENCE_CHECK_COOLDOWN_MS||(this.lastDivergenceCheckMs=n,this._checkDescriptorsVsFilesystemAsync(e,t,r).catch((e=>{ey.warn(o,"Divergence check failed",e)})))}async _checkDescriptorsVsFilesystemAsync(e,t,r){const o=this.getLogContext(e),n=(0,s.join)(this.projectDir,ty),i=new Set,a=new Map;for(const e of t){const t=xy(e.serverIdentifier);i.add(t),a.set(t,e.tools.length)}let c=[];try{c=await(0,Os.readdir)(n),c=c.filter((e=>!e.endsWith(oy)&&!e.endsWith(ny)))}catch(e){if("ENOENT"!==e?.code)throw e}const l=new Set(c);let u=!0,d=0,h=0,p=0;const f=function(e){return 0===e?"0":e<=3?"1-3":e<=6?"4-6":e<=10?"7-10":"11+"}(i.size);for(const t of i)l.has(t)||(u=!1,d++,zw.increment(e,1,this.getMetricTags({divergence_type:"server_missing",mcp_source:r,configured_servers:f})),ey.warn(o,"Divergence detected: server missing from filesystem",{mcpFileSystemMeta:{divergenceType:"server_missing",serverId:t,source:r,configuredServers:i.size,configuredServersBucket:f}},{includeStructuredLogs:!0}));for(const t of l)i.has(t)||(u=!1,h++,zw.increment(e,1,this.getMetricTags({divergence_type:"server_stale",mcp_source:r,configured_servers:f})));for(const t of i){if(!l.has(t))continue;const c=a.get(t)??0,d=(0,s.join)(n,t,ry);let h=0;try{h=(await(0,Os.readdir)(d)).filter((e=>e.endsWith(".json"))).length}catch{}h!==c&&(u=!1,p++,zw.increment(e,1,this.getMetricTags({divergence_type:"tool_count_mismatch",mcp_source:r,configured_servers:f})),ey.warn(o,"Divergence detected: tool count mismatch",{mcpFileSystemMeta:{divergenceType:"tool_count_mismatch",serverId:t,expected:c,actual:h,source:r,configuredServers:i.size,configuredServersBucket:f}},{includeStructuredLogs:!0}))}Gw.increment(e,1,this.getMetricTags({synced:String(u),mcp_source:r,configured_servers:f})),Vw.gauge(e,i.size,this.getMetricTags({mcp_source:r})),Jw.gauge(e,l.size,this.getMetricTags({mcp_source:r})),Kw.gauge(e,d,this.getMetricTags({mcp_source:r})),Zw.gauge(e,p,this.getMetricTags({mcp_source:r})),ey.info(o,"MCP filesystem sync check",{mcpFileSystemMeta:{synced:u,expectedServers:i.size,actualServers:l.size,serversMissing:d,serversStale:h,toolMismatches:p,source:r,configuredServers:i.size,configuredServersBucket:f}},{includeStructuredLogs:!0}),u||ey.warn(o,"MCP filesystem divergence summary",{mcpFileSystemMeta:{synced:u,expectedServers:i.size,actualServers:l.size,serversMissing:d,serversStale:h,toolMismatches:p,source:r,configuredServers:i.size,configuredServersBucket:f}},{includeStructuredLogs:!0})}dispose(){this.disposed||(this.disposed=!0,void 0!==this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0),this.leaseChangeDisposable&&(this.leaseChangeDisposable.dispose(),this.leaseChangeDisposable=void 0),this.cachedServerData=void 0,this.cachedFingerprints.clear())}}yy.DIVERGENCE_CHECK_COOLDOWN_MS=1e4;var vy=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},by=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 Sy=(0,m.h)("local-exec:mcp");function ky(e,t){const r=s.default.relative(e,t);return""===r||!s.default.isAbsolute(r)&&".."!==r&&!r.startsWith(`..${s.default.sep}`)}function Ey(e){return e instanceof Error&&"code"in e&&"string"==typeof e.code?e.code:void 0}function Cy(e){return new Lt._Z({content:{case:"text",value:new Lt.zN({text:e})}})}function xy(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 _y(e,t,r){const o=await r.permissionsService.shouldBlockMcp(e,t,r.toolDef,{alreadyApproved:t.skipApproval});if(!o)return;const n=await Pc(o,{onNeedsApproval:async(e,o)=>{if("mcp"!==o.type)return new Lt.iz({result:{case:"error",value:new Lt.Nh({error:"Invalid approval details type for MCP execution"})}});const n=await r.pendingDecisionProvider.requestApproval({type:vm.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,allowlistEntry:o.allowlistEntry,computerUseApp:o.computerUseApp},toolCallId:t.toolCallId});return n.approved&&void 0!==o.computerUseApp&&!0!==o.computerUseApp.allowOnce&&r.permissionsService.allowComputerUseAppForSession?.({bundleId:o.computerUseApp.bundleId}),n.approved?t.smartModeApprovalOnly?new Lt.iz({result:{case:"approved",value:new Lt.Ke}}):null:new Lt.iz({result:{case:"rejected",value:new Lt.xo({reason:`User rejected MCP: ${t.name}${n.reason?` - ${n.reason}`:""}`})}})},onUserRejected:e=>new Lt.iz({result:{case:"error",value:new Lt.Nh({error:`User rejected MCP: ${t.name}${e?` - ${e}`:""}`})}}),onPermissionDenied:(e,r)=>{const o=`MCP tool execution blocked: ${t.name} - ${e}`;return new Lt.iz({result:{case:"permissionDenied",value:new Lt.HQ({error:o,isReadonly:r?.isReadonly??!1})}})}});return n??void 0}class Py{constructor(e,t,r,o,n=4e4,s,i){this.toolSet=e,this.permissionsService=t,this.pendingDecisionProvider=r,this.projectDir=o,this.fileOutputThresholdBytes=n,this.elicitationFactory=s,this.ensureMcpServersLoaded=i}async describeDisconnectedServer(e,t){const r=new Set(t.filter((e=>""!==e)));if(0===r.size)return;let o;try{o=await this.toolSet.getClients(e)}catch{return}const n=Object.entries(o).find((([e,t])=>r.has(e)||r.has(t.serverName)));if(void 0===n)return;const[s,i]=n;let a;try{a=await i.getState(e)}catch{return}if("ready"===a.kind)return;const c=function(e){switch(e){case"needsAuth":return"This MCP server requires authentication before its tools can be used.";case"error":return"This MCP server failed during live tool discovery. Its tools are unavailable until the connection is fixed.";case"loading":return"This MCP server is still loading; tools may not be available yet.";default:return}}(Tt(a));return void 0!==c?`MCP server "${s}" has no callable tools right now. ${c}${"error"===a.kind&&a.message?` (${a.message})`:""}`:void 0}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=vy(r,(0,i.VI)(e.withName("LocalMcpToolExecutor.execute")),!1).ctx,a=t.serverIdentifier||t.providerIdentifier;await(this.ensureMcpServersLoaded?.(n,[a]));const c=await this.toolSet.getTools(n),l=Array.from(new Set(c.map((e=>e.clientKey)))).sort(),u=c.find((e=>e.clientKey===a&&e.toolName===t.toolName)),d=c.find((e=>e.name===t.name));if(void 0!==d&&(void 0!==u?d!==u:d.toolName!==t.toolName||d.clientKey!==a&&d.providerIdentifier!==a))return new Lt.iz({result:{case:"error",value:new Lt.Nh({error:`MCP tool "${t.name}" is not the tool "${t.toolName}" on server "${a}" that the call names.`})}});const h=await _y(n,t,{permissionsService:this.permissionsService,pendingDecisionProvider:this.pendingDecisionProvider,toolDef:u});if(void 0!==h)return h;const p=await this.toolSet.getToolSet(n);let f;try{f=await p.execute(u?.name??t.name,Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t.toJson()]))),t.toolCallId,this.elicitationFactory)}catch(e){let r=e;if(Ft(r)&&t.providerIdentifier.length>0&&!c.some((e=>e.clientKey===t.providerIdentifier||e.providerIdentifier===t.providerIdentifier))&&(r=new jg(t.providerIdentifier,l)),r instanceof jg){const e=await this.describeDisconnectedServer(n,[a,t.providerIdentifier]);return void 0!==e?new Lt.iz({result:{case:"error",value:new Lt.Nh({error:e})}}):new Lt.iz({result:{case:"serverNotFound",value:new Lt.JL({name:r.serverName,availableServers:r.availableServers})}})}if(Ft(r))return new Lt.iz({result:{case:"toolNotFound",value:new Lt.WV({name:r.toolName,availableTools:r.availableTools})}});throw r}const m=[];for(const e of f.content){const r=e.type;if("text"===r){const t=e;m.push(Cy(t.text))}else if("resource"===r)m.push(Cy(Km(e)));else if("image"===r){const r=e,s="string"==typeof r.data?Buffer.from(r.data,"base64"):Buffer.alloc(0);let i;try{i=await Uw(s)}catch(e){Sy.warn(n,"Omitting undecodable MCP tool image",{toolName:t.toolName,mimeType:"string"==typeof r.mimeType?r.mimeType.slice(0,100):typeof r.mimeType,bytes:s.byteLength,error:e instanceof Error?e.message:String(e)}),m.push(Cy(`[Image omitted: the tool returned ${o=r.mimeType,"string"==typeof o&&/^image\/[\w.+-]{1,40}$/.test(o)?o:"image"} data (${s.byteLength} bytes) that could not be decoded.]`));continue}m.push(new Lt._Z({content:{case:"image",value:new Lt.do({data:i.data,mimeType:i.mimeType})}}))}else if("image"!==r){const t=Km(e);m.push(Cy(t))}}const g=await async function({contentItems:e,thresholdBytes:t,write:r}){const o=e.filter((e=>"text"===e.content.case&&void 0===e.content.value.outputLocation)).map((e=>"text"===e.content.case?e.content.value.text:"")).join("\n\n");if(t<=0||Buffer.byteLength(o,"utf8")<=t)return e;const n=await r(o);if(void 0===n)return;const s=[];let i=!1;for(const t of e)"text"===t.content.case&&void 0===t.content.value.outputLocation?i||(s.push(new Lt._Z({content:{case:"text",value:new Lt.zN({text:"",outputLocation:n})}})),i=!0):s.push(t);return s}({contentItems:m,thresholdBytes:this.fileOutputThresholdBytes,write:e=>async function(e,t){const r=s.default.join(t,oc),o=s.default.join(r,`${(0,Ts.randomUUID)()}.txt`);await(0,Os.mkdir)(s.default.dirname(o),{recursive:!0});const n=e.slice(0,nc),i=Bi(n),a=Buffer.byteLength(n,"utf8");return await(0,Os.writeFile)(o,n,"utf8"),new ac.pV({filePath:o,sizeBytes:BigInt(a),lineCount:BigInt(i)})}(e,this.projectDir)});if(void 0===g)throw new Error("Failed to materialize MCP text output");const w=f.structuredContent&&"object"==typeof f.structuredContent&&!Array.isArray(f.structuredContent)?qt.Struct.fromJson(f.structuredContent):void 0,y=new Lt.QW({content:g,isError:f.isError,structuredContent:w,resultMeta:void 0===f._meta?void 0:qt.Struct.fromJson(f._meta)});return new Lt.iz({result:{case:"success",value:y}})}catch(e){r.error=e,r.hasError=!0}finally{by(r)}var o}}class Iy{constructor(e,t){this.mcpLease=e,this.ensureMcpServersLoaded=t}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const o=vy(r,(0,i.VI)(e.withName("LocalListMcpResourcesExecutor.execute")),!1).ctx;try{if(t.server){await(this.ensureMcpServersLoaded?.(o,[t.server]));const e=await this.mcpLease.getClients(o),r=e[t.server]??Object.values(e).find((e=>e.serverName===t.server));if(!r)return new Lt.kP({result:{case:"error",value:new Lt.w2({error:`Server "${t.server}" not found`})}});const n=await this.listResourcesFromClient(o,r,t.server,!0);return new Lt.kP({result:{case:"success",value:new Lt.T2({resources:n})}})}const e=await this.mcpLease.getClients(o),r=new Set,n=await this.mcpLease.getTools(o);for(const e of n)r.add(e.providerIdentifier),r.add(`user-${e.providerIdentifier}`);const s=[];for(const[t,n]of Object.entries(e)){if(r.size>0&&!r.has(t))continue;const e=await this.listResourcesFromClient(o,n,t);s.push(...e)}return new Lt.kP({result:{case:"success",value:new Lt.T2({resources:s})}})}catch(e){const t=e instanceof Error?e.message:String(e);return new Lt.kP({result:{case:"error",value:new Lt.w2({error:`Failed to list MCP resources: ${t}`})}})}}catch(e){r.error=e,r.hasError=!0}finally{by(r)}}async listResourcesFromClient(e,t,r,o=!1){const n=await t.getState(e);if("ready"!==n.kind&&(!o||"loading"!==n.kind))return[];const s=await t.listResources(e);return s&&s.resources?s.resources.map((e=>new Lt.X2({uri:e.uri,name:e.name,description:e.description,mimeType:e.mimeType,server:r,annotations:e.annotations}))):[]}}class Ry{constructor(e,t=".",r,o=[],n,s){this.mcpLease=e,this.projectDir=t,this.permissionsService=r,this.pendingDecisionProvider=n,this.ensureMcpServersLoaded=s,this.workspacePaths=o.filter((e=>e.length>0))}resolveProjectDir(e){const t=e.get(yt),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=vy(r,(0,i.VI)(e.withName("LocalReadMcpResourceExecutor.execute")),!1).ctx,n=t.smartModeApproval?.reason;if(void 0!==n){if(void 0===this.pendingDecisionProvider)return new Lt.ZD({result:{case:"error",value:new Lt.Jx({uri:t.uri,error:"Auto-review approval provider is not configured"})}});const e=await this.pendingDecisionProvider.requestApproval({type:vm.Mcp,details:{name:"FetchMcpResource",toolName:"FetchMcpResource",providerIdentifier:t.server,args:{server:qt.Value.fromJson(t.server),uri:qt.Value.fromJson(t.uri),...void 0!==t.downloadPath?{downloadPath:qt.Value.fromJson(t.downloadPath)}:{}},reason:"smartMode",canAllowlist:!1,smartModeApprovalReason:n,smartModeApprovalRequestId:t.smartModeApproval?.requestId},toolCallId:t.toolCallId});if(!e.approved)return new Lt.ZD({result:{case:"rejected",value:new Lt.Dh({reason:"User rejected MCP resource fetch"+(e.reason?` - ${e.reason}`:"")})}})}await(this.ensureMcpServersLoaded?.(o,[t.server]));const a=await this.mcpLease.getClients(o),c=a[t.server]??Object.values(a).find((e=>e.serverName===t.server));if(!c)return new Lt.ZD({result:{case:"error",value:new Lt.Jx({uri:t.uri,error:`Server "${t.server}" not found`})}});try{if("ready"!==(await c.getState(o)).kind)return new Lt.ZD({result:{case:"error",value:new Lt.Jx({uri:t.uri,error:`Server "${t.server}" is not ready`})}});const e=await c.readResource(o,{uri:t.uri});if(!e||!e.contents||0===e.contents.length)return new Lt.ZD({result:{case:"notFound",value:new Lt.ov({uri:t.uri})}});const r=e.contents[0];if(t.downloadPath){const e=await async function(e,t){const r=s.default.resolve(e),o=await(0,Os.realpath)(r),n=s.default.resolve(r,t.replace(/^\/+/,""));if(!ky(r,n))throw new Error("downloadPath must stay within the workspace");let i=s.default.dirname(n);for(;;)try{if(!ky(o,await(0,Os.realpath)(i)))throw new Error("downloadPath must stay within the workspace");break}catch(e){if("ENOENT"!==Ey(e))throw e;const t=s.default.dirname(i);if(t===i)throw e;i=t}if(await(0,Os.mkdir)(s.default.dirname(n),{recursive:!0}),!ky(o,await(0,Os.realpath)(s.default.dirname(n))))throw new Error("downloadPath must stay within the workspace");try{if((await(0,Os.lstat)(n)).isSymbolicLink())throw new Error("downloadPath must stay within the workspace")}catch(e){if("ENOENT"!==Ey(e))throw e}return n}(this.resolveProjectDir(o),t.downloadPath);if(r.text)await(0,Os.writeFile)(e,r.text,"utf8");else if(r.blob){const t=Buffer.from(r.blob,"base64");await(0,Os.writeFile)(e,t)}return new Lt.ZD({result:{case:"success",value:new Lt.KZ({uri:t.uri,name:r.name,description:r.description,mimeType:r.mimeType,downloadPath:e})}})}if(r.text)return new Lt.ZD({result:{case:"success",value:new Lt.KZ({uri:t.uri,name:r.name,description:r.description,mimeType:r.mimeType,annotations:r.annotations,metaJson:_t(r._meta),content:{case:"text",value:r.text}})}});if(r.blob){const e=Buffer.from(r.blob,"base64");return new Lt.ZD({result:{case:"success",value:new Lt.KZ({uri:t.uri,name:r.name,description:r.description,mimeType:r.mimeType,annotations:r.annotations,metaJson:_t(r._meta),content:{case:"blob",value:e}})}})}return new Lt.ZD({result:{case:"error",value:new Lt.Jx({uri:t.uri,error:"Failed to read resource"})}})}catch(e){const r=e instanceof Error?e.message:String(e);return Sy.warn(o,"LocalReadMcpResourceExecutor.execute failed",{server:t.server,hasDownloadPath:Boolean(t.downloadPath),errorName:e instanceof Error?e.name:typeof e,errorMessage:r}),new Lt.ZD({result:{case:"error",value:new Lt.Jx({uri:t.uri,error:`Failed to read MCP resource: ${r}`})}})}}catch(e){r.error=e,r.hasError=!0}finally{by(r)}}}async function Ty(e,t){const r=xy(t),o=(0,s.join)(e,"mcps",r,"tools");let n;try{n=await(0,Os.readdir)(o)}catch(e){if("ENOENT"===e?.code)return{toolNames:[],toolsDirExists:!1};throw e}const i=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{return}}(await(0,Os.readFile)((0,s.join)(o,e),"utf8"))}catch{return}}))),a=new Set;for(const e of i)e&&a.add(e);return{toolNames:Array.from(a).sort(((e,t)=>e.localeCompare(t))),toolsDirExists:!0}}const Ay=(0,m.h)("local-exec:mcp-disk-freshness-on-access"),My="/mcps/",Dy=(0,g.Pu)("mcp.discovery_freshness.check",{description:"MCP discovery surface freshness comparison outcome against canonical live tools",labelNames:["surface","outcome"]}),Oy=(0,g.v5)("mcp.discovery_freshness.missing_tools",{description:"Number of tools present in canonical live state but missing from the observed discovery surface",labelNames:["surface"]}),Ny=(0,g.v5)("mcp.discovery_freshness.extra_tools",{description:"Number of tools present on the observed discovery surface but absent from canonical live state",labelNames:["surface"]}),$y=(0,g.v5)("mcp.discovery_freshness.symmetric_difference",{description:"Total symmetric difference between canonical live tools and the observed discovery surface",labelNames:["surface"]}),Fy=new Map;function jy(e){const t=e.replace(/\\/g,"/");return t.endsWith("/mcps")?`${t}/`:t}async function Ly({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 Ay.warn(e,"mcp_disk_state_read_failed",{error_type:t instanceof Error?t.name:typeof t})}const a=i.servers.find((e=>xy(e.serverIdentifier)===o));if(void 0===a)return;let c;try{c=await n(r,a.serverIdentifier)}catch(t){return void Ay.warn(e,"mcp_disk_catalog_read_failed",{error_type:t instanceof Error?t.name:typeof t})}if(!c.toolsDirExists)return;const l=a.tools.map((e=>e.toolName)).filter((e=>e.length>0)).sort(((e,t)=>e.localeCompare(t)));!function({ctx:e,serverIdentifier:t,canonicalToolNames:r,observedToolNames:o}){const n=new Set(o),s=new Set(r),i=r.filter((e=>!n.has(e))),a=o.filter((e=>!s.has(e))),c=0===i.length&&0===a.length?"match":"mismatch",l={surface:"disk"};Dy.increment(e,1,{...l,outcome:c}),Oy.histogram(e,i.length,l),Ny.histogram(e,a.length,l),$y.histogram(e,i.length+a.length,l),"mismatch"===c&&Ay.warn(e,"mcp_disk_discovery_freshness_mismatch",{server_identifier:t,missing_tool_count:i.length,extra_tool_count:a.length})}({ctx:e,serverIdentifier:a.serverIdentifier,canonicalToolNames:l,observedToolNames:c.toolNames})}function Uy(e,t,r,o=Ty){if(void 0===r||(void 0===(n=r)||!jy(n).includes(My)))return;var n;const s=function(e){const t=jy(e),r=t.indexOf(My);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 c="mcps_root"===s.kind;"mcps_root"===s.kind?(i=`${s.projectDir}\0__mcps_root__`,a=void 0):(i=`${s.projectDir}\0${s.sanitizedServerFolder}`,a=s.sanitizedServerFolder);const l=Fy.get(i);void 0!==l&&clearTimeout(l);const u=e,d=setTimeout((()=>{Fy.delete(i),(async()=>{if(c){const e=await t.getState(u);for(const r of e.servers){const n=xy(r.serverIdentifier);await Ly({ctx:u,mcpStateAccessor:t,projectDir:s.projectDir,sanitizedServerFolder:n,readDiskCatalog:o,state:e})}}else void 0!==a&&await Ly({ctx:u,mcpStateAccessor:t,projectDir:s.projectDir,sanitizedServerFolder:a,readDiskCatalog:o})})().catch((e=>{Ay.warn(u,"mcp_disk_discovery_freshness_schedule_failed",{error_type:e instanceof Error?e.name:typeof e})}))}),2e3);Fy.set(i,d)}async function By(e){try{return(await(0,Os.stat)(e,{bigint:!0})).mtimeNs}catch{return}}function Wy(e,t,r){const o=e.map(((e,o)=>({file:e,mtime:t[o],segments:e.path.split(r)})));return o.sort(((e,t)=>e.mtime!==t.mtime?void 0===e.mtime?1:void 0===t.mtime||e.mtime>t.mtime?-1:1:function({left:e,right:t}){const r=Math.min(e.length,t.length);for(let o=0;o<r;o++){const r=e[o]??"",n=t[o]??"";if(r!==n)return r<n?-1:1}return e.length-t.length}({left:e.segments,right:t.segments}))),o.map((e=>e.file))}async function Hy(e,t,r=By){const o=e.map((e=>({item:e,path:t(e)})));let n;try{n=await(0,Ht.wj)(Promise.all(o.map((({path:e})=>r(e)))),2e3,"stat timed out")}catch(t){if(t instanceof Ht.MU)return{items:[...e],statTimedOut:!0};throw t}return{items:Wy(o,n,s.sep).map((({item:e})=>e)),statTimedOut:!1}}var qy=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},zy=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 Gy(e){return`Path '${e}' could not be verified while resolving symlinks. This can happen when access is denied or the path contains a symlink loop.`}function Vy(e){return`Path '${e}' is neither a file nor a directory`}async function Jy(e){const t=await(0,Os.stat)(e).catch((()=>{}));return void 0!==t&&!t.isFile()&&!t.isDirectory()}function Ky(e,t,r){const o=function(e,t){let r;for(const o of t)(0,Gs.ZU)({basePath:o,targetPath:e})&&(void 0===r||o.length>r.length)&&(r=o);return r}((0,s.resolve)(e,t),r);return void 0===o||o===e}class Zy extends Error{}function Xy(e){const t=new AbortController,r=setTimeout((()=>t.abort()),e);return{signal:t.signal,clear:()=>clearTimeout(r)}}function Qy(e){switch(e.result.case){case"content":return e.result.value.matches.length>0;case"files":return e.result.value.files.length>0;case"count":return e.result.value.counts.length>0;case void 0:return!1;default:{const t=e.result;throw new Error(`Unknown grep result: ${String(t)}`)}}}function Yy(e){switch(e){case"content":return new Tm.vD({result:{case:"content",value:new Tm.Zp({ripgrepTruncated:!0})}});case"files_with_matches":return new Tm.vD({result:{case:"files",value:new Tm.T7({ripgrepTruncated:!0})}});case"count":return new Tm.vD({result:{case:"count",value:new Tm.xA({ripgrepTruncated:!0})}});default:throw new Error(`Unknown output mode: ${String(e)}`)}}const ev=(0,m.h)("local-exec/grep"),tv=(0,g.Pu)("local_exec.grep.deadline_reached",{description:"Grep and Glob searches the search deadline stopped, by whether they kept what was found",labelNames:["output_mode","outcome","streaming"]}),rv=(0,g.Pu)("local_exec.grep.newest_first_stat_fallback",{description:"Grep and Glob results left in ripgrep's order because stat was too slow to sort them",labelNames:["output_mode"]});function ov(e){return e instanceof Error&&e.message.includes("ENOENT")&&e.message.includes("spawn")}function nv(e){try{return(0,$s.existsSync)(e)}catch{return"check_failed"}}function sv(e,t,r,o){return{...av(e),...o,cwd:t,cwdExists:nv(t),errorMessage:r.message,errorCode:r.code,errno:r.errno,syscall:r.syscall,errorPath:r.path}}function iv(e){return new Error(`Path does not exist: ${e}`)}function av(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,s.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,s.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,s.join)(o,"@vscode","ripgrep");t.ripgrepPkgDirExists=(0,$s.existsSync)(e)}}catch{t.asarUnpackedDirExists="check_failed"}}}return t}class cv{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,this.permissionsService=o?.permissionsService,this.useStreamingGrep=o?.useStreamingGrep}computeRelativeTarget(e,t){const r=(0,Gs.o1)(e,this.singleWorkspacePath??t);return r===t?".":(0,s.relative)(t,r)}isRootIndependentSearchPath(e){return(0,s.isAbsolute)(e)||/^~(?=$|[/\\])/.test(e)||e.startsWith("file://")}resolveSearchTargets(e,t){const r=this.isRootIndependentSearchPath(e);return t.map((t=>{const o=(0,s.resolve)(t);return{root:t,resolvedRoot:o,target:(0,Gs.o1)(e,r?void 0:o)}}))}findOutsideTargets(e,t){if(void 0===e||""===e)return;const r=this.resolveSearchTargets(e,t);return r.some((({resolvedRoot:e,target:t})=>(0,Gs.BJ)(t,e)))?void 0:[...new Set(r.map((({target:e})=>e)))]}searchTarget(e,t){if(!t.path)return".";const r=(0,Gs.o1)(t.path,this.singleWorkspacePath??e);return(0,Gs.BJ)(r,(0,s.resolve)(e))?this.computeRelativeTarget(t.path,e):r}sortsAfterRipgrep(e,t,r){return void 0===t.sort&&(r?!0!==t.sortAscending:(0,s.isAbsolute)(this.searchTarget(e,t)))}async buildArgs(e,t,r,o){const n=[],s=function(e,t){return"files_with_matches"===t&&""===e.pattern&&Boolean(e.glob)}(t,r),i=await this.ignoreService.listCursorIgnoreFilesByRoot(e);for(const e of i)n.push("--cursor-ignore",e);if("content"===r)n.push("--line-number","--with-filename","--no-heading","-0"),void 0!==t.contextBefore&&n.push("--before-context",String(t.contextBefore)),void 0!==t.contextAfter&&n.push("--after-context",String(t.contextAfter)),n.push("--max-columns",String(1e3),"--max-columns-preview"),void 0!==t.context&&void 0===t.contextBefore&&void 0===t.contextAfter&&n.push("--before-context",String(t.context),"--after-context",String(t.context));else if("files_with_matches"===r)n.push(s?"--files":"-l");else{if("count"!==r)throw new Error(`Unknown output mode: ${r}`);n.push("-c","--with-filename")}!0===t.caseInsensitive?n.push("--ignore-case"):n.push("--case-sensitive"),t.type&&n.push("--type",t.type),t.glob&&(n.push("--iglob",t.glob),s&&n.push("--iglob","!**/.git")),t.multiline&&n.push("--multiline","--multiline-dotall");const a=o?"none":t.sort??"modified";if(o&&n.push("--line-buffered"),"none"!==a){const e=!0===t.sortAscending?"--sort":"--sortr";n.push(e,a)}return n.push("--no-config","--color=never"),n.push("--hidden"),n.push("--follow"),s||n.push("--regexp",t.pattern),n.push("--"),n.push(this.searchTarget(e,t)),n}async filterBlockedFiles(e,t){const r=new Map,o=await(this.permissionsService?.getFileReadBoundaryBlocker?.()),n=[];for(const s of e){const e=(0,Gs.o1)(s.file,t),i=await Xa(e);null===i||await this.isPostRipgrepBlocked(i,r)||void 0!==o&&await o(e,i)||n.push(s)}return n}async isPostRipgrepBlocked(e,t){const[r,o]=await Promise.all([this.ignoreService.isCursorIgnored(e,t),this.ignoreService.isRepoBlocked(e)]);return r||o}throwOnRipgrepFailure(e,t,r){if((""!==e.stderr||2===e.exitCode)&&""===e.stdout.trim()&&!function({stderr:e,target:t}){return e.trim().split(/\r?\n/).every((e=>{const r=/^rg: (.+?): .*\(os error (?:13|5|2|1)\)$/.exec(e)?.[1]??/^rg: File system loop found: (.+) points to an ancestor /.exec(e)?.[1];return void 0!==r&&r!==t}))}({stderr:e.stderr,target:this.searchTarget(t,r)}))throw new Error(e.stderr||`ripgrep exited with code ${e.exitCode}`)}async orderNewestFirst(e,t,r,o,n){const s=await Hy(t,(e=>(0,Gs.o1)(o(e),r)));return s.statTimedOut&&(ev.info(e,"newest_first.stat_timeout_fallback",{toolCallId:n.toolCallId,execId:n.execId,outputMode:n.outputMode,fileCount:t.length}),rv.increment(e,1,{output_mode:n.outputMode})),s.items}async keepNewestPage(e,t,r,o,n){return(await this.orderNewestFirst(e,t,r,o,n)).slice(0,cv.CLIENT_LIMIT_LINES)}async runFilesMode(e,t,r,o,n,s,a){const c={stack:[],error:void 0,hasError:!1};try{const h=qy(c,(0,i.VI)(e.withName("LocalGrepExecutor.runFilesMode")),!1),p=await this.buildArgs(t,r,"files_with_matches",o),f=await this.executeRg(h.ctx,t,p,void 0,n,s,a);this.throwOnRipgrepFailure(f,t,r);const m=(l=f.stdout,u=o?cv.HARD_MAX_OUTPUT_LINES:cv.CLIENT_LIMIT_LINES,d=cv.HARD_MAX_OUTPUT_LINES,function(e,t,r){const o=e.trim();if(""===o)return{files:[],totalFiles:0,clientTruncated:!1,ripgrepTruncated:!1};const n=new Nm;let s=0,i=0,a=0;for(;$m(o,a,n);)a=n.nextStart,s<t&&(i=n.nextStart),s++;const c=s>t?Buffer.from(o.slice(0,i)).toString():o,l=[];for(a=0;l.length<t&&$m(c,a,n);)l.push(c.slice(a,n.lineEnd)),a=n.nextStart;return{files:l,totalFiles:Dm(s),clientTruncated:s>t,ripgrepTruncated:s>=r}}(l,u,d)),g=m.totalFiles>cv.CLIENT_LIMIT_LINES;let w=m.files;o&&(w=await this.keepNewestPage(h.ctx,w,t,(e=>e),a),g&&(w=w.join("\0").split("\0")));const y=(await this.filterBlockedFiles(w.map((e=>({file:e}))),t)).map((({file:e})=>e)),v=w.length-y.length,b=new Tm.T7({files:y,totalFiles:Dm(m.totalFiles-v),clientTruncated:g,ripgrepTruncated:m.ripgrepTruncated||f.timedOut||f.stdoutByteCapped});return{result:new Tm.vD({result:{case:"files",value:b}}),timedOut:f.timedOut}}catch(e){c.error=e,c.hasError=!0}finally{zy(c)}var l,u,d}async runCountMode(e,t,r,o,n,s,a){const c={stack:[],error:void 0,hasError:!1};try{const h=qy(c,(0,i.VI)(e.withName("LocalGrepExecutor.runCountMode")),!1),p=await this.buildArgs(t,r,"count",o),f=await this.executeRg(h.ctx,t,p,void 0,n,s,a);this.throwOnRipgrepFailure(f,t,r);const m=(l=f.stdout,u=o?cv.HARD_MAX_OUTPUT_LINES:cv.CLIENT_LIMIT_LINES,d=cv.HARD_MAX_OUTPUT_LINES,function(e,t,r){const o=e.trim();if(""===o)return{counts:[],totalFiles:0,totalMatches:0,clientTruncated:!1,ripgrepTruncated:!1};const n=[],s=new Nm;let i=0;for(;$m(o,i,s);){const e=i,t=s.lineEnd;if(i=s.nextStart,t===e)continue;const r=o.lastIndexOf(":",t-1);if(r<e||r===e)continue;const a=o.slice(r+1,t).trim(),c=parseInt(a,10);Number.isFinite(c)&&n.push({file:o.slice(e,r),count:c})}const a=n.length;let c=0;for(let e=0;e<n.length;e++){const t=n[e];void 0!==t&&(c+=t.count)}const l=[],u=a<t?a:t;for(let e=0;e<u;e++){const t=n[e];void 0!==t&&l.push(t)}return{counts:l,totalFiles:Dm(a),totalMatches:Dm(c),clientTruncated:a>t,ripgrepTruncated:a>=r}}(l,u,d)),g=o?await this.keepNewestPage(h.ctx,m.counts,t,(e=>e.file),a):m.counts,w=await this.filterBlockedFiles(g,t),y=w.reduce(((e,t)=>e+t.count),0),v=g.length-w.length,b=g.reduce(((e,t)=>e+t.count),0)-y,S=new Tm.xA({counts:w.map((e=>new Tm.sS({file:e.file,count:Dm(e.count)}))),totalFiles:Dm(m.totalFiles-v),totalMatches:Dm(m.totalMatches-b),clientTruncated:m.totalFiles>cv.CLIENT_LIMIT_LINES,ripgrepTruncated:m.ripgrepTruncated||f.timedOut||f.stdoutByteCapped});return{result:new Tm.vD({result:{case:"count",value:S}}),timedOut:f.timedOut}}catch(e){c.error=e,c.hasError=!0}finally{zy(c)}var l,u,d}async runContentMode(e,t,r,o,n,s,a){const c={stack:[],error:void 0,hasError:!1};try{const l=qy(c,(0,i.VI)(e.withName("LocalGrepExecutor.runContentMode")),!1),u=await this.buildArgs(t,r,"content",o),d=void 0!==r.context||void 0!==r.contextBefore||void 0!==r.contextAfter,h=cv.CLIENT_LIMIT_LINES*(d?2:1),p=await this.executeRg(l.ctx,t,u,h,n,s,a);this.throwOnRipgrepFailure(p,t,r);const{byFile:f,totalLines:m,totalMatchedLines:g,clientTruncated:w,ripgrepTruncated:y}=function(e,t,r,o){const n={stack:[],error:void 0,hasError:!1};try{return qy(n,(0,i.VI)(o.withName("parseContentOutput")),!1),function(e,t,r){const o={byFile:new Map,totalLines:0,totalMatchedLines:0,totalFiles:0,clientTruncated:!1,ripgrepTruncated:!1};if(""===e.trim())return o;const n=new Map,s=new Set,i=new Nm;let a=0,c=0,l=0,u=0;for(;$m(e,u,i);){const r=u,o=i.lineEnd;if(u=i.nextStart,l++,d=e,o-(h=r)==2&&45===d.charCodeAt(h)&&45===d.charCodeAt(h+1))continue;let p=-1;for(let t=r;t<o;t++)if(0===e.charCodeAt(t)){p=t;break}if(-1===p)continue;let f=p+1;if(f>=o)continue;let m=0,g=0;for(;f<o;){const t=e.charCodeAt(f);if(t<48||t>57)break;m=10*m+(t-48),g++,f++}if(0===g||f>=o||!Number.isFinite(m))continue;const w=e.charCodeAt(f);if(58!==w&&45!==w)continue;const y=45===w;!1===y&&a++;const v=e.slice(r,p);if(s.has(v)||s.add(v),c>=t)continue;const b=e.slice(f+1,o);let S=n.get(v);void 0===S&&(S={file:v,matches:[]},n.set(v,S)),S.matches.push({lineNumber:m,content:b,isContextLine:y}),c++}var d,h;return{byFile:n,totalLines:Dm(l),totalMatchedLines:Dm(a),totalFiles:Dm(s.size),clientTruncated:c>=t,ripgrepTruncated:l>=r}}(e,t,r)}catch(e){n.error=e,n.hasError=!0}finally{zy(n)}}(p.stdout,cv.CLIENT_LIMIT_LINES,h,l.ctx),v=Array.from(f.values()),b=await this.filterBlockedFiles(v,t),S=v.filter((e=>!b.includes(e))),k=S.reduce(((e,t)=>e+t.matches.length),0),E=S.reduce(((e,t)=>e+t.matches.filter((e=>!e.isContextLine)).length),0),C=o?await this.orderNewestFirst(l.ctx,b,t,(e=>e.file),a):b,x=new Tm.Zp({matches:C.map((e=>new Tm.uI({file:e.file,matches:e.matches.map((e=>new Tm.dx({lineNumber:e.lineNumber,content:e.content,isContextLine:e.isContextLine})))}))),totalLines:Dm(m-k),totalMatchedLines:Dm(g-E),clientTruncated:w,ripgrepTruncated:y||p.timedOut||p.stdoutByteCapped});return{result:new Tm.vD({result:{case:"content",value:x}}),timedOut:p.timedOut}}catch(e){c.error=e,c.hasError=!0}finally{zy(c)}}runMode(e,t,r,o,n,s,i,a){const c=this.sortsAfterRipgrep(r,o,n);switch(t){case"content":return this.runContentMode(e,r,o,c,s,i,a);case"files_with_matches":return this.runFilesMode(e,r,o,c,s,i,a);case"count":return this.runCountMode(e,r,o,c,s,i,a);default:throw new Error(`Unknown output mode: ${t}`)}}async streamingEnabled(e,t){const r=this.useStreamingGrep;if(void 0===r)return!0;try{return await r()}catch(r){return ev.warn(e,"streaming_grep_flag.read_failed",{toolCallId:t.toolCallId,execId:t.execId,errorName:r instanceof Error?r.name:typeof r}),!0}}reportDeadlineReached(e,t,r){ev.info(e,"ripgrep.deadline_reached",{toolCallId:t.toolCallId,execId:t.execId,outputMode:t.outputMode,...r}),tv.increment(e,1,{output_mode:t.outputMode,outcome:r.outcome,streaming:String(r.streaming)})}async executeIndexedGrepWithTimeout(e,t,r,o){if(void 0===this.grepProvider.executeIndexedGrep)return;const[n,s]=e.withTimeoutAndCancel(cv.INDEXED_GREP_CONTEXT_TIMEOUT_MS),i={phase:"provider"},a=performance.now();try{return await(0,Ht.wj)(this.grepProvider.executeIndexedGrep(n,t,r,i),cv.INDEXED_GREP_TIMEOUT_MS,`Indexed grep timed out after ${cv.INDEXED_GREP_TIMEOUT_MS/1e3}s`)}catch(t){if(t instanceof Ht.MU)return void ev.debug(e,"indexed_grep.timeout_fallback",{...o,totalMs:Math.round(performance.now()-a),...i});throw t}finally{s()}}static ripgrepTimeoutError(){return new Zy(`Timed out after ${cv.MAIN_TIMEOUT_MS/1e3}s`)}async executeRg(e,t,r,o,n,s,a){const c=(0,i.VI)(e.withName("LocalGrepExecutor.executeRg")),l="utf8",u=8388608;return o=o??cv.HARD_MAX_OUTPUT_LINES,new Promise(((i,d)=>{let h=!1,p=!1;const f=()=>{p||(p=!0,c.span.end())};if(e.signal.aborted)return f(),void d(new Error("Grep was cancelled"));if(n.aborted)return f(),void d(cv.ripgrepTimeoutError());let m;try{const e=s;m=(0,Fs.spawnInSandbox)((0,Fs.Ko)(),r,{cwd:t},e),0}catch(r){if(f(),ov(r)){const o=r,n=(0,Fs.Ko)();if(ev.error(e,"rg_diagnostics.spawn_throw",void 0,sv(n,t,o,a)),!1===nv(t))return d(iv(t))}return d(r)}const g=[],w=[];let y=0,v=0,b=0,S=!1,k=!1;const E=()=>{if(!h)try{f();const e=Buffer.concat(g).toString(l),t=e.slice(0,e.lastIndexOf("\n")+1);""===t?d(cv.ripgrepTimeoutError()):i({stdout:t,stderr:"",exitCode:0,timedOut:!0,stdoutByteCapped:k}),m.kill()}catch{}};n.addEventListener("abort",E,{once:!0});const C=()=>{n.removeEventListener("abort",E),f(),d(new Error("Grep was cancelled"));try{m.kill()}catch{}};e.signal.addEventListener("abort",C,{once:!0}),m.stdout?.on("data",(e=>{if(!k&&!S)if(y+=e.length,y>u){k=!0;try{m.kill()}catch{}}else if(void 0!==o){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;g.push(n)}else g.push(e)})),m.stderr?.on("data",(e=>{v+=e.length,v<=u&&w.push(e)})),m.on("error",(r=>{if(n.removeEventListener("abort",E),e.signal.removeEventListener("abort",C),f(),ov(r)){const o=(0,Fs.Ko)(),n=r;if(ev.error(e,"rg_diagnostics.spawn_enoent",void 0,sv(o,t,n,a)),!1===nv(t))return void d(iv(t))}d(r)})),m.on("close",(t=>{h=!0,n.removeEventListener("abort",E),e.signal.removeEventListener("abort",C);const r=Buffer.concat(g).toString(l),o=k?r.slice(0,r.lastIndexOf("\n")+1):r,s=Buffer.concat(w).toString(l);f(),i({stdout:o,stderr:s,exitCode:t??0,timedOut:!1,stdoutByteCapped:k})}))}))}async checkOutsideTarget(e,t){if(1!==t.length||void 0===t[0])return{error:`Path '${e}' points to a different folder from each workspace root; use an absolute path`};const r=await Xa(t[0]);return null===r?{error:Gy(e)}:await this.ignoreService.isCursorIgnored(r)?{error:`Path '${e}' is filtered out by .cursorignore`}:await Jy(t[0])?{error:Vy(e)}:{resolvedTarget:r}}async execute(e,t,r){const o={stack:[],error:void 0,hasError:!1};try{const n=qy(o,(0,i.VI)(e.withName("LocalGrepExecutor.execute")),!1),a=Array.isArray(this.workspacePath)?this.workspacePath:[this.workspacePath??process.cwd()],c=t.outputMode??"content",l={toolCallId:t.toolCallId,execId:r?.execId,outputMode:c,targetPath:t.path,workspacePaths:a},u=yi(t.sandboxPolicy),d=this.grepProvider.getWorktreeGuardInfo?.(a);if((0,Gs.fl)({targetPath:t.path,workspacePaths:a,mainWorktreePath:d?.mainWorktreePath}))return new Tm.Ud({result:{case:"error",value:new Tm.ts({error:Gs.PS})}});const h=this.findOutsideTargets(t.path,a);let p=t,f=a;try{if(t.path&&void 0!==h){const r=await this.checkOutsideTarget(t.path,h);if("error"in r)return new Tm.Ud({result:{case:"error",value:new Tm.ts({error:r.error})}});void 0!==this.mcpStateAccessor&&Uy(e,this.mcpStateAccessor,r.resolvedTarget),f=a.slice(0,1),p=t.clone(),p.path=h[0]}else if(p.path){const t=[];let r=!1;for(const{root:o,resolvedRoot:n,target:s}of this.resolveSearchTargets(p.path,a)){if(!(0,Gs.BJ)(s,n))continue;const i=await Xa(s);if(null!==i)if(await this.ignoreService.isCursorIgnored(i))r=!0;else{if(await Jy(s))return new Tm.Ud({result:{case:"error",value:new Tm.ts({error:Vy(p.path)})}});t.push(o),void 0!==this.mcpStateAccessor&&Uy(e,this.mcpStateAccessor,i)}}if(0===t.length){const e=r?`Path '${p.path}' is filtered out by .cursorignore`:Gy(p.path);return new Tm.Ud({result:{case:"error",value:new Tm.ts({error:e})}})}f=t}let r={};const o=void 0===h?await this.executeIndexedGrepWithTimeout(n.ctx,f,p,l):void 0;if(void 0!==o){r=o;for(const[e,t]of Object.entries(r)){const r=t.result;switch(r.case){case"content":r.value.matches=await this.filterBlockedFiles(r.value.matches,e);break;case"files":r.value.files=(await this.filterBlockedFiles(r.value.files.map((e=>({file:e}))),e)).map((({file:e})=>e));break;case"count":r.value.counts=await this.filterBlockedFiles(r.value.counts,e)}}}else{const e=await this.streamingEnabled(n.ctx,l),t=e?Xy(cv.MAIN_TIMEOUT_MS):void 0;let o=0,s=!1;try{for(const i of f){if(!0===t?.signal.aborted){r[i]=Yy(c),o++,s=!0;continue}if(!1===nv(i))return new Tm.Ud({result:{case:"error",value:new Tm.ts({error:`Path does not exist: ${i}`})}});const a=t??Xy(cv.MAIN_TIMEOUT_MS);try{const t=await this.runMode(n.ctx,c,i,p,e,a.signal,u,l);r[i]=t.result,t.timedOut&&o++}catch(t){if(!(t instanceof Zy))throw t;if(r[i]=Yy(c),o++,s=!0,!e)break}finally{a!==t&&a.clear()}}}finally{t?.clear()}if(o>0){const t=s&&(!e||!Object.values(r).some(Qy));if(this.reportDeadlineReached(n.ctx,l,{streaming:e,folderCount:f.length,stoppedFolderCount:o,outcome:t?"failed":"partial"}),t)throw cv.ripgrepTimeoutError()}}const i=function(e,t){if(t.length<=1)return e;const r=[...new Set(t.map((e=>(0,s.resolve)(e))))],o={};for(const[t,n]of Object.entries(e)){const e=(0,s.resolve)(t),i=t=>Ky(e,t,r),a=n.result;switch(a.case){case"content":{const e=a.value,r=[];let n=0,s=0;for(const t of e.matches)i(t.file)?r.push(t):(n+=t.matches.length,s+=t.matches.filter((e=>!e.isContextLine)).length);o[t]=new Tm.vD({result:{case:"content",value:new Tm.Zp({...e,matches:r,totalLines:Math.max(0,e.totalLines-n),totalMatchedLines:Math.max(0,e.totalMatchedLines-s)})}});break}case"files":{const e=a.value,r=e.files.filter((e=>i(e)));o[t]=new Tm.vD({result:{case:"files",value:new Tm.T7({...e,files:r,totalFiles:Math.max(0,e.totalFiles-(e.files.length-r.length))})}});break}case"count":{const e=a.value,r=[];let n=0;for(const t of e.counts)i(t.file)?r.push(t):n+=t.count;o[t]=new Tm.vD({result:{case:"count",value:new Tm.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}(r,f),d=new Tm._0({pattern:p.pattern,path:void 0!==p.path&&this.isRootIndependentSearchPath(p.path)?(0,Gs.o1)(p.path):p.path,outputMode:c,workspaceResults:i});return new Tm.Ud({result:{case:"success",value:d}})}catch(e){if(p.path){const e=(0,Gs.o1)(p.path,this.singleWorkspacePath);try{await(0,Os.stat)(e)}catch(t){return new Tm.Ud({result:{case:"error",value:new Tm.ts({error:`Path does not exist: ${e}`})}})}}return new Tm.Ud({result:{case:"error",value:new Tm.ts({error:e instanceof Error?e.message:String(e)})}})}}catch(e){o.error=e,o.hasError=!0}finally{zy(o)}}}cv.MAIN_TIMEOUT_MS=25e3,cv.INDEXED_GREP_TIMEOUT_MS=25e3,cv.INDEXED_GREP_CONTEXT_TIMEOUT_MS=cv.INDEXED_GREP_TIMEOUT_MS+100,cv.HARD_MAX_OUTPUT_LINES=1e4,cv.CLIENT_LIMIT_LINES=2e3,Io.object({record_v:Io.number().int().nullish(),pid:Io.number().int().nonnegative().nullish(),version:Io.string().nullish(),started_at:Io.number().nullish(),control_sock:Io.string().nullish(),runtime_dir:Io.string().nullish(),data_dir:Io.string().nullish(),config_path:Io.string().nullish(),log_path:Io.string().nullish(),metrics_addr:Io.string().nullish(),exe:Io.string().nullish()}),Io.object({mountpoint:Io.string().nullish(),capabilities:Io.array(Io.string()).nullish(),nfs_transport:Io.string().nullish(),bind_ignored:Io.object({active:Io.array(Io.string()).nullish()}).passthrough().nullish()}),Io.object({daemon_alive:Io.boolean().nullish(),mounts:Io.array(Io.unknown()).nullish(),data_plane:Io.object({enabled:Io.boolean().nullish()}).passthrough().nullish()});const lv=Io.number().int().nonnegative(),uv=Io.object({line_no:Io.number().int().positive(),kind:Io.enum(["match","before","after"]),text:Io.string().optional(),bytes:Io.string().regex(/^(?:[0-9a-fA-F]{2})*$/).optional(),truncated:Io.boolean().default(!1)}).refine((e=>void 0!==e.text||void 0!==e.bytes));Io.object({type:Io.literal("file"),path:Io.string(),lines:Io.array(uv)}),Io.object({type:Io.literal("summary"),files_searched:lv,more:Io.boolean(),stop_reason:Io.string().nullable(),skipped:Io.object({over_size:lv,size_unknown:lv,budget_exhausted:lv,fetch_failed:lv,unreadable:lv})}),Io.object({type:Io.string()}),(0,m.h)("local-exec/grove-grep");var dv=r("../proto/dist/generated/agent/v1/ls_exec_pb.js"),hv=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},pv=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 fv{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{hv(r,(0,i.VI)(e.withName("LocalLsExecutor.execute")),!1).ctx;const o=(0,Gs.o1)(t.path,this.workspacePath);try{let r;try{r=await(0,Os.stat)(o)}catch(e){return"ENOENT"===e.code?function(e){const t=Bt(e,"terminals");return null!==t&&0===t.remainingPath.length}(o)?new dv.fv({result:{case:"error",value:new dv.uj({path:o,error:"No active terminals."})}}):new dv.fv({result:{case:"error",value:new dv.uj({path:o,error:`Path does not exist: ${o}`})}}):new dv.fv({result:{case:"error",value:new dv.uj({path:o,error:e.message})}})}if(!r.isDirectory())return new dv.fv({result:{case:"error",value:new dv.uj({path:o,error:`Path is not a directory: ${o}`})}});const n=yi(t.sandboxPolicy),s=t.timeoutMs??5e3,i=e.withTimeout(s),{tree:a,didTimeout:c}=await this.getDirectoryTree(i,o,t.ignore,n);return c?new dv.fv({result:{case:"timeout",value:new dv.ze({directoryTreeRoot:a})}}):new dv.fv({result:{case:"success",value:new dv.PC({directoryTreeRoot:a})}})}catch(e){return new dv.fv({result:{case:"error",value:new dv.uj({path:o,error:e instanceof Error?e.message:"Unknown error occurred"})}})}}catch(e){r.error=e,r.hasError=!0}finally{pv(r)}}async getDirectoryTree(e,t,r,o){const n={stack:[],error:void 0,hasError:!1};try{return hv(n,(0,i.VI)(e.withName("LocalLsExecutor.getDirectoryTree")),!1),await this.buildTreeFromRipgrepStream(e,t,r,o,2500)}catch(e){n.error=e,n.hasError=!0}finally{pv(n)}}async buildTreeFromRipgrepStream(e,t,r,o,n){const a={stack:[],error:void 0,hasError:!1};try{hv(a,(0,i.VI)(e.withName("LocalLsExecutor.buildTreeFromRipgrepStream")),!1);const c=(0,s.resolve)(t),l=new dv.vq({absPath:c,childrenDirs:[],childrenFiles:[],childrenWereProcessed:!0,fullSubtreeExtensionCounts:{}}),u=new Map;u.set(c,l);const d={charactersUsed:c.length,budgetExceeded:!1},[h,p]=await Promise.all([this.ignoreService.listCursorIgnoreFilesByRoot(t),this.ignoreService.getRepoBlockExcludeGlobs(t)]),f=[...r,...p],{lines:m,didTimeout:g}=Ta(e,{root:t,excludeGlobs:f,caseSensitive:!0,cursorIgnoreFiles:h,sandboxPolicy:o,source:"ls"});for await(const e of m){if(!e)continue;const r=(0,s.resolve)(t,e),o=await Xa(r);null===o||await this.ignoreService.isCursorIgnored(o)||await this.ignoreService.isRepoBlocked(o)||this.addPathToTree(r,c,u,d,n)}return this.sortTreeChildren(l),{tree:l,didTimeout:await g}}catch(e){a.error=e,a.hasError=!0}finally{pv(a)}}addPathToTree(e,t,r,o,n){const i=(0,s.basename)(e),a=(0,s.dirname)(e);this.ensureDirectoryPath(a,t,r,o.budgetExceeded);const c=r.get(a);if(!c)return;const l=i.length;if(!o.budgetExceeded&&o.charactersUsed+l<=n){const e=new dv.ur({name:i});c.childrenFiles.push(e),o.charactersUsed+=l}else{if(!o.budgetExceeded){o.budgetExceeded=!0;let e=a;for(;e.startsWith(t);){const t=r.get(e);t&&(t.childrenWereProcessed=!1);const o=(0,s.dirname)(e);if(o===e)break;e=o}}let n=o.overflowChain;if(o.overflowDir!==a||void 0===n){n=[];let e=a;for(;e.startsWith(t);){const t=r.get(e);t&&n.push(t);const o=(0,s.dirname)(e);if(o===e)break;e=o}o.overflowDir=a,o.overflowChain=n}const i=(0,s.extname)(e);for(const e of n)e.fullSubtreeExtensionCounts[i]??=0,e.fullSubtreeExtensionCounts[i]=Dm(e.fullSubtreeExtensionCounts[i]+1),e.numFiles??=0,e.numFiles=Dm(e.numFiles+1)}}ensureDirectoryPath(e,t,r,o){if(r.has(e)||e===t)return;const n=(0,s.dirname)(e);n!==e&&n.startsWith(t)&&this.ensureDirectoryPath(n,t,r,o);const i=new dv.vq({absPath:e,childrenDirs:[],childrenFiles:[],childrenWereProcessed:!o,fullSubtreeExtensionCounts:{}});r.set(e,i);const a=r.get(n);a&&a.childrenDirs.push(i)}sortTreeChildren(e){e.childrenDirs.sort(((e,t)=>(0,s.basename)(e.absPath).localeCompare((0,s.basename)(t.absPath)))),e.childrenFiles.sort(((e,t)=>e.name.localeCompare(t.name)));for(const t of e.childrenDirs)this.sortTreeChildren(t)}}var mv=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 gv=1e4,wv={PAGER:"cat",MANPAGER:"cat",LESS:"-R",PIP_PROGRESS_BAR:"off",TQDM_DISABLE:"1"};class yv{constructor(){this.fullOutput="",this.outputHead="",this.outputTail="",this.totalChars=0}append(e){if(0===e.length)return;const t=this.totalChars;if(this.totalChars+=e.length,this.outputHead.length<5e3&&(this.outputHead=(this.outputHead+e).slice(0,5e3)),this.outputTail=(this.outputTail+e).slice(-5e3),t<gv){const r=Math.min(e.length,gv-t);this.fullOutput+=e.slice(0,r)}this.totalChars>gv&&(this.fullOutput="")}getOutput(){return this.totalChars<=gv?this.fullOutput:void 0}getTruncation(){if(!(this.totalChars<=gv))return{outputHead:this.outputHead,outputTail:this.outputTail,elidedChars:this.totalChars-gv}}}function vv(e,t){const r=Ks-e.length;return r<=0?e:e+t.slice(0,r)}function bv(e,t){return null!==e?e:null===t?-1:-n.constants.signals[t]}class Sv{constructor(e,t,r){this.permissionsService=e,this.ignoreService=t,this.defaultCwd=r}buildResult({args:e,workingDirectory:t,processResult:r,sandboxPolicy:o}){const n={command:e.command,workingDirectory:t,exitCode:r.returncode,signal:r.signal,stdout:r.stdout,stderr:r.exceptionInfo||r.stderr,interleavedOutput:r.output,outputHead:r.outputTruncation?.outputHead,outputTail:r.outputTruncation?.outputTail,elidedChars:r.outputTruncation?.elidedChars,executionTime:r.localExecutionTimeMs??0,localExecutionTimeMs:r.localExecutionTimeMs},s=r.exceptionInfo.length>0,i=0!==r.returncode||s?{case:"failure",value:new yr.xC({...n,aborted:s,abortReason:r.abortReason})}:{case:"success",value:new yr.QR(n)};return new yr.W4({result:i,sandboxPolicy:vi(o)})}async runProcess({ctx:e,args:t,workingDirectory:r,sandboxPolicy:o,timeoutMs:n}){const s=performance.now(),i=this.defaultCwd,a=(await(0,Fs.resolveSandboxPolicyForWorkspace)(i,o?{perRepo:o}:void 0)).policy,c="insecure_none"!==a.type?{...a,sandboxWorkspaceRoot:i}:a;return await new Promise((o=>{const i=new yv;let a,l,u="",d="",h=!1,p=!1,f="",m=()=>{};const g=(0,Fs.Xw)({...process.env,...wv,CURSOR_AGENT:"1"}),w={cwd:r,env:g,stdio:["pipe","pipe","pipe"],detached:"win32"!==process.platform,windowsVerbatimArguments:"win32"===process.platform},y="win32"===process.platform?{executable:process.env.ComSpec??"cmd.exe",args:(v=t.command,["/d","/s","/c",`"${v}"`])}:{executable:"/bin/sh",args:["-c",t.command]};var v;const b="insecure_none"===c.type?(0,Of.D9)(Iu.spawn,y.executable,y.args,w):(0,Fs.spawnInSandbox)(y.executable,y.args,w,c);b.stdin?.end();const S=e=>{h||(h=!0,clearTimeout(l),m(),o({...e,output:i.getOutput(),outputTruncation:i.getTruncation(),localExecutionTimeMs:Om(performance.now()-s)}))};l=setTimeout((()=>{if(p=!0,void 0===a&&(f=`An error occurred while executing the command: Command timed out after ${n}ms`,a=yr.Lv.TIMEOUT,m()),void 0!==b.pid&&"win32"!==process.platform)try{return void process.kill(-b.pid,"SIGKILL")}catch{}b.kill("SIGKILL")}),n);const k=()=>{if(void 0===a){if(f="An error occurred while executing the command: Command aborted",a=yr.Lv.USER_ABORT,void 0!==b.pid&&"win32"!==process.platform)try{return void process.kill(-b.pid,"SIGTERM")}catch{}b.kill("SIGTERM")}};e.signal.aborted?k():(e.signal.addEventListener("abort",k,{once:!0}),m=()=>{e.signal.removeEventListener("abort",k)}),b.stdout?.on("data",(e=>{const t=e.toString();u=vv(u,t),i.append(t)})),b.stderr?.on("data",(e=>{const t=e.toString();d=vv(d,t),i.append(t)})),b.on("error",(e=>{S({stdout:u,stderr:d,returncode:-1,signal:"",exceptionInfo:`An error occurred while executing the command: ${e.message}`})})),b.on("close",((e,t)=>{S({stdout:u,stderr:d,returncode:f.length>0?-1:bv(e,t),signal:t??(p?"SIGKILL":""),exceptionInfo:f,abortReason:a})}))}))}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,i.VI)(e.withName("LocalMiniSweAgentBashExecutor.execute")),!1).ctx;(0,i.HF)(o,"LocalMiniSweAgentBashExecutor.execute");const n=t.command,s=(0,Gs.o1)(t.workingDirectory||this.defaultCwd),a=t.timeout>0?t.timeout:3e4;if(!t.parsingResult)return new yr.W4({result:{case:"spawnError",value:new yr.mJ({command:n,workingDirectory:s,error:"Parsing result is required"})}});let c=t.requestedSandboxPolicy?yi(t.requestedSandboxPolicy):void 0;const l=await this.permissionsService.shouldBlockShellCommand(o,n,{workingDirectory:s,timeout:a,parsingResult:t.parsingResult,toolCallId:t.toolCallId},c);if("block"===l.kind)return"permissionsConfig"===l.reason.type&&l.reason.isReadonly?new yr.W4({result:{case:"permissionDenied",value:new yr.jn({command:n,workingDirectory:s,error:"Command blocked by permissions configuration",isReadonly:!0})}}):new yr.W4({result:{case:"rejected",value:new yr.pZ({command:n,workingDirectory:s,reason:Ic(l.reason)})}});c=l.policy,ii()&&(c=hi(n,t.parsingResult)),c&&"insecure_none"!==c.type&&(c={...c,ignoreMapping:await this.ignoreService.getCursorIgnoreMapping()});const u=await this.runProcess({ctx:o,args:t,workingDirectory:s,sandboxPolicy:c,timeoutMs:a});return this.buildResult({args:t,workingDirectory:s,processResult:u,sandboxPolicy:c})}catch(e){r.error=e,r.hasError=!0}finally{mv(r)}}}var kv=r("../proto/dist/generated/agent/v1/pi_bash_exec_pb.js"),Ev=r("../proto/dist/generated/agent/v1/pi_common_pb.js");const Cv=51200;function xv(e){return Buffer.byteLength(e,"utf8")}function _v(e){return e<1024?`${e}B`:`${Math.round(e/1024)}KB`}function Pv(e){return new Ev.d({truncated:e.truncated,truncatedBy:e.truncatedBy??"",totalLines:e.totalLines,outputLines:e.outputLines,outputBytes:e.outputBytes,maxLines:e.maxLines,maxBytes:e.maxBytes,firstLineExceedsLimit:e.firstLineExceedsLimit??!1,lastLinePartial:e.lastLinePartial??!1})}function Iv(e,t){const r=t?.maxLines??2e3,o=t?.maxBytes??Cv,n=e.split("\n"),s=n.length;if(xv(n[0]??"")>o)return{content:"",truncation:Pv({truncated:!0,truncatedBy:"bytes",totalLines:s,outputLines:0,outputBytes:0,maxLines:r,maxBytes:o,firstLineExceedsLimit:!0})};const i=[];let a,c=0;for(let e=0;e<n.length;e++){if(i.length>=r){a="lines";break}const t=n[e],s=i.length>0?1:0,l=xv(t)+s;if(c+l>o){a="bytes";break}i.push(t),c+=l}return{content:i.join("\n"),truncation:Pv({truncated:void 0!==a,truncatedBy:a,totalLines:s,outputLines:i.length,outputBytes:c,maxLines:r,maxBytes:o})}}function Rv(e){return e.length<=500?{text:e,wasTruncated:!1}:{text:`${e.slice(0,500)}... [truncated]`,wasTruncated:!0}}var Tv=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});async function Av(e){const{content:t,truncation:r}=function(e){const t=Cv,r=e.split("\n"),o=r.length,n=[];let s,i=0,a=!1;for(let e=r.length-1;e>=0;e--){if(n.length>=2e3){s="lines";break}const o=r[e],c=n.length>0?1:0,l=xv(o)+c;if(i+l>t){if(s="bytes",0===n.length){const e=Buffer.from(o,"utf8");n.unshift(e.subarray(Math.max(0,e.length-t)).toString("utf8")),i=xv(n[0]),a=!0}break}n.unshift(o),i+=l}return{content:n.join("\n"),truncation:Pv({truncated:void 0!==s,truncatedBy:s,totalLines:o,outputLines:n.length,outputBytes:i,maxLines:2e3,maxBytes:t,lastLinePartial:a})}}(e||"(no output)");if(!r.truncated)return{output:t};const o=await(0,Os.mkdtemp)((0,s.join)((0,n.tmpdir)(),"pi-bash-")),i=(0,s.join)(o,"output.log");await(0,Os.writeFile)(i,e,"utf8");const a=r.totalLines-r.outputLines+1,c=r.totalLines;return{output:`${t}\n\n${r.lastLinePartial?`[Showing last ${_v(r.outputBytes)} of line ${c} (${_v(Cv)} limit). Full output: ${i}]`:`[Showing lines ${a}-${c} of ${r.totalLines}. Full output: ${i}]`}`,fullOutputPath:i,truncation:r}}class Mv{constructor(e){this.shellExecutor=e}async execute(e,t,r){const o={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}(o,(0,i.VI)(e.withName("LocalPiBashExecutor.execute")),!1),s=await this.shellExecutor.execute(n.ctx,function(e,t){const r=void 0!==e.timeout&&e.timeout>0?Math.round(1e3*e.timeout):2147483647,o=e.command.trim().split(/\s+/)[0]??"";return new yr.a({command:e.command,timeout:r,toolCallId:t?.execId??"",fileOutputThresholdBytes:BigInt(0),parsingResult:new yr.HO({parsingFailed:!1,executableCommands:[{name:o,fullText:e.command,args:[]}]})})}(t,r),r);switch(s.result.case){case"success":{const e=await Av(`${s.result.value.stdout}${s.result.value.stderr}`);return new kv.AH({result:{case:"success",value:new kv.cV(e)}})}case"failure":{const e=await Av(`${s.result.value.stdout}${s.result.value.stderr}`);return new kv.AH({result:{case:"success",value:new kv.cV({...e,output:`${e.output}\n\nCommand exited with code ${s.result.value.exitCode}`})}})}case"timeout":return this.error(`Command timed out after ${Math.round(s.result.value.timeoutMs/1e3)} seconds`);case"rejected":return this.error(s.result.value.reason||"Command aborted");case"permissionDenied":case"spawnError":return this.error(s.result.value.error);default:return this.error("Command failed")}}catch(e){o.error=e,o.hasError=!0}finally{Tv(o)}}error(e){return new kv.AH({result:{case:"error",value:new kv.bD({error:e})}})}}var Dv=r("../proto/dist/generated/agent/v1/pi_edit_exec_pb.js");function Ov(e){switch(e.type){case"cursorIgnore":return"Path is blocked by cursorignore";case"adminBlock":return`Blocked by ${e.source}`;case"adminCommandDenylist":return Ai(e.pattern);case"userRejected":return e.reason??"User rejected the operation";case"permissionsConfig":return e.isReadonly?"Blocked by readonly permissions configuration":"Blocked by permissions configuration";case"cursorFiles":return"Path is blocked because it is a Cursor internal file";case"unsafeResolution":return e.message;case"needsApproval":return e.approvalReason}}var Nv=r("../../node_modules/.pnpm/diff@8.0.3/node_modules/diff/libesm/patch/create.js");function $v(e){return e.replace(/\r\n/g,"\n").replace(/\r/g,"\n")}function Fv(e){return e.normalize("NFKC").replace(/[\u2018\u2019]/g,"'").replace(/[\u201c\u201d]/g,'"').replace(/[\u2013\u2014]/g,"-").replace(/\u00a0/g," ").split("\n").map((e=>e.trimEnd())).join("\n")}function jv(e,t){if(0===t.length)return 0;let r=0,o=e.indexOf(t);for(;-1!==o;)r++,o=e.indexOf(t,o+t.length);return r}function Lv(e,t){const r=e.split("\n"),o=t.split("\n"),n=Math.max(r.length,o.length);for(let e=0;e<n;e++)if(r[e]!==o[e])return e+1}const Uv=new Map;async function Bv(e,t){const r=await async function(e){try{return await(0,Os.realpath)(e)}catch{return e}}(e),o=Uv.get(r)??Promise.resolve();let n;const s=new Promise((e=>{n=e})),i=o.then((()=>s));Uv.set(r,i),await o;try{return await t()}finally{n(),Uv.get(r)===i&&Uv.delete(r)}}function Wv(e,t){let r=e.trim().replace(/\u00a0/g," ");return r.startsWith("@")&&(r=r.slice(1)),r.startsWith("file://")&&(r=(0,th.fileURLToPath)(r)),("~"===r||r.startsWith("~/"))&&(r=(0,s.join)((0,n.homedir)(),r.slice(2))),(0,s.normalize)((0,s.isAbsolute)(r)?r:(0,s.resolve)(t??process.cwd(),r))}var Hv=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 qv{constructor(e,t,r){this.permissionsService=e,this.writeExecutor=t,this.workspacePath=r}async execute(e,t,r){const o={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}(o,(0,i.VI)(e.withName("LocalPiEditExecutor.execute")),!1),s=Wv(t.path,this.workspacePath);return Bv(s,(async()=>{const e=await this.permissionsService.shouldBlockRead(s);if(e)return this.error(`Read blocked: ${Ov(e)}`);try{if((await(0,Os.stat)(s)).isDirectory())return this.error(`Path is a directory: ${s}`);const e=(await(0,Os.readFile)(s)).toString("utf8"),o=function(e,t,r){if(0===r.length)throw new Error("edits must contain at least one replacement.");const{bom:o,text:n}=65279===(s=t).charCodeAt(0)?{bom:s[0],text:s.slice(1)}:{bom:"",text:s};var s;const i=function(e){return e.includes("\r\n")?"\r\n":"\n"}(n),a=$v(n),{matches:c,matchedContent:l}=function(e,t){const r=[];let o=!1;for(const n of t){if(0===n.oldText.length)throw new Error("oldText must not be empty.");const t=$v(n.oldText),s=jv(e,t);if(1!==s){if(s>1)throw new Error("oldText must be unique in the file.");o=!0;break}r.push({index:e.indexOf(t),length:t.length,replacement:$v(n.newText)})}if(!o)return{matches:r,matchedContent:e};const n=Fv(e),s=[];for(const e of t){const t=Fv($v(e.oldText)),r=jv(n,t);if(0===r)throw new Error("oldText was not found in the file.");if(r>1)throw new Error("oldText must be unique in the file.");s.push({index:n.indexOf(t),length:t.length,replacement:Fv($v(e.newText))})}return{matches:s,matchedContent:n}}(a,r),u=function(e,t){const r=[...t].sort(((e,t)=>e.index-t.index));for(let e=1;e<r.length;e++){const t=r[e-1];if(r[e].index<t.index+t.length)throw new Error("edits must not overlap.")}let o=e;for(const e of r.reverse())o=o.slice(0,e.index)+e.replacement+o.slice(e.index+e.length);return o}(l,c);if(u===a)throw new Error("edits did not change the file.");const d=o+function(e,t){return"\n"===t?e:e.replace(/\n/g,"\r\n")}(u,i),h=(0,Nv.ss)(e,e,a,u,"","",{context:4});return{newContent:d,diff:h,patch:h,firstChangedLine:Lv(a,u)}}(t.path,e,t.edits),i=await this.writeExecutor.execute(n.ctx,new vr.hY({path:s,fileText:o.newContent,toolCallId:r?.execId??""}),r);switch(i.result.case){case"success":return new Dv.u7({result:{case:"success",value:new Dv.uL({output:`Successfully replaced ${t.edits.length} block(s) in ${t.path}.`,diff:o.diff,patch:o.patch,firstChangedLine:o.firstChangedLine})}});case"rejected":return new Dv.u7({result:{case:"rejected",value:new Dv.pE({reason:i.result.value.reason})}});default:return this.error(this.writeErrorMessage(i.result.value,t.path))}}catch(e){return this.error(e instanceof Error?e.message:"Unknown edit error")}}))}catch(e){o.error=e,o.hasError=!0}finally{Hv(o)}}writeErrorMessage(e,t){if(null!=e&&"object"==typeof e&&"error"in e){const t=e.error;if("string"==typeof t)return t}return`Failed to edit ${t}`}error(e){return new Dv.u7({result:{case:"error",value:new Dv.Nd({error:e})}})}}var zv=r("../proto/dist/generated/agent/v1/pi_find_exec_pb.js"),Gv=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 Vv(e){return e.split(s.sep).join("/")}class Jv{constructor(e,t){this.permissionsService=e,this.workspacePath=t}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,i.VI)(e.withName("LocalPiFindExecutor.execute")),!1);const o=Wv(t.path||".",this.workspacePath),n=await this.permissionsService.shouldBlockRead(o);if(n)return this.error(`Find blocked: ${Ov(n)}`);try{if(!(await(0,Os.stat)(o)).isDirectory())return this.error(`Not a directory: ${o}`);const e=Math.max(1,t.limit??1e3),r=await async function(e,t,r){const o=[];return await async function e(n){if(o.length>=t)return;const i=await(0,Os.readdir)(n,{withFileTypes:!0});for(const a of i){if(o.length>=t)return;if(".git"===a.name||"node_modules"===a.name)continue;const i=(0,s.join)(n,a.name);await r(i)&&(o.push(i+(a.isDirectory()?s.sep:"")),a.isDirectory()&&await e(i))}}(e),o}(o,e,(async e=>!await this.permissionsService.shouldBlockRead(e))),n=t.pattern.includes("/")&&!t.pattern.startsWith("**/")?`**/${t.pattern}`:t.pattern,i=r.map((e=>({raw:e,relative:Vv((0,s.relative)(o,e))}))).filter((({relative:e})=>(0,Vc.xF)(e,n,{dot:!0})));if(0===i.length)return this.success("No files found matching pattern");const a=Iv(i.map((e=>e.relative)).join("\n"),{maxLines:Number.MAX_SAFE_INTEGER}),c=r.length>=e?e:void 0,l=[];return void 0!==c&&l.push(`${e} results limit reached. Use limit=${2*e} for more, or refine pattern`),a.truncation.truncated&&l.push(`${_v(Cv)} limit reached`),this.success(l.length>0?`${a.content}\n\n[${l.join(". ")}]`:a.content,{resultLimitReached:c,truncation:a.truncation.truncated?a.truncation:void 0})}catch(e){return this.error(e instanceof Error?e.message:"Unknown find error")}}catch(e){r.error=e,r.hasError=!0}finally{Gv(r)}}success(e,t){return new zv.bT({result:{case:"success",value:new zv.x9({output:e,truncation:t?.truncation,resultLimitReached:t?.resultLimitReached})}})}error(e){return new zv.bT({result:{case:"error",value:new zv.Uy({error:e})}})}}var Kv=r("../proto/dist/generated/agent/v1/pi_grep_exec_pb.js"),Zv=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 Xv=Iu.spawn;class Qv{constructor(e,t){this.permissionsService=e,this.workspacePath=t}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,i.VI)(e.withName("LocalPiGrepExecutor.execute")),!1);const o=Wv(t.path||".",this.workspacePath),n=await this.permissionsService.shouldBlockRead(o);if(n)return this.error(`Search blocked: ${Ov(n)}`);try{const e=(await(0,Os.stat)(o)).isDirectory(),r=["--json","--line-number","--color=never","--hidden"];t.ignoreCase&&r.push("--ignore-case"),t.literal&&r.push("--fixed-strings"),void 0!==t.glob&&r.push("--glob",t.glob),r.push("--",t.pattern,o);const n=(0,Of.D9)(Xv,(0,Fs.Ko)(),r,{stdio:["ignore","pipe","pipe"]}),s=[];let i="",a=!1;const c=Math.max(1,t.limit??100),l=(0,Df.createInterface)({input:n.stdout});n.stderr.on("data",(e=>{i+=e.toString()})),l.on("line",(e=>{if(s.length>=c||0===e.trim().length)return;const t=JSON.parse(e);if("match"!==t.type)return;const r=t.data?.path?.text,o=t.data?.line_number;void 0!==r&&void 0!==o&&(s.push({filePath:r,lineNumber:o,lineText:t.data?.lines?.text?.replace(/\n$/,"")}),s.length>=c&&(a=!0,n.kill()))}));const u=await new Promise(((e,t)=>{n.on("error",t),n.on("close",e)}));if(l.close(),!a&&0!==u&&1!==u)return this.error(i.trim()||`ripgrep exited with code ${u}`);if(0===s.length)return this.success("No matches found");const d=[];for(const e of s)await this.permissionsService.shouldBlockRead(e.filePath)||d.push(e);if(0===d.length)return this.success("No matches found");const{output:h,linesTruncated:p}=await this.formatMatches(d,o,e,Math.max(0,t.context??0)),f=Iv(h,{maxLines:Number.MAX_SAFE_INTEGER}),m=[];return a&&m.push(`${c} matches limit reached. Use limit=${2*c} for more, or refine pattern`),f.truncation.truncated&&m.push(`${_v(Cv)} limit reached`),p&&m.push("Some lines truncated to 500 chars. Use read tool to see full lines"),this.success(m.length>0?`${f.content}\n\n[${m.join(". ")}]`:f.content,{matchLimitReached:a?c:void 0,linesTruncated:p,truncation:f.truncation.truncated?f.truncation:void 0})}catch(e){return this.error(e instanceof Error?e.message:"Unknown grep error")}}catch(e){r.error=e,r.hasError=!0}finally{Zv(r)}}async formatMatches(e,t,r,o){const n=[];let i=!1;for(const a of e){const e=r?(0,s.relative)(t,a.filePath):(0,s.basename)(a.filePath);if(0===o&&void 0!==a.lineText){const t=Rv(a.lineText);i=i||t.wasTruncated,n.push(`${e}:${a.lineNumber}: ${t.text}`);continue}const c=(await(0,Os.readFile)(a.filePath,"utf8")).replace(/\r\n/g,"\n").replace(/\r/g,"\n").split("\n"),l=Math.max(1,a.lineNumber-o),u=Math.min(c.length,a.lineNumber+o);for(let t=l;t<=u;t++){const r=Rv(c[t-1]??"");i=i||r.wasTruncated,n.push(t===a.lineNumber?`${e}:${t}: ${r.text}`:`${e}-${t}- ${r.text}`)}}return{output:n.join("\n"),linesTruncated:i}}success(e,t){return new Kv.mr({result:{case:"success",value:new Kv.oC({output:e,truncation:t?.truncation,matchLimitReached:t?.matchLimitReached,linesTruncated:t?.linesTruncated??!1})}})}error(e){return new Kv.mr({result:{case:"error",value:new Kv.hP({error:e})}})}}var Yv=r("../proto/dist/generated/agent/v1/pi_ls_exec_pb.js"),eb=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 tb{constructor(e,t){this.permissionsService=e,this.workspacePath=t}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,i.VI)(e.withName("LocalPiLsExecutor.execute")),!1);const o=Wv(t.path||".",this.workspacePath),n=await this.permissionsService.shouldBlockRead(o);if(n)return this.error(`List blocked: ${Ov(n)}`);try{if(!(await(0,Os.stat)(o)).isDirectory())return this.error(`Not a directory: ${o}`);const e=Math.max(1,t.limit??500),r=(await(0,Os.readdir)(o)).sort(((e,t)=>e.toLowerCase().localeCompare(t.toLowerCase()))),n=[];let i=!1;for(const t of r){if(n.length>=e){i=!0;break}try{const e=(0,s.join)(o,t);if(await this.permissionsService.shouldBlockRead(e))continue;const r=await(0,Os.stat)(e);n.push(t+(r.isDirectory()?"/":""))}catch{}}if(0===n.length)return this.success("(empty directory)");const a=Iv(n.join("\n"),{maxLines:Number.MAX_SAFE_INTEGER}),c=[];return i&&c.push(`${e} entries limit reached. Use limit=${2*e} for more`),a.truncation.truncated&&c.push(`${_v(Cv)} limit reached`),this.success(c.length>0?`${a.content}\n\n[${c.join(". ")}]`:a.content,{entryLimitReached:i?e:void 0,truncation:a.truncation.truncated?a.truncation:void 0})}catch(e){return this.error(e instanceof Error?e.message:"Unknown ls error")}}catch(e){r.error=e,r.hasError=!0}finally{eb(r)}}success(e,t){return new Yv.pX({result:{case:"success",value:new Yv.f5({output:e,truncation:t?.truncation,entryLimitReached:t?.entryLimitReached})}})}error(e){return new Yv.pX({result:{case:"error",value:new Yv.iG({error:e})}})}}var rb=r("../proto/dist/generated/agent/v1/pi_read_exec_pb.js"),ob=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 nb{constructor(e,t){this.permissionsService=e,this.workspacePath=t}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,i.VI)(e.withName("LocalPiReadExecutor.execute")),!1);const o=function(e,t){const r=Wv(e,t);if((0,$s.existsSync)(r))return r;for(const e of function(e){const t=(0,s.dirname)(e),r=e.slice(t.length+1),o=new Set;return o.add(e),o.add((0,s.join)(t,r.normalize("NFD"))),o.add((0,s.join)(t,r.replace(/'/g,"’"))),o.add((0,s.join)(t,r.replace(/ /g," "))),o.add((0,s.join)(t,r.replace(/'/g,"’").normalize("NFD"))),[...o]}(r))if((0,$s.existsSync)(e))return e;return r}(t.path,this.workspacePath),n=await this.permissionsService.shouldBlockRead(o);if(n)return this.error(`Read blocked: ${Ov(n)}`);try{if((await(0,Os.stat)(o)).isDirectory())return this.error(`Path is a directory: ${o}`);const e=(await(0,Os.readFile)(o)).toString("utf8").split("\n"),r=void 0!==t.offset?Math.max(0,t.offset-1):0;if(r>=e.length)return this.error(`Offset ${t.offset} is beyond end of file (${e.length} lines total)`);const n=void 0!==t.limit?e.slice(r,r+t.limit).join("\n"):e.slice(r).join("\n"),{content:s,truncation:i}=Iv(n),a=r+1;let c=s;if(i.firstLineExceedsLimit)c=`[Line ${a} is ${_v(Buffer.byteLength(e[r]??"","utf8"))}, exceeds ${_v(Cv)} limit. Use bash: sed -n '${a}p' ${t.path} | head -c 51200]`;else if(i.truncated){const t=a+i.outputLines-1;c+=`\n\n[Showing lines ${a}-${t} of ${e.length}. Use offset=${t+1} to continue.]`}else if(void 0!==t.limit&&r+t.limit<e.length){const o=r+t.limit+1;c+=`\n\n[${e.length-(r+t.limit)} more lines in file. Use offset=${o} to continue.]`}return new rb.Q({result:{case:"success",value:new rb.yP({output:c,truncation:i.truncated?i:void 0})}})}catch(e){return this.error(e instanceof Error?e.message:"Unknown read error")}}catch(e){r.error=e,r.hasError=!0}finally{ob(r)}}error(e){return new rb.Q({result:{case:"error",value:new rb.tB({error:e})}})}}var sb=r("../proto/dist/generated/agent/v1/pi_write_exec_pb.js"),ib=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 ab{constructor(e,t){this.writeExecutor=e,this.workspacePath=t}async execute(e,t,r){const o={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}(o,(0,i.VI)(e.withName("LocalPiWriteExecutor.execute")),!1),s=Wv(t.path,this.workspacePath);return Bv(s,(async()=>{const e=await this.writeExecutor.execute(n.ctx,new vr.hY({path:s,fileText:t.content,toolCallId:r?.execId??""}),r);switch(e.result.case){case"success":return new sb.hO({result:{case:"success",value:new sb.vu({output:`Successfully wrote ${t.content.length} bytes to ${t.path}`})}});case"rejected":return new sb.hO({result:{case:"rejected",value:new sb.Ye({reason:e.result.value.reason})}});case"permissionDenied":case"noSpace":case"error":return new sb.hO({result:{case:"error",value:new sb.OD({error:"error"in e.result.value?e.result.value.error:`Failed to write ${t.path}`})}});default:return new sb.hO({result:{case:"error",value:new sb.OD({error:`Failed to write ${t.path}`})}})}}))}catch(e){o.error=e,o.hasError=!0}finally{ib(o)}}}var cb=r("../proto/dist/generated/agent/v1/agent_store_conflict_exec_pb.js");function lb(e){if(void 0!==e)return{journalEpoch:e.journalEpoch,seq:Number(e.seq),lastEventId:e.lastEventId}}class ub{constructor(e){this.drainer=e}async execute(e,t){try{void 0!==t.includeQuotaNotices&&this.drainer.setIncludeQuotaNoticesOverride(t.includeQuotaNotices);const e=await this.drainer.drain({cursor:lb(t.cursor),advance:!1!==t.advance});return new cb.Ev({result:{case:"success",value:new cb.iS({events:e.events.map((e=>new cb.RZ({v:e.v,eventId:e.event_id,journalEpoch:e.journal_epoch,seq:BigInt(e.seq),tsMs:BigInt(e.ts_ms),kind:e.kind,storeId:e.store_id,originalRelPath:e.original_rel_path,conflictRelPath:e.conflict_rel_path,originalAbsPath:e.original_abs_path,conflictAbsPath:e.conflict_abs_path,preservedBytes:void 0===e.preserved_bytes?void 0:BigInt(e.preserved_bytes),scopeKind:e.scope_kind,limitBytes:void 0===e.limit_bytes?void 0:BigInt(e.limit_bytes),usageBytes:void 0===e.usage_bytes?void 0:BigInt(e.usage_bytes)}))),nextCursor:(r=e.nextCursor,new cb.LK({journalEpoch:r.journalEpoch,seq:BigInt(r.seq),lastEventId:r.lastEventId})),gap:e.gap})}})}catch(e){return new cb.Ev({result:{case:"error",value:new cb.h6({error:e instanceof Error?e.message:String(e)})}})}var r}}class db{constructor(e){this.shellStdinWriter=e}async execute(e,t){const r=t.shellId;try{await this.shellStdinWriter(r,t.chars)}catch(e){return new gr.nt({result:{case:"error",value:new gr.Gv({error:`Failed to write to shell ${r} stdin: ${e instanceof Error?e.message:"Unknown error"}`})}})}return new gr.nt({result:{case:"success",value:new gr.tR({shellId:r,terminalFileLengthBeforeInputWritten:0})}})}}class hb{constructor(e){this.pastElements=[],this.closed=!1,this.forks=new Set,this.consume(e)}async consume(e){try{for await(const t of e){this.pastElements.push(t);const e=[];for(const r of this.forks)e.push(r.write(t).catch((()=>{})));await Promise.allSettled(e)}}catch(e){this.error=e instanceof Error?e:new Error(String(e))}finally{this.closed=!0;for(const e of this.forks)this.error?e.throw(this.error):e.close();this.forks.clear()}}fork(){if(this.closed){const e=this.pastElements,t=this.error;return async function*(){for(const t of e)yield t;if(t)throw t}()}const e=(0,y.Jt)(),t=this.pastElements.slice();this.forks.add(e);const r=this;return async function*(){for(const e of t)yield e;try{for await(const t of e)yield t}finally{r.forks.delete(e)}}()}}function pb(e,t){return`${e}:${(0,Ts.createHash)("sha256").update(t.toBinary()).digest("hex")}`}function fb(e,t){const r=new Ns.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=pb(n.execId,o),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 mb=r("../proto/dist/generated/agent/v1/canvas_diagnostics_exec_pb.js"),gb=r("../proto/dist/generated/agent/v1/diagnostics_exec_pb.js");class wb{constructor(e,t){this.getCanvasDiagnostics=e,this.beginCanvasSave=t}async execute(e,t){let r=()=>{};const o=new Promise((e=>{r=e}));let n;if(void 0===this.beginCanvasSave)n=Promise.resolve(void 0);else try{n=this.beginCanvasSave(t.path,{typecheckOutcome:o}).catch((()=>{}))}catch{n=Promise.resolve(void 0)}try{const e=await this.getCanvasDiagnostics(t.path);return void 0===e?(r("unavailable"),yb(vb(t.path,"diagnostics unavailable"),await n)):(r(e.some((e=>1===e.severity))?"failed":"passed"),yb(new mb.GL({result:{case:"success",value:new mb.uX({path:t.path,diagnostics:e.map(bb)})}}),await n))}catch(e){return r("unavailable"),yb(vb(t.path,e instanceof Error?e.message:String(e)),await n)}}}function yb(e,t){return void 0===t||(e.saveState=t.saveState,e.canvasId=t.canvasId,e.title=t.title,e.saveDetail=t.saveDetail),e}function vb(e,t){return new mb.GL({result:{case:"error",value:new mb.HW({path:e,error:t})}})}function bb(e){return new gb.oQ({severity:Sb(e.severity),range:new ac.Q6({start:new ac.yX({line:e.range.start.line+1,column:e.range.start.character+1}),end:new ac.yX({line:e.range.end.line+1,column:e.range.end.character+1})}),message:e.message,source:"ts",code:e.code??""})}function Sb(e){switch(e){case 1:return gb.h_.ERROR;case 2:return gb.h_.WARNING;case 3:return gb.h_.INFORMATION;case 4:return gb.h_.HINT;default:return gb.h_.UNSPECIFIED}}class kb{constructor(e){if(e.startsWith("file://")){if(!this.isValidFileUrl(e))throw new Error(`Invalid file URL: ${e}`);this.urlString=e}else{const t=this.resolvePath(e);this.urlString=this.pathToFileUrl(t)}}isValidFileUrl(e){try{return"file:"===new URL(e).protocol}catch{return!1}}resolvePath(e){if(e.includes("\\")&&(e=e.replace(/\\/g,"/")),/^[a-zA-Z]:\//.test(e)||/^\//.test(e))return e;const t=e.split("/"),r=[];for(let e=0;e<t.length;e++){const o=t[e];".."===o?r.pop():"."!==o&&""!==o&&r.push(o)}return 0===r.length?".":`/${r.join("/")}`}pathToFileUrl(e){return/^[a-zA-Z]:\//.test(e)?`file:///${e.charAt(0).toLowerCase()}:${e.substring(2).replace(/\\/g,"/")}`:(e.startsWith("/")||(e=`/${e}`),`file://${encodeURIComponent(e).replace(/%2F/g,"/")}`)}fileUrlToPath(e){try{const t=new URL(e);if(t.pathname.startsWith("/")&&/^\/[a-zA-Z]:\//.test(t.pathname)){return`${t.pathname[1].toUpperCase()}:${t.pathname.substring(3)}`}return decodeURIComponent(t.pathname)}catch{throw new Error(`Invalid file URL format: ${e}`)}}get fsPath(){return this.toPath()}static fromPath(e){return new kb(e)}static fromUrl(e){if(!e.startsWith("file://"))throw new Error(`Expected file:// URL, got: ${e}`);return new kb(e)}static fromString(e){return new kb(e)}toPath(){return this.fileUrlToPath(this.urlString)}toString(){return this.urlString}serialize(){return this.toString()}toURL(){try{return new URL(this.urlString)}catch{throw new Error(`Invalid URL format: ${this.urlString}`)}}getFilename(){const e=this.toPath(),t=e.includes("\\")?"\\":"/";return e.split(t).pop()||""}getDirectory(){const e=this.toPath(),t=e.includes("\\")?"\\":"/",r=e.lastIndexOf(t);return-1===r?e:e.substring(0,r)}equals(e){return this.urlString===e.urlString}toJSON(){return this.toString()}}var Eb=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 Cb{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,i.VI)(e.withName("LocalDiagnosticsExecutor.execute")),!1),[e,o]=e.withTimeoutAndCancel(1e4);try{const r=(0,Gs.o1)(t.path,this.workspacePath);try{const e=await(0,Os.stat)(r);if(!e.isFile()&&!e.isDirectory())return new gb.Ek({result:{case:"fileNotFound",value:new gb.Mu({path:t.path})}})}catch(e){if("ENOENT"===e.code)return new gb.Ek({result:{case:"fileNotFound",value:new gb.Mu({path:t.path})}});if("EACCES"===e.code)return new gb.Ek({result:{case:"permissionDenied",value:new gb.RP({path:t.path})}});throw e}const o=(0,Gs.o1)(r,this.workspacePath),n=new kb(o);await this.diagnosticsProvider.open(e,n);const s=(await this.diagnosticsProvider.getDiagnostics(e,n)).map((e=>this.convertDiagnostic(e)));return new gb.Ek({result:{case:"success",value:new gb.a1({path:t.path,diagnostics:s,totalDiagnostics:s.length})}})}catch(r){return e.canceled?new gb.Ek({result:{case:"error",value:new gb.Ho({path:t.path,error:"Request timed out after 10 seconds"})}}):new gb.Ek({result:{case:"error",value:new gb.Ho({path:t.path,error:r instanceof Error?r.message:String(r)})}})}finally{o()}}catch(e){r.error=e,r.hasError=!0}finally{Eb(r)}}convertDiagnostic(e){const t=e.message,r="string"==typeof t?t:t&&"object"==typeof t&&"value"in t&&"string"==typeof t.value?t.value:"";return new gb.oQ({severity:this.convertSeverity(e.severity),range:e.range?new ac.Q6({start:new ac.yX({line:e.range.start.line,column:e.range.start.character}),end:new ac.yX({line:e.range.end.line,column:e.range.end.character})}):void 0,message:r,source:e.source,code:e.code?String(e.code):void 0})}convertSeverity(e){switch(e){case 1:return gb.h_.ERROR;case 2:return gb.h_.WARNING;case 3:return gb.h_.INFORMATION;case 4:return gb.h_.HINT;default:return gb.h_.UNSPECIFIED}}}async function xb(e){const{repoRoot:t,filePaths:r,getContent:o}=e,n=new Map;if(0===r.length)return n;const s=await async function(e,t){const r=new Map;if(0===t.length)return r;try{const o=await new Promise(((r,o)=>{const n=(0,Iu.spawn)("git",["check-attr","linguist-generated","--stdin"],{cwd:e});let s="";n.stdout.on("data",(e=>{s+=e.toString()})),n.stdin.write(`${t.join("\n")}\n`),n.stdin.end(),n.on("close",(e=>{r(s)})),n.on("error",(e=>{o(e)}))}));for(const e of o.trim().split("\n")){const t=e.match(/^(.+): linguist-generated: (.+)$/);if(t){const e=t[1],o=t[2];"true"===o||"set"===o?r.set(e,!0):"false"!==o&&"unset"!==o||r.set(e,!1)}}}catch{}return r}(t,r);return await Promise.all(r.map((async e=>{const t=s.get(e);if(!0!==t)if(!1!==t)if(function(e){return new _b(e).isGeneratedByPath()}(e))n.set(e,{isGenerated:!0,source:"path-heuristic"});else{if(o){const t=await o(e);if(void 0!==t&&function(e,t){return new _b(e,(()=>t)).isGeneratedByContent()}(e,t))return void n.set(e,{isGenerated:!0,source:"content-heuristic"})}n.set(e,{isGenerated:!1,source:"none"})}else n.set(e,{isGenerated:!1,source:"gitattributes"});else n.set(e,{isGenerated:!0,source:"gitattributes"})}))),n}class _b{constructor(e,t){this.name=e,this.extname=s.extname(e).toLowerCase(),this.getContent=t}get lines(){if(void 0===this.cachedLines){const e=this.getContent?.();this.cachedLines=e?e.split("\n"):[]}return this.cachedLines}get data(){return this.getContent?.()}isGeneratedByPath(){return this.xcodeFile()||this.intellijFile()||this.cocoapods()||this.carthageBuild()||this.generatedGraphqlRelay()||this.generatedNetDesignerFile()||this.generatedNetSpecflowFeatureFile()||this.composerLock()||this.cargoLock()||this.cargoOrig()||this.denoLock()||this.flakeLock()||this.bazelLock()||this.nodeModules()||this.goVendor()||this.goLock()||this.packageResolved()||this.poetryLock()||this.pdmLock()||this.uvLock()||this.pixiLock()||this.esyLock()||this.npmShrinkwrapOrPackageLock()||this.pnpmLock()||this.bunLock()||this.terraformLock()||this.generatedYarnPlugnplay()||this.godeps()||this.generatedByZephir()||this.htmlcov()||this.gradleWrapper()||this.mavenWrapper()||this.pipenvLock()||this.generatedPascalTlb()||this.generatedSqlxQuery()||this.sourceMapByName()}isGeneratedByContent(){return!!this.getContent&&(this.minifiedFiles()||this.hasSourceMap()||this.sourceMap()||this.compiledCoffeescript()||this.generatedParser()||this.generatedNetDocfile()||this.generatedPostscript()||this.compiledCythonFile()||this.generatedGo()||this.generatedProtocolBufferFromGo()||this.generatedProtocolBuffer()||this.generatedJavascriptProtocolBuffer()||this.generatedTypescriptProtocolBuffer()||this.generatedApacheThrift()||this.generatedJniHeader()||this.vcrCassette()||this.generatedAntlr()||this.generatedModule()||this.generatedUnity3dMeta()||this.generatedRacc()||this.generatedJflex()||this.generatedGrammarkit()||this.generatedRoxygen2()||this.generatedHtml()||this.generatedJison()||this.generatedGrpcCpp()||this.generatedDart()||this.generatedPerlPpportHeader()||this.generatedGamemakerstudio()||this.generatedGimp()||this.generatedVisualstudio6()||this.generatedHaxe()||this.generatedJooq()||this.generatedSorbetRbi()||this.generatedMysqlViewDefinitionFormat())}xcodeFile(){return[".nib",".xcworkspacedata",".xcuserstate"].includes(this.extname)}intellijFile(){return/(?:^|\/)\.idea\//.test(this.name)}cocoapods(){return/(^Pods|\/Pods)\//.test(this.name)}carthageBuild(){return/(^|\/)Carthage\/Build\//.test(this.name)}generatedGraphqlRelay(){return/__generated__\//.test(this.name)}generatedNetDesignerFile(){return/\.designer\.(cs|vb)$/i.test(this.name)}generatedNetSpecflowFeatureFile(){return/\.feature\.cs$/i.test(this.name)}composerLock(){return/composer\.lock/.test(this.name)}cargoLock(){return/Cargo\.lock/.test(this.name)}cargoOrig(){return/Cargo\.toml\.orig/.test(this.name)}denoLock(){return/deno\.lock/.test(this.name)}flakeLock(){return/(^|\/)flake\.lock$/.test(this.name)}bazelLock(){return/(^|\/)MODULE\.bazel\.lock$/.test(this.name)}nodeModules(){return/node_modules\//.test(this.name)}goVendor(){return/vendor\/((?!-)[-0-9A-Za-z]+(?<!-)\.)+(com|edu|gov|in|me|net|org|fm|io)/.test(this.name)}goLock(){return/(Gopkg|glide)\.lock/.test(this.name)}packageResolved(){return/Package\.resolved/.test(this.name)}poetryLock(){return/poetry\.lock/.test(this.name)}pdmLock(){return/pdm\.lock/.test(this.name)}uvLock(){return/uv\.lock/.test(this.name)}pixiLock(){return/pixi\.lock/.test(this.name)}esyLock(){return/(^|\/)(\w+\.)?esy\.lock$/.test(this.name)}npmShrinkwrapOrPackageLock(){return/npm-shrinkwrap\.json/.test(this.name)||/package-lock\.json/.test(this.name)}pnpmLock(){return/pnpm-lock\.yaml/.test(this.name)}bunLock(){return/(?:^|\/)bun\.lockb?$/.test(this.name)}terraformLock(){return/(?:^|\/)\.terraform\.lock\.hcl$/.test(this.name)}generatedYarnPlugnplay(){return/(^|\/)\.pnp\..*$/.test(this.name)}godeps(){return/Godeps\//.test(this.name)}generatedByZephir(){return/\.zep\.(c|h|php)$/.test(this.name)}htmlcov(){return/(?:^|\/)htmlcov\//.test(this.name)}gradleWrapper(){return/(?:^|\/)gradlew(?:\.bat)?$/i.test(this.name)}mavenWrapper(){return/(?:^|\/)mvnw(?:\.cmd)?$/i.test(this.name)}pipenvLock(){return/Pipfile\.lock/.test(this.name)}generatedPascalTlb(){return/_tlb\.pas$/i.test(this.name)}generatedSqlxQuery(){return/(?:^|\/)\.sqlx\/query-[a-f\d]{64}\.json$/.test(this.name)}sourceMapByName(){return/\.(css|js)\.map$/i.test(this.name)}maybeMinified(){return[".js",".css"].includes(this.extname)}minifiedFiles(){return!(!this.maybeMinified()||0===this.lines.length)&&this.lines.reduce(((e,t)=>e+t.length),0)/this.lines.length>110}hasSourceMap(){return!!this.maybeMinified()&&this.lines.slice(-2).some((e=>/^\/[*/][#@] source(?:Mapping)?URL|sourceURL=/.test(e)))}sourceMap(){if(".map"!==this.extname)return!1;if(/\.(css|js)\.map$/i.test(this.name))return!0;const e=this.lines[0]||"";return/^{"version":\d+,/.test(e)||/^\/\*\* Begin line maps\. \*\*\/{/.test(e)}compiledCoffeescript(){if(".js"!==this.extname)return!1;const e=this.lines[0]||"";if(/^\/\/ Generated by /.test(e))return!0;if("(function() {"===e&&"}).call(this);"===(this.lines[this.lines.length-2]||"")&&""===(this.lines[this.lines.length-1]||"")){let e=0;for(const t of this.lines)if(/var /.test(t)){const r=t.match(/_fn|_i|_len|_ref|_results/g);e+=1*(r?.length||0);const o=t.match(/__bind|__extends|__hasProp|__indexOf|__slice/g);e+=3*(o?.length||0)}return e>=3}return!1}generatedNetDocfile(){return".xml"===this.extname&&!(this.lines.length<=3)&&(this.lines[1]||"").includes("<doc>")&&(this.lines[2]||"").includes("<assembly>")&&(this.lines[this.lines.length-2]||"").includes("</doc>")}generatedParser(){if(".js"!==this.extname)return!1;const e=this.lines.slice(0,5).join("");return/^(?:[^/]|\/[^*])*\/\*(?:[^*]|\*[^/])*Generated by PEG\.js/.test(e)}generatedPostscript(){if(![".ps",".eps",".pfa"].includes(this.extname))return!1;const e=this.data;if(!e)return!1;if(/^\s*(?:currentfile eexec\s+|\/sfnts\s+\[\s<)/.test(e))return!0;const t=this.lines.slice(0,10).find((e=>/^%%Creator: /.test(e)));return!!t&&(!(!/[0-9]|draw|mpage|ImageMagick|inkscape|MATLAB/.test(t)&&!/PCBNEW|pnmtops|\(Unknown\)|Serif Affinity|Filterimage -tops/.test(t))||!!t.includes("EAGLE")&&this.lines.slice(0,5).some((e=>/^%%Title: EAGLE Drawing /.test(e))))}generatedGo(){return".go"===this.extname&&!(this.lines.length<=1)&&this.lines.slice(0,40).some((e=>/^\/\/ Code generated .*/.test(e)))}generatedProtocolBufferFromGo(){return".proto"===this.extname&&!(this.lines.length<=1)&&this.lines.slice(0,20).some((e=>e.includes("This file was autogenerated by go-to-protobuf")))}generatedProtocolBuffer(){return!![".py",".java",".h",".cc",".cpp",".m",".rb",".php"].includes(this.extname)&&!(this.lines.length<=1)&&this.lines.slice(0,3).some((e=>e.includes("Generated by the protocol buffer compiler. DO NOT EDIT!")))}generatedJavascriptProtocolBuffer(){return".js"===this.extname&&!(this.lines.length<=6)&&(this.lines[5]||"").includes("GENERATED CODE -- DO NOT EDIT!")}generatedTypescriptProtocolBuffer(){return".ts"===this.extname&&!(this.lines.length<=4)&&(this.lines[0]||"").includes("Code generated by protoc-gen-ts_proto. DO NOT EDIT.")}generatedApacheThrift(){return!![".rb",".py",".go",".js",".m",".java",".h",".cc",".cpp",".php"].includes(this.extname)&&this.lines.slice(0,6).some((e=>e.includes("Autogenerated by Thrift Compiler")))}generatedJniHeader(){return".h"===this.extname&&!(this.lines.length<=2)&&(this.lines[0]||"").includes("/* DO NOT EDIT THIS FILE - it is machine generated */")&&(this.lines[1]||"").includes("#include <jni.h>")}vcrCassette(){return".yml"===this.extname&&!(this.lines.length<=2)&&(this.lines[this.lines.length-2]||"").includes("recorded_with: VCR")}generatedAntlr(){return".g"===this.extname&&!(this.lines.length<=2)&&(this.lines[1]||"").includes("generated by Xtest")}compiledCythonFile(){return!![".c",".cpp"].includes(this.extname)&&!(this.lines.length<=1)&&(this.lines[0]||"").includes("Generated by Cython")}generatedModule(){if(".mod"!==this.extname)return!1;if(this.lines.length<=1)return!1;const e=this.lines[0]||"";return e.includes("PCBNEW-LibModule-V")||e.includes("GFORTRAN module version '")}generatedUnity3dMeta(){return".meta"===this.extname&&!(this.lines.length<=1)&&(this.lines[0]||"").includes("fileFormatVersion: ")}generatedRacc(){return".rb"===this.extname&&!(this.lines.length<=2)&&(this.lines[2]||"").startsWith("# This file is automatically generated by Racc")}generatedJflex(){return".java"===this.extname&&!(this.lines.length<=1)&&(this.lines[0]||"").startsWith("/* The following code was generated by JFlex ")}generatedGrammarkit(){return".java"===this.extname&&!(this.lines.length<=1)&&(this.lines[0]||"").startsWith("// This is a generated file. Not intended for manual editing.")}generatedRoxygen2(){return".rd"===this.extname&&!(this.lines.length<=1)&&(this.lines[0]||"").includes("% Generated by roxygen2: do not edit by hand")}generatedHtml(){if(![".html",".htm",".xhtml"].includes(this.extname))return!1;if(this.lines.length<=1)return!1;if(this.lines.slice(0,2).some((e=>/<!-- Generated by pkgdown: do not edit by hand -->/.test(e))))return!0;if(this.lines.length>2&&(this.lines[2]||"").startsWith("\x3c!-- This is an automatically generated file."))return!0;if(this.lines.slice(0,31).some((e=>/<!--\s+Generated by Doxygen\s+[.0-9]+\s*-->/i.test(e))))return!0;const e=this.lines.slice(0,31).join(" ").match(/<meta(\s+[^>]+)>/gi);if(!e)return!1;for(const t of e){const e=this.extractHtmlMeta(t);if("generator"===e.name?.toLowerCase()&&(e.content||e.value)){const t=e.content||e.value||"";if(/^(org\s+mode|j?latex2html|groff|makeinfo|texi2html|ronn)\b/i.test(t))return!0}}return!1}extractHtmlMeta(e){const t={},r=e.matchAll(/(?<=^|\s)(name|content|value)\s*=\s*("[^"]+"|'[^']+'|[^\s"']+)/gi);for(const e of r){const r=e[1].toLowerCase();let o=e[2];(o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'"))&&(o=o.slice(1,-1)),t[r]=o}return t}generatedJison(){if(".js"!==this.extname)return!1;if(this.lines.length<=1)return!1;const e=this.lines[0]||"";return e.startsWith("/* parser generated by jison ")||e.startsWith("/* generated by jison-lex ")}generatedGrpcCpp(){return!![".cpp",".hpp",".h",".cc"].includes(this.extname)&&!(this.lines.length<=1)&&(this.lines[0]||"").startsWith("// Generated by the gRPC")}generatedDart(){return".dart"===this.extname&&!(this.lines.length<=1)&&this.lines.slice(0,3).some((e=>/generated code\W{2,3}do not modify/i.test(e)))}generatedPerlPpportHeader(){return!!/ppport\.h$/.test(this.name)&&!(this.lines.length<=10)&&(this.lines[8]||"").includes("Automatically created by Devel::PPPort")}generatedGamemakerstudio(){if(![".yy",".yyp"].includes(this.extname))return!1;if(this.lines.length<=3)return!1;const e=this.lines.slice(0,3).join("");return/^\s*[{[]/.test(e)||/^\d\.\d\.\d.+\|\{/.test(this.lines[0]||"")}generatedGimp(){if(![".c",".h"].includes(this.extname))return!1;if(0===this.lines.length)return!1;const e=this.lines[0]||"";return/^\/\* GIMP [a-zA-Z0-9- ]+ C-Source image dump \(.+?\.c\) \*\//.test(e)||/^\/\* {2}GIMP header image file format \([a-zA-Z0-9- ]+\): .+?\.h {2}\*\//.test(e)}generatedVisualstudio6(){return".dsp"===this.extname&&this.lines.slice(0,3).some((e=>e.includes("# Microsoft Developer Studio Generated Build File")))}generatedHaxe(){return!![".js",".py",".lua",".cpp",".h",".java",".cs",".php"].includes(this.extname)&&this.lines.slice(0,3).some((e=>e.includes("Generated by Haxe")))}generatedJooq(){return".java"===this.extname&&this.lines.slice(0,2).some((e=>e.includes("This file is generated by jOOQ.")))}generatedSorbetRbi(){return".rbi"===this.extname&&!(this.lines.length<5)&&/^# typed:/.test(this.lines[0]||"")&&(this.lines[2]||"").includes("DO NOT EDIT MANUALLY")&&/^# Please (run|instead update this file by running) `bin\/tapioca/.test(this.lines[4]||"")}generatedMysqlViewDefinitionFormat(){return".frm"===this.extname&&(this.lines[0]||"").includes("TYPE=VIEW")}}const Pb=e=>{if(!e)return[];if("string"!=typeof e||e.match(/^\s+$/))return[];const t=e.split("\n");if(0===t.length)return[];const r=[];let o=null,n=null,s=0,i=0,a=null;const c=e=>{n?.changes.push({type:"normal",normal:!0,ln1:s++,ln2:i++,content:e}),a.oldLines--,a.newLines--},l=e=>{const[t,n]=Tb(e)??[];o={chunks:[],deletions:0,additions:0,from:t,to:n},r.push(o)},u=()=>{o&&!o.chunks.length||l()},d=e=>+(e||1),h=e=>{n&&(n.changes.push({type:"del",del:!0,ln:s++,content:e}),o.deletions++,a.oldLines--)},p=e=>{n&&(n.changes.push({type:"add",add:!0,ln:i++,content:e}),o.additions++,a.newLines--)},f=e=>{if(!n)return;const[t]=n.changes.slice(-1);n.changes.push({type:t.type,[t.type]:!0,ln1:t.ln1,ln2:t.ln2,ln:t.ln,content:e})},m=[[/^diff\s/,l],[/^new file mode (\d+)$/,(e,t)=>{u(),o.new=!0,o.newMode=t[1],o.from="/dev/null"}],[/^deleted file mode (\d+)$/,(e,t)=>{u(),o.deleted=!0,o.oldMode=t[1],o.to="/dev/null"}],[/^old mode (\d+)$/,(e,t)=>{u(),o.oldMode=t[1]}],[/^new mode (\d+)$/,(e,t)=>{u(),o.newMode=t[1]}],[/^index\s[\da-zA-Z]+\.\.[\da-zA-Z]+(\s(\d+))?$/,(e,t)=>{u(),o.index=e.split(" ").slice(1),t[1]&&(o.oldMode=o.newMode=t[1].trim())}],[/^---\s/,e=>{u(),o.from=Mb(e)}],[/^\+\+\+\s/,e=>{u(),o.to=Mb(e)}],[/^@@\s+-(\d+),?(\d+)?\s+\+(\d+),?(\d+)?\s@@/,(e,t)=>{o||l(e);const[r,c,u,h]=t.slice(1);s=+r,i=+u,n={content:e,changes:[],oldStart:+r,oldLines:d(c),newStart:+u,newLines:d(h)},a={oldLines:d(c),newLines:d(h)},o.chunks.push(n)}],[/^\$/,f]],g=[[/^\$/,f],[/^-/,h],[/^\+/,p],[/^\s+/,c]],w=e=>{a?(e=>{const t=e.charCodeAt(0);if(43===t)p(e);else if(45===t)h(e);else if(32===t)c(e);else if(92===t&&/^\$/.test(e))f(e);else for(const[t,r]of g){const o=e.match(t);if(o){r(e,o);break}}0===a.oldLines&&0===a.newLines&&(a=null)})(e):(e=>{for(const[t,r]of m){const o=e.match(t);if(o){r(e,o);break}}})(e)};for(const e of t)w(e);return r},Ib=/(a|i|w|c|o|1|2)\/.*(?=["']? ["']?(b|i|w|c|o|1|2)\/)|(b|i|w|c|o|1|2)\/.*$/g,Rb=/^(a|b|i|w|c|o|1|2)\//,Tb=e=>{const t=e?.match(Ib);return t?.map((e=>e.replace(Rb,"").replace(/("|')$/,"")))},Ab=/^\\?['"]|\\?['"]$/g,Mb=e=>{let t=Db(e,"-+").trim();return t=Nb(t),t.replace(Ab,"").replace(Rb,"")},Db=(e,t)=>{if(e=Fb(e),!t&&String.prototype.trimLeft)return e.trimLeft();const r=$b(t);return e.replace(new RegExp(`^${r}+`),"")},Ob=/\t.*|\d{4}-\d\d-\d\d\s\d\d:\d\d:\d\d(.\d+)?\s(\+|-)\d\d\d\d/,Nb=e=>{const t=Ob.exec(e);return t&&(e=e.substring(0,t.index).trim()),e},$b=e=>null==e?"\\s":e instanceof RegExp?e.source:`[${Fb(e).replace(/([.*+?^=!:${}()|[\]/\\])/g,"\\$1")}]`,Fb=e=>`${e??""}`,jb=(0,m.h)("local-mercurial-diff"),Lb=5242880,Ub="0000000000000000000000000000000000000000";let Bb,Wb;async function Hb(e,t,r={}){const o=await async function(){if(void 0===Bb&&(Bb=await async function(e){const t="win32"===process.platform?["hg.com","hg.exe"]:["hg"];for(const r of e.split(s.default.delimiter))if(s.default.isAbsolute(r))for(const e of t){const t=s.default.join(r,e);try{if(!(await Os.stat(t)).isFile())continue;return"win32"!==process.platform&&await Os.access(t,$s.constants.X_OK),t}catch{}}}(process.env.PATH??"")??null),null===Bb){const e=new Error("hg executable not found");throw e.code="ENOENT",e}return Bb}();return await new Promise(((n,s)=>{const i=(0,Iu.spawn)(o,t,{cwd:e,env:{...process.env,HGPLAIN:"+strictflags",HGRCPATH:"",HGRCSKIPREPO:"1"},shell:!1});let a="";i.stdout.on("data",(e=>{a+=e.toString()})),i.stderr.on("data",(()=>{})),i.on("error",(e=>{!0===r.allowFailure?n(""):s(e)})),i.on("close",(e=>{if(0===e||!0===r.allowFailure)n(a);else{const r=t.find((e=>!e.startsWith("-")))??"hg";s(new Error(`MercurialDiffFailed: hg ${r} exited ${e??"unknown"}`))}}))}))}async function qb(e){const t=await async function(e){let t=s.default.resolve(e);for(;;){try{if((await Os.stat(s.default.join(t,".hg"))).isDirectory())return!0}catch{}const e=s.default.dirname(t);if(e===t)return!1;t=e}}(e);if(!t)return;const r=function(e,t){return e&&"absent"!==t?"skips-repo-config"!==t?"unsafe":"proceed":"not-mercurial"}(t,await async function(){if(void 0!==Wb)return Wb;const e=await Os.mkdtemp(s.default.join((0,n.tmpdir)(),"hg-probe-"));try{const t=await Hb(e,["help","environment"]);Wb=/\bHGRCSKIPREPO\b/.test(t)?"skips-repo-config":"reads-repo-config"}catch(e){Wb=function(e){return"object"==typeof e&&null!==e&&"code"in e&&"ENOENT"===e.code}(e)?"absent":"reads-repo-config"}finally{await Os.rm(e,{recursive:!0,force:!0})}return Wb}());if("not-mercurial"===r)return;if("unsafe"===r)throw new Error("MercurialClientUnsafe: hg would read repository config");let o;try{o=(await Hb(e,["root"])).trim()}catch{return}if(0!==o.length)try{return(await Os.stat(s.default.join(o,".hg"))).isDirectory()?o:void 0}catch{return}}function zb(e,t){return"win32"===process.platform?s.default.win32.normalize(e).toLowerCase()===s.default.win32.normalize(t).toLowerCase():s.default.resolve(e)===s.default.resolve(t)}function Gb(e,t){const r=s.default.relative(s.default.resolve(t),s.default.resolve(e));return 0===r.length||!s.default.isAbsolute(r)&&!r.split(s.default.sep).includes("..")}async function Vb(e){const t=s.default.resolve(e);try{return await Os.realpath(t)}catch{return t}}function Jb(e){if(0===e.length)return[];const t=e.replace(/\r\n/g,"\n").replace(/\r/g,"\n"),r=t.split("\n");return t.endsWith("\n")&&r.pop(),r}function Kb(e){if(e.includes("\0")||/[\r\n]/.test(e))throw new Error("MercurialDiffFailed: base ref contains a newline")}async function Zb({repositoryRoot:e,rev:t,filePath:r}){const o=await async function({repositoryRoot:e,rev:t,filePath:r}){let o;try{o=await Hb(e,["files","-r",t,"-T","{size}","--",r])}catch{return}const n=o.trim();if(!/^\d+$/.test(n))return;const s=Number(n);return Number.isFinite(s)?s:void 0}({repositoryRoot:e,rev:t,filePath:r});return void 0===o||o>Lb?"":Hb(e,["cat","-r",t,"--",r])}async function Xb(e,t,r){const o=function(e){switch(e){case Po.ek.NAME_STATUS:return Po.ek.NAME_STATUS;case Po.ek.NAME_STATUS_AND_NUMSTAT:return Po.ek.NAME_STATUS_AND_NUMSTAT;case Po.ek.FILE_DIFFS:return Po.ek.FILE_DIFFS;case Po.ek.DIFFS_WITH_BEFORE_AND_AFTER:return Po.ek.DIFFS_WITH_BEFORE_AND_AFTER;default:return Po.ek.FILE_DIFFS}}(r.outputFormat),n=["root"],i=(await Hb(t,["root"])).trim();if(0===i.length)throw new Error("MercurialDiffFailed: hg root did not resolve");let a,c;if(0!==r.ref.length||"HEAD"!==r.baseRef&&(r.mergeBase||0!==r.baseRef.length)){if(r.mergeBase||0===r.baseRef.length)a=await async function({cwd:e,baseRef:t,commands:r}){if(t.length>0&&"HEAD"!==t){Kb(t),r.push("log");const o=(await Hb(e,["log","-r",`ancestor(., (${t}))`,"-T","{node}"])).trim();if(0===o.length||o===Ub)throw new Error("MercurialDiffFailed: base ref did not resolve");return o}r.push("log");const o=(await Hb(e,["log","-r","max(::. and public())","-T","{node}"],{allowFailure:!0})).trim();if(o.length>0&&o!==Ub)return o;const n=(await Hb(e,["log","-r","ancestor(., default)","-T","{node}"],{allowFailure:!0})).trim();if(n.length>0&&n!==Ub)return n;const s=(await Hb(e,["log","-r",".","-T","{node}"],{allowFailure:!0})).trim();return s.length>0?s:Ub}({cwd:t,baseRef:r.baseRef,commands:n});else if(Kb(r.baseRef),n.push("log"),a=(await Hb(t,["log","-r",r.baseRef,"-T","{node}"])).trim(),0===a.length)throw new Error("MercurialDiffFailed: base ref did not resolve");r.ref.length>0&&(Kb(r.ref),n.push("log"),c=(await Hb(t,["log","-r",r.ref,"-T","{node}"])).trim())}const l=["diff","--git"];r.includeSpaceChanges||l.push("-b"),void 0!==r.unifiedContextLines&&l.push(`-U${r.unifiedContextLines}`),void 0!==a&&l.push("-r",a),void 0!==c&&l.push("-r",c),r.targetPaths.length>0&&l.push("--",...r.targetPaths),n.push("diff");const u=await Hb(t,l),d=function(e){const t=e.replace(/\r\n/g,"\n");return new Po.o$({diffs:Pb(t).map((e=>function(e){const t=new Po.QP({from:e.from,to:e.to,chunks:e.chunks.map((e=>new Po.Ei({content:e.content,lines:e.changes.map((e=>e.content)),oldStart:e.oldStart,oldLines:e.oldLines,newStart:e.newStart,newLines:e.newLines})))});return t.added=e.additions,t.removed=e.deletions,t}(e))),diffType:Po.Wf.UNSPECIFIED})}(u);let h=[];if(r.maxUntrackedFiles>0&&(n.push("status"),h=await async function({cwd:e,repositoryRoot:t,maxUnknownFiles:r}){let o=(await Hb(e,["status","-un0"])).split("\0").filter((e=>e.length>0));return o.length>r&&(o=o.slice(0,r)),(await Promise.all(o.map((async e=>{try{const r=s.default.join(t,e),o=await Os.stat(r);if(o.size>Lb){const t=await async function(e){const t=(0,Ts.createHash)("sha256"),r=await Os.open(e,"r");try{const e=Buffer.alloc(65536);let o=0;for(;;){const{bytesRead:n}=await r.read(e,0,e.length,o);if(0===n)break;t.update(e.subarray(0,n)),o+=n}}finally{await r.close()}return t.digest("hex")}(r);return{contents:"",path:e,omittedDueToSize:!0,byteSize:o.size,contentHash:t}}return{contents:await Os.readFile(r,"utf8"),path:e}}catch{return}})))).filter((e=>void 0!==e))}({cwd:t,repositoryRoot:i,maxUnknownFiles:r.maxUntrackedFiles}),d.diffs.push(...h.map((e=>function(e){if(!0===e.omittedDueToSize)return new Po.QP({from:"/dev/null",to:e.path,chunks:[],added:0,removed:0});const t=Jb(e.contents);if(0===t.length)return new Po.QP({from:"/dev/null",to:e.path,chunks:[],added:0,removed:0});const r=t.length;return new Po.QP({from:"/dev/null",to:e.path,chunks:[new Po.Ei({content:`@@ -0,0 +1${1===r?"":`,${r}`} @@`,lines:t.map((e=>`+${e}`)),oldStart:0,oldLines:0,newStart:1,newLines:r})],added:r,removed:0})}(e))))),o!==Po.ek.FILE_DIFFS)for(const e of d.diffs)e.chunks=[];if(o===Po.ek.DIFFS_WITH_BEFORE_AND_AFTER){const e=a??".";await Promise.all(d.diffs.map((async t=>{if("/dev/null"!==t.from)try{t.beforeFileContents=await Zb({repositoryRoot:i,rev:e,filePath:t.from})}catch{t.beforeFileContents=""}else t.beforeFileContents="";if("/dev/null"!==t.to)if(void 0===c)try{const e=s.default.join(i,t.to),r=await Os.stat(e);t.afterFileContents=r.size>Lb?"":await Os.readFile(e,"utf8")}catch{t.afterFileContents=""}else try{t.afterFileContents=await Zb({repositoryRoot:i,rev:c,filePath:t.to})}catch{t.afterFileContents=""}else t.afterFileContents=""})))}const p=[u,function(e){const t=[];for(const r of e){const e=Jb(r.contents);if(t.push(`diff --git a/${r.path} b/${r.path}`),t.push("new file mode 100644"),t.push("--- /dev/null"),t.push(`+++ b/${r.path}`),0===e.length)continue;const o=e.length;t.push(`@@ -0,0 +1${1===o?"":`,${o}`} @@`),t.push(...e.map((e=>`+${e}`)))}return t.join("\n")}(h.filter((e=>!0!==e.omittedDueToSize))),h.filter((e=>!0===e.omittedDueToSize)).map((e=>`omitted-untracked ${e.byteSize??0} ${e.contentHash??""} ${JSON.stringify(e.path)}`)).join("\n")].filter((e=>e.length>0)).join("\n"),f=!0===r.computePatchId?function(e){if(0!==e.length)return`hg:${(0,Ts.createHash)("sha256").update(e).digest("hex")}`}(p.length>0?`${p}\n`:""):void 0;let m,g;if(!0===r.returnHeadSha){n.push("log","status");const e=(await Hb(t,["log","-r",".","-T","{node}"],{allowFailure:!0})).trim();m=e.length>0?e:Ub,g=(await Hb(t,["status","-0"])).length>0}jb.info(e,"Local mercurial diff commands",{sourceControl:"mercurial",commands:n});const w=new Po.df({diff:d,submoduleDiffs:[],patchId:f,headSha:m,hasUncommittedChanges:g}),y=r.maxResponseBytes??0;if(y>0){const t=w.toBinary().byteLength;if(t>y)throw jb.info(e,"Local diff outcome",{sourceControl:"mercurial",outcome:"too_large"}),new Error(`GetDiffResponseTooLarge: ${t} bytes exceeds the ${y} byte limit`)}return jb.info(e,"Local diff outcome",{sourceControl:"mercurial",outcome:"ok",fileCount:d.diffs.length,patchIdPrefixed:!0===f?.startsWith("hg:")}),w}const Qb=(0,m.h)("local-git-diff");async function Yb(e,t,r={}){const o=await new Promise(((o,n)=>{const s=Uu("git",t,{cwd:e});let i="",a="";s.stdout.on("data",(e=>{i+=e.toString()})),s.stderr.on("data",(e=>{a+=e.toString()})),s.on("close",(e=>{0===e||!0===r.ignoreErrors?o(i):n(new Error(`Git command failed with code ${e}: ${a}`))})),s.on("error",(e=>{!0===r.ignoreErrors?o(i):n(e)}))}));return!0===r.shouldNotTrimOutput?o:o.trim()}function eS(e){const t=Pb(e);return new Po.o$({diffs:t.map((e=>function(e){const t=new Po.QP({from:e.from,to:e.to,chunks:e.chunks.map((e=>new Po.Ei({content:e.content,lines:e.changes.map((e=>e.content)),oldStart:e.oldStart,oldLines:e.oldLines,newStart:e.newStart,newLines:e.newLines})))});return t.added=e.additions,t.removed=e.deletions,t}(e))),diffType:Po.Wf.UNSPECIFIED})}const tS=["main","master","develop"];async function rS(e,t,r){const o=await async function(e){let t;try{const r=(await Yb(e,["rev-parse","--show-toplevel"])).trim();r.length>0&&(t=r)}catch{}if(void 0!==t){const r=await async function({cwd:e,gitRoot:t}){const r=await Vb(t);let o=await Vb(e);if(zb(o,r))return;let n=!1;for(;Gb(o,r)&&!zb(o,r);){try{if((await Os.stat(s.default.join(o,".hg"))).isDirectory()){n=!0;break}}catch{}const e=s.default.dirname(o);if(e===o)break;o=e}return n?qb(e):void 0}({cwd:e,gitRoot:t});return void 0!==r?"mercurial":"git"}return void 0===await qb(e)?"none":"mercurial"}(t);if(Qb.info(e,"Local diff source control",{sourceControl:o}),"none"===o)throw Qb.info(e,"Local diff outcome",{sourceControl:o,outcome:"no_version_control"}),new Error("NoVersionControl: no git or mercurial repository");if("mercurial"===o)return Xb(e,t,r);const n=function(e){switch(e){case Po.ek.NAME_STATUS:return Po.ek.NAME_STATUS;case Po.ek.NAME_STATUS_AND_NUMSTAT:return Po.ek.NAME_STATUS_AND_NUMSTAT;case Po.ek.FILE_DIFFS:return Po.ek.FILE_DIFFS;case Po.ek.DIFFS_WITH_BEFORE_AND_AFTER:return Po.ek.DIFFS_WITH_BEFORE_AND_AFTER;default:return Po.ek.FILE_DIFFS}}(r.outputFormat),i=await(async()=>{let e=r.baseRef.length>0?r.baseRef:await async function(e){try{const t=await Yb(e,["symbolic-ref","--short","refs/remotes/origin/HEAD"]);if(t)return t.trim()}catch{}for(const t of tS){const r=`origin/${t}`;try{return await Yb(e,["rev-parse","--verify",r]),r}catch{}}try{const t=(await Yb(e,["branch","-r"])).split("\n").map((e=>e.trim())).find((e=>e.startsWith("origin/")));if(t)return t}catch{}try{const t=await Yb(e,["config","--get","init.defaultBranch"]);if(t)return t.trim()}catch{}throw new Error("Could not determine default branch")}(t);return r.mergeBase&&(e=(await Yb(t,["merge-base",e,r.ref.length>0?r.ref:"HEAD"])).trim()),e})(),a=["diff","--no-color"];r.includeSpaceChanges||a.push("--ignore-space-change"),void 0!==r.unifiedContextLines&&a.push(`-U${r.unifiedContextLines}`),a.push(i),r.ref.length>0&&a.push(r.ref),r.targetPaths.length>0&&(a.push("--"),a.push(...r.targetPaths));const c=await Yb(t,a,{shouldNotTrimOutput:!0}),l=eS(c);let u=[];if(r.maxUntrackedFiles>0){u=await async function(e,t){let r=(await Yb(e,["ls-files","--others","--exclude-standard"])).split("\n").map((e=>e.trim())).filter((e=>e.length>0));return r.length>t&&(r=r.slice(0,t)),(await Promise.all(r.map((async t=>{try{return{contents:await Os.readFile(s.default.join(e,t),"utf8"),path:t}}catch{return}})))).filter((e=>void 0!==e))}(t,r.maxUntrackedFiles);for(const e of u){const r=await Yb(t,["diff","--no-color","--no-index","/dev/null",e.path],{ignoreErrors:!0,shouldNotTrimOutput:!0});l.diffs.push(...eS(r).diffs)}}if(n!==Po.ek.FILE_DIFFS)for(const e of l.diffs)e.chunks=[];if(n===Po.ek.DIFFS_WITH_BEFORE_AND_AFTER){const o=r.ref.length>0?r.ref:"HEAD";await Promise.all(l.diffs.map((async n=>{try{if("/dev/null"!==n.from)try{n.beforeFileContents=await Yb(t,["show",`${i}:${n.from}`],{shouldNotTrimOutput:!0})}catch{n.beforeFileContents=""}else n.beforeFileContents="";if("/dev/null"!==n.to)if(r.ref.length>0)try{n.afterFileContents=await Yb(t,["show",`${o}:${n.to}`],{shouldNotTrimOutput:!0})}catch{n.afterFileContents=""}else try{n.afterFileContents=await Os.readFile(s.default.join(t,n.to),"utf8")}catch{try{n.afterFileContents=await Yb(t,["show",`${o}:${n.to}`],{shouldNotTrimOutput:!0})}catch{n.afterFileContents=""}}else n.afterFileContents=""}catch(t){Qb.error(e,"Error fetching file contents for diff",t)}})))}const d=new Map;for(const e of l.diffs){const t="/dev/null"!==e.to?e.to:e.from;t&&d.set(t,e)}const h=[...d.keys()],p=r.ref.length>0?r.ref:"HEAD";try{const e=await xb({repoRoot:t,filePaths:h,getContent:async e=>{const r=d.get(e);if(r){if(void 0!==r.afterFileContents)return r.afterFileContents;try{if(r.to&&"/dev/null"!==r.to)return await Yb(t,["show",`${p}:${r.to}`],{shouldNotTrimOutput:!0})}catch{}}}});for(const[t,r]of e){const e=d.get(t);e&&(e.isGenerated=r.isGenerated)}}catch(t){Qb.warn(e,"Generated-file detection failed; continuing without it",{error:t instanceof Error?t.message:String(t)})}const f=!0===r.computePatchId?await async function(e,t){if(0===t.length)return;return(await new Promise(((r,o)=>{const n=Uu("git",["patch-id","--stable"],{cwd:e});let s="",i="";n.stdout.on("data",(e=>{s+=e.toString()})),n.stderr.on("data",(e=>{i+=e.toString()})),n.on("close",(e=>{0===e?r(s):o(new Error(`git patch-id failed with code ${e}: ${i}`))})),n.on("error",o),n.stdin.end(t)}))).trim().split(/\s+/)[0]||void 0}(t,function(...e){const t=e.filter((e=>e.length>0));return 0===t.length?"":`${t.join("\n")}\n`}(c,function(e){const t=[];for(const o of e){const e={body:`+${(r=o.contents).replaceAll("\n","\n+")}`,numLines:Bi(r)},n=1===e.numLines?"@@ -0,0 +1 @@":`@@ -0,0 +1,${e.numLines} @@`;t.push(`diff --git a/${o.path} b/${o.path}\n--- /dev/null\n+++ b/${o.path}\n${n}\n${e.body}`)}var r;return t.join("\n")}(u))):void 0,m=!0===r.returnHeadSha?(await Yb(t,["rev-parse","HEAD"])).trim():void 0,g=!0===r.returnHeadSha?(await Yb(t,["status","--porcelain=v1","--untracked-files=all"])).trim().length>0:void 0,w=new Po.df({diff:l,submoduleDiffs:[],patchId:f,headSha:m,hasUncommittedChanges:g}),y=r.maxResponseBytes??0;if(y>0){const e=w.toBinary().byteLength;if(e>y)throw new Error(`GetDiffResponseTooLarge: ${e} bytes exceeds the ${y} byte limit`)}return w}class oS{async execute(e,t){return rS(e,t.cwd,t)}}var nS=r("../proto/dist/generated/agent/v1/mcp_allowlist_precheck_exec_pb.js");class sS{constructor(e){this.permissionsService=e}async execute(e,t){const r=await this.permissionsService.isMcpFullyAllowlisted(e,{providerIdentifier:t.providerIdentifier,toolName:t.toolName,annotationsJson:t.annotationsJson});return new nS.M({allowlisted:r})}}const iS=BigInt(0),aS=BigInt(8),cS=BigInt(16),lS=BigInt(65535);function uS(e){const t=e.trim().toLowerCase();return t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t}function dS(e){const t=e.split(".");if(4!==t.length)return;let r=iS;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<<aS|BigInt(t)}return{version:4,value:r}}function hS(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=dS(o);if(!n)return;t.push(Number(n.value>>cS&lS)),t.push(Number(n.value&lS))}else{if(!/^[0-9a-f]{1,4}$/i.test(o))return;t.push(Number.parseInt(o,16))}}return t}function pS(e){return dS(e)??function(e){const t=uS(e);if(0===t.length||t.includes(":::"))return;const r=t.indexOf("::");if(-1===r){const e=hS(t);if(!e||8!==e.length)return;return{version:6,value:e.reduce(((e,t)=>e<<cS|BigInt(t)),iS)}}if(-1!==t.indexOf("::",r+1))return;const o=t.slice(0,r),n=t.slice(r+2),s=hS(o),i=hS(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<<cS|BigInt(t)),iS)}}(e)}function fS(e,t){const r=uS(e),o=uS(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=pS(t.slice(0,r)),n=pS(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}function mS(e,t){const r=function(e){const t=e.trim();if(0===t.length)return;const r=t.includes("://")?t:`https://${t}`;try{return new URL(r)}catch{return}}(e);return!!r&&function(e,t){return t.some((t=>fS(e,t)))}(r.hostname,t)}var gS=r("../mcp-core/dist/admin-mcp-tool-allowlist.js");const wS=new Set(["ash","bash","csh","dash","fish","ksh","powershell","pwsh","sh","tcsh","zsh","cmd"]);function yS(e){return e.trim().split(/\s+/).filter(Boolean)}function vS(e){const t=function(e){const t=e.trim(),r=t[0];if('"'===r||"'"===r){const e=t.indexOf(r,1);if(-1!==e)return t.slice(0,e+1)}return yS(t)[0]}(e);if(!t)return!1;const r=t.replace(/^["']|["']$/g,"").replaceAll("\\","/").split("/"),o=(r[r.length-1]??"").replace(/\.exe$/i,"").toLowerCase();return wS.has(o)}function bS(e,t){if(e.length>t.length)return!1;for(let r=0;r<e.length;r++)if(e[r]!==t[r])return!1;return!0}function SS(e,t){return e.commandName.localeCompare(t.commandName)}function kS(e){return e.split(" ")[0]??e}function ES(e,t){return function(e,t){const r=function(e){const t=new Set,r=[];for(const o of e){const e=o.trim();if(!e||t.has(e))continue;t.add(e);const n=yS(e),s=n[0]??e;r.push({id:e,label:e,value:e,commandName:s,tokenCount:n.length,indentLevel:0,tokens:n,ancestorIds:[e]})}r.sort(SS);for(let e=0;e<r.length;e++){const t=r[e],o=new Set(t.tokens);let n,s=!1;for(let i=0;i<e;i++){const e=r[i];if(e.commandName!==t.commandName)continue;if(e.tokenCount>=t.tokenCount)continue;let a=!0;for(const t of e.tokens)if(!o.has(t)){a=!1;break}if(!a)continue;const c=bS(e.tokens,t.tokens);void 0!==n?e.tokenCount>n.tokenCount?(n=e,s=c):e.tokenCount===n.tokenCount&&c&&!s&&(n=e,s=!0):(n=e,s=c)}void 0!==n&&(t.indentLevel=n.indentLevel+1,t.ancestorIds=[...n.ancestorIds,t.id])}const o=r.filter((e=>!r.some((t=>t.id!==e.id&&t.tokenCount<e.tokenCount&&bS(t.tokens,e.tokens))))).map((e=>e.id));return{options:r,defaultSelectedOptionIds:o}}(e),o=[...r.defaultSelectedOptionIds];if(!t||0===t.length)return{defaultSelectedOptionIds:o,hasClassifierSuggestions:!1};const n=[],s=new Set;for(const e of t){const t=r.options.find((t=>t.id===e));if(t){n.push(t.id),s.add(kS(t.id));continue}const o=r.options.filter((t=>t.id.startsWith(`${e} `)||t.id===e)),i=r.options.filter((t=>e.startsWith(`${t.id} `)||e===t.id));if(i.length>0){const e=i.reduce(((e,t)=>e.id.length>t.id.length?e:t));n.push(e.id),s.add(kS(e.id))}else if(o.length>0){const e=o.reduce(((e,t)=>e.id.length<t.id.length?e:t));n.push(e.id),s.add(kS(e.id))}}if(0===n.length)return{defaultSelectedOptionIds:o,hasClassifierSuggestions:!1};const i=o.filter((e=>!s.has(kS(e))));return{defaultSelectedOptionIds:[...new Set([...i,...n])],hasClassifierSuggestions:!0}}(e,t).defaultSelectedOptionIds}const CS=["com.todesktop.230313mzl4w4u92","co.anysphere.cursor"];function xS(e){return CS.some((t=>e===t||e.startsWith(`${t}.`)))}const _S=[{bundleId:"com.apple.terminal",name:"Terminal"},{bundleId:"com.googlecode.iterm2",name:"iTerm",aliases:["iTerm2"]},{bundleId:"dev.warp.warp-stable",name:"Warp"},{bundleId:"dev.warp.warp-preview",name:"WarpPreview",aliases:["Warp Preview"]},{bundleId:"com.mitchellh.ghostty",name:"Ghostty"},{bundleId:"org.alacritty",name:"Alacritty"},{bundleId:"net.kovidgoyal.kitty",name:"kitty"},{bundleId:"com.github.wez.wezterm",name:"WezTerm"},{bundleId:"co.zeit.hyper",name:"Hyper"},{bundleId:"org.tabby",name:"Tabby"},{bundleId:CS[0],name:"Cursor"}];function PS(e){const t=e.toLowerCase(),r=(0,s.basename)(e,".app").toLowerCase(),o=_S.find((({bundleId:e,name:o,aliases:n=[]})=>e===t||[o,...n].some((e=>{const o=e.toLowerCase();return o===t||o===r}))));return void 0!==o?{bundleId:o.bundleId,name:o.name}:xS(t)?{bundleId:t,name:"Cursor"}:[t,r].some((e=>"cursor"===e||e.startsWith("cursor ")))?{bundleId:CS[0],name:"Cursor"}:void 0}const IS=new Set(["com.apple.systempreferences","com.apple.keychainaccess","com.apple.passwords","com.1password.1password","com.agilebits.onepassword7","com.bitwarden.desktop","com.lastpass.lastpass","org.keepassxc.keepassxc"]);function RS(e){return IS.has(e.toLowerCase())}function TS(e){return`app/${e}`}function AS(e){if("object"!=typeof e||null===e)return;const{appArg:t,appSelectorArgs:r,capturesScreen:o}=e;if("boolean"==typeof o){if(void 0!==r){const e=r;return void 0===t&&"object"==typeof r&&null!==r&&Object.keys(e).length>0&&Object.entries(e).every((([e,t])=>MS.includes(e)&&"string"==typeof t&&t.length>0))?{appSelectorArgs:e,capturesScreen:o}:void 0}return void 0===t?{capturesScreen:o}:"string"==typeof t&&t.length>0?{appArg:t,capturesScreen:o}:void 0}}const MS=["pid","bundleId","path","appName"],DS=/^[+-]?\d+$/;const OS="win32"===process.platform;function NS(e,t){return OS&&(e=e.toLowerCase(),t=t.toLowerCase()),e===t||(e.charAt(e.length-1)!==s.sep&&(e+=s.sep),t.startsWith(e))}process.platform;const $S=(0,s.join)((0,n.homedir)(),".cursor","projects"),FS=(0,s.join)((0,n.homedir)(),".cursor","worktrees");function jS(e){return NS($S,e)&&e!==$S}function LS(e){return NS(FS,e)&&e!==FS}function US(e,t){const r=function(e){if(!NS($S,e))return;if(e===$S)return;const t=(0,s.relative)($S,e).split(s.sep).filter(Boolean);return t.length>=2?t[1]:void 0}(e);return void 0!==r&&t.includes(r)}function BS(e,t,r){return{resolvedPath:e,originalPath:t,resolution:r}}function WS(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 HS(e,t){const r=(0,Gs.o1)(e,t);try{return BS(await(0,Os.realpath)(r),r,{status:"resolved"})}catch(e){const t=e;if("ENOENT"!==t.code)return BS(r,r,WS(t));try{if((await(0,Os.lstat)(r)).isSymbolicLink()){let e=null;try{e=await(0,Os.readlink)(r)}catch{}return BS(r,r,{status:"danglingSymlink",symlinkTarget:e})}try{return BS(await(0,Os.realpath)(r),r,{status:"resolved"})}catch(e){const t=e;if("ENOENT"!==t.code)return BS(r,r,WS(t))}return BS(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,s.dirname)(e);const r=[(0,s.basename)(e)];for(;(0,s.dirname)(t)!==t;){try{const o=await(0,Os.realpath)(t);return BS((0,s.join)(o,...r),e,{status:"newFile"})}catch(t){const r=t;if("ENOENT"!==r.code)return BS(e,e,WS(r))}r.unshift((0,s.basename)(t)),t=(0,s.dirname)(t)}return BS(e,e,{status:"newFile"})}(r):BS(r,r,WS(t))}}}function qS(e){return"resolved"===e.status||"newFile"===e.status}function zS(e,t){switch(t.status){case"resolved":case"newFile":return"";case"danglingSymlink":return`Write blocked: \`${e}\` is a dangling symlink${t.symlinkTarget?` (target: ${t.symlinkTarget})`:""}. Cannot verify it does not point to a protected file.`;case"permissionDenied":return`Write blocked: cannot verify \`${e}\` -- permission denied resolving symlinks (${t.errno}).`;case"symlinkLoop":return`Write blocked: \`${e}\` has a symlink loop (${t.errno}). Cannot verify target.`;case"unknownError":return`Write blocked: cannot verify \`${e}\` -- ${t.errno}: ${t.message}.`;default:return`Write blocked: unknown resolution status for \`${e}\`.`}}function GS({requestedAbsolutePath:e,realAbsolutePath:t,setting:r,resolvedWorkspaceRoots:o,resolvedAllowFolders:n}){return"workspace"===r.boundary&&!VS(t,o)&&!VS(t,n)&&!(KS(t,r.allowPaths)||e!==t&&KS(e,r.allowPaths))}function VS(e,t){return t.some((t=>(0,Gs.BJ)(e,t)))}function JS(e){return e.flatMap((e=>{const t=(0,Gs.jl)(e.trim());return!t.includes("*")&&(0,s.isAbsolute)(t)?[(0,s.resolve)(t)]:[]}))}function KS(e,t){const r="win32"===process.platform?Gs.oL:e=>e,o=r(e);return t.some((e=>{const t=(0,Gs.jl)(e.trim());return!(!t.includes("*")&&(0,s.isAbsolute)(t))&&xi(r(t),o)}))}const ZS=/(?<![\w-])(?:rm|rmdir|rd|del|erase|ri|remove-item)(?![\w-])/i,XS=/\s(?:-[dfiv]*r[dfiv]*|--recursive|-recurse|-recurs|-recur|-recu|-rec|-re)(?![\w-])/i;function QS(e,t,r){const o=t.exec(e);return null!==o&&r.test(e.slice(o.index+o[0].length))}var YS=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},ek=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 tk=(0,m.h)("permissions-service"),rk=(0,g.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 ok(e){return Promise.all(e.map((async e=>{const t=await HS(e);return qS(t.resolution)?t.resolvedPath:(0,Gs.o1)(e)})))}function nk(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 sk(e){return[...new Set(e)]}function ik(){return{fdTargets:new Map([[0,"original-stdin"],[1,"original-stdout"],[2,"original-stderr"]])}}function ak({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 ck(e){return">"===e||">>"===e||">|"===e||"&>"===e||"&>>"===e}function lk(e){return"<"!==e.operator&&"<&"!==e.operator}function uk(e){if(void 0===e||e.trim()!==e)return;const t=Number(e);return Number.isInteger(t)&&t>=0?t:void 0}function dk(e){return"<<"===e.operator&&"heredoc_redirect"===e.targetNodeType&&1===e.destinationFds.length&&0===Number(e.destinationFds[0])&&void 0!==e.targetText}async function hk({targetText:e,workingDirectory:t,rootDirectories:r,allowTmpRedirects:o,resolvePathForPermissions:n,pathModule:s,tempPathOptions:i}){if(""!==s.parse(e).root&&!s.isAbsolute(e))return;const a=await n(e,t);if(qS(a.resolution)){for(const e of r){const t=await n(e);if(qS(t.resolution)&&ak({basePath:t.resolvedPath,targetPath:a.resolvedPath,pathModule:s}))return"workspace-file"}return o&&kk(a.resolvedPath,i)?"tmp-file":void 0}}function pk(e){return sk(e.map((e=>e.trim())).filter(Boolean))}function fk(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 mk(e,t){const r=t.trim();return!!r&&e.some((e=>e===r||e.startsWith(`${r} `)))}function gk(e){const t=e.name.trim(),r=e.arguments.map((e=>e.trim())).filter(Boolean).map((e=>new yr.r6({type:"word",value:e})));return new yr.Pv({name:t,args:r,fullText:[t,...r.map((e=>e.value))].join(" ").trim()})}function wk(e,t={}){return{type:e,...t}}function yk(e){const t=[];for(const r of e){const e=r.match(/^\s*Read\s*\((.*)\)\s*$/);e&&t.push((e[1]??"").trim())}return t}function vk(e,t){if("workspace"===e&&void 0!==t)return t}const bk={workspace:0,system:1};function Sk(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 kk(e,{platform:t,env:r,pathModule:o,homeDirectory:n}){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}const s=e=>{const r=o.normalize(e);return"darwin"!==t?r:"/tmp"===r||r.startsWith("/tmp/")||"/var"===r||r.startsWith("/var/")?`/private${r}`:r},i=s(e);return(void 0===n||!ak({basePath:s(n),targetPath:i,pathModule:o}))&&("darwin"===t?["/private/tmp/","/private/var/folders/"].some((e=>i.startsWith(e))):["/tmp/","/private/tmp/","/var/folders/","/private/var/folders/","/var/tmp/"].some((e=>i.startsWith(e))))}function Ek(e,t){if("insecure_none"===t.type)return!0;if("insecure_none"===e.type)return!1;const r=(0,Fs.$b)(e.networkPolicy),o=(0,Fs.$b)(t.networkPolicy);if(r&&!o)return!1;const n=(0,Fs._B)(e.networkPolicy),s=(0,Fs._B)(t.networkPolicy);if(n&&o&&!s)return!1;if("workspace_readonly"===e.type&&"workspace_readwrite"===t.type)return!0;if("workspace_readwrite"===e.type&&"workspace_readonly"===t.type)return!1;const i=e.readBoundary??"system",a=t.readBoundary??"system";return!(bk[i]>bk[a])}class Ck{constructor(e,t,r,o){this.command=e,this.requestedPolicy=t;const n=void 0!==r&&Ek(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||!Ek(this.requestedPolicy,e)||(this.state="allowlisted")}deny(){this.state="denied"}isRunnable(){return"preapproved"===this.state||"allowlisted"===this.state}}function xk(e){return e?.type??"undefined"}const _k=["skills","skills-cursor","rules","plugins"];async function Pk(e,t,r){return e.shouldBlockFileRead?.(t,r)??e.shouldBlockRead(t,r)}function Ik(e){const t=e.lastIndexOf("::mcpScope:");return-1===t?e:e.slice(0,t)}function Rk({server:e,tool:t}){const r=e=>e.length>0&&e.length<=256&&!/[:*]/.test(e),o=e.trim().toLowerCase(),n=t.trim().toLowerCase();return r(o)&&r(n)?`${o}:${n}`:void 0}const Tk=/^\s*Read\s*\((.*)\)\s*$/,Ak=/^\s*Write\s*\((.*)\)\s*$/;class Mk{constructor(e,t,r,o,i,a=!1,c){this.ignoreService=e,this.pendingDecisionStore=t,this.permissionsProvider=r,this.teamSettingsService=o,this.adminNetworkControlsEnabled=a,this.computerUseAppsAllowedForSession=[],this.rootDirectories=Array.isArray(i)?i:[i??process.cwd()],this.perUserSandboxConfigPath=c?.perUserSandboxConfigPath??(0,s.join)((0,n.homedir)(),".cursor","sandbox.json"),this.mcpAllowlistLog=c?.mcpAllowlistLog,this.computerUse=c?.computerUse}async shouldBlockRead(e,t={}){return this.shouldBlockReadInternal(e,t,!1)}async shouldBlockFileRead(e,t={}){return this.shouldBlockReadInternal(e,t,!0)}async getFileReadBoundaryBlocker(){const{perms:e,setting:t}=await this.readControlSetting(),r=e.deny.filter((e=>this.isPathEntry("Read",e))),o="workspace"===t.boundary&&"unrestricted"!==e.approvalMode;if(!o&&0===r.length)return;const[n,s]=o?await Promise.all([this.resolveWorkspaceReadRoots(e.userSandboxDataFolderName),this.resolvedReadAllowFolders(t.allowPaths)]):[[],[]],i=r.map((e=>this.compileReadDenyMatcher(e))),a=e=>i.some((t=>t(e)));return async(e,r)=>a(e)||a(r)||o&&GS({requestedAbsolutePath:e,realAbsolutePath:r,setting:t,resolvedWorkspaceRoots:n,resolvedAllowFolders:s})}async readControlSetting(){const[e,t,r]=await Promise.all([this.teamSettingsService.isReadControlEnabled?.()??!0,this.teamSettingsService.getSandboxingControls(),this.getPermissions()]);return{perms:r,setting:function(e){if(!e.enabled)return{boundary:"system",allowPaths:[],enforcedByAdmin:!1};const t="workspace"===e.admin.boundary,r=t||"workspace"===e.local.boundary?"workspace":"system",o=t?e.admin.allowPaths:[];return{boundary:r,allowPaths:t&&!1===e.admin.allowUserOverride?[...o]:[...new Set([...o,...e.local.allowPaths])],enforcedByAdmin:t}}({enabled:e,admin:{boundary:t.readBoundary,allowPaths:t.readAllowlistPaths??[],allowUserOverride:t.allowUserOverrideReadAllowlist},local:{boundary:r.readBoundary,allowPaths:yk(r.allow)}})}}resolvedReadAllowFolders(e){return ok([...JS(e),...(0,Fs.r5)()])}async resolveWorkspaceReadRoots(e){const t=(0,s.join)((0,n.homedir)(),void 0!==e&&e.length>0?e:".cursor"),r=[...this.rootDirectories.map((e=>(0,s.join)(t,"projects",(0,As.r_)(e)))),..._k.map((e=>(0,s.join)(t,e)))],o=this.rootDirectories.flatMap((e=>(0,Fs.W1)(e)??[]));return ok([...this.rootDirectories,...r,...o])}async shouldBlockReadInternal(e,{cursorIgnoreChecked:t=!1},r){const o=(0,Gs.o1)(e),n=await Xa(o);if(null===n)return{type:"unsafeResolution",message:nk("Read","path",o)};if(await this.ignoreService.isRepoBlocked(n))return{type:"adminBlock",source:"Team repo blocklist"};if(await this.isPathExplicitlyDenied("Read",o))return{type:"permissionsConfig"};if(!jS(n)&&!LS(n)&&!t&&await this.ignoreService.isCursorIgnored(n))return{type:"cursorIgnore"};if(r){const e=await this.shouldBlockReadForBoundary({realAbsolutePath:n,requestedAbsolutePath:o});if(e)return e}return!1}async shouldBlockReadForBoundary({realAbsolutePath:e,requestedAbsolutePath:t}){const{perms:r,setting:o}=await this.readControlSetting();if("workspace"!==o.boundary||"unrestricted"===r.approvalMode)return!1;const n=await this.resolveWorkspaceReadRoots(r.userSandboxDataFolderName);return!VS(e,n)&&(!!GS({requestedAbsolutePath:t,realAbsolutePath:e,setting:o,resolvedWorkspaceRoots:n,resolvedAllowFolders:await this.resolvedReadAllowFolders(o.allowPaths)})&&{type:"needsApproval",approvalReason:o.enforcedByAdmin?"This reads a file outside your workspace and requires approval under your team's read policy.":"This reads a file outside your workspace.",approvalDetails:{type:"fileRead",path:e}})}async shouldBlockWrite(e,t,r){const o={stack:[],error:void 0,hasError:!1};try{YS(o,(0,i.VI)(e.withName("InteractivePermissionsService.shouldBlockWrite")),!1).ctx;const a=await HS(t);if(!qS(a.resolution))return{type:"unsafeResolution",message:zS(a.originalPath,a.resolution)};const c=a.resolvedPath,l=c;if(await this.ignoreService.isRepoBlocked(l))return{type:"adminBlock",source:"Team repo blocklist"};if(await this.isPathExplicitlyDenied("Write",c))return{type:"permissionsConfig"};const u=a.originalPath.split(s.sep).pop()?.toLowerCase()??"",d=c.split(s.sep).pop()?.toLowerCase()??"";if(".cursorignore"===u||".cursorignore"===d)return{type:"permissionsConfig"};const h=jS(l),p=LS(l),f=!h&&!p&&await this.ignoreService.isCursorIgnored(l);if(h||p);else if(f)return{type:"cursorIgnore"};if(await this.isPathExplicitlyAllowed("Write",c))return!1;if(function(e){const t=e.replace(/\\/g,"/");return/(^|\/)\.cursor\/debug(?:-[a-zA-Z0-9-]+)?\.log$/i.test(t)}(c))return!1;const m=await this.getPermissions();if("workspace_readonly"===m.userConfiguredPolicy.type)return{type:"permissionsConfig",isReadonly:!0};if("unrestricted"===m.approvalMode)return!1;for(const e of this.rootDirectories){const t=await HS(e);if(!qS(t.resolution))continue;const r=t.resolvedPath;if((0,Gs.BJ)(c,r)){const e=(0,s.relative)(r,c).split(s.sep).map((e=>"win32"===process.platform&&e.includes(":")?e.split(":")[0]:e)),t=await this.checkCursorFileProtection(e);if(t)return t;break}}const g=async()=>{let e=!1,t="";try{t=await ua(c),e=!1}catch{e=!0}let o="";if(e)o=r;else{const e=e=>e.endsWith("\n")?e:`${e}\n`,{hunks:n}=(0,Nv.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,y=!1;for(const e of this.rootDirectories){const t=await HS(e);if(!qS(t.resolution))continue;const r=t.resolvedPath;if((0,Gs.BJ)(c,r)){y=!0,w=r;break}}const v=y?void 0:function(e){if(!LS(e))return;const t=(0,s.relative)(FS,e).split(s.sep).filter(Boolean);return 0!==t.length?(0,s.join)(FS,t[0]):void 0}(c);if(!y&&void 0===v){if(function(e){return kk(e,{platform:process.platform,env:process.env,pathModule:s,homeDirectory:(0,n.homedir)()})}(c))return!1;if(US(c,["assets","agent-notes","agent-tools","swarm-agents"]))return!1;const e=`${(0,n.homedir)()}${s.sep}.cursor${s.sep}`;if(c.startsWith(e)){const e=c.split(s.sep).pop()?.toLowerCase()??"";if(e.endsWith(".md")||e.endsWith(".mdc")||".cursorrules"===e)return!1}const{isNewFile:t,diffString:r}=await g();return{type:"needsApproval",approvalReason:"Out of workspace",approvalDetails:{type:"fileEdit",isNewFile:t,diffString:r,blockReason:"outOfWorkspace"}}}const b=w??v,S=c;let k=(0,s.relative)(b,S).split(s.sep);if(k=k.map((e=>"win32"===process.platform&&e.includes(":")?e.split(":")[0]:e)),"win32"===process.platform&&k.some((e=>e.includes("~")))){const{isNewFile:e,diffString:t}=await g();return{type:"needsApproval",approvalReason:`Protected config file: ${k[k.length-1]??""}`,approvalDetails:{type:"fileEdit",isNewFile:e,diffString:t,blockReason:"protectedConfig"}}}if(await(0,Fs.OK)(c,b)){const e=k[k.length-1]?.toLowerCase()??"",{isNewFile:t,diffString:r}=await g();return{type:"needsApproval",approvalReason:`Protected config file: ${e}`,approvalDetails:{type:"fileEdit",isNewFile:t,diffString:r,blockReason:"protectedConfig"}}}const E=await this.checkCursorFileProtection(k);if(E)return E;if(!0===m.promptWorkspaceWrites){const{isNewFile:e,diffString:t}=await g();return{type:"needsApproval",approvalReason:"Workspace write",approvalDetails:{type:"fileEdit",isNewFile:e,diffString:t,blockReason:"workspaceWrite"}}}return!1}catch(e){o.error=e,o.hasError=!0}finally{ek(o)}}async shouldEnforceShellInvariantBlocks(e,t,r){const o=await this.getAdminCommandDenylistBlock(e,{command:t.command,parsingResult:t.parsingResult,toolCallId:t.toolCallId});if(void 0!==o)return{kind:"block",reason:o};const n=await Xa(t.workingDirectory);if(null===n){if(!0!==t.skipUnsafeWorkingDirectoryBlock)return{kind:"block",reason:{type:"unsafeResolution",message:nk("Command","working directory",t.workingDirectory)}}}else if(await this.ignoreService.isRepoBlocked(n))return{kind:"block",reason:{type:"adminBlock",source:"Team repo blocklist"}};const s=(await this.getPermissions()).userConfiguredPolicy,i=r??s;return"workspace_readonly"===s.type&&"workspace_readonly"!==i.type?{kind:"block",reason:{type:"permissionsConfig",isReadonly:!0}}:{kind:"allow"}}async shouldBlockShellCommand(e,t,r,o){const n="insecure_none"===o?.type,s=await this.shouldEnforceShellInvariantBlocks(e,{workingDirectory:r.workingDirectory,command:t,parsingResult:r.parsingResult,toolCallId:r.toolCallId},o);if("block"===s.kind)return s;const i=await this.getPermissions(),a=i.approvalMode,c="unrestricted"===a,l=i.userConfiguredPolicy,u=!i.dashboardTerminalAllowlistOverriddenByPermissionsFile;if(tk.info(e,"Shell permissions: evaluating shell command",{toolCallId:r.toolCallId,approvalMode:a,userConfiguredPolicyType:xk(l),requestedPolicyType:xk(o),effectiveRequestedPolicyType:xk(o??l),smartAllowlistEnabled:!0===i.smartAllowlistEnabled,hasSmartModeApprovalReason:void 0!==r.smartModeApprovalReason,hasSmartModeApprovalRequestId:void 0!==r.smartModeApprovalRequestId,hookForcesPrompt:Or(r.hookApprovalRequirement),classifierClassificationFailed:!0===r.classifierResult?.classificationFailed,classifierCommandCount:r.classifierResult?.commands.length??0,parserCommandCount:r.parsingResult.executableCommands.length,parsingFailed:r.parsingResult.parsingFailed,hasRedirects:r.parsingResult.hasRedirects,commandLength:t.length}),await this.shouldPromptForEmptyPlainShellAllowlist(t,i))return tk.info(e,"Shell permissions: prompting for empty allowlist",{toolCallId:r.toolCallId,approvalMode:a,userConfiguredPolicyType:xk(l),requestedPolicyType:xk(o),hasSmartModeApprovalReason:void 0!==r.smartModeApprovalReason,hasSmartModeApprovalRequestId:void 0!==r.smartModeApprovalRequestId}),await this.requestApprovalForEmptyShellAllowlist(t,r,o??l);const d=r.parsingResult.executableCommands,h=r.parsingResult.hasRedirects,p=!0===r.parsingResult.allRedirectsAreDevNull,f=r.parsingResult.parsingFailed,m=r.classifierResult,g=r.smartModeApprovalReason,w=r.smartModeApprovalRequestId,y=void 0!==m&&!m.classificationFailed&&m.commands.length>0?m:void 0,v="allowlist"===a&&i.smartAllowlistEnabled?y?.commands:void 0,b=void 0!==v,S=v?v.map(gk):d,k=void 0!==v?v.map(fk):S.map((e=>[e.fullText.trim()].filter(Boolean))),E=void 0!==y?y.commands.map(fk):k;if(o||(o=i.userConfiguredPolicy),"insecure_none"!==o.type&&void 0===o.skipStatsigDefaults&&"insecure_none"!==l.type&&(o={...o,skipStatsigDefaults:l.skipStatsigDefaults??!0}),"insecure_none"!==l.type&&(0,Fs.$b)(l.networkPolicy)&&"insecure_none"!==o.type&&!(0,Fs._B)(o.networkPolicy)){const e=l.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}}o=function({requestedPolicy:e,userConfiguredPolicy:t}){if("insecure_none"===e.type||"insecure_none"===t.type)return e;const r=(0,Fs.XX)(e.readBoundary,t.readBoundary),o="workspace"===r?(0,Fs.wG)(vk(e.readBoundary,e.additionalReadPaths),vk(t.readBoundary,t.additionalReadPaths)):void 0;return{...e,readBoundary:r,additionalReadPaths:o}}({requestedPolicy:o,userConfiguredPolicy:l}),m&&tk.info(e,"Smart allowlist: classifier result received",{classificationFailed:m.classificationFailed,suggestedSandboxMode:m.suggestedSandboxMode,commandCount:m.commands.length,suggestedAllowlistEntryCount:m.commands.filter((e=>e.suggestedAllowlistEntry)).length});let C=!1;const x=[],_=[];let P=[],I=[],R=[];const T=pk(i.smartAllowlistDenylist??[]);if(T.length>0){I=[];const t=E.map((e=>e[0]??""));for(let e=0;e<E.length;e++){const r=E[e];if(r&&0!==r.length&&T.some((e=>mk(r,e)))){const r=t[e];r&&I.push(r)}}I.length>0&&(tk.info(e,"Command blocklist: commands require approval",{count:I.length}),x.push(`In blocklist: ${I.join(", ")}`))}if(b&&m){const t=k.map((e=>e[0]??"")),r=i.allow.filter((e=>this.isShellEntry(e)));tk.info(e,"Smart allowlist: checking commands against lists",{commandCount:t.length,allowlistCount:r.length,commandBlocklistCount:T.length});const o=k.map((e=>r.some((t=>e.some((e=>this.matchesShell(t,e))))))),n=o.every(Boolean),s=[];for(let e=0;e<m.commands.length;e++){if(o[e])continue;const t=m.commands[e];t&&s.push(t)}if(P=pk(s.flatMap((e=>function(e){const t=e.name.trim();if(!t)return[];if(vS(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),pk(n)}(e)))),R=s.map((e=>e.suggestedAllowlistEntry)).filter((e=>"string"==typeof e)).filter((e=>P.includes(e))),P.length>0){const e=ES(P,R),t=e.length>0?e.join(", "):P.join(", ");_.push(`Not in allowlist: ${t}`)}C=n&&0===I.length,C&&tk.info(e,"Smart allowlist: all commands in allowlist, will check security",{commandCount:t.length})}const A="ask-every-time"===a||"insecure_none"===o.type&&"allowlist"===a?void 0:l,M=S.map(((e,t)=>new Ck(e,o,A,k[t])));if((0===S.length||f&&!b)&&!c){tk.info(e,"Shell permissions: prompting after parser miss",{toolCallId:r.toolCallId,approvalMode:a,requestedPolicyType:xk(o),userConfiguredPolicyType:xk(l),isSmartAllowlistActive:b,parsingFailed:f,parserCommandCount:S.length,hasSmartModeApprovalReason:void 0!==g,hasSmartModeApprovalRequestId:void 0!==w});const n={type:vm.Shell,toolCallId:r.toolCallId,details:{command:t,workingDirectory:r.workingDirectory,timeout:r.timeout,reason:g??(f?"Parser failed to parse command (possible bypass)":"Parser found no commands (possible bypass)"),isSandboxAvailable:!1,isSandboxEnabled:!1,canAllowlist:!1,notAllowedCommands:[],smartModeApprovalReason:g,smartModeApprovalRequestId:w}},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,M))return{kind:"block",reason:{type:"permissionsConfig",..."workspace_readonly"===l.type?{isReadonly:!0}:{}}};const{allRedirectsAreWorkspaceFileSafe:D,redirectsAllowlistSafe:O}=await this.computeRedirectAllowlistSafety(r.parsingResult,r.workingDirectory,"insecure_none"===l.type||"workspace"!==l.readBoundary),N=await this.teamSettingsService.getAutoRunControls(),$={type:"insecure_none"};for(const e of M)await this.cmdIsAllowedByAllowlist(e,{redirectsAllowlistSafe:O,autoRunControls:N,applyTeamAllowlist:u})&&e.approveWithPolicy($);for(const e of M)N&&this.isInTeamBlocklist(N,e)&&e.deny();const F=await this.teamSettingsService.getDeleteFileProtection();if(F)for(const e of M)"rm"===e.command.name&&e.deny();const j=this.buildShellApprovalDecisionFacts({commands:M,autoRunControls:N,shouldApplyTeamShellAllowlist:u,deleteProtectionEnabled:F,softDenylistedCommands:I});if("workspace_readonly"===l.type&&"workspace_readonly"!==o.type)return tk.info(e,"Shell permissions: blocked by readonly mode"),{kind:"block",reason:{type:"permissionsConfig",isReadonly:!0}};const L=Or(r.hookApprovalRequirement),U=r.hookApprovalRequirement?.reason,B=n&&"insecure_none"!==l.type&&function(e){if(/\brimraf\b/i.test(e))return!0;for(const t of e.replace(/[\\`^]\r?\n/g," ").split(/(?<![>|])&|\|\||[;\n]/)){let e=!1;for(const r of t.split("|")){if(e&&ZS.test(r)||QS(r,ZS,XS)||QS(r,/(?<![\w-])(?:rmdir|rd|del|erase)(?![\w-])/i,/\/s(?![\w-])/i)||QS(r,/(?<![\w-])find(?![\w-])/i,/\s-delete\b/i))return!0;e||=QS(r,/(?<![\w-])(?:get-childitem|gci|ls|dir)(?![\w-])/i,XS)}}return!1}(t);let W=L||B?void 0:this.getShellAutoApprovalPolicy({approvalMode:a,isUnrestricted:c,requestedPolicy:o,facts:j,preserveRequestedPolicyForAllowlistedCommands:b});const H=void 0!==W&&j.allCommandsAllowlisted&&"insecure_none"===W.type&&"allowlistEscalated"in W&&!0===W.allowlistEscalated;if("insecure_none"===W?.type){const{readBoundary:e}=await this.getAdminReadSandboxing();"workspace"===e&&(n?W=void 0:"insecure_none"!==o.type&&(W=o))}const q=void 0!==W&&H;if(W&&(c||void 0===g||q)){b&&j.allCommandsPreapproved&&!j.allCommandsAllowlisted&&tk.info(e,"Shell permissions: all commands allowed by sandbox policy");const t=await this.applyServerAndAdminPolicies(W);return tk.info(e,"Shell permissions: auto-approved shell command",{toolCallId:r.toolCallId,approvalMode:a,requestedPolicyType:xk(o),userConfiguredPolicyType:xk(l),autoApprovalPolicyType:xk(W),mergedPolicyType:xk(t),isSmartAllowlistActive:b,smartModeApprovalBypassedByAllowlist:q,allCommandsRunnable:j.allCommandsRunnable,allCommandsAllowlisted:j.allCommandsAllowlisted,allCommandsPreapproved:j.allCommandsPreapproved,hasSmartModeApprovalReason:void 0!==g,commandCount:M.length}),{kind:"allow",policy:t}}let z=(b||(!h||p||D)&&!f)&&("allowlist"===a||"ask-every-time"===a)&&j.canAllowlistInPrompt;const G=[],V=void 0!==g,J=j.notInTeamAllowlist.length>0&&(j.hasSecurityDenies||j.hasSoftDenies||!j.allCommandsRunnable);if(void 0!==g&&G.push(g),L&&(V||G.push(U?`Hook requested approval: ${U}`:"Hook requested approval"),z=!1),B&&(V||G.push("Recursive delete outside the sandbox"),z=!1),x.length>0&&(V||G.push(...x),z=!1),!V)if(b&&_.length>0)G.push(..._);else if(j.unapprovedCommands.length>0){const e=ES(this.generateAllowlistPatterns(j.unapprovedCommands.map((e=>e.command)))),t=e.length>0?e.join(", "):j.unapprovedCommands.map((e=>e.command.fullText)).join(", ");G.push(`Not in allowlist: ${t}`)}if(j.hasSecurityDenies&&(V||(j.rmDeniedByDeleteProtection.length>0&&G.push("Delete protection is enabled"),j.teamBlocklistedCommands.length>0&&G.push(`In team blocklist: ${j.teamBlocklistedCommands.map((e=>e.command.name)).join(", ")}`)),z=!1),J){const t=j.notInTeamAllowlist.map((e=>e.command.fullText)).join(", ");tk.info(e,"Shell permissions: commands not in team allowlist",{commandCount:j.notInTeamAllowlist.length}),V||G.push(`Not in team allowlist: ${t}`),z=!1}const K=G.join(" • "),Z=[];if(z){const e=void 0!==g?M.filter((e=>"allowlisted"!==e.state)):j.unapprovedCommands;Z.push(...this.generateAllowlistPatterns(e.map((e=>e.command))))}const X=b&&_.length>0,Q=X?P:Z,Y=X&&R.length>0?R:void 0,ee="insecure_none"!==o.type&&"insecure_none"!==l.type,te="insecure_none"!==o.type,re=[void 0!==g?"smart_mode_approval":void 0,L?"hook_forces_prompt":void 0,B?"unsandboxed_recursive_delete":void 0,x.length>0?"command_blocklist":void 0,b&&_.length>0?"smart_allowlist_miss":void 0,j.unapprovedCommands.length>0?"unapproved_commands":void 0,j.hasSecurityDenies?"security_denies":void 0,J?"team_allowlist_miss":void 0].filter((e=>void 0!==e));tk.info(e,"Shell permissions: requesting shell approval",{toolCallId:r.toolCallId,approvalMode:a,requestedPolicyType:xk(o),userConfiguredPolicyType:xk(l),isSandboxAvailable:ee,isSandboxEnabled:te,canAllowlist:z,isSmartAllowlistActive:b,hasSmartModeApprovalReason:void 0!==g,hasSmartModeApprovalRequestId:void 0!==w,hookForcesPrompt:L,approvalReasonTypes:re,commandCount:M.length,unapprovedCommandCount:j.unapprovedCommands.length,deniedCommandCount:j.deniedCommands.length,notInTeamAllowlistCount:j.notInTeamAllowlist.length,notAllowedCommandCount:Q.length,suggestedAllowlistEntryCount:Y?.length??0,allCommandsRunnable:j.allCommandsRunnable,allCommandsAllowlisted:j.allCommandsAllowlisted,allCommandsPreapproved:j.allCommandsPreapproved,hasSecurityDenies:j.hasSecurityDenies,hasSoftDenies:j.hasSoftDenies});const oe={type:vm.Shell,toolCallId:r.toolCallId,details:{command:t,workingDirectory:r.workingDirectory,timeout:r.timeout,reason:K,isSandboxAvailable:"allowlist"===a&&ee,isSandboxEnabled:"allowlist"===a&&te,canAllowlist:z,notAllowedCommands:Q,suggestedAllowlistEntries:Y,smartModeApprovalReason:g,smartModeApprovalRequestId:w}},ne=await this.pendingDecisionStore.requestApproval(oe);if(ne.approved){const e="unrestricted"===a?{type:"insecure_none"}:o;return{kind:"allow",policy:await this.applyServerAndAdminPolicies(e)}}return{kind:"block",reason:{type:"userRejected",reason:ne.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{redirectsAllowlistSafe:i}=await this.computeRedirectAllowlistSafety(r.parsingResult,r.workingDirectory,"insecure_none"===n.userConfiguredPolicy.type||"workspace"!==n.userConfiguredPolicy.readBoundary);if(!i)return!1;const a=r.classifierResult,c=void 0!==a&&!a.classificationFailed&&a.commands.length>0?a:void 0,l=(n.smartAllowlistEnabled??!1)&&void 0!==c;if(r.parsingResult.parsingFailed&&!l)return!1;const u=r.parsingResult.executableCommands,d=l?c.commands.map(gk):u;if(0===d.length)return!1;const h=l?c.commands.map(fk):d.map((e=>[e.fullText.trim()].filter(Boolean))),p=void 0!==c?c.commands.map(fk):h,f={type:"insecure_none"},m=d.map(((e,t)=>new Ck(e,f,void 0,h[t])));if(await this.hasHardDeny(o,m))return!1;const g=pk(n.smartAllowlistDenylist??[]);if(g.length>0)for(const e of p)if(e&&0!==e.length&&g.some((t=>mk(e,t))))return!1;if(await this.teamSettingsService.getDeleteFileProtection()&&m.some((e=>"rm"===e.command.name)))return!1;const w=await this.teamSettingsService.getAutoRunControls();if(void 0!==w&&m.some((e=>this.isInTeamBlocklist(w,e))))return!1;for(const e of m)if(!await this.cmdIsAllowedByAllowlist(e,{redirectsAllowlistSafe:i,autoRunControls:w,applyTeamAllowlist:s}))return!1;return!0}async applyServerAndAdminPolicies(e){if("insecure_none"===e.type)return e;const{userSandboxDataFolderName:t}=await this.getPermissions(),r=void 0!==t&&t.length>0?(0,s.join)((0,n.homedir)(),t,"sandbox.json"):this.perUserSandboxConfigPath,o=await this.foldPerUserFilePolicy(e,r),i=o.skipStatsigDefaults?o:await this.applyStatsigDefaults(o),a=await this.loadPerRepoFilePolicy(i.type),c=await this.buildTeamAdminPolicy(i.type),l=(0,Fs._B)(e.networkPolicy),{policy:u}=await(0,Fs.resolveSandboxPolicyForWorkspace)(this.rootDirectories[0],{perUser:i,perRepo:a,teamAdmin:c});return l?{...u,networkPolicy:(0,Fs.T6)()}:u}async foldPerUserFilePolicy(e,t=this.perUserSandboxConfigPath){const r=await(0,Fs.tv)(t,(0,n.homedir)());if(!r||"insecure_none"===r.type)return e;let o=(0,Fs.fZ)(r.networkPolicy,e.networkPolicy);o&&void 0!==e.networkPolicy?.default&&(o={...o,default:e.networkPolicy.default});const s=(0,Fs.s9)(r.additionalReadonlyPaths,e.additionalReadonlyPaths),i={...e,networkPolicy:o,additionalReadonlyPaths:s.length>0?s:void 0,readBoundary:r.readBoundary??e.readBoundary,additionalReadPaths:void 0!==r.additionalReadPaths?r.additionalReadPaths:e.additionalReadPaths};if("workspace_readwrite"===e.type&&"workspace_readwrite"===r.type){const t=(0,Fs.s9)(r.additionalReadwritePaths,e.additionalReadwritePaths);return{...i,additionalReadwritePaths:t.length>0?t:void 0}}return i}async applyStatsigDefaults(e){const t=await this.teamSettingsService.getDefaultNetworkAllowlist();if(!t.available||0===t.allowlist.length)return e;if((0,Fs._B)(e.networkPolicy))return e;const r={default:"deny",allow:sk(t.allowlist)};return{...e,networkPolicy:(0,Fs.fZ)(e.networkPolicy,r)}}async loadPerRepoFilePolicy(e){const t=this.rootDirectories[0];if(!t)return;const r=await(0,Fs.tv)((0,s.join)(t,".cursor","sandbox.json"),t);return r&&"insecure_none"!==r.type?r.type!==e?wk(e,{networkPolicy:r.networkPolicy,additionalReadonlyPaths:r.additionalReadonlyPaths,..."additionalReadwritePaths"in r?{additionalReadwritePaths:r.additionalReadwritePaths}:{},disableTmpWrite:r.disableTmpWrite,networkPolicyStrict:r.networkPolicyStrict,readBoundary:r.readBoundary,additionalReadPaths:r.additionalReadPaths}):r:void 0}async buildTeamAdminPolicy(e){const t=await this.buildTeamAdminNetworkPolicy(e),{readBoundary:r,readAllowlistPaths:o,allowUserOverrideReadAllowlist:n}=await this.getAdminReadSandboxing();return void 0===r?t:{...t??wk(e),readBoundary:r,additionalReadPaths:o,allowUserOverrideReadPaths:n}}async getAdminReadSandboxing(){const[e,t]=await Promise.all([this.teamSettingsService.isReadControlEnabled?.()??!0,this.teamSettingsService.getSandboxingControls()]);return e?{readBoundary:"workspace"===t.readBoundary?"workspace":void 0,readAllowlistPaths:t.readAllowlistPaths??[],allowUserOverrideReadAllowlist:t.allowUserOverrideReadAllowlist}:{readBoundary:void 0,readAllowlistPaths:[]}}async buildTeamAdminNetworkPolicy(e){if(!this.adminNetworkControlsEnabled)return;const t=await this.teamSettingsService.getNetworkAccessControls();if(!t.available)return wk(e,{networkPolicy:(0,Fs.Po)()});if(0===t.allowlist.length&&0===t.denylist.length)return;const r={};return t.allowlist.length>0&&(r.default="deny",r.allow=sk(t.allowlist)),t.denylist.length>0&&(r.deny=sk(t.denylist)),wk(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)))}async computeRedirectAllowlistSafety(e,t,r){const o=e.hasRedirects,i=e.parsingFailed,a=!0===e.allRedirectsAreDevNull,c=!(!o||a||i)&&await async function({parsingResult:e,workingDirectory:t,rootDirectories:r,allowTmpRedirects:o=!0,resolvePathForPermissions:i=HS,pathModule:a=s,tempPathOptions:c={platform:process.platform,env:process.env,pathModule:a,homeDirectory:(0,n.homedir)()}}){if(!e.hasRedirects)return!0;const l=e.redirects;if(0===l.length)return!1;const u=e.executableCommands.length>1,d=ik();for(const e of l){if(dk(e))continue;const n=u?ik():d,{operator:s,targetText:l}=e,p=e.destinationFds.map((e=>Number(e)));if(">&"===s){const e=uk(l),t=void 0===e?void 0:n.fdTargets.get(e);if("original-stdout"!==(h=t)&&"original-stderr"!==h&&"dev-null"!==h&&"workspace-file"!==h&&"tmp-file"!==h){for(const e of p)n.fdTargets.set(e,"unsafe");return!1}for(const e of p)n.fdTargets.set(e,t);continue}if("<&"===s){const e=uk(l),t=void 0===e?void 0:n.fdTargets.get(e);if("dev-null"!==t){for(const e of p)n.fdTargets.set(e,"unsafe");return!1}for(const e of p)n.fdTargets.set(e,t);continue}if("/dev/null"===l){for(const e of p)n.fdTargets.set(e,"dev-null");continue}if(!ck(s)||void 0===l){for(const e of p)n.fdTargets.set(e,"unsafe");return!1}const f=await hk({targetText:l,workingDirectory:t,rootDirectories:r,allowTmpRedirects:o,resolvePathForPermissions:i,pathModule:a,tempPathOptions:c});if(!f){for(const e of p)n.fdTargets.set(e,"unsafe");return!1}for(const e of p)n.fdTargets.set(e,f)}var h;return!0}({parsingResult:e,workingDirectory:t,rootDirectories:this.rootDirectories,allowTmpRedirects:r}),l=!function({parsingResult:e,hasRedirects:t,parsingFailed:r,allRedirectsAreAllowlistSafe:o,allRedirectsAreWorkspaceFileSafe:n}){return!(!t||r||o||n)&&(0===e.redirects.length||e.redirects.some(lk))}({parsingResult:e,hasRedirects:o,parsingFailed:i,allRedirectsAreAllowlistSafe:a,allRedirectsAreWorkspaceFileSafe:c});return{allRedirectsAreAllowlistSafe:a,allRedirectsAreWorkspaceFileSafe:c,redirectsAllowlistSafe:l}}async cmdIsAllowedByAllowlist(e,t){return!!t.redirectsAllowlistSafe&&(!!await this.isInShellAllowlist(e)||t.applyTeamAllowlist&&void 0!==t.autoRunControls&&this.isInTeamAllowlist(t.autoRunControls,e))}buildShellApprovalDecisionFacts({commands:e,softDenylistedCommands:t,autoRunControls:r,shouldApplyTeamShellAllowlist: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))):[],c=s.filter((e=>void 0!==r&&this.isInTeamBlocklist(r,e))),l=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:c,rmDeniedByDeleteProtection:l}}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:vm.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 getAdminCommandDenylistBlock(e,t){const r=(await this.teamSettingsService.getAdminCommandDenylist()).rules;if(0===r.length)return;const o=Ti({matchForms:t.parsingResult?_i({command:t.command,parsingResult:t.parsingResult}):[t.command],blockedCommands:r});return void 0!==o?(tk.info(e,"Admin command denylist hard-blocked shell at execution time",{toolCallId:t.toolCallId,parsingFailed:t.parsingResult?.parsingFailed??!0,parserCommandCount:t.parsingResult?.executableCommands.length??0}),{type:"adminCommandDenylist",pattern:o}):void 0}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!==Sk(e)}isPathEntry(e,t){return new RegExp(`^\\s*${e}\\s*\\(`).test(t)}matchesShell(e,t){const r=Sk(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","npx"];for(const o of e)vS(o.name)||(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)]}pathEntryRawPattern(e,t){const r=t.match(function(e){return"Read"===e?Tk:Ak}(e));if(r)return(r[1]??"").trim()}compileReadDenyMatcher(e){try{const t=this.pathEntryRawPattern("Read",e);if(void 0===t)return()=>!1;const r=function(e){const{trimmedPattern:t,regexSource:r}=Ci(e);let o;try{o=new RegExp(r)}catch{return e=>t===e}return e=>{try{return o.test(e)}catch{return t===e}}}((0,Gs.jl)(t));return e=>r(e)}catch(e){return()=>{throw e}}}matchesPathEntry(e,t,r){const o=this.pathEntryRawPattern(e,t);return void 0!==o&&this.matchGlob((0,Gs.jl)(o),r)}async isPathExplicitlyDenied(e,t){return(await this.getPermissions()).deny.some((r=>this.isPathEntry(e,r)&&this.matchesPathEntry(e,r,t)))}async isPathExplicitlyAllowed(e,t){return(await this.getPermissions()).allow.some((r=>this.isPathEntry(e,r)&&this.matchesPathEntry(e,r,t)))}matchGlob(e,t){return xi(e,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,r,o){const n={stack:[],error:void 0,hasError:!1};try{YS(n,(0,i.VI)(e.withName("InteractivePermissionsService.shouldBlockMcp")),!1);const{name:s,toolName:a,providerIdentifier:c,args:l}=t,u=function(e,t){if(void 0!==t)return t;const r=e;return void 0!==r.annotations?r.annotations:(0,Ww.yC)(r.annotationsJson)}(t,r?.annotations),d=e=>{this.mcpAllowlistLog?.(e)};d(`[permissions-service] shouldBlockMcp: toolName="${a}", providerIdentifier="${c}"`);const h=await this.computerUseDecision(t,r);if(!0===o?.alreadyApproved&&"block"!==h.kind&&"askEachCall"!==h.kind)return!1;const p=await this.getPermissions(),f=await this.teamSettingsService.getMcpToolControls(),m=!0===f?.enabled;if(await this.isMcpExplicitlyDenied(e,c,a))return d(`[permissions-service] shouldBlockMcp: BLOCKED (explicitly denied) toolName="${a}", providerIdentifier="${c}"`),{type:"permissionsConfig"};const g=m&&"block"!==h.kind?{kind:"notComputerUse"}:h,w="workspace_readonly"===p.userConfiguredPolicy.type&&"unrestricted"!==p.approvalMode,y=void 0!==t.smartModeApproval?.reason&&w,v=Rk({server:Ik(c),tool:a});let b,S,k;switch(g.kind){case"block":return d(`[permissions-service] shouldBlockMcp: BLOCKED (Computer Use app) toolName="${a}", providerIdentifier="${c}"`),{type:"unsafeResolution",message:g.message};case"noAccess":if(!w&&!await this.teamSettingsService.getShouldBlockMcp())return d(`[permissions-service] shouldBlockMcp: ALLOWED (Computer Use no access) toolName="${a}", providerIdentifier="${c}"`),!1;b=v,k=!0;break;case"app":if(!y&&(this.computerUseAppsAllowedForSession.includes(g.entry)||await this.isComputerUseAppSaved(g.entry)))return d(`[permissions-service] shouldBlockMcp: ALLOWED (Computer Use app grant) toolName="${a}", providerIdentifier="${c}"`),!1;b=g.entry,S=g.app,k=!1;break;case"askEachCall":b=void 0,S=g.app&&{...g.app,allowOnce:!0},k=!1;break;case"notComputerUse":b=v,k=!0}const E=k||void 0!==b,C=t.smartModeApproval?.reason;if(void 0!==C)return"workspace_readonly"===p.userConfiguredPolicy.type&&"unrestricted"!==p.approvalMode?(d(`[permissions-service] shouldBlockMcp: BLOCKED (readonly mode, Smart Mode forced approval) toolName="${a}", providerIdentifier="${c}"`),{type:"permissionsConfig",isReadonly:!0}):(d(`[permissions-service] shouldBlockMcp: needsApproval (Smart Mode) toolName="${a}", providerIdentifier="${c}"`),!(m?this.isMcpInTeamAllowlist(f,{providerIdentifier:c,toolName:a,annotations:u}):k&&await this.isMcpExplicitlyAllowed(e,c,a))&&!("unrestricted"===p.approvalMode&&!await this.teamSettingsService.getShouldBlockMcp())&&{type:"needsApproval",approvalReason:C,approvalDetails:{type:"mcp",name:s,toolName:a,providerIdentifier:c,args:l,reason:"smartMode",canAllowlist:E&&!this.isComputerUseServer(c),smartModeApprovalReason:C,smartModeApprovalRequestId:t.smartModeApproval?.requestId,allowlistEntry:b,computerUseApp:S}});if(m){const t=this.isMcpInTeamAllowlist(f,{providerIdentifier:c,toolName:a,annotations:u});if(this.recordMcpAllowlistCheckResult(e,{allowlistScope:"team",outcome:t?"pass":"fail"}),t)return d(`[permissions-service] shouldBlockMcp: ALLOWED (in admin MCP allowlist) toolName="${a}", providerIdentifier="${c}"`),!1}else if(k){const t=await this.isMcpExplicitlyAllowed(e,c,a);if(this.recordMcpAllowlistCheckResult(e,{allowlistScope:"user",outcome:t?"pass":"fail"}),t)return d(`[permissions-service] shouldBlockMcp: ALLOWED (explicitly in allowlist) toolName="${a}", providerIdentifier="${c}"`),!1}if("workspace_readonly"===p.userConfiguredPolicy.type&&"unrestricted"!==p.approvalMode)return d(`[permissions-service] shouldBlockMcp: BLOCKED (readonly mode) toolName="${a}", providerIdentifier="${c}"`),{type:"permissionsConfig",isReadonly:!0};if("unrestricted"===p.approvalMode){if(!await this.teamSettingsService.getShouldBlockMcp())return d(`[permissions-service] shouldBlockMcp: ALLOWED (auto-run, no team block) toolName="${a}", providerIdentifier="${c}"`),!1;d(`[permissions-service] shouldBlockMcp: needsApproval (auto-run but team blocks MCP) toolName="${a}", providerIdentifier="${c}"`)}return d(`[permissions-service] shouldBlockMcp: needsApproval (not in allowlist) toolName="${a}", providerIdentifier="${c}", approvalMode="${p.approvalMode}"`),{type:"needsApproval",approvalReason:`MCP tool: ${a}`,approvalDetails:{type:"mcp",name:s,toolName:a,providerIdentifier:c,args:l,canAllowlist:E,allowlistEntry:b,computerUseApp:S}}}catch(e){n.error=e,n.hasError=!0}finally{ek(n)}}async computerUseDecision(e,t){const r=this.computerUse;if(void 0===r||!this.isComputerUseServer(e.providerIdentifier))return{kind:"notComputerUse"};const o=await r.isOwnServer(Ik(e.serverIdentifier||e.providerIdentifier),t);if(!1===o)return{kind:"notComputerUse"};const n=await async function(e,t){const r=AS(e.meta?.["cursor/computerUseScope"])??AS(t.toolScopes?.[e.toolName]);if(void 0===r)return{kind:"screen"};let o;if(void 0!==r.appSelectorArgs){const t=Object.entries(r.appSelectorArgs).flatMap((([t,r])=>void 0===r||void 0===e.args[r]||null===e.args[r]?[]:[{selector:t,value:e.args[r]}]));if(0===t.length){const t=new Intl.ListFormat("en",{type:"disjunction"}).format(Object.values(r.appSelectorArgs).filter((e=>void 0!==e)));return{kind:"noAppSelector",message:`${e.toolName} needs exactly one of ${t} to name the app. Call it again with one of them.`}}const n=t.filter((({selector:e,value:t})=>function(e,t){return"pid"===e?"number"==typeof t&&Number.isInteger(t)||"string"==typeof t&&DS.test(t):"string"==typeof t&&t.length>0}(e,t)));if(1!==n.length){for(const{value:e}of t){const t="string"==typeof e?PS(e.trim()):void 0;if(void 0!==t)return{kind:"app",app:t}}return{kind:"unknownApp"}}o=function(e,t){if("pid"===e){const e="string"==typeof t&&DS.test(t)?Number(t):t;return"number"==typeof e&&Number.isSafeInteger(e)&&e>0?{pid:e}:void 0}const r="string"==typeof t?t.trim():"";if(0!==r.length)return"bundleId"===e?{bundleId:r}:"path"===e?{path:r}:{appName:r}}(n[0].selector,n[0].value)}else{if(void 0===r.appArg)return r.capturesScreen?{kind:"screen"}:{kind:"none"};{const t=e.args[r.appArg];if(null==t||function(e){return"object"==typeof e&&null!==e&&"screen"===e.scope}(t))return{kind:"screen"};o=function(e){if("string"==typeof e){const t=e.trim();return t.length>0?{name:t}:void 0}if("object"!=typeof e||null===e)return;const{scope:t,pid:r}=e;return"app"===t&&"number"==typeof r&&Number.isInteger(r)&&r>0?{pid:r}:void 0}(t)}}if(void 0===o)return{kind:"unknownApp"};const n=function(e){return"pid"in e?void 0:"name"in e?e.name:"bundleId"in e?e.bundleId:"path"in e?e.path:e.appName}(o),s=await t.describeApp(o)??(void 0===n?void 0:PS(n));return void 0===s?{kind:"unknownApp"}:{kind:"app",app:s}}({toolName:e.toolName,args:Object.fromEntries(Object.entries(e.args).map((([e,t])=>[e,t.toJson()]))),meta:t?._meta},r);if(void 0===o&&"app"!==n.kind)return{kind:"askEachCall"};switch(n.kind){case"none":return{kind:"noAccess"};case"screen":return{kind:"notComputerUse"};case"unknownApp":return{kind:"askEachCall"};case"noAppSelector":return{kind:"block",message:n.message};case"app":{const e=function(e){const t=e.toLowerCase();return xS(t)?"Computer Use doesn't control Cursor itself, including its approval cards. Ask the user to do it instead.":_S.some((e=>e.bundleId===t))?"Computer Use doesn't control terminal apps. Use your shell tool to run commands instead.":void 0}(n.app.bundleId);if(void 0!==e)return{kind:"block",message:e};if(void 0===o)return{kind:"askEachCall"};const t=RS(n.app.bundleId)?void 0:Rk({server:r.serverId,tool:TS(n.app.bundleId)});return void 0===t?{kind:"askEachCall",app:n.app}:{kind:"app",app:n.app,entry:t}}}}isComputerUseServer(e){const t=Ik(e);return!0===this.computerUse?.providerIdentifiers.has(t)}allowComputerUseAppForSession({bundleId:e}){const t=void 0===this.computerUse||RS(e)?void 0:Rk({server:this.computerUse.serverId,tool:TS(e)});void 0!==t&&this.computerUseAppsAllowedForSession.push(t)}async isMcpFullyAllowlisted(e,t){const r=e.withName("InteractivePermissionsService.isMcpFullyAllowlisted"),{providerIdentifier:o,toolName:n}=t,s=t.annotations??(0,Ww.yC)(t.annotationsJson);if(await this.isMcpExplicitlyDenied(r,o,n))return!1;const i=await this.teamSettingsService.getMcpToolControls();return!0===i?.enabled?!!this.isMcpInTeamAllowlist(i,{providerIdentifier:o,toolName:n,annotations:s}):!this.isComputerUseServer(o)&&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=Ik(t).toLowerCase().trim(),c=r.toLowerCase().trim(),l="*"===s||this.matchGlob(s,a),u="*"===i||this.matchGlob(i,c),d=l&&u,h=`[permissions-service] ${o}: serverPattern="${s}", toolPattern="${i}", normalizedProviderIdentifier="${a}", normalizedToolName="${c}", serverMatches=${l}, toolMatches=${u}, result=${d}`;return this.mcpAllowlistLog?.(h),d}recordMcpAllowlistCheckResult(e,{allowlistScope:t,outcome:r}){rk.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&&fS(t,r[1]?.trim()??"")}matchesMcpEntryBare({pattern:e,providerIdentifier:t,toolName:r}){return this.matchesMcpPattern({pattern:e,providerIdentifier:t,toolName:r,logLabel:"matchesMcpEntryBare"})}isMcpInTeamAllowlist(e,{providerIdentifier:t,toolName:r,annotations:o}){if(e.mcpToolAllowlist.some((e=>this.matchesMcpEntryBare({pattern:e,providerIdentifier:t,toolName:r}))))return!0;const n=this.findTeamMcpServerPolicy(e,t);return void 0!==n&&"reads"===n.mode&&(0,gS.rh)(n,{name:r,annotations:o})}findTeamMcpServerPolicy(e,t){for(const r of e.serverPolicies??[])if(this.matchesMcpEntryBare({pattern:`${r.name}:*`,providerIdentifier:t,toolName:""}))return r.policy}async isMcpExplicitlyDenied(e,t,r){return(await this.getPermissions()).deny.some((e=>this.matchesMcpEntry(e,t,r)))}async isComputerUseAppSaved(e){return(await this.getPermissions()).allow.some((t=>t.match(/^\s*Mcp\s*\((.*)\)\s*$/)?.[1]?.trim().toLowerCase()===e))}async isMcpExplicitlyAllowed(e,t,r){return(await this.getPermissions()).allow.some((e=>this.matchesMcpEntry(e,t,r)))}}var Dk=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 Ok=(0,m.h)("LocalReadExecutor"),Nk=async(e,t,r,o)=>{const n=setTimeout((()=>{Ok.warn(e,`[watchdog, LocalReadExecutor] ${t} still not completed after ${r}ms`)}),r);try{return await o()}finally{clearTimeout(n)}};function $k(e){return BigInt(Math.min(e,4294967295))}function Fk(e){if(e.length<5||45!==e[0]||45!==e[1]||45!==e[2]||10!==e[3])return 0;const t=Buffer.from("\n---\n"),r=e.indexOf(t,4);return-1===r?0:r+t.length}function jk(e){return e>=32&&e<=126||9===e||10===e||13===e}function Lk(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&&jk(t)&&r++,0===t&&jk(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"}const Uk=Buffer.from("\n---\n");function Bk(e,t){const r=e.length;if(r<2*Uk.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(Uk,r-Uk.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+Uk.length,r-4).toString("utf-8"))?n:r}const Wk=[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 Hk(e){return new Ut.sV({result:{case:"invalidFile",value:new Ut.cW({path:e,reason:"File content is binary data, not text"})}})}function qk(e,t,r){if(void 0===r.offset&&void 0===r.limit)return{applied:!1};if(t)return{applied:!1};const o=r.offset??1,n=r.limit??(o<0?Math.abs(o):e),s=o<0?Math.max(0,e+o):Math.max(0,o-1);if(s>=e)return{applied:!1};const i=Math.min(e,s+n),a=zk(s,e),c=zk(i,e);return{applied:!0,start:a,end:Math.max(a,c)}}function zk(e,t){if(Number.isNaN(e)||0===e)return 0;if(e===Number.POSITIVE_INFINITY)return t;if(e===Number.NEGATIVE_INFINITY)return 0;const r=Math.trunc(e);return r<0?Math.max(t+r,0):Math.min(r,t)}function Gk(e){return-1===e.indexOf("\r\n")?e:e.replaceAll("\r\n","\n")}function Vk(e,t,r,o,n,s){if(o>=n)return{from:0,to:0};let i=0,a=0,c=0===o,l=0;for(;i<n;){const t=e(l);if(t<0)break;if(i++,i===o&&(a=t+1,c=!0),i===n)return{from:a,to:s&&t>a&&13===r(t)?t-1:t};l=t+1}return c?{from:a,to:t}:{from:t,to:t}}function Jk(e,t,r){const o=Vk((t=>e.indexOf("\n",t)),e.length,(t=>e.charCodeAt(t-1)),t,r,!1);return 0===o.from&&o.to===e.length?e:o.from>=o.to?"":e.slice(o.from,o.to)}function Kk(e,t,r,o,n){if(t>=r)return{text:"",truncated:!1};const s=o>=0?o+3:-1;let i=t;if(o>=0&&i>=o&&i<s&&(i=s),i>=r)return{text:"",truncated:!1};const a=function(e,t,r,o){if(r>=o)return o;if(r<=t)return t;const n=Math.max(t,r-3);let s=r;for(;s>n;){if(128!=(192&(e[s]??0)))return s;s--}return 192&~(e[s]??0)?r:s}(e,i,Math.min(r,i+3*(n+1)+3),r);let c=Gk(function(e,t,r,o){if(t>=r)return"";if(o<0)return e.toString("utf8",t,r);const n=o+3;return r<=o||t>=n?e.toString("utf8",t,r):t>=o&&r<=n?"":(t<o?e.toString("utf8",t,Math.min(r,o)):"")+(r>n?e.toString("utf8",Math.max(t,n),r):"")}(e,i,a,o));const l=c.length>n||a<r;return c.length>n&&(c=c.slice(0,n)),{text:c,truncated:l}}function Zk(e,t,r,o){if(t>=r)return{text:"",truncated:!1};const n=Math.min(r,t+2*o+1);let s=Gk(e.slice(t,n));const i=s.length>o||n<r;return s.length>o&&(s=s.slice(0,o)),{text:s,truncated:i}}function Xk(e,t,r=8388608){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 Qk(e,t){const r=Xk(e,t);return{text:r.text,truncated:r.truncated}}function Yk(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=Xk(o,"\n")),o=Xk(o,n.text),n.truncated&&(o={text:o.text,truncated:!0})})),o}function eE(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 tE extends Error{constructor(){super("Invalid UTF-8 while streaming read"),this.name="InvalidUtf8Error"}}async function rE(e,t,r,o,n,s){const i=void 0!==r.offset||void 0!==r.limit,a=(r.offset??1)<0,c=r.offset??1,l=Math.max(0,c-1),u=void 0===r.limit?void 0:l+r.limit,d=a?Math.abs(c):0;let h=[],p=0,f=!1,m=!(a||i&&l<=0),g=!1;const w=[];let y=0,v=!1;const b=[];let S=0,k=!1,E={text:"",truncated:!1},C=0,x=0,_=0,P=!1,I=!1;const R=e=>{let t=e;return!P&&t.length>0&&(P=!0,65279===t.charCodeAt(0)&&(I=!0,t=t.slice(1))),t},T=(e,t)=>{e&&(t?x++:_++),C++},A=(e,t,r)=>{const o=C;if(0===o&&(g=0===e.text.length),!a&&i&&m&&o>=l&&(m=!1,h=[]),m&&((e,t)=>{if(f&&p>=jt)return;const r=h.length>0?1:0;let o=jt-p;if(r>0){if(o<=0)return void(f=!0);o--}const n=e.text.length>o?{line:{text:e.text.slice(0,o),truncated:!0},hasNewline:t}:{line:e,hasNewline:t};h.push(n),p+=r+n.line.text.length,(e.truncated||n.line.truncated)&&(f=!0)})(e,t),a){if(d>0){for(b.push({line:e,hasNewline:t}),S+=e.text.length+1;b.length>d;){const e=b.shift();void 0!==e&&(S-=e.line.text.length+1)}for(;b.length>1&&S>jt;){const e=b.shift();void 0!==e&&(S-=e.line.text.length+1,k=!0)}}}else i&&o>=l&&(void 0===u||o<u)&&((e,t)=>{if(v&&y>=jt)return;const r=w.length>0?1:0;let o=jt-y;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};w.push(n),y+=r+n.line.text.length,e.truncated&&(v=!0),n.line.truncated&&(v=!0)})(e,t);T(t,r)},M=()=>!(!m||f&&p>=jt)||!(!i||0!==C)||(a?d>0:!(!i||v&&y>=jt)&&C>=l&&C<(u??1/0));let D=!1;for await(const r of async function*(e,t,r,o){const n=o>0?{start:0,end:o-1}:{};if("strictUtf8"===r.kind){const r=new ji.TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}),o=(0,$s.createReadStream)(t,{highWaterMark:65536,signal:e.signal,...n});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 tE;throw e}return}const s=(0,$s.createReadStream)(t,{highWaterMark:65536,signal:e.signal,...n}).pipe(Li.decodeStream(r.decoderEncoding));for await(const e of s)yield"string"==typeof e?e:String(e)}(e,t,o,s)){const e=R(r);let t=0,o=e.indexOf("\n",t);for(;-1!==o;){const r=o>t?13===e.charCodeAt(o-1):D;M()?(E=Qk(E,e.slice(t,o)),A(E,!0,r)):T(!0,r),E={text:"",truncated:!1},D=!1,t=o+1,o=e.indexOf("\n",t)}t<e.length&&(M()&&(E=Qk(E,e.slice(t))),D=13===e.charCodeAt(e.length-1))}M()?A(E,!1,!1):T(!1,!1);const O=x+_,N=O>0&&x/O*100>=5,$="utf8"===o.cacheEncoding&&I?"utf8bom":o.cacheEncoding;n&&function(e,t){if(na.has(e)&&na.delete(e),na.set(e,t),na.size<=100)return;const r=na.keys().next().value;void 0!==r&&na.delete(r)}(t,$);const F=()=>Yk({text:"",truncated:f},h,N);if(!i){const e=F();return{content:e.text,totalLines:C,truncated:e.truncated,rangeApplied:!1}}if(C<=1&&g)return{content:"",totalLines:C,truncated:!1,rangeApplied:!1};if(a){const e=r.limit??d;let t={text:"",truncated:k};return t=Yk(t,b.slice(0,e),N),{content:t.text,totalLines:C,truncated:t.truncated,rangeApplied:!0}}if(l>=C){const e=F();return{content:e.text,totalLines:C,truncated:e.truncated,rangeApplied:!1}}let j={text:"",truncated:v};return j=Yk(j,w,N),{content:j.text,totalLines:C,truncated:j.truncated,rangeApplied:!0}}class oE{constructor(e,t,r){this.permissionsService=e,this.workspacePath=t,this.mcpStateAccessor=r?.mcpStateAccessor,this.useStreamingRead=r?.useStreamingRead,this.pendingDecisionProvider=r?.pendingDecisionProvider}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,i.VI)(e.withName("LocalReadExecutor.execute")),!1);const n=t.path;if(""===n.trim())return new Ut.sV({result:{case:"error",value:new Ut.F_({path:n,error:Vs})}});const a=(0,Gs.o1)(n,this.workspacePath),c=await Nk(e,"permissionsService.shouldBlockFileRead",3e3,(()=>Pk(this.permissionsService,a)));if(c){const r=await Nk(e,"resolveFileReadBlock",3e3,(()=>async function(e,t){return await Pc(e,{onNeedsApproval:async(e,r)=>{const o=t.pendingDecisionProvider?.requestReadApproval?.bind(t.pendingDecisionProvider);if("fileRead"!==r.type||!o)return{kind:"denied",message:"Blocked by permissions configuration"};const n=await o({type:vm.Read,details:{path:r.path,reason:e},toolCallId:t.toolCallId});return n.approved?null:{kind:"rejected",reason:n.reason}},onUserRejected:e=>({kind:"rejected",reason:e}),onPermissionDenied:e=>({kind:"denied",message:e})})??{kind:"proceed"}}(c,{pendingDecisionProvider:this.pendingDecisionProvider,toolCallId:t.toolCallId})));if("rejected"===r.kind)return new Ut.sV({result:{case:"rejected",value:new Ut.f4({path:a,reason:r.reason??""})}});if("denied"===r.kind)return new Ut.sV({result:{case:"permissionDenied",value:new Ut.lW({path:a})}})}void 0!==this.mcpStateAccessor&&Uy(e,this.mcpStateAccessor,a);try{const r=await Nk(e,"stat",3e3,(()=>(0,Os.stat)(a)));if(r.isDirectory())return new Ut.sV({result:{case:"invalidFile",value:new Ut.cW({path:a,reason:"Path is a directory, not a file"})}});if(!r.isFile())return new Ut.sV({result:{case:"invalidFile",value:new Ut.cW({path:a,reason:"Path is neither a file nor a directory"})}});const n=function(e){return null!==function(e){const t=Bt(e,"terminals");if(!t||1!==t.remainingPath.length)return null;const r=t.remainingPath[0],o=/^(\d+)\.txt$/.exec(r);if(!o)return null;const n=Number.parseInt(o[1],10);return Number.isNaN(n)?null:{id:n}}(e)}(a),i=function(e){const t=Bt(e,"agent-tools");return null!==t&&1===t.remainingPath.length&&t.remainingPath[0].endsWith(".txt")}(a);if(n||i)return await this.readTerminalFile(e,a,r,t,i&&!n);const c=await Nk(e,"getFormatForFile",3e3,(()=>ha(a))),l=c.isImageFile,u=function(e){return".pdf"===(0,s.extname)(e).toLowerCase()}(a),d=ca(a);if(l){const t=await Nk(e,"prepareImageForModel",3e3,(async()=>(async e=>{let t;try{t=await Uw(e)}catch(t){const r=await Bw(e);if("undecodable"===r.kind)return r;throw t}if(!0===t.reencoded)return{kind:"image",image:t};const r=await Bw(t.data);return"undecodable"===r.kind?r:{kind:"image",image:t}})(await(0,Os.readFile)(a))));return"undecodable"===t.kind?new Ut.sV({result:{case:"invalidFile",value:new Ut.cW({path:a,reason:(o=t.reason,`File is not a valid image: its data could not be decoded (${o}). A truncated or hand-copied file does this; write it again from the original bytes with code.`)})}}):new Ut.sV({result:{case:"success",value:new Ut.mE({path:a,output:{case:"data",value:t.image.data},totalLines:0,fileSize:$k(r.size),truncated:!1})}})}if(u){const t=await Nk(e,"readPdfBinary",3e3,(()=>(0,Os.readFile)(a)));return new Ut.sV({result:{case:"success",value:new Ut.mE({path:a,output:{case:"data",value:t},totalLines:0,fileSize:$k(r.size),truncated:!1})}})}if(c.isBinaryFile&&d){const t=await Nk(e,"readBinaryFile",3e3,(()=>(0,Os.readFile)(a)));return new Ut.sV({result:{case:"success",value:new Ut.mE({path:a,output:{case:"data",value:t},totalLines:0,fileSize:$k(r.size),truncated:!1})}})}if(c.isBinaryFile)return Hk(a);{const o=this.useStreamingRead,n=!o||await Nk(e,"useStreamingRead",3e3,(()=>o()));if(n||r.size>jt){const o=await Nk(e,"readTextStreaming",7e3,(()=>async function(e,t,r,o,n,s){const i=function(e,t,r){const o=function(e,t,r){return eE(r??na.get(e)??t.encoding)}(e,t,r),n=function(e){const t=eE(e);return"utf8bom"===t?"utf8":t}(o);return"utf8"===n?{kind:"strictUtf8",cacheEncoding:"utf8"}:Li.encodingExists(n)?{kind:"iconv",decoderEncoding:n,cacheEncoding:o}:{kind:"strictUtf8",cacheEncoding:"utf8"}}(t,r,o.encodingHint);try{return await rE(e,t,o,i,n,s)}catch(r){if(r instanceof tE)return await rE(e,t,o,{kind:"iconv",decoderEncoding:"latin1",cacheEncoding:"latin1"},n,s);throw r}}(e,a,c,t,n,r.size)));return new Ut.sV({result:{case:"success",value:new Ut.mE({path:a,output:{case:"content",value:o.content},totalLines:o.totalLines,fileSize:$k(r.size),truncated:o.truncated,rangeApplied:o.rangeApplied})}})}const s=await Nk(e,"readText",3e3,(()=>ua(a,t.encodingHint))),i=await Nk(e,"countLines",3e3,(()=>Bi(s))),l=function(e,t,r){const o=qk(t,""===e,r);return o.applied?o.start>=o.end?{content:"",rangeApplied:!0}:{content:Jk(e,o.start,o.end),rangeApplied:!0}:{content:e,rangeApplied:!1}}(s,i,t);let u=l.content,d=!1;return u.length>jt&&(u=u.substring(0,jt),d=!0),new Ut.sV({result:{case:"success",value:new Ut.mE({path:a,output:{case:"content",value:u},totalLines:i,fileSize:$k(r.size),truncated:d,rangeApplied:l.rangeApplied})}})}}catch(e){const t=e;return"ENOENT"===t.code?new Ut.sV({result:{case:"fileNotFound",value:new Ut.Ko({path:a})}}):"EACCES"===t.code||"EPERM"===t.code?new Ut.sV({result:{case:"permissionDenied",value:new Ut.lW({path:a})}}):new Ut.sV({result:{case:"error",value:new Ut.F_({path:a,error:t instanceof Error?t.message:"Unknown error occurred"})}})}}catch(e){r.error=e,r.hasError=!0}finally{Dk(r)}var o}async readTerminalFile(e,t,r,o,n){const s=await Nk(e,"readTerminalFile",3e3,(()=>async function(e,t){if(0===t)return(0,Os.readFile)(e);if(t>2147483647)throw new RangeError(`File size (${t}) is greater than 2 GiB`);const r=await(0,Os.open)(e,"r");try{const e=Buffer.allocUnsafe(t);let o=0;for(;o<t;){const{bytesRead:n}=await r.read(e,o,t-o,o);if(0===n)break;o+=n}return e.subarray(0,o)}finally{await r.close()}}(t,r.size)));if(n&&(i=s,Wk.some((e=>function(e,t){return e.length>=t.length&&e.subarray(0,t.length).equals(t)}(i,e)))))return Hk(t);var i;const a=function(e,t,r=8388608){if(0===e.length)return{content:"",totalLines:1,rangeApplied:!1,truncated:!1};const o=Fk(e),n=Bk(e,o);if("utf-8"!==Lk(e.subarray(o,n)))return function(e,t,r){const o=0===e.length,n=function(e){let t=0,r=0;const o=e.length;for(;r<o;){const o=e.indexOf("\n",r);if(o<0)break;t++,r=o+1}return t}(e)+1,s=qk(n,o,t);if(!s.applied){const t=Zk(e,0,e.length,r);return{content:t.text,totalLines:n,rangeApplied:!1,truncated:t.truncated}}if(s.start>=s.end)return{content:"",totalLines:n,rangeApplied:!0,truncated:!1};const i=Vk((t=>e.indexOf("\n",t)),e.length,(t=>e.charCodeAt(t-1)),s.start,s.end,!0),a=Zk(e,i.from,i.to,r);return{content:a.text,totalLines:n,rangeApplied:!0,truncated:a.truncated}}(function(e){const t=Fk(e),r=t>0?e.subarray(0,t).toString("utf-8"):"",o=Bk(e,t),n=o<e.length?e.subarray(o).toString("utf-8"):"",s=e.subarray(t,o),i=Lk(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}(e),t,r);const s=function(e,t,r){return t+3>r?-1:239===e[t]&&187===e[t+1]&&191===e[t+2]?t:-1}(e,o,n);return function(e,t,r,o){const n=e.length-(t>=0?3:0)==0,s=function(e){let t=0,r=0;const o=e.length;for(;r<o;){const o=e.indexOf(10,r);if(o<0)break;t++,r=o+1}return t}(e)+1,i=qk(s,n,r);if(!i.applied){if(n)return{content:"",totalLines:s,rangeApplied:!1,truncated:!1};const r=Kk(e,0,e.length,t,o);return{content:r.text,totalLines:s,rangeApplied:!1,truncated:r.truncated}}if(i.start>=i.end)return{content:"",totalLines:s,rangeApplied:!0,truncated:!1};const a=Vk((t=>e.indexOf(10,t)),e.length,(t=>e[t-1]??0),i.start,i.end,!0),c=Kk(e,a.from,a.to,t,o);return{content:c.text,totalLines:s,rangeApplied:!0,truncated:c.truncated}}(e,s,t,r)}(s,o);return new Ut.sV({result:{case:"success",value:new Ut.mE({path:t,output:{case:"content",value:a.content},totalLines:a.totalLines,fileSize:$k(r.size),truncated:a.truncated,rangeApplied:a.rangeApplied})}})}}var nE=r("../proto/dist/generated/agent/v1/record_screen_exec_pb.js"),sE=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var 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 iE(e){return null!==e.exitCode||null!==e.signalCode||e.killed}function aE(e,t){return"object"==typeof e&&null!==e&&"code"in e&&e.code===t}function cE(e){return e instanceof Error?e.message:String(e)}function lE(e,t,r,o){const n=[],s=function(e,t){const r=e.ffmpegExitCode??e.childProcess.exitCode,o=e.ffmpegExitSignal??e.childProcess.signalCode;if(e.ffmpegDiedEarly||null!==e.ffmpegDiedTime||null!==r||null!==o)return`ffmpeg exited code=${r} signal=${o}${null!==e.ffmpegDiedTime?` ${Math.max(0,Math.round((t-e.ffmpegDiedTime)/1e3))}s before SAVE`:""}`}(t,o);return void 0!==s&&n.push(s),void 0!==r&&n.push(`stop failed: ${cE(r)}`),n.length>0?`${e} (${n.join("; ")})`:e}const uE=(0,ji.promisify)(Iu.execFile);class dE{constructor(e){if(this.activeRecording=null,this.inFlightSaves=[],this.onRecordingStartedCallback=null,this.onRecordingStoppedCallback=null,this.recordingStoppedCallbackInvoked=!1,this.artifactsDir=e.artifactsDir,this.stagingDir=e.stagingDir??"/opt/cursor/recording-staging/",this.display=e.display,this.disablePolishedRendering=e.disablePolishedRendering??!1,this.polishedRenderer=e.polishedRenderer,!this.disablePolishedRendering){if(!this.polishedRenderer)throw new Error("record_screen requires a polished recording renderer when polished rendering is enabled. This tool should run via exec-daemon where that dependency is bundled.");this.polishedRenderer.assertAvailable()}}setOnRecordingStarted(e){this.onRecordingStartedCallback=e}setOnRecordingStopped(e){this.onRecordingStoppedCallback=e}invokeStoppedCallbackOnce(){!this.recordingStoppedCallbackInvoked&&this.onRecordingStoppedCallback&&(this.recordingStoppedCallbackInvoked=!0,this.onRecordingStoppedCallback())}async cleanupRecording(e){try{await e.inputEventLogger.stop()}catch{}if(!iE(e.childProcess)&&e.childProcess.pid)try{await this.stopFfmpegRecording(e)}catch{try{process.kill(e.childProcess.pid,"SIGKILL")}catch{}}}getActiveInputEventLogger(){return this.activeRecording?.inputEventLogger??null}async dispose(){const e=this.inFlightSaves.map((e=>e.promise));if(e.length>0)try{await(0,Ht.wj)(Promise.all(e),dE.IN_FLIGHT_SAVE_DISPOSE_TIMEOUT_MS,"Timed out waiting for in-flight recording save")}catch{}if(this.activeRecording){await this.cleanupRecording(this.activeRecording),this.invokeStoppedCallbackOnce();try{await Os.rm(this.activeRecording.sessionDir,{force:!0,recursive:!0})}catch{}this.activeRecording=null}}findInFlightSave(e){return this.inFlightSaves.find((t=>t.state===e))}clearActiveRecordingIfCurrent(e){this.activeRecording===e&&(this.activeRecording=null)}invokeStoppedCallbackIfCurrent(e){this.activeRecording===e&&this.invokeStoppedCallbackOnce()}sanitizeToolCallId(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_")}async ensureRecordingDirectoryExists(){await Os.mkdir(this.stagingDir,{recursive:!0}),await Os.mkdir(this.artifactsDir,{recursive:!0})}buildSessionDir(e){const t=this.sanitizeToolCallId(e),r=`session-${(new Date).toISOString().replace(/[:.]/g,"-")}-${t}`;return s.join(this.stagingDir,r)}validateAndNormalizeSaveAsFilename(e){let t=e.trim();return t.startsWith(this.artifactsDir)&&(t=t.slice(this.artifactsDir.length),t.startsWith("/")&&(t=t.slice(1))),t=t.trim(),0===t.length?{success:!1,reason:nE.y.UNSPECIFIED}:t.includes("/")||t.includes("\\")?{success:!1,reason:nE.y.SLASHES_NOT_ALLOWED}:(t=t.replace(/[^a-zA-Z0-9 ._-]/g,"_"),t=t.trim(),0===t.length?{success:!1,reason:nE.y.UNSPECIFIED}:(t.length>128&&(t=t.slice(0,128).trim()),t.toLowerCase().endsWith(".mp4")||(t=`${t}.mp4`),{success:!0,filename:t}))}async movePolishedVideo(e,t){try{return void await Os.rename(e,t)}catch(e){if(!aE(e,"EXDEV"))throw e}try{await Os.copyFile(e,t)}catch(e){throw await Os.rm(t,{force:!0}).catch((()=>{})),e}try{await Os.unlink(e)}catch(e){throw await Os.rm(t,{force:!0}).catch((()=>{})),e}}async getUniqueArtifactVideoPath(e){const t=s.parse(e),r=t.name||"recording",o=t.ext||".mp4";let n=`${r}${o}`,i=2;for(;;){const e=s.join(this.artifactsDir,n);try{const t=await Os.open(e,"wx");return await t.close(),e}catch(e){if(!aE(e,"EEXIST"))throw e;n=`${r}-${i}${o}`,i++}}}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=`${s.basename(r)}.mp4`)}else n=`${s.basename(r)}.mp4`;return{finalVideoPath:await this.getUniqueArtifactVideoPath(n),requestedFilePathRejectedReason:o}}async getVideoDurationMs(e){const{stdout:t}=await(0,Of.D9)(uE,"ffprobe",["-v","error","-show_entries","format=duration","-of","default=noprint_wrappers=1:nokey=1",e],{encoding:"utf8"}),r=parseFloat(t.trim());if(!Number.isFinite(r)||r<0)throw new Error(`Invalid video duration from ffprobe: ${t.trim()}`);return Math.floor(1e3*r)}async getVideoDimensions(e){const{stdout:t}=await(0,Of.D9)(uE,"ffprobe",["-v","error","-select_streams","v:0","-show_entries","stream=width,height","-of","csv=p=0:s=x",e],{encoding:"utf8"}),[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,t){const r=s.join(t,"recording"),o=s.join(r,"recording_full.mp4");try{await this.polishedRenderer.renderRecordingSession({stagingSessionDir:t,outputVideoPath:o,fps:dE.PROXY_TARGET_FPS,includeBrandTag:!0}),await Os.access(o,Os.constants.R_OK)}catch(t){const r=(0,i.fU)(e);throw r?.setAttribute("error.type",function(e){return e instanceof Error?e.message.startsWith("Failed to load polished-renderer native binding")?"binding_load_failed":"code"in e&&"string"==typeof e.code?e.code:e.name:typeof e}(t)),r?.setStatus({code:2}),t}return o}async getVideoFramerate(e){try{const{stdout:t}=await(0,Of.D9)(uE,"ffprobe",["-v","error","-select_streams","v:0","-show_entries","stream=r_frame_rate","-of","default=noprint_wrappers=1:nokey=1",e],{encoding:"utf8"}),r=t.trim();if(r.includes("/")){const[e,t]=r.split("/"),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 ${dE.PROXY_TARGET_FPS}fps`)}catch(e){console.warn(`[record-screen] Failed to read video framerate: ${e instanceof Error?e.message:String(e)}, defaulting to ${dE.PROXY_TARGET_FPS}fps`)}return dE.PROXY_TARGET_FPS}async startFfmpegRecording(e,t){const r=s.join(t,"recording");await Os.mkdir(r,{recursive:!0});const o=s.join(r,"recording_render_proxy_1080p.mp4");let n;try{n=(await Lf(this.display)).display.refreshRate}catch(e){console.warn(`[record-screen] Failed to detect refresh rate: ${e instanceof Error?e.message:String(e)}, using default ${dE.DEFAULT_REFRESH_RATE}Hz`),n=dE.DEFAULT_REFRESH_RATE}const i=["-video_size",e,"-framerate",String(n),"-draw_mouse","0","-f","x11grab","-i",this.display,"-vf",`scale=${dE.PROXY_TARGET_WIDTH}:-2:flags=lanczos,fps=${dE.PROXY_TARGET_FPS}`,"-c:v","libx264","-preset",dE.PROXY_PRESET,"-crf",String(dE.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],a=(0,Of.D9)(Iu.spawn,"ffmpeg",i,{stdio:["ignore","pipe","pipe"],detached:!0}),c=new Promise(((e,t)=>{let r="",o=!1;a.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);a.once("exit",((e,r)=>{clearTimeout(n),o||t(new Error(`ffmpeg exited before starting: code=${e} signal=${r}`))})),a.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);a.once("error",(e=>{clearTimeout(r),t(new Error(`Failed to start ffmpeg: ${e.message}`))})),a.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:a,videoStartedPromise:c}}async runFfmpegCommand(e,t){return await new Promise(((r,o)=>{const n=(0,Of.D9)(Iu.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:i,resolution:a,renderProxies:c}=e,l=s.join(t,"recording"),u=s.join(l,"recording-data.json"),d=n-o,h=i.map((e=>({executionTimestampMs:e.executionTimestampMs,commandDurationMs:e.commandDurationMs,positionBefore:e.positionBefore,positionAfter:e.positionAfter,cursorTypeAfter:e.cursorTypeAfter,action:{action:this.serializeAction(e.action)}}))),p={version:3,durationMs:r,recordingStartEpochMs:o,ffmpegStartedEpochMs:n,eventToVideoOffsetMs:d,displayWidth:a.display.width,displayHeight:a.display.height,apiWidth:a.api.width,apiHeight:a.api.height,inputEvents:h,renderProxies:c??null};await Os.writeFile(u,JSON.stringify(p,null,2))}serializeAction(e){const{action:t}=e,r={case:t.case};switch(t.case){case"click":r.value={coordinate:t.value.coordinate?{x:t.value.coordinate.x,y:t.value.coordinate.y}:null,button:t.value.button,count:t.value.count,modifierKeys:t.value.modifierKeys};break;case"mouseMove":r.value={coordinate:t.value.coordinate?{x:t.value.coordinate.x,y:t.value.coordinate.y}:null};break;case"type":r.value={text:t.value.text};break;case"key":r.value={key:t.value.key,holdDurationMs:t.value.holdDurationMs};break;case"scroll":r.value={coordinate:t.value.coordinate?{x:t.value.coordinate.x,y:t.value.coordinate.y}:null,direction:t.value.direction,amount:t.value.amount,modifierKeys:t.value.modifierKeys};break;case"drag":r.value={path:t.value.path.map((e=>({x:e.x,y:e.y}))),button:t.value.button};break;case"wait":r.value={durationMs:t.value.durationMs};break;case"screenshot":case"cursorPosition":case"mouseDown":case"mouseUp":r.value=t.value;break;default:r.value={}}return r}async stopFfmpegRecording(e){const{childProcess:t}=e;if(iE(t)||!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(t){if(clearTimeout(n),aE(t,"ESRCH"))return void e();o(new Error(`Failed to send SIGTERM: ${t instanceof Error?t.message:String(t)}`))}}))}async performSave(e,t,r){const o=Date.now();try{const n=await r.inputEventLogger.stop(),i=r.inputEventLogger.getRecordingStartTime();let a;this.invokeStoppedCallbackIfCurrent(r);try{!iE(r.childProcess)&&r.childProcess.pid&&await this.stopFfmpegRecording(r)}catch(e){a=e,console.warn(`[record-screen] Failed to stop ffmpeg: ${cE(e)}`)}const c=r.ffmpegStartedEpochMs??i,l=r.sessionDir,u=s.join(l,"recording"),d=s.join(u,"recording_render_proxy_1080p.mp4");let h,p,f;try{await Os.access(d,Os.constants.R_OK)}catch(e){await this.cleanupRecording(r),this.clearActiveRecordingIfCurrent(r);const t=aE(e,"ENOENT")?`Recording proxy not found at ${d}`:`Recording proxy at ${d} could not be validated: ${cE(e)}`;return new nE.Tj({result:{case:"failure",value:new nE.yH({error:lE(t,r,a,o)})}})}try{if([h,p,f]=await Promise.all([this.getVideoDurationMs(d),this.getVideoDimensions(d),this.getVideoFramerate(d)]),h<=0)throw new Error(`Recording proxy has zero duration at ${d}`)}catch(e){await this.cleanupRecording(r);const t=cE(e),n=t.includes(d)?t:`Recording proxy at ${d} could not be validated: ${t}`;return new nE.Tj({result:{case:"failure",value:new nE.yH({error:lE(n,r,a,o)})}})}const m={profileVersion:dE.PROXY_PROFILE_VERSION,generatedAtEpochMs:Date.now(),source:{width:p.width,height:p.height,durationMs:h,fps:f},artifacts:[{name:"render_proxy_1080p",path:"recording_render_proxy_1080p.mp4",width:p.width,height:p.height,fps:dE.PROXY_TARGET_FPS,codec:"h264",profile:dE.PROXY_PROFILE_VERSION,keyint:1,status:"success",elapsedMs:0}]};await this.saveRecordingDataPackage({sessionDir:l,durationMs:h,recordingStartEpochMs:i,ffmpegStartedEpochMs:c,inputEvents:n,resolution:r.resolution,renderProxies:m});const{finalVideoPath:g,requestedFilePathRejectedReason:w}=await this.resolveArtifactVideoPath({saveAsFilename:t.saveAsFilename,stagingSessionDir:l});try{if(this.disablePolishedRendering)await Os.copyFile(d,g);else{const t=await this.renderPolished(e,l);await this.movePolishedVideo(t,g)}}catch(e){throw await Os.rm(g,{force:!0}).catch((()=>{})),e}try{await Os.rm(l,{force:!0,recursive:!0})}catch(e){console.warn(`[record-screen] Failed to remove staging session ${l}: ${cE(e)}`)}return this.clearActiveRecordingIfCurrent(r),new nE.Tj({result:{case:"saveSuccess",value:new nE.ol({path:g,recordingDurationMs:qt.protoInt64.parse(h.toString()),requestedFilePathRejectedReason:w})}})}catch(e){return await this.cleanupRecording(r),this.invokeStoppedCallbackIfCurrent(r),new nE.Tj({result:{case:"failure",value:new nE.yH({error:cE(e)})}})}}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,i.VI)(e.withName("LocalRecordScreenExecutor.execute")),!1);try{await this.ensureRecordingDirectoryExists()}catch(e){return new nE.Tj({result:{case:"failure",value:new nE.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===nE.$u.UNSPECIFIED)return new nE.Tj({result:{case:"failure",value:new nE.yH({error:"Mode must be one of START_RECORDING, SAVE_RECORDING, DISCARD_RECORDING"})}});switch(t.mode){case nE.$u.START_RECORDING:{this.recordingStoppedCallbackInvoked=!1;let e=!1;if(this.activeRecording){const t=this.activeRecording;if(!this.inFlightSaves.some((e=>e.state===t))){e=!0;try{await this.cleanupRecording(t),await Os.rm(t.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 Os.mkdir(n,{recursive:!0});const{resolutionString:s,resolution:i}=await Lf(this.display),{process:a,videoStartedPromise:c}=await this.startFfmpegRecording(s,n);r=a;const l=function(e){const t=e.lastIndexOf(":");if(-1===t)throw new Error(`Invalid X11 display string: ${e} (missing ':')`);const r=e.slice(t+1).split(".")[0],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 qf({displayNum:l,resolution:i}),await o.start();const u=o.getRecordingStartTime();let d;try{d=await c}catch(e){throw new Error(`ffmpeg failed to start encoding: ${e instanceof Error?e.message:String(e)}`)}const h={childProcess:r,sessionDir:n,startTime:u,inputEventLogger:o,resolution:i,ffmpegStartedEpochMs:d,ffmpegDiedEarly:!1,ffmpegDiedTime:null,ffmpegExitCode:null,ffmpegExitSignal:null};this.activeRecording=h,this.onRecordingStartedCallback&&this.onRecordingStartedCallback(o),r.once("exit",((e,t)=>{h.ffmpegDiedEarly=!0,h.ffmpegDiedTime=Date.now(),h.ffmpegExitCode=e,h.ffmpegExitSignal=t}));const p=!!t.saveAsFilename;return new nE.Tj({result:{case:"startSuccess",value:new nE.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 Os.rm(n,{force:!0,recursive:!0}).catch((()=>{})),this.activeRecording=null,new nE.Tj({result:{case:"failure",value:new nE.yH({error:e instanceof Error?e.message:String(e)})}})}}case nE.$u.SAVE_RECORDING:{if(!this.activeRecording)return 1===this.inFlightSaves.length?await this.inFlightSaves[0].promise:new nE.Tj({result:{case:"failure",value:new nE.yH({error:"No active recording to save"})}});const e=this.activeRecording,r=this.findInFlightSave(e);if(r)return await r.promise;const n=Promise.resolve().then((()=>this.performSave(o.ctx,t,e))),s={state:e,promise:n};this.inFlightSaves.push(s);try{return await n}finally{this.inFlightSaves=this.inFlightSaves.filter((e=>e!==s))}}case nE.$u.DISCARD_RECORDING:{if(!this.activeRecording)return new nE.Tj({result:{case:"failure",value:new nE.yH({error:"No active recording to discard"})}});const e=this.activeRecording;if(this.findInFlightSave(e))return new nE.Tj({result:{case:"failure",value:new nE.yH({error:"Save in progress for this recording; wait for it or start a new recording"})}});try{return await e.inputEventLogger.stop(),this.invokeStoppedCallbackOnce(),!iE(e.childProcess)&&e.childProcess.pid&&await this.stopFfmpegRecording(e),await Os.rm(e.sessionDir,{force:!0,recursive:!0}),this.activeRecording=null,new nE.Tj({result:{case:"discardSuccess",value:new nE.N8}})}catch(t){await this.cleanupRecording(e),this.invokeStoppedCallbackOnce();const r=e.sessionDir;let o=!1;try{await Os.rm(r,{force:!0,recursive:!0}),o=!0}catch{}this.activeRecording=null;const n=t instanceof Error?t.message:String(t),s=o?"":`. Session may remain at: ${r}`;return new nE.Tj({result:{case:"failure",value:new nE.yH({error:`Failed to discard recording: ${n}${s}`})}})}}default:{const e=t.mode;return new nE.Tj({result:{case:"failure",value:new nE.yH({error:`Unhandled recording mode: ${e}`})}})}}}catch(e){r.error=e,r.hasError=!0}finally{sE(r)}}}async function hE(e){const t=await(0,Os.readdir)(e,{withFileTypes:!0}).catch((()=>[])),r=[];for(const o of t){const t=s.join(e,o.name),n={name:o.name,path:t,isDirectory:o.isDirectory()};o.isDirectory()&&(n.children=await hE(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 pE(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(...pE(t,e,s))}))}return o}async function fE(e){if(!await(0,Os.access)(e,Os.constants.R_OK).then((()=>!0),(()=>!1)))return"(No notes directory yet - will be created when you write your first note)";const t=await hE(e);return 0===t.length?"(Notes directory is empty)":t.flatMap(((e,r)=>pE(e,"",r===t.length-1))).join("\n")}async function mE(e,t){return fE(s.join(e,"agent-notes",t))}async function gE(e){return fE(s.join(e,"agent-notes","shared"))}dE.IN_FLIGHT_SAVE_DISPOSE_TIMEOUT_MS=3e4,dE.PROXY_TARGET_WIDTH=1920,dE.PROXY_TARGET_FPS=60,dE.PROXY_CRF=17,dE.PROXY_PRESET="veryfast",dE.PROXY_PROFILE_VERSION="render-proxy-h264-all-i-v1",dE.DEFAULT_REFRESH_RATE=60;var wE=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},yE=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 vE=(0,m.h)("local-exec:request-context"),bE=Symbol("sectionLoadTimedOut");async function SE(e,t,r,o){const n={stack:[],error:void 0,hasError:!1};try{wE(n,(0,i.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{yE(n)}}async function kE(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 EE(e,t,r={}){const{projectDir:o,notesSessionId:s,metaAgentNotesEnabled:i,agentNotesEnabled:a,reportProcessWorkingDirectory:c,getSmartModeClassifierAutoModeEnabled:l,devForceNextSmartModeClassifierBlockToken:u,isWorkingDirHomeDir:d,getSandboxEnabled:h,getSandboxSupported:p,getNetworkAllowlistInfo:f,userTerminalHint:m,artifactsFolder:g,secretRedactionEnabled:w,getComputerUseSupported:y,getComputerUseDesktop:v,getMockPromptTime:b}=r,S=v?.(),k=`${n.default.platform()} ${n.default.release()}`,E=(0,Fs.G6)(m),C=b?.(),x=(()=>{try{return(new Intl.DateTimeFormat).resolvedOptions().timeZone??void 0}catch{return}})(),_=o,P=o?`${o}/terminals`:void 0,I=o&&!0!==i&&!1!==a?`${o}/agent-notes/shared`:void 0,R=o&&s&&!1!==a?`${o}/agent-notes/${s}`:void 0,T=o?`${o}/agent-transcripts`:void 0,A=!!h&&h(),M=p?.(),D=l?.();let O;if(f)try{O=await f()}catch{O=void 0}return new Rr.GE({osVersion:k,workspacePaths:t,shell:E,sandboxEnabled:A,projectFolder:_,terminalsFolder:P,agentSharedNotesFolder:I,agentConversationNotesFolder:R,agentTranscriptsFolder:T,timeZone:x,...!1!==c&&{processWorkingDirectory:process.cwd()},artifactsFolder:g,...void 0!==D&&{smartModeClassifierAutoModeEnabled:D},...void 0!==u&&{devForceNextSmartModeClassifierBlockToken:u},...void 0!==C&&{devMockPromptTime:qt.Timestamp.fromDate(C)},...void 0!==w&&{secretRedactionEnabled:w},...void 0!==M&&{sandboxSupported:M},...void 0!==O?.hasDefaults&&{sandboxNetworkHasDefaults:O.hasDefaults},...O?.explicitEntries&&O.explicitEntries.length>0&&{sandboxNetworkExplicitAllowlist:O.explicitEntries},...void 0!==y&&{computerUseSupported:y()},...void 0!==S&&{computerUseDesktop:S},...void 0!==d&&{isWorkingDirHomeDir:d}})}const CE={type:"object",properties:{},additionalProperties:!1};function xE(e,t){return{tools:(!0===t?.internalBrowserProvidersOnly?e.servers.filter((e=>xt.has(e.serverIdentifier))):e.servers).flatMap((e=>e.tools)).map((e=>new Jn.gd({name:e.name,providerIdentifier:e.providerIdentifier,toolName:e.toolName,description:e.description,...!0===t?.inputSchemaJson?{inputSchemaJson:void 0===e.inputSchema?void 0:JSON.stringify(e.inputSchema)}:{inputSchema:e.inputSchema?qt.Value.fromJson(e.inputSchema):void 0}}))),mcpInstructions:e.servers.flatMap((e=>e.instructions))}}function _E(e,t){const r=!0===t?.slimDescriptors,o=e.servers.map((e=>{const o=e.instructions.map((e=>e.instructions)).filter(Boolean).join("\n"),n=e.tools.map((e=>new Jn.E$({toolName:e.toolName,...(0,Ww.hT)(e.annotations),...r?{}:{description:e.description,...!0===t?.inputSchemaJson?{inputSchemaJson:void 0===e.inputSchema?void 0:JSON.stringify(e.inputSchema)}:{inputSchema:void 0!==e.inputSchema?qt.Value.fromJson(e.inputSchema):void 0}}})));return!Ct(e.serverIdentifier)||!0!==t?.alwaysExposeVirtualMcpAuthTool&&"needsAuth"!==e.status||n.some((e=>e.toolName===sy))||n.push(new Jn.E$({toolName:sy,...r?{}:{description:iy,...!0===t?.inputSchemaJson?{inputSchemaJson:JSON.stringify(CE)}:{inputSchema:qt.Value.fromJson(CE)}}})),new Jn.UC({serverIdentifier:e.serverIdentifier,serverName:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginDbId:e.pluginId,marketplaceId:e.marketplaceId,serverUseInstructions:o||void 0,tools:n})}));return new Jn.U_({enabled:!0,mcpDescriptors:o})}function PE(e){const t=e?.trim();return t||void 0}function IE(e,t){const r=function(e){return PE(e.serverIdentifier)}(e);if(r)return r;const o=PE(e.serverName);return o?t.get(o)??o:void 0}class RE{constructor(e){this.mcpLease=e}async getState(e){const[t,r]=await Promise.all([this.mcpLease.getTools(e).catch((t=>(vE.warn(e,"Error fetching MCP tools",{error:t}),[]))),this.mcpLease.getInstructions(e).catch((t=>(vE.warn(e,"Error fetching MCP instructions",{error:t}),[])))]);return function(e,t,r,o=!1){const n=new Map;for(const t of e)n.has(t.providerIdentifier)||n.set(t.providerIdentifier,t.clientKey);const s=t.map((e=>IE(e,n))).filter((e=>Boolean(e))),i=[...new Set([...e.map((e=>e.clientKey)),...s,...Array.from(r?.entries()??[]).filter((([,e])=>"connected"!==e.status)).map((([e])=>e))])];if(o&&void 0!==r){const e=new Map(Array.from(r.keys(),((e,t)=>[e,t])));i.sort(((t,r)=>(e.get(t)??e.size)-(e.get(r)??e.size)))}return{servers:i.map((o=>{const s=e.filter((e=>e.clientKey===o));return{serverName:s[0]?.providerIdentifier??o,serverIdentifier:o,plugin:s[0]?.plugin,marketplace:s[0]?.marketplace,tools:s,instructions:t.filter((e=>IE(e,n)===o)),status:r?.get(o)?.status,errorMessage:r?.get(o)?.errorMessage}}))}}(t,r,await async function(e,t){const r=await t.getClients(e).catch((t=>(vE.warn(e,"Error fetching MCP clients",{error:t}),{}))),o=await Promise.all(Object.entries(r).map((async([t,r])=>{const o=await r.getState(e).catch((()=>({kind:"error",message:"Failed to fetch MCP client state"})));return[t,{status:Tt(o),errorMessage:"error"===o.kind&&void 0!==o.message?o.message:void 0}]})));return new Map(o)}(e,this.mcpLease))}}function TE(e){return new Lt._W({result:{case:"success",value:new Lt.pv({servers:e.servers.map((e=>new Lt.XE({serverName:e.serverName,serverIdentifier:e.serverIdentifier,plugin:e.plugin,marketplace:e.marketplace,tools:e.tools.map((e=>new Jn.gd({name:e.name,providerIdentifier:e.providerIdentifier,toolName:e.toolName,description:e.description,inputSchema:e.inputSchema?qt.Value.fromJson(e.inputSchema):void 0,metaJson:_t(e._meta),...(0,Ww.hT)(e.annotations)}))),instructions:e.instructions,status:e.status,errorMessage:e.errorMessage})))})}})}class AE{constructor(e,t,r){this.mcpStateAccessor=e,this.ensureMcpServersLoaded=t,this.options=r}async execute(e,t){try{await(this.ensureMcpServersLoaded?.(e,t.serverIdentifiers,{wait:!t.kickOnly}))}catch{}t.refreshPolicy!==Lt.ew.FORCE_IF_MISSING&&t.refreshPolicy!==Lt.ew.FORCE||await(this.mcpStateAccessor.refreshNow?.(e));const r=await this.mcpStateAccessor.getState(e);if(!0===this.options?.filterToRequestedServers&&t.serverIdentifiers.length>0){const e=new Set(t.serverIdentifiers),o=r.servers.filter((t=>e.has(t.serverIdentifier)));if(o.length>0)return TE({...r,servers:o})}return TE(r)}}class ME{constructor(e,t,r,o,n,s,i,a,c={}){this.cursorRulesService=e,this.cloudRulesService=t,this.subagentsService=r,this.repositoryProvider=o,this.grepProvider=n,this.mcpStateAccessor=s,this.gitExecutor=i,this.workspacePaths=a,this.cachedWorkspaces=new Map,this.inFlightWorkspaceWarms=new Map;const{projectDir:l,getSmartModeClassifierAutoModeEnabled:u,getAdminCommandDenylist:d,devForceNextSmartModeClassifierBlockToken:h,isWorkingDirHomeDir:p,agentNotesEnabled:f,reportProcessWorkingDirectory:m,createFileWatcher:g,getSandboxEnabled:w,getSandboxSupported:y,getNetworkAllowlistInfo:v,userTerminalHint:b,getMcpFileSystemOptions:S,mcpMetaToolEnabled:k,mcpMetaToolSlimDescriptors:E,mcpInputSchemaJson:C,alwaysExposeVirtualMcpAuthTool:x,getArtifactsFolder:_,secretRedactionEnabled:P,attributionConfigProvider:I,isAttributionDisabledByAdmin:R,getAgentSkills:T,additionalRules:A,getComputerUseSupported:M,getComputerUseDesktop:D,getMockPromptTime:O}=c;this.projectDir=l,this.isWorkingDirHomeDir=p,this.agentNotesEnabled=f??!0,this.reportProcessWorkingDirectory=m??!0,this.getSandboxEnabled=w,this.getSandboxSupported=y,this.getNetworkAllowlistInfo=v,this.getSmartModeClassifierAutoModeEnabled=u,this.getAdminCommandDenylist=d,this.devForceNextSmartModeClassifierBlockToken=h,this.getMockPromptTime=O,this.userTerminalHint=b,this.getMcpFileSystemOptions=S,this.mcpMetaToolEnabled=k??!1,this.mcpMetaToolSlimDescriptors=E??!1,this.mcpInputSchemaJson=C??!1,this.alwaysExposeVirtualMcpAuthTool=x??!1,this.getArtifactsFolder=_,this.secretRedactionEnabled=P,this.attributionConfigProvider=I,this.isAttributionDisabledByAdmin=R,this.getAgentSkills=T,this.additionalRules=A??[],this.getComputerUseSupported=M,this.getComputerUseDesktop=D,this.reduceContextHotPath=c.reduceContextHotPath??!1,this.sectionLoadTimeoutMs=c.sectionLoadTimeoutMs,this.reportSectionCompleteness=c.reportSectionCompleteness??!1,this.onRequestContext=c.onRequestContext,this.warmWorkspaceCaches(),this.rebuildGlobalCache(),void 0!==g&&(this.fileWatcher=g(),this.fileWatcher.onDidChange((e=>{this.onWorkspacePathChanged(e)})),this.fileWatcher.onDidCreate((e=>{this.onWorkspacePathChanged(e)})),this.fileWatcher.onDidDelete((e=>{this.onWorkspacePathChanged(e)})))}onWorkspacePathChanged(e){this.rebuildAllCaches()}getWorkspaceCache(e){return this.cachedWorkspaces.get(e)}warmWorkspaceCaches(){const e=(0,ce.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=wE(r,(0,i.VI)(e.withName("LocalRequestContextExecutor.warmWorkspaceCache")),!1),n=await Ba(o.ctx,this.gitExecutor,t),s=n?await Wa(o.ctx,this.gitExecutor,n):void 0,a={repoPath:n??void 0,remoteUrl:void 0!==s?Ha(s):void 0};this.cachedWorkspaces.set(t,a)}catch(e){r.error=e,r.hasError=!0}finally{yE(r)}}rebuildAllCaches(){this.cacheDebounceTimeout&&clearTimeout(this.cacheDebounceTimeout),this.cacheDebounceTimeout=setTimeout((()=>{this.cacheDebounceTimeout=void 0,this.rebuildGlobalCache()}),5e3)}invalidateGlobalCache(){this.globalCache=void 0,this.lastGoodGlobalCache=void 0,this.globalCacheTraceId=void 0}rebuildGlobalCache(){const e={stack:[],error:void 0,hasError:!1};try{const t=(0,ce.q6)(),r=wE(e,(0,i.VI)(t.withName("LocalRequestContextExecutor.rebuildGlobalCache")),!1);this.globalCacheTraceId=r.span.spanContext().traceId;const o=this.computeGlobalCache(r.ctx);return this.globalCache=o,(this.reduceContextHotPath||void 0!==this.sectionLoadTimeoutMs)&&o.then((e=>{this.globalCache===o&&(this.lastGoodGlobalCache=e)}),(()=>{this.globalCache===o&&(this.globalCache=void 0)})),o}catch(t){e.error=t,e.hasError=!0}finally{yE(e)}}async computeGlobalCache(e){const t={stack:[],error:void 0,hasError:!1};try{const r=wE(t,(0,i.VI)(e.withName("LocalRequestContextExecutor.computeGlobalCache")),!1),o=AbortSignal.timeout(1e3),n=performance.now(),s={},a=(e,t)=>{const r=performance.now();return t.finally((()=>{s[e]=Math.round(performance.now()-r)}))},[c,l,u,d]=await Promise.all([a("cursorRules",this.cursorRulesService.getAllCursorRules(r.ctx)),a("cloudRule",this.cloudRulesService?this.cloudRulesService.getCloudRule(r.ctx):Promise.resolve(null)),a("codebaseRef",this.repositoryProvider.getCodebaseReference(r.ctx,o).catch((()=>{}))),a("subagents",this.subagentsService?this.subagentsService.getAllSubagents().catch((()=>[])):Promise.resolve([]))]),h=Math.round(performance.now()-n);return h>1e3&&vE.warn(r.ctx,"computeGlobalCache: slow",{totalMs:h,...s,ruleCount:c.length}),{rules:[...this.additionalRules,...c],cloudRule:l,codebaseReference:u,customSubagents:d}}catch(e){t.error=e,t.hasError=!0}finally{yE(t)}}dispose(){this.cacheDebounceTimeout&&(clearTimeout(this.cacheDebounceTimeout),this.cacheDebounceTimeout=void 0),this.fileWatcher&&(this.fileWatcher.dispose(),this.fileWatcher=void 0),this.globalCache=void 0,this.lastGoodGlobalCache=void 0}async collectWorkspaceCaches(e,t){const r={stack:[],error:void 0,hasError:!1};try{const o=wE(r,(0,i.VI)(e.withName("LocalRequestContextExecutor.collectWorkspaceCaches")),!1);let n;if(this.grepProvider.getTrackedState)try{n=await this.grepProvider.getTrackedState(this.workspacePaths)}catch{n=void 0}let s=!0,a=!0;const c=(await Promise.all(this.workspacePaths.map((async e=>{let r=this.getWorkspaceCache(e);if(void 0===r){if(!t.waitForWorkspaceCache)return s=!1,void this.ensureWorkspaceCacheWarm(o.ctx,e);if(await this.ensureWorkspaceCacheWarm(o.ctx,e),r=this.getWorkspaceCache(e),void 0===r)return void(s=!1)}const i=n?.[e];if(void 0!==i)return void 0!==r.repoPath&&void 0===i.gitStatus&&(a=!1),new Rr.DS({path:r.repoPath,status:i.gitStatus,branchName:i.gitBranchName,remoteUrl:r.remoteUrl,isOriginBacked:La(r.remoteUrl)});if(void 0===r.repoPath)return;const{status:c,branchName:l}=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(SE(e,t,r,o)),n(kE(e,t,r,o))]);return{status:s,branchName:i}}(o.ctx,this.gitExecutor,r.repoPath,3e3);return void 0===c&&(a=!1),new Rr.DS({path:r.repoPath,status:c,branchName:l,remoteUrl:r.remoteUrl,isOriginBacked:La(r.remoteUrl)})})))).filter((e=>void 0!==e));return{gitRepos:c,gitRepoInfoComplete:s,gitStatusInfoComplete:s&&a}}catch(e){r.error=e,r.hasError=!0}finally{yE(r)}}shareBoundedSectionLoad(e,t,r){if(void 0===this.sectionLoadTimeoutMs)return r();const o=e();if(void 0!==o)return o;const n=r();t(n);const s=()=>{e()===n&&t(void 0)};return n.then(s,s),n}async computeCachedRequestContext(e,t){const r={stack:[],error:void 0,hasError:!1};try{const o=wE(r,(0,i.VI)(e.withName("LocalRequestContextExecutor.computeCachedRequestContext")),!1),n=this.projectDir,s=async()=>{const e={stack:[],error:void 0,hasError:!1};try{const t=wE(e,(0,i.VI)(o.ctx.withName("LocalRequestContextExecutor.computeCachedRequestContext.getGlobalData")),!1);if(this.globalCacheTraceId&&t.span.setAttribute("cacheTraceId",this.globalCacheTraceId),!this.reduceContextHotPath){if(void 0===this.globalCache){const e=this.computeGlobalCache(o.ctx);this.globalCache=e,e.catch((()=>{this.globalCache===e&&(this.globalCache=void 0)})),void 0!==this.sectionLoadTimeoutMs&&e.then((t=>{this.globalCache===e&&(this.lastGoodGlobalCache=t)}),(()=>{}))}return this.globalCache}return void 0!==this.lastGoodGlobalCache?this.lastGoodGlobalCache:this.globalCache??this.rebuildGlobalCache()}catch(t){e.error=t,e.hasError=!0}finally{yE(e)}},a=performance.now(),c={},l=(e,t)=>{const r=performance.now();return t.finally((()=>{c[e]=Math.round(performance.now()-r)}))},u=e=>function(e,t){if(void 0===t)return e;let r;const o=new Promise((e=>{r=setTimeout((()=>e(bE)),t)}));return e.catch((()=>{})),Promise.race([e,o]).finally((()=>{clearTimeout(r)}))}(e,this.sectionLoadTimeoutMs),d=(e,t,r)=>this.shareBoundedSectionLoad(e,t,r),[h,p,f,{gitRepos:m,gitRepoInfoComplete:g,gitStatusInfoComplete:w},y,v,b,S,k,E]=await Promise.all([l("globalCache",u(s())),l("mcpState",u(d((()=>this.inFlightMcpState),(e=>{this.inFlightMcpState=e}),(()=>this.mcpStateAccessor.getState(o.ctx))))),l("env",EE(o.ctx,this.workspacePaths,{projectDir:n,notesSessionId:t.notesSessionId,metaAgentNotesEnabled:!1,agentNotesEnabled:this.agentNotesEnabled,reportProcessWorkingDirectory:this.reportProcessWorkingDirectory,getSmartModeClassifierAutoModeEnabled:this.getSmartModeClassifierAutoModeEnabled,devForceNextSmartModeClassifierBlockToken:this.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:this.getMockPromptTime,isWorkingDirHomeDir:this.isWorkingDirHomeDir,getSandboxEnabled:this.getSandboxEnabled,getSandboxSupported:this.getSandboxSupported,getNetworkAllowlistInfo:this.getNetworkAllowlistInfo,userTerminalHint:this.userTerminalHint,artifactsFolder:this.getArtifactsFolder?.(o.ctx),secretRedactionEnabled:this.secretRedactionEnabled,getComputerUseSupported:this.getComputerUseSupported,getComputerUseDesktop:this.getComputerUseDesktop})),l("git",this.collectWorkspaceCaches(o.ctx,{waitForWorkspaceCache:!0===t.waitForWorkspaceCache})),l("conversationNotes",this.agentNotesEnabled&&n&&t.notesSessionId?mE(n,t.notesSessionId):Promise.resolve(void 0)),l("sharedNotes",this.agentNotesEnabled&&n?gE(n):Promise.resolve(void 0)),l("mcpFileSystemOptions",this.getMcpFileSystemOptions?this.getMcpFileSystemOptions(o.ctx,{timeoutMs:3e3}):Promise.resolve(void 0)),l("attribution",this.isAttributionDisabledByAdmin?this.isAttributionDisabledByAdmin().catch((()=>!0)):Promise.resolve(!1)),l("agentSkills",u(d((()=>this.inFlightAgentSkills),(e=>{this.inFlightAgentSkills=e}),(()=>this.getAgentSkills?this.getAgentSkills(o.ctx):Promise.resolve([]))))),l("adminCommandDenylist",u(d((()=>this.inFlightAdminCommandDenylist),(e=>{this.inFlightAdminCommandDenylist=e}),(()=>this.getAdminCommandDenylist?this.getAdminCommandDenylist():Promise.resolve(void 0)))))]),C=h===bE,x=p===bE,_=k===bE,P=E===bE,I=C?this.lastGoodGlobalCache??{rules:[...this.additionalRules],cloudRule:null,codebaseReference:void 0,customSubagents:[]}:h,R=x?{servers:[]}:p,T=_?[]:k,A=P?void 0:E;(C||x||_||P)&&vE.warn(o.ctx,"computeCachedRequestContext: section load timed out",{timeoutMs:this.sectionLoadTimeoutMs,rulesAndSubagents:C,mcpState:x,agentSkills:_,adminCommandDenylist:P});const M=performance.now()-a;for(const[e,t]of Object.entries(c))o.span.setAttribute(`requestContext.timing.${e}Ms`,t);o.span.setAttribute("requestContext.timing.totalMs",Math.round(M)),M>1e3&&vE.warn(o.ctx,"computeCachedRequestContext: slow parallel data collection",{durationMs:Math.round(M),...c});const D=this.mcpMetaToolEnabled?_E(R,{alwaysExposeVirtualMcpAuthTool:this.alwaysExposeVirtualMcpAuthTool,slimDescriptors:this.mcpMetaToolSlimDescriptors,inputSchemaJson:this.mcpInputSchemaJson}):void 0,O=this.attributionConfigProvider?.get(),N=!S&&(O?.attribution?.attributeCommitsToAgent??!0),$=!S&&(O?.attribution?.attributePRsToAgent??!0),F=new Rr.bb({rules:I.rules,env:f,gitRepos:m,gitRepoInfoComplete:g,repositoryInfo:I.codebaseReference?[{relativeWorkspacePath:I.codebaseReference.relativeWorkspacePath,repoName:I.codebaseReference.repoName,repoOwner:I.codebaseReference.repoOwner,isTracked:I.codebaseReference.isTracked,isLocal:I.codebaseReference.isLocal,orthogonalTransformSeed:I.codebaseReference.orthogonalTransformSeed,pathEncryptionKey:I.codebaseReference.pathEncryptionKey}]:[],...xE(R,{internalBrowserProvidersOnly:this.mcpMetaToolEnabled&&this.mcpMetaToolSlimDescriptors,inputSchemaJson:this.mcpInputSchemaJson}),conversationNotesListing:y,sharedNotesListing:v,customSubagents:I.customSubagents,mcpFileSystemOptions:b,mcpMetaToolOptions:D,supportsMcpAuth:!0,commitAttributionMessage:N?"enabled":void 0,prAttributionMessage:$?"enabled":void 0,agentSkills:T,adminCommandDenylist:A?.rules??[]});return null!==I.cloudRule&&void 0!==I.cloudRule&&(F.cloudRule=I.cloudRule),this.reportSectionCompleteness&&(F.rulesInfoComplete=!C,F.customSubagentsInfoComplete=!C,F.agentSkillsInfoComplete=!_,F.mcpInfoComplete=!x,F.mcpFileSystemInfoComplete=this.mcpMetaToolEnabled||void 0!==b,F.envInfoComplete=!0,F.gitStatusInfoComplete=w),F}catch(e){r.error=e,r.hasError=!0}finally{yE(r)}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{this.onRequestContext?.();const o=wE(r,(0,i.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 Rr._G({result:{case:"success",value:new Rr.yW({requestContext:e})}})}catch(e){return o.span.recordException(e),new Rr._G({result:{case:"error",value:new Rr.nf({error:e instanceof Error?e.message:String(e)})}})}}catch(e){r.error=e,r.hasError=!0}finally{yE(r)}}}function DE(e){return 0!==e.timeout?e.timeout:e.isBackground||e.timeoutBehavior===yr._d.BACKGROUND||void 0!==e.hardTimeout&&e.hardTimeout>0?0:3e4}var OE=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 NE{constructor(e,t,r,o){this.permissionsService=e,this.coreExecutor=t,this.ignoreService=r}buildResultFromExit(e){return 0===(e.exitCode??-1)?new yr.W4({result:{case:"success",value:new yr.QR({...e,stdout:e.outputLocation?"":e.stdout,stderr:e.outputLocation?"":e.stderr})},sandboxPolicy:vi(e.sandboxPolicy)}):new yr.W4({result:{case:"failure",value:new yr.xC({...e,aborted:void 0!==e.abortReason,stdout:e.outputLocation?"":e.stdout,stderr:e.outputLocation?"":e.stderr})},sandboxPolicy:vi(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,c=setTimeout((()=>{i.abort()}),o);try{let o,l,u,d="",h="",p=null;const f=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,requestId:t.requestId,secretScopeId:t.secretScopeId,sandboxPolicy:f,fileOutputThresholdBytes:t.fileOutputThresholdBytes,pipeStdin:!1}))"stdout"===n.type?d+=n.data:"stderr"===n.type?h+=n.data:"exit"===n.type&&(p=null!=n.code?0|n.code:null,l=n.outputLocation,o=n.aborted?a.aborted?i.signal.aborted&&a.reason===i.signal.reason?yr.Lv.TIMEOUT:yr.Lv.USER_ABORT:yr.Lv.UNSPECIFIED:void 0,u=Om(n.localExecutionTimeMs));clearTimeout(c);const m=Date.now()-s,g={command:t.command,workingDirectory:r,exitCode:void 0!==o?-1:p??-1,signal:void 0!==o?"SIGTERM":"",abortReason:o,stdout:d,stderr:h,executionTime:m,localExecutionTimeMs:u,sandboxPolicy:n,outputLocation:l};return this.buildResultFromExit(g)}catch(s){return clearTimeout(c),i.signal.aborted&&!e.signal.aborted?new yr.W4({result:{case:"timeout",value:new yr.eG({command:t.command,workingDirectory:r,timeoutMs:o})},sandboxPolicy:vi(n)}):e.signal.aborted?new yr.W4({result:{case:"rejected",value:new yr.pZ({command:t.command,workingDirectory:r,reason:"Command aborted"})},sandboxPolicy:vi(n)}):new yr.W4({result:{case:"spawnError",value:new yr.mJ({command:t.command,workingDirectory:r,error:s instanceof Error?s.message:"Unknown error"})},sandboxPolicy:vi(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,i.VI)(e.withName("LocalShellExecutor.execute")),!1).ctx;(0,i.HF)(o,"LocalShellExecutor.execute");const n=t.command,s=t.requestedSandboxPolicy?yi(t.requestedSandboxPolicy):void 0,a=t.workingDirectory||await this.coreExecutor.getCwd(t.conversationId),c=DE(t),l=(0,Gs.o1)(a);if(!t.parsingResult)return new yr.W4({result:{case:"spawnError",value:new yr.mJ({command:n,workingDirectory:l,error:"Parsing result is required"})}});let u;if(t.skipApproval){const e=await this.permissionsService.shouldEnforceShellInvariantBlocks(o,{workingDirectory:l,skipUnsafeWorkingDirectoryBlock:!0,command:n,parsingResult:t.parsingResult,toolCallId:t.toolCallId},s);if("block"===e.kind)return new yr.W4({result:Rc(n,l,e.reason)});u=s}else{const e=await this.permissionsService.shouldBlockShellCommand(o,n,{workingDirectory:l,timeout:c,parsingResult:t.parsingResult,toolCallId:t.toolCallId,smartModeApprovalReason:t.smartModeApproval?.reason,smartModeApprovalRequestId:t.smartModeApproval?.requestId,hookApprovalRequirement:Dr(t)},s);if("block"===e.kind)return new yr.W4({result:Rc(n,l,e.reason)});u=e.policy}if(ii()&&(u=hi(n,t.parsingResult)),u&&"insecure_none"!==u.type){const e=await Qa(this.ignoreService);u={...u,ignoreMapping:e}}return this.executeWithPolicy(o,t,a,c,u)}catch(e){r.error=e,r.hasError=!0}finally{OE(r)}}}var $E=r("../proto/dist/generated/agent/v1/shell_allowlist_precheck_exec_pb.js");class FE{constructor(e){this.permissionsService=e}async execute(e,t){const r=t.parsingResult??new yr.HO,o=await this.permissionsService.isShellCommandFullyAllowlisted(e,t.command,{workingDirectory:t.workingDirectory,parsingResult:r,classifierResult:t.classifierResult,toolCallId:t.toolCallId});return new $E.e({allowlisted:o})}}class jE{constructor(e){this.shellStreamExecutor=e}async execute(e,t,r){return""===t.toolCallId.trim()?new yr.jK({status:yr.iA.NOT_FOUND}):this.shellStreamExecutor.forceBackgroundByToolCallId(t.toolCallId)}}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});const UE=(0,m.h)("local-exec:shell-stream");class BE{constructor(e,t){this.iterator=e,this.timeoutMs=t,this.pendingPromise=null,this.stopPromise=new Promise((e=>{this.stopResolve=e}))}stop(e){return void 0===this.stopReason&&(this.stopReason=e,this.stopResolve?.(),!0)}get timedOut(){return"background"===this.stopReason?.kind&&this.stopReason.reason===yr.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:yr.Jg.TIMEOUT})}),this.timeoutMs);try{for(;;){if(void 0!==this.stopReason)return;this.pendingPromise=this.iterator.next();const e=await Promise.race([this.pendingPromise.then((e=>({kind:"result",result:e}))),this.stopPromise.then((()=>({kind:"stopped"})))]);if("stopped"===e.kind)return;if(this.pendingPromise=null,e.result.done)return;yield e.result.value}}finally{clearTimeout(this.timer)}}requestBackground(){return this.stop({kind:"background",reason:yr.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 WE{constructor(e,t,r,o){this.permissionsService=e,this.coreExecutor=t,this.ignoreService=r,this.backgroundShellManager=o,this.activeForegroundExecutions=new Map}async forceBackgroundByToolCallId(e){const t=this.activeForegroundExecutions.get(e),r=t?.requestBackground();return r?new yr.jK({status:yr.iA.ACCEPTED,shellResult:r}):new yr.jK({status:yr.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,i.VI)(e.withName("LocalShellStreamExecutor.execute")),!1);const o=t.command;let n=t.requestedSandboxPolicy?yi(t.requestedSandboxPolicy):void 0;const s=t.workingDirectory||await this.coreExecutor.getCwd(t.conversationId),a=DE(t),c=(0,Gs.o1)(s),l=Date.now(),u=new yr.HO(qs(o).structured),d=Mi({command:o,parsingResult:u,blockedCommands:t.adminCommandDenylist});if(void 0!==d)return void(yield new yr.FI({event:{case:"rejected",value:new yr.pZ({command:o,workingDirectory:c,reason:d})}}));const h=await this.permissionsService.shouldEnforceShellInvariantBlocks(e,{workingDirectory:c,skipUnsafeWorkingDirectoryBlock:!0,command:o,parsingResult:u,toolCallId:t.toolCallId},n);if("block"===h.kind)return"permissionsConfig"===h.reason.type?void(yield new yr.FI({event:{case:"permissionDenied",value:new yr.jn({command:o,workingDirectory:c,error:"Command blocked by permissions configuration",isReadonly:h.reason.isReadonly??!1})}})):void(yield new yr.FI({event:{case:"rejected",value:new yr.pZ({command:o,workingDirectory:c,reason:Ic(h.reason)})}}));if(UE.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:u.executableCommands.length,classifierCommandCount:t.classifierResult?.commands.length??0,commandLength:o.length}),t.skipApproval)UE.info(e,"Shell stream: skipped local approval",{toolCallId:t.toolCallId,requestedPolicyType:n?.type??"undefined"});else{const r=await this.permissionsService.shouldBlockShellCommand(e,o,{workingDirectory:c,timeout:a,parsingResult:u,toolCallId:t.toolCallId,classifierResult:t.classifierResult,smartModeApprovalReason:t.smartModeApproval?.reason,smartModeApprovalRequestId:t.smartModeApproval?.requestId,hookApprovalRequirement:Dr(t)},n);if("block"===r.kind){if(UE.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 yr.FI({event:{case:"permissionDenied",value:new yr.jn({command:o,workingDirectory:c,error:"Command blocked by permissions configuration",isReadonly:r.reason.isReadonly??!1})}}));const n=Ic(r.reason);return void(yield new yr.FI({event:{case:"rejected",value:new yr.pZ({command:o,workingDirectory:c,reason:n})}}))}n=r.policy,UE.info(e,"Shell stream: approval gate allowed command",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,effectivePolicyType:n.type})}if(ii()&&(n=hi(o,u)),n&&"insecure_none"!==n.type){const e=await Qa(this.ignoreService);n={...n,ignoreMapping:e}}yield new yr.FI({event:{case:"start",value:new yr.tD({sandboxPolicy:vi(n)})}});const p=t.timeoutBehavior===yr._d.BACKGROUND,f=p&&!t.closeStdin&&void 0===t.smartModeApproval,m=new AbortController,g=p?m.signal:e.signal?AbortSignal.any([e.signal,m.signal]):m.signal,w=!0,y=n?{perRepo:n}:void 0,v=this.coreExecutor.execute(e,{command:o,workingDirectory:s,signal:g,toolCallId:t.toolCallId,conversationId:t.conversationId,requestId:t.requestId,secretScopeId:t.secretScopeId,sandboxPolicy:y,fileOutputThresholdBytes:t.fileOutputThresholdBytes,pipeStdin:f,showElapsedTime:w});let b;p||(b=setTimeout((()=>m.abort()),a));const S=p?new BE(v[Symbol.asyncIterator](),a):null;let k,E,C,x="",_=!1;const P=t.toolCallId&&S?{requestBackground:()=>{if(S.requestBackground())return C=C??this.backgroundShellManager.generateShellId(),new yr.W4({result:{case:"success",value:new yr.QR({shellId:C,pid:E,command:o,workingDirectory:c,msToWait:Om(Date.now()-l),backgroundReason:yr.Jg.USER_REQUEST,interleavedOutput:x})}})}}:void 0;t.toolCallId&&P&&this.activeForegroundExecutions.set(t.toolCallId,P);const I=()=>{t.toolCallId&&this.activeForegroundExecutions.get(t.toolCallId)===P&&this.activeForegroundExecutions.delete(t.toolCallId)};if(S&&e.signal){const t=()=>{S.backgroundRequested||(m.abort(),S.abort())};e.signal.aborted?t():e.signal.addEventListener("abort",t,{once:!0})}let R;const T=t.hardTimeout;void 0!==T&&T>0&&(R=setTimeout((()=>{void 0!==C?this.backgroundShellManager.abort(C)||m.abort():(_=!0,m.abort(),S?.abort())}),T));const A=S?.iterate()??v;try{for await(const r of A)if("stdout"===r.type)x+=r.data,yield new yr.FI({event:{case:"stdout",value:new yr.o0({data:r.data})}});else if("stderr"===r.type)x+=r.data,yield new yr.FI({event:{case:"stderr",value:new yr.Db({data:r.data})}});else if("stdin_ready"===r.type)k=r.stdin,E=r.pid;else if("exit"===r.type){let o;r.aborted&&(o=e.signal?.aborted?yr.Lv.USER_ABORT:S?.timedOut||m.signal.aborted?yr.Lv.TIMEOUT:yr.Lv.USER_ABORT),yield new yr.FI({event:{case:"exit",value:new yr.vb({code:(r.code??-1)>>>0,cwd:await this.coreExecutor.getCwd(t.conversationId),outputLocation:r.outputLocation,aborted:r.aborted,abortReason:o,localExecutionTimeMs:Om(r.localExecutionTimeMs)})}})}}catch(r){if(!(r instanceof Fs.SandboxUnsupportedError))throw r;const s=n?.type??"unknown";return UE.debug(e,"Shell stream: sandbox policy unsupported on this host",{toolCallId:t.toolCallId,policyType:s,reason:r.reason}),void(yield new yr.FI({event:{case:"sandboxUnsupported",value:new yr.rI({command:o,workingDirectory:c,sandboxPolicyType:s,reason:r.reason??r.message,isReadonly:"workspace_readonly"===s})}}))}finally{clearTimeout(b),S?.backgroundRequested||clearTimeout(R),I()}if(S?.backgroundRequested&&!_){const r=C??this.backgroundShellManager.generateShellId();C=r;const n=S.backgroundReasonValue===yr.Jg.USER_REQUEST?yr.Jg.USER_REQUEST:yr.Jg.TIMEOUT,s=n===yr.Jg.USER_REQUEST?Date.now()-l:a;await this.backgroundShellManager.adopt({ctx:e,shellId:r,command:o,workingDirectory:c,toolCallId:t.toolCallId,sandboxPolicy:y,initialOutput:x,stdin:k,pid:E,abortController:m,eventIterator:S.getHandoffIterator(),startTime:l,showElapsedTime:w,description:t.description,outputNotification:t.outputNotification,onCleanup:()=>clearTimeout(R)}),yield new yr.FI({event:{case:"backgrounded",value:new yr.Y9({shellId:r,command:o,workingDirectory:c,pid:E,msToWait:w?s:void 0,reason:n})}})}else e.signal?.aborted&&void 0!==S?.stopReasonValue?(clearTimeout(R),yield new yr.FI({event:{case:"exit",value:new yr.vb({code:4294967295,cwd:await this.coreExecutor.getCwd(t.conversationId),aborted:!0,abortReason:yr.Lv.USER_ABORT})}})):clearTimeout(R)}catch(e){r.error=e,r.hasError=!0}finally{LE(r)}}}const HE={kind:"absent"};class qE{constructor(e){this.cells=new Map,this.takenCells=new WeakMap,this.collectedCells=new FinalizationRegistry((e=>{void 0===this.cells.get(e)?.deref()&&this.cells.delete(e)})),this.claims=new Map,this.nextGeneration=0,this.entries=new Ns.q({max:1e3,ttl:6e4,ttlResolution:0,perf:e})}begin(e){const t=++this.nextGeneration;return this.claims.set(ZE(e),t),t}record(e,t,r){if(!this.claim(e,r))return;const o=ZE(e);this.entries.set(o,{recorded:t,generation:r}),this.commitGeneration(o,r)}forget(e,t){if(!this.claim(e,t))return;const r=ZE(e);this.entries.delete(r),this.commitGeneration(r,t)}end(e,t){this.claim(e,t)}take(e){const t=ZE(e),r=this.entries.get(t);if(void 0===r)return;const o=this.entries.getRemainingTTL(t);this.entries.delete(t);let n=this.cells.get(t)?.deref();void 0===n&&(n={committed:r.generation},this.cells.set(t,new WeakRef(n)),this.collectedCells.register(n,t));const s={read:e,recorded:r.recorded,remainingTtlMs:o,generation:r.generation};return this.takenCells.set(s,n),s}restore(e){const t=this.takenCells.get(e);if(void 0===t||t.committed!==e.generation)return;const r=ZE(e.read);this.entries.has(r)||!Number.isFinite(e.remainingTtlMs)||e.remainingTtlMs<=0||this.entries.set(r,{recorded:e.recorded,generation:e.generation},{ttl:e.remainingTtlMs})}commitGeneration(e,t){const r=this.cells.get(e)?.deref();void 0!==r&&(r.committed=t)}claim(e,t){const r=ZE(e);return this.claims.get(r)===t&&(this.claims.delete(r),!0)}}async function zE(e,t){if(void 0===e)return!1;try{if("absent"===e.kind)return await KE(t);const r=await VE(t);return void 0===r||r.byteLength!==e.byteLength||r.sha256!==e.sha256}catch{return!1}}class GE{constructor(e,t,r,o){this.inner=e,this.reads=t,this.permissionsService=r,this.workspacePath=o}async execute(e,t,r){const o=function(e,t){if(""!==e.toolCallId&&void 0===e.offset&&void 0===e.limit)return{toolCallId:e.toolCallId,resolvedPath:(0,Gs.o1)(e.path,t)}}(t,this.workspacePath);if(void 0===o)return this.inner.execute(e,t,r);const n=this.reads.begin(o);try{let s,i;try{s=await Pk(this.permissionsService,o.resolvedPath)}catch{return await this.readAndForget(e,t,r,o,n)}if(!1!==s&&"needsApproval"!==s.type)return await this.readAndForget(e,t,r,o,n);if(!1!==s){const s=await this.inner.execute(e,t,r),i=await async function(e,t){if("success"===e.result.case&&"content"===e.result.value.output.case)try{return await VE(t)}catch{return}}(s,o.resolvedPath);return this.commit(o,n,s,i),s}try{i=await VE(o.resolvedPath)}catch{return await this.readAndForget(e,t,r,o,n)}const a=await this.inner.execute(e,t,r);return this.commit(o,n,a,i),a}finally{this.reads.end(o,n)}}commit(e,t,r,o){"fileNotFound"!==r.result.case?void 0===o||"success"!==r.result.case||"content"!==r.result.value.output.case?this.reads.forget(e,t):this.reads.record(e,{kind:"fingerprint",...o},t):this.reads.record(e,HE,t)}async readAndForget(e,t,r,o,n){const s=await this.inner.execute(e,t,r);return this.reads.forget(o,n),s}}async function VE(e){try{const t=await(0,Os.stat)(e);if(!t.isFile()||t.size>jt)return}catch(e){return XE(e)}let t;try{t=await(0,Os.open)(e,function(){const e=$s.constants;return e.O_RDONLY|(e.O_NONBLOCK??0)}());const r=await t.stat();if(!r.isFile()||r.size>jt)return;const o=(0,Ts.createHash)("sha256");let n=0;const s=Buffer.alloc(65536);for(;n<=jt;){const{bytesRead:e}=await t.read(s,0,s.length,n);if(0===e)break;n+=e,o.update(s.subarray(0,e))}if(n>jt)return;return{byteLength:n,sha256:o.digest("hex")}}catch(e){return XE(e)}finally{await(t?.close())}}function JE(e){return`${e} changed on disk after this tool call read it. Nothing was written. Read the file again and retry.`}async function KE(e){try{return await(0,Os.stat)(e),!0}catch(e){if(QE(e))return!1;throw e}}function ZE({toolCallId:e,resolvedPath:t}){return`${e}\0${t}`}function XE(e){if(!QE(e))throw e}function QE(e){const t=e.code;return"ENOENT"===t||"ENOTDIR"===t}var YE=r("../proto/dist/generated/agent/v1/web_fetch_allowlist_precheck_exec_pb.js");class eC{constructor(e){this.permissionsService=e}async execute(e,t){const r=await this.permissionsService.isWebFetchFullyAllowlisted(e,{url:t.url});return new YE.M({allowlisted:r})}}var tC=r("node:constants");class rC extends Error{constructor(e,t){super(t),this.name="SymlinkRefusedError",this.path=e}}var 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});const nC=(0,m.h)("LocalWriteExecutor"),sC=async(e,t,r,o)=>{const n=setTimeout((()=>{nC.warn(e,`[watchdog, LocalWriteExecutor] ${t} still not completed after ${r}ms`)}),r);try{return await o()}finally{clearTimeout(n)}};class iC{constructor(e,t,r,{workspacePaths:o,workspacePath:n,worktreeMainPath:s,onWriteForAiTracking:i,writeFileMutationGuard:a,toolCallReads:c}){this.fileChangeTracker=e,this.permissionsService=t,this.pendingDecisionProvider=r,this.workspacePaths=o,this.workspacePath=n,this.worktreeMainPath=s,this.onWriteForAiTracking=i,this.writeFileMutationGuard=a,this.toolCallReads=c}async execute(e,t){if(function(e){if(!e.startsWith("file://"))return!1;try{return(0,th.fileURLToPath)(e),!1}catch{return!0}}(t.path))return new vr.v3({result:{case:"error",value:new vr.QM({path:t.path,error:`${t.path} is not a valid file URL. Use an absolute path instead.`})}});const r=(0,Gs.o1)(t.path,this.workspacePath),o=this.toolCallReads,n=void 0!==o&&""!==t.toolCallId?o.take({toolCallId:t.toolCallId,resolvedPath:r}):void 0,s={writeStarted:!1},i=()=>{void 0===n||s.writeStarted||o?.restore(n)};try{const o=await this.executeWithRecord(e,t,r,n?.recorded,s);return lC(o)&&i(),o}catch(e){throw i(),e}}async executeWithRecord(e,t,r,o,n){const a={stack:[],error:void 0,hasError:!1};try{const c=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var 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}(a,(0,i.VI)(e.withName("LocalWriteExecutor.execute")),!1).ctx,l=(t.path,t.fileText),u=t.fileBytes.length>0?t.fileBytes:void 0,d=US(r,["assets","agent-tools","swarm-agents"]);if((0,Gs.fl)({targetPath:r,workspacePaths:this.workspacePaths,mainWorktreePath:this.worktreeMainPath}))return new vr.v3({result:{case:"error",value:new vr.QM({path:r,error:Gs.PS})}});let h,p=!1;try{(await(0,Os.stat)(r)).size<=Zs?h=await sC(c,"readText before write",3e3,(()=>ua(r,t.encodingHint))):p=!0}catch{}const f=(await HS(r)).resolvedPath,m=(".cursorignore"===(r.split(s.sep).pop()?.toLowerCase()??"")?{type:"permissionsConfig"}:void 0)??await sC(c,"permissionsService.shouldBlockWrite",3e3,(()=>this.permissionsService.shouldBlockWrite(c,f,l)));if(m){const e=await sC(c,"handleBlockReason",3e3,(()=>Pc(m,{onNeedsApproval:async(e,n)=>{const s="fileEdit"!==n?.type||n.isNewFile,i="fileEdit"===n?.type?n.diffString:l,a="fileEdit"===n?.type?n.blockReason:void 0;if(await zE(o,f))return aC(r);const c=await this.pendingDecisionProvider.requestApproval({type:vm.Write,details:{path:r,reason:e,isNewFile:s,diffString:i,before:h,after:l,blockReason:a},toolCallId:t.toolCallId});return c.approved?null:new vr.v3({result:{case:"rejected",value:new vr.en({path:r,reason:c.reason||""})}})},onUserRejected:e=>new vr.v3({result:{case:"rejected",value:new vr.en({path:r,reason:e||""})}}),onPermissionDenied:(e,t)=>new vr.v3({result:{case:"permissionDenied",value:new vr.U7({path:r,error:e,isReadonly:t?.isReadonly??!1})}})})));if(null!==e)return e}const g=(0,s.dirname)(f);if(await async function(e,t){if("fingerprint"!==e?.kind)return!1;try{return!await KE(t)}catch{return!1}}(o,g))return aC(r);try{await sC(c,"mkdir",3e3,(()=>(0,Os.mkdir)(g,{recursive:!0})))}catch(e){const t=e.code;return"EACCES"===t||"EPERM"===t?new vr.v3({result:{case:"permissionDenied",value:new vr.U7({path:r,directory:g,operation:"create_directory",error:"Permission denied"})}}):new vr.v3({result:{case:"error",value:new vr.QM({path:r,error:e.message})}})}let w,y;if(void 0!==u)w=u,y=0;else{const e=await sC(c,"getBufferForWrite",3e3,(()=>da(r,l,this.workspacePath,t.encodingHint)));w=e.buffer,y=e.lines}const v=()=>sC(c,"writeFile",3e3,(async()=>{if(await zE(o,f))throw new Error(JE(r));let e;n.writeStarted=!0,await async function(e,t,r){let o;try{o=await(0,Os.open)(e,function(){const e=$s.constants;let t=e.O_WRONLY|e.O_CREAT;return"number"==typeof e.O_NOFOLLOW&&(t|=e.O_NOFOLLOW),"number"==typeof e.O_CLOEXEC&&(t|=e.O_CLOEXEC),t}(),438)}catch(t){if(function(e){const t=e?.code;return"ELOOP"===t||"EMLINK"===t||"EPERM"===t&&"number"==typeof $s.constants.O_NOFOLLOW}(t))throw new rC(e,`Refusing to write through a symlink at ${e}`);throw t}try{let n;try{n=(0,$s.realpathSync)(e)}catch{throw new rC(e,`Cannot verify canonical path before writing: ${e}`)}if(n!==e)throw new rC(e,`Refusing write: ${e} now resolves through a symlinked parent to ${n}`);if(!(await o.stat()).isFile())throw new rC(e,`Refusing to write to non-regular file at ${e}`);await o.truncate(0);const s=function(e){return Buffer.isBuffer(e)?e:Buffer.from(e)}(t);let i=0;for(;i<s.length;){const{bytesWritten:e}=await o.write(s,i,s.length-i,i);if(0===e)break;i+=e}r?.flush&&await o.sync()}finally{await o.close()}}(f,w,{flush:!0});try{e=await(0,Os.open)((0,s.dirname)(f),tC.default.O_RDONLY),await e.sync()}catch{}finally{await(e?.close())}}));let b,S=!1;const k=async()=>{try{await v()}catch(e){throw b=e,S=!0,e}};try{void 0===this.writeFileMutationGuard?await v():await this.writeFileMutationGuard.runExclusive(f,k)}catch(e){if(void 0!==this.writeFileMutationGuard&&(!S||e!==b))return new vr.v3({result:{case:"error",value:new vr.QM({path:r,error:e instanceof Error?e.message:String(e)})}});if(e instanceof rC)return new vr.v3({result:{case:"permissionDenied",value:new vr.U7({path:r,directory:"",operation:"create_file",error:e.message})}});const t=e.code;return"EACCES"===t||"EPERM"===t?new vr.v3({result:{case:"permissionDenied",value:new vr.U7({path:r,directory:"",operation:"create_file",error:"Permission denied"})}}):"ENOSPC"===e.code?new vr.v3({result:{case:"noSpace",value:new vr.bM({path:r})}}):"EDQUOT"===t?new vr.v3({result:{case:"error",value:new vr.QM({path:r,error:"Agent-store quota exceeded: this write was rejected because the storage quota is full. Nothing was written; your local copy is intact. Delete or truncate files to free space (including resolved *.conflict* files), then retry. Do not retry the same write without freeing space first."})}}):new vr.v3({result:{case:"error",value:new vr.QM({path:r,error:e.message})}})}if(this.fileChangeTracker&&void 0===u&&!d&&!p){const e=t.toolCallId?{toolCallId:t.toolCallId}:void 0;await this.fileChangeTracker.trackChange(r,h,l,e)}if(this.onWriteForAiTracking&&void 0===u&&!d){const e=t.toolCallId?{toolCallId:t.toolCallId}:{};try{await this.onWriteForAiTracking({path:r,beforeContent:h,afterContent:l,metadata:e})}catch(e){nC.warn(c,"onWriteForAiTracking failed (write succeeded)",{path:r,error:e instanceof Error?e.message:String(e)})}}const E=w.byteLength;let C;if(t.returnFileContentAfterWrite)try{C=await sC(c,"readText after write",3e3,(()=>ua(r,t.encodingHint)))}catch{}return new vr.v3({result:{case:"success",value:new vr.j6({path:r,linesCreated:y,fileSize:E,...void 0!==C&&{fileContentAfterWrite:C}})}})}catch(e){a.error=e,a.hasError=!0}finally{oC(a)}}}function aC(e){return new vr.v3({result:{case:"error",value:new vr.QM({path:e,error:JE(e)})}})}class cC extends Error{constructor(e){super("stale write refusal"),this.result=e,this.name="StaleWriteRefusal"}}function lC(e){return"error"===e.result.case&&e.result.value.error===JE(e.result.value.path)}const uC=(0,m.h)("local-exec:provider"),dC=new Set;class hC extends G{getMcpExecutionPolicyDeps(){return{permissionsService:this.permissionsService,pendingDecisionProvider:this.pendingDecisionStore}}static dropOwnedRequestContextCaches(){for(const e of dC)e.ownedRequestContextExecutor?.invalidateGlobalCache()}constructor(e){super(),this.pendingDecisionStore=e.pendingDecisionStore,this.fileChangeTracker=e.fileChangeTracker,this.gitExecutor=e.gitExecutor,this.ignoreService=e.ignoreService,this.grepProvider=e.grepProvider,this.permissionsService=e.permissionsService,this.workspacePaths=e.workspacePaths,this.worktreeMainPath=e.worktreeMainPath,this.diagnosticsProvider=e.diagnosticsProvider,this.mcpLease=e.mcpLease,this.mcpStateAccessor=e.mcpStateAccessor,this.cursorRulesService=e.cursorRulesService,this.cloudRulesService=e.cloudRulesService,this.subagentsService=e.subagentsService,this.repositoryProvider=e.repositoryProvider,this.projectDir=e.projectDir,this.shellManager=e.shellManager,this._sandboxPolicyResolver=e._sandboxPolicyResolver,this._defaultSandboxPolicy=e._defaultSandboxPolicy??{type:"insecure_none"};const t=e.workspacePaths[0],r=t?function(e){const t=(0,s.join)(e,".cursor/sandbox.json");try{const r=(0,$s.readFileSync)(t,"utf-8"),o=JSON.parse(r),n=(0,Fs.$6)(o);return(0,Fs.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.wakeupOwnerConversationId=e.wakeupOwnerConversationId,this.mcpElicitationFactory=e.mcpElicitationFactory,this.createFileWatcher=e.createFileWatcher,this.sharedRequestContextExecutor=e.sharedRequestContextExecutor,this.terminalExecutor=e.terminalExecutor,this.mcpMetaToolEnabled=e.mcpMetaToolEnabled??!1,this.mcpMetaToolSlimDescriptors=e.mcpMetaToolSlimDescriptors??!1,this.mcpInputSchemaJson=e.mcpInputSchemaJson??!1,this.alwaysExposeVirtualMcpAuthTool=e.alwaysExposeVirtualMcpAuthTool??!1,this.enableRecordScreen=e.enableRecordScreen??!1,this.recordScreenArtifactsDir=e.recordScreenArtifactsDir,this.recordScreenDisplay=e.recordScreenDisplay,this.disableRecordScreenRendering=e.disableRecordScreenRendering??!1,this.userTerminalHint=e.userTerminalHint,this.attributionConfigProvider=e.attributionConfigProvider,this.isAttributionDisabledByAdmin=e.isAttributionDisabledByAdmin,this.getAgentSkills=e.getAgentSkills,this.getSmartModeClassifierAutoModeEnabled=e.getSmartModeClassifierAutoModeEnabled,this.getAdminCommandDenylist=e.getAdminCommandDenylist,this.devForceNextSmartModeClassifierBlockToken=e.devForceNextSmartModeClassifierBlockToken,this.getMockPromptTime=e.getMockPromptTime,this.additionalRules=e.additionalRules??[],this.askpassConfig=e.askpassConfig,this.rebuildRequestContextOnRulesChange=!0===e.rebuildRequestContextOnRulesChange;const i=this.terminalExecutor??(0,Fs.Fn)({env:{CURSOR_AGENT:"1"},userTerminalHint:this.userTerminalHint});let a;if(this.workspacePaths.length>1){const e=this.workspacePaths.map((e=>(0,s.dirname)(e)));a=e.every((t=>t===e[0]))?e[0]:void 0}else a=t;let c=new Cc(i,t??(0,n.homedir)(),this.projectDir,{shellOutputBackpressureOptions:e.shellOutputBackpressureOptions,extraEnvProvider:e.shellExtraEnvProvider,powershellUtf8Console:e.powershellUtf8Console,powershellUtf8ChildEnv:e.powershellUtf8ChildEnv,keepBackgroundJobs:e.keepShellBackgroundJobs});e.shellCoreWrapper&&(c=e.shellCoreWrapper(c)),this.askpassConfig&&(c=new _c(c,this.askpassConfig)),this.shellManager&&(c=new xc(c,this.shellManager));const l=e.overrideShellExecutor??(!0===e.suppressDefaultShellExecutor?void 0:new NE(this.permissionsService,c,this.ignoreService,this.pendingDecisionStore));void 0!==l&&this.register(br,fb(l)),this.register(cr,fb(new Sv(this.permissionsService,this.ignoreService,a??t??this.projectDir)));const u=new qE,d=e.overrideWriteExecutor??new iC(this.fileChangeTracker,this.permissionsService,this.pendingDecisionStore,{workspacePaths:this.workspacePaths,workspacePath:a,worktreeMainPath:this.worktreeMainPath,onWriteForAiTracking:e.onWriteForAiTracking,writeFileMutationGuard:e.writeFileMutationGuard,toolCallReads:u});this.register(kr,function(e){const t=(r={execute:(t,r,o)=>e.execute(t,r,o).then((e=>{if(lC(e))throw new cC(e);return e}))},fb(r));var r;return{async execute(e,r,o){try{return await t.execute(e,r,o)}catch(e){if(e instanceof cC)return e.result;throw e}}}}(d)),this.register(ie,fb(new Sm(this.pendingDecisionStore,this.fileChangeTracker,this.permissionsService,a,e.onDeleteForAiTracking))),this.register(le,fb(new _m)),this.register(ue,new oS);const h=this.mcpStateAccessor??new RE(this.mcpLease),p=e.overrideGrepExecutor??new cv(this.ignoreService,this.grepProvider,this.workspacePaths,{mcpStateAccessor:h,permissionsService:this.permissionsService,useStreamingGrep:e.useStreamingGrep});this.register(de,fb(p));const f=e.overrideReadExecutor??new GE(new oE(this.permissionsService,a,{mcpStateAccessor:h,useStreamingRead:e.useStreamingRead,pendingDecisionProvider:this.pendingDecisionStore}),u,this.permissionsService,a),m=new Vt(f);this.register(Jt,m),e.registerRedactedReadExecutor&&this.register(Kt,m);const g=e.overrideLsExecutor??new fv(this.permissionsService,this.ignoreService,a);this.register(vt,fb(g)),this.register(fr,fb(new nb(this.permissionsService,a))),void 0!==l&&this.register(lr,fb(new Mv(l))),this.register(ur,fb(new qv(this.permissionsService,d,a))),this.register(mr,fb(new ab(d,a))),this.register(hr,fb(new Qv(this.permissionsService,a))),this.register(dr,fb(new Jv(this.permissionsService,a))),this.register(pr,fb(new tb(this.permissionsService,a))),this.register(ae,fb(new Cb(a,this.diagnosticsProvider))),e.getCanvasDiagnostics&&this.register(ne,fb(new wb(e.getCanvasDiagnostics,e.beginCanvasSave))),this.register(At,fb(new ar(new Py(this.mcpLease,this.permissionsService,this.pendingDecisionStore,this.projectDir,this.mcpFileOutputThresholdBytes,this.mcpElicitationFactory,e.ensureMcpServersLoaded),(()=>this.get(Jt))))),this.register(Mt,fb(new Iy(this.mcpLease,e.ensureMcpServersLoaded))),this.register(Dt,fb(new Ry(this.mcpLease,a||this.projectDir,this.permissionsService,this.workspacePaths,this.pendingDecisionStore,e.ensureMcpServersLoaded))),this.register(Ot,fb(new AE(h,e.ensureMcpServersLoaded,{filterToRequestedServers:this.mcpMetaToolEnabled&&this.mcpMetaToolSlimDescriptors})));const w=fb(this.sharedRequestContextExecutor??this.createOwnedRequestContextExecutor(h,t,e));this.register(Ir,{execute:async(t,r,o)=>{const n=await w.execute(t,r,o);if("success"!==n.result.case||void 0===n.result.value.requestContext)return n;const s=n.clone();if("success"!==s.result.case)return n;const i=s.result.value.requestContext;if(void 0===i)return s;const a=await h.getState(t),c=xE(a,{internalBrowserProvidersOnly:this.mcpMetaToolEnabled&&this.mcpMetaToolSlimDescriptors,inputSchemaJson:this.mcpInputSchemaJson});if(i.tools=c.tools,i.mcpInstructions=c.mcpInstructions,i.mcpMetaToolOptions=this.mcpMetaToolEnabled?_E(a,{alwaysExposeVirtualMcpAuthTool:this.alwaysExposeVirtualMcpAuthTool,slimDescriptors:this.mcpMetaToolSlimDescriptors,inputSchemaJson:this.mcpInputSchemaJson}):void 0,i.mcpFileSystemOptions=await(e.getMcpFileSystemOptions?.(t)),void 0!==i.env&&(i.env.artifactsFolder=e.getArtifactsFolder?.(t),void 0!==e.getSandboxEnabled&&(i.env.sandboxEnabled=e.getSandboxEnabled()),void 0!==e.getSessionSandboxSupported&&(i.env.sandboxSupported=e.getSessionSandboxSupported())),void 0!==e.getMountedAgentStores&&void 0!==i.env)try{const r=await e.getMountedAgentStores(t);i.env.mountedAgentStores=r.map((e=>e.clone()))}catch{i.env.mountedAgentStores=[],uC.warn(t,"Failed to get mounted agent stores; continuing without prompt inventory")}return s}}),this.backgroundShellExecutor=new Gc(this.permissionsService,c,this.ignoreService,this.projectDir,this.backgroundShellFactory,this.backgroundWorkRegistry,this.wakeupOwnerConversationId),this.register(ee,fb(this.backgroundShellExecutor));const y=new WE(this.permissionsService,c,this.ignoreService,this.backgroundShellExecutor.getManager());this.register(Sr,function(e,t){const r=new Ns.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=pb(n.execId,o),i=r.get(s);if(i)return void(yield*i.fork());const a=e.execute(t,o,n),c=new hb(a);r.set(s,c),yield*c.fork()}}}(y)),void 0!==e.agentStoreConflictDrainer&&this.register(Q,new ub(e.agentStoreConflictDrainer)),this.register(Tr,new FE(this.permissionsService)),this.register(Nt,new sS(this.permissionsService)),this.register(fo,new eC(this.permissionsService));const v=new jE(y);this.register(Ar,fb(v));const b=!1===e.enableWriteBackgroundShellStdin?new db((async()=>{throw new Error(e.writeBackgroundShellStdinDisabledReason??"write_shell_stdin is disabled for this session")})):new db(((e,t)=>this.backgroundShellExecutor.writeStdin(e,t)));if(this.register(te,fb(b)),e.computerUseExecutor&&(this.computerUseExecutor=e.computerUseExecutor,this.register(se,fb(this.computerUseExecutor))),this.enableRecordScreen){if(!this.recordScreenArtifactsDir||!this.recordScreenDisplay)throw new Error("recordScreenArtifactsDir and recordScreenDisplay are required when enableRecordScreen is true");this.recordScreenExecutor=new dE({artifactsDir:this.recordScreenArtifactsDir,display:this.recordScreenDisplay,disablePolishedRendering:this.disableRecordScreenRendering,polishedRenderer:e.polishedRecordingRenderer}),this.register(Pr,fb(this.recordScreenExecutor))}}createOwnedRequestContextExecutor(e,t,r){const o=new ME(this.cursorRulesService,this.cloudRulesService,this.subagentsService,this.repositoryProvider,this.grepProvider,e,this.gitExecutor,void 0===r.requestContextWorkspacePaths?this.workspacePaths:[...r.requestContextWorkspacePaths],{projectDir:this.projectDir,isWorkingDirHomeDir:r.requestContextIsWorkingDirHomeDir??(0,Gs.yn)(t,(0,n.homedir)()),agentNotesEnabled:r.agentNotesEnabled,reportProcessWorkingDirectory:r.reportProcessWorkingDirectory,sectionLoadTimeoutMs:r.requestContextSectionLoadTimeoutMs,reportSectionCompleteness:r.reportRequestContextSectionCompleteness,createFileWatcher:this.createFileWatcher,getSandboxEnabled:r.getSandboxEnabled,getSandboxSupported:r.getSandboxSupported,getNetworkAllowlistInfo:r.getNetworkAllowlistInfo,getSmartModeClassifierAutoModeEnabled:this.getSmartModeClassifierAutoModeEnabled,getAdminCommandDenylist:this.getAdminCommandDenylist,devForceNextSmartModeClassifierBlockToken:this.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:this.getMockPromptTime,userTerminalHint:this.userTerminalHint,getMcpFileSystemOptions:r.getMcpFileSystemOptions,mcpMetaToolEnabled:this.mcpMetaToolEnabled,mcpMetaToolSlimDescriptors:this.mcpMetaToolSlimDescriptors,mcpInputSchemaJson:this.mcpInputSchemaJson,alwaysExposeVirtualMcpAuthTool:this.alwaysExposeVirtualMcpAuthTool,getArtifactsFolder:r.getArtifactsFolder,secretRedactionEnabled:r.secretRedactionEnabled,attributionConfigProvider:this.attributionConfigProvider,isAttributionDisabledByAdmin:this.isAttributionDisabledByAdmin,getAgentSkills:this.getAgentSkills,additionalRules:this.additionalRules,getComputerUseSupported:()=>void 0!==this.computerUseExecutor,onRequestContext:r.onRequestContext});return this.rebuildRequestContextOnRulesChange&&(this.ownedRequestContextExecutor=o,dC.add(this),this.disposeRulesChangeListener=this.cursorRulesService.onDidChangeRules?.((()=>{o.rebuildAllCaches()}))),o}getRecordScreenExecutor(){return this.recordScreenExecutor}async dispose(){this.rebuildRequestContextOnRulesChange&&(dC.delete(this),this.disposeRulesChangeListener?.(),this.disposeRulesChangeListener=void 0,this.ownedRequestContextExecutor?.dispose(),this.ownedRequestContextExecutor=void 0),this.backgroundShellExecutor.dispose(),this.recordScreenExecutor&&await this.recordScreenExecutor.dispose()}}function pC(e){return e.replace(/\\/g,"/")}function fC(e,t){for(const r of t){const t=pC(r);if(e===t||e.startsWith(`${t}/`))return!0}return!1}var mC;function gC(e,t,r){if(function(e){return Boolean(e.plugin?.trim()||e.pluginId?.trim()||e.marketplaceId?.trim())}(e))return mC.Plugin;const o=pC(e.fullPath);return fC(o,r.builtinDirs)?mC.Builtin:Fp(e.fullPath,t).inAgentStore?mC.UserStore:fC(o,r.userDirs)?mC.UserHome:(fC(o,r.workspaceDirs),mC.Workspace)}"function"==typeof SuppressedError&&SuppressedError,function(e){e[e.Builtin=0]="Builtin",e[e.UserStore=1]="UserStore",e[e.UserHome=2]="UserHome",e[e.Workspace=3]="Workspace",e[e.Plugin=4]="Plugin"}(mC||(mC={}));var wC=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 yC=(0,ji.debuglog)("merged-agent-skills"),vC=(0,m.h)("merged-agent-skills");class bC{constructor(e,t=()=>[],r){this.services=e,this.getDisabledManagedSkillPaths=t,this.getPromptSortContext=r,this.onChangeCallbacks=new Set}async getAllAgentSkills(e){const t={stack:[],error:void 0,hasError:!1};try{const r=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var 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,i.VI)(e.withName("MergedAgentSkillsService.getAllAgentSkills")),!1),o=this.services.map((e=>e.getAllAgentSkills(r.ctx).catch((e=>(yC("Failed to load agent skills from service: %s",e instanceof Error?e.message:String(e)),[]))))),n=async()=>{try{return{ok:!0,paths:await this.getDisabledManagedSkillPaths()}}catch(e){return vC.warn(r.ctx,"getDisabledManagedSkillPaths failed; failing closed by dropping all managed skills for this call",{error:e instanceof Error?e.message:String(e)}),{ok:!1}}},[a,c]=await Promise.all([Promise.all(o),n()]),l=a.flat(),u=this.getPromptSortContext?.(),d=Lp(l,u??Np);let h=d;return c.ok?c.paths.length>0&&(h=d.filter((e=>!function(e,t){if(!e)return!1;const r=e.replace(/\\/g,"/");return t.some((e=>r.endsWith(e)))}(e.fullPath,c.paths)))):h=d.filter((e=>{return!((t=e.fullPath)&&t.replace(/\\/g,"/").includes(SC));var t})),void 0!==u?function(e,t){if(e.length<=1)return e;const r=function(e){const t=[Sp(e.userHomeDirectory).dirPath],r=Cp(e.userHomeDirectory,!0).map((e=>e.dirPath)),o=[];for(const t of e.workspacePaths){o.push((0,s.join)(t,".cursor","rules"));for(const e of Ep(t,!0))o.push(e.dirPath)}return{builtinDirs:t,userDirs:r,workspaceDirs:o}}(t),o=e.map(((e,o)=>({skill:e,index:o,tier:gC(e,t,r)})));return o.sort(((e,t)=>e.tier-t.tier||e.index-t.index)),o.map((e=>e.skill))}(h,u):h}catch(e){t.error=e,t.hasError=!0}finally{wC(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()}),bC.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()}}bC.CHANGE_COALESCE_MS=1500;const SC=`/${wp.configDir}/${wp.subdir}/`,kC=(0,m.h)("skill-sync-manifest"),EC=".sync-manifest.json";async function CC(e,t){try{const r=await(0,Os.readFile)((0,s.join)(e,EC),"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:(kC.warn(t,"Manifest failed schema validation, resetting",{skillDir:e}),{version:1,skills:{}})}catch(r){return r instanceof Error&&"ENOENT"===r.code||kC.debug(t,"Failed to read sync manifest, resetting",{skillDir:e,error:String(r)}),{version:1,skills:{}}}}function xC(e,t,r){e.skills[t]={lastSyncedAt:r}}function _C(e,t){delete e.skills[t]}var 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});const IC=(0,m.h)("builtin-skills-sync");function RC(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function TC(e){for(const t of Object.keys(e.resources??{}))if(0===t.length||t.includes("\\")||t.includes("\0")||s.posix.isAbsolute(t)||s.posix.normalize(t)!==t||t.split("/").includes("..")||"SKILL.md"===s.posix.basename(t)||!t.endsWith(".md"))throw new Error(`Unsafe managed skill resource path: ${JSON.stringify(t)}`)}function AC(e){const t=nh(e.content),r=RC(t.data)?t.data:{};return sh(`${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={...RC(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 MC(e,t,r){const o=(0,s.join)(t,r.id),n=(0,s.join)(o,"SKILL.md"),i=r.fileContent,a=Object.keys(r.resources),c=await DC(o);if(a.length>0||c.length>0){const e=new Map([["SKILL.md",i],...Object.entries(r.resources)]),n=new Set(["SKILL.md",...c]);if(n.size===e.size&&[...e.keys()].every((e=>n.has(e)))){let t=!0;for(const[r,n]of e)try{if(await(0,Os.readFile)((0,s.join)(o,...r.split("/")),"utf-8")!==n){t=!1;break}}catch{t=!1;break}if(t)return!1}return await async function(e,t){const r=(0,s.join)(e,t.id),o=await(0,Os.mkdtemp)((0,s.join)(e,`.${t.id}-staging-`)),n=`${o}-backup`;let i=!1;try{await(0,Os.writeFile)((0,s.join)(o,"SKILL.md"),t.fileContent,"utf-8");for(const[e,r]of Object.entries(t.resources)){const t=(0,s.join)(o,...e.split("/"));await(0,Os.mkdir)((0,s.dirname)(t),{recursive:!0}),await(0,Os.writeFile)(t,r,"utf-8")}try{await(0,Os.rename)(r,n),i=!0}catch(e){if(!(e instanceof Error)||"ENOENT"!==e.code)throw e}try{await(0,Os.rename)(o,r)}catch(e){throw i&&(await(0,Os.rename)(n,r),i=!1),e}i&&(await(0,Os.rm)(n,{recursive:!0,force:!0}),i=!1)}finally{await(0,Os.rm)(o,{recursive:!0,force:!0})}}(t,r),!0}try{if(await(0,Os.readFile)(n,"utf-8")===i)return!1}catch(t){t instanceof Error&&"ENOENT"===t.code||IC.warn(e,"Unexpected error reading skill file",{skillId:r.id,error:String(t)})}return await(0,Os.mkdir)(o,{recursive:!0}),await(0,Os.writeFile)(n,i,"utf-8"),!0}async function DC(e,t=""){const r=t?(0,s.join)(e,...t.split("/")):e;let o;try{o=await(0,Os.readdir)(r,{withFileTypes:!0})}catch(e){if(e instanceof Error&&"ENOENT"===e.code)return[];throw e}const n=[];for(const r of o){const o=t?`${t}/${r.name}`:r.name;r.isDirectory()?n.push(...await DC(e,o)):r.isFile()&&r.name.endsWith(".md")&&"SKILL.md"!==o&&n.push(o)}return n}async function OC(e,t){try{return(await(0,Os.readdir)(t,{withFileTypes:!0})).filter((e=>e.isDirectory()&&!e.name.startsWith("."))).map((e=>e.name))}catch(r){return r instanceof Error&&"ENOENT"===r.code||IC.warn(e,"Failed to list skills directory, skipping cleanup",{skillDir:t,error:String(r)}),[]}}async function NC(e,t={}){const r={stack:[],error:void 0,hasError:!1};try{const a=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,i.VI)(e.withName("syncBuiltinSkills")),!1).ctx,c=Date.now(),l=Sp((0,n.homedir)()).dirPath;await(0,Os.mkdir)(l,{recursive:!0});const[u,d]=await Promise.all([CC(l,a),OC(a,l)]),h=u.lastInventoryAt;(void 0===h||c-h>=864e5)&&(await async function(e,t,r,o){try{const n=await Promise.all(r.map((async e=>{const r=(0,s.join)(t,e),[n,i]=await Promise.all([$C((0,s.join)(r,"SKILL.md")),"canvas"===e?$C((0,s.join)(r,"sdk")):Promise.resolve(!1)]);return{skill_id:e,has_skill_md:n,has_sdk_dir:i,last_synced_at:o.skills[e]?.lastSyncedAt??null}})));IC.info(e,"managed_skills.startup_inventory",{skills_on_disk:n,manifest_present:Object.keys(o.skills).length>0})}catch(t){IC.warn(e,"Failed to emit managed skills startup inventory",{error:String(t)})}}(a,l,d,u),u.lastInventoryAt=c);const p=new Map;for(const e of t.managedSkills??[])(o=e.id)&&o===o.trim()&&!(o.includes("..")||o.includes("/")||o.includes("\\"))?p.set(e.id,e):IC.warn(a,"Skipping managed skill with unsafe id",{skillId:e.id});const f=new Set([...p.keys(),...d]);let m=0,g=0;const w=[];for(const e of f)try{const t=p.get(e),r=u.skills[e],o=r?c-r.lastSyncedAt:0,n=void 0!==r&&o>2592e5,i=void 0!==t&&ru(t,"local"),h=void 0!==t&&!i,f=void 0!==r||d.includes(e);if(t&&!1!==t.enabled&&i)TC(t),await MC(a,l,{id:e,fileContent:AC(t),resources:t.resources??{}})?m++:g++,xC(u,e,c);else if(!1===t?.enabled||h||n){const o=!1===t?.enabled?"enabled_false":h?"environment_ineligible":"grace_expired";await(0,Os.rm)((0,s.join)(l,e),{recursive:!0,force:!0}),_C(u,e),f&&(w.push(e),IC.info(a,"managed_skills.removed",{skill_id:e,reason:o,server_enabled:t?.enabled??null,had_manifest_entry:void 0!==r,last_synced_ms_ago:r?c-r.lastSyncedAt:null}))}else r||xC(u,e,c)}catch(t){IC.warn(a,"Failed to apply skill, will retry next sync",{skillId:e,error:String(t)})}try{await async function(e,t){const r=(0,s.join)(e,".sync-manifest.json.tmp"),o=(0,s.join)(e,EC);await(0,Os.mkdir)(e,{recursive:!0}),await(0,Os.writeFile)(r,JSON.stringify(t,null,2),"utf-8"),await(0,Os.rename)(r,o)}(l,u)}catch(e){!function(e){if(e instanceof Error&&"ENOENT"===e.code)return!0;const t=String(e);return t.includes("ENOENT")||t.includes("no such file or directory")}(e)?IC.warn(a,"Failed to persist sync manifest",{skillDir:l,error:String(e)}):IC.debug(a,"Skipped persisting sync manifest, path removed concurrently",{skillDir:l,error:String(e)})}return{synced:m,upToDate:g,removed:w}}catch(e){r.error=e,r.hasError=!0}finally{PC(r)}var o}async function $C(e){try{return await(0,Os.stat)(e),!0}catch(e){const t=e.code;if("ENOENT"===t||"ENOTDIR"===t)return!1;throw e}}const FC=(0,m.h)("managed-skills-sync");function jC(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 LC{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(...wu(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=jC(o.url);r.has(e)||(r.add(e),t.push(o))}return t}(t)}}var UC=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 BC(e,t){return void 0===e?[]:(Array.isArray(e)?e:[e]).map((e=>({...e,userHomeDir:t})))}class WC{constructor(e,t,r,o,n,s){this.workspacePaths=e,this.userHomeDirectory=t,this.getSettings=r,this.marketplaceOptions=o,this.localPluginVariablesLookup=s,this.plugins=[],this._loadFailures=[],this._pluginSetIncomplete=!0,this._retainedFromPreviousLoad=0,this._wasFirstLoad=!0,this.loadedOnce=!1,this._extensionPlugins=new Map,this._extensionPluginOriginalPaths=new Map,this.pluginLogger=n??Jc,this.reload()}async getAllEnabledPlugins(){return await this.ensureLoaded(),[...this.plugins]}getLoadFailures(){return[...this._loadFailures]}isPluginSetIncomplete(){return this._pluginSetIncomplete}getLoadDiagnostics(){return{userHomeDirectory:this.userHomeDirectory,pluginsLoaded:this.plugins.length,retainedFromPreviousLoad:this._retainedFromPreviousLoad,wasFirstLoad:this._wasFirstLoad,sourceUnavailable:this._pluginSetIncomplete}}async reload(){return this.loadPromise||(this.loadPromise=this.load().then((async e=>{const t=!this.loadedOnce;let r=[];try{r=await this._reloadExtensionPlugins()}catch(e){this.pluginLogger.log("error",`Failed to reload extension plugins after base load success: ${e}`)}const o=e.sourceUnavailable?this._retainPluginsMissingFromPartialLoad(e.plugins):[],n=[...e.plugins,...o],s=new Set(n.map((e=>e.installPath))),i=r.filter((e=>!s.has(e.installPath)));return this.plugins=[...n,...i],e.sourceUnavailable||(this._loadFailures=e.failures),this._pluginSetIncomplete=e.sourceUnavailable,this._retainedFromPreviousLoad=o.length,this._wasFirstLoad=t,this.loadedOnce=!0,this.pluginLogger.log("info",`Plugins reload completed: ${this.plugins.length} plugins loaded (${i.length} extension, ${o.length} retained), ${e.failures.length} failures`),this.plugins})).catch((async e=>{const t=!this.loadedOnce;this.pluginLogger.log("error",`Failed to load plugins: ${e}`),this._pluginSetIncomplete=!0,this._retainedFromPreviousLoad=0,this._wasFirstLoad=t;try{const e=await this._reloadExtensionPlugins(),t=new Set(this.plugins.map((e=>e.installPath)));this.plugins=[...this.plugins,...e.filter((e=>!t.has(e.installPath)))]}catch(e){this.pluginLogger.log("error",`Failed to reload extension plugins after base load failure: ${e}`)}return this.loadedOnce=!0,this.plugins})).finally((()=>{this.loadPromise=void 0}))),this.loadPromise}_retainPluginsMissingFromPartialLoad(e){if(!this.loadedOnce)return[];const t=new Set(e.map(Zh));return this.plugins.filter((e=>"extension"!==e.identifier.source&&void 0===e.loadError&&e.installPath.length>0&&!t.has(Zh(e))))}async reloadPlugin(e){this.loadPromise&&await this.loadPromise;const t=BC(this.marketplaceOptions,this.userHomeDirectory);if(0===t.length)return;if(!(this.getSettings().loadCursorFirstParty??t.length>0))return;const r=t=>t.pluginDbId===e.pluginDbId,o=e=>"cursor-first-party"===e.identifier.source||"cursor-third-party"===e.identifier.source?e.identifier.sourceInfo:void 0,n=t=>o(t)?.pluginDbId===e.pluginDbId,s=(t,r)=>void 0!==t.pluginDbId?t.pluginDbId===e.pluginDbId:t.pluginName===r?.name&&t.marketplaceName===r?.marketplace;let i,a,c;for(const l of t){let t;try{t=await Jh({...l,log:l.log??this.pluginLogger,pluginFilter:r})}catch(t){this.pluginLogger.log("error",`reloadPlugin: source load failed for ${e.name}: ${t}`);continue}const u=t.plugins.find((e=>n(e)&&void 0===e.loadError));if(void 0!==u){i=u;break}const d=t.plugins.find(n);if(void 0!==d&&void 0===a){const e=o(d);a=d,c=t.failures.find((t=>s(t,e)))}}if(void 0===i){if(void 0!==a){const t=o(a),r={...c??{pluginName:t?.name??e.name,errorMessage:a.loadError??"Plugin load failed",errorType:"unknown",...void 0!==t?.marketplace&&{marketplaceName:t.marketplace}},pluginDbId:e.pluginDbId};this._loadFailures=[...this._loadFailures.filter((e=>!s(e,t))),r]}return}const l=this.plugins.findIndex(n);if(-1===l)this.plugins=[...this.plugins,i];else{const e=[...this.plugins];e[l]=i,this.plugins=e}this.loadedOnce=!0;const u=o(i);return this._loadFailures=this._loadFailures.filter((e=>!s(e,u))),i}async registerExtensionPlugin({path:e,extensionId:t}){const r=(0,s.resolve)(e),o=await(0,Os.realpath)(r);if(!(await(0,Os.stat)(o)).isDirectory())throw new Error(`Extension plugin path is not a directory: ${o}`);const i=n.homedir();if(o.split(s.sep).filter(Boolean).length<3||o===i||"/"===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 a=this._extensionPlugins.get(t);if(a||(a=new Map,this._extensionPlugins.set(t,a)),a.has(o))return void this._rememberExtensionPluginOriginalPath({extensionId:t,originalPath:r,canonicalPath:o});const c=(0,s.basename)(o),l=await this._loadExtensionPluginContent(o,t);a.set(o,l),this._rememberExtensionPluginOriginalPath({extensionId:t,originalPath:r,canonicalPath:o}),this.pluginLogger.log("info",`Registered extension plugin: ${c} from ${o} (extension: ${t})`)}async unregisterExtensionPlugin({path:e,extensionId:t}){const r=this._extensionPlugins.get(t);if(!r)return!1;const o=(0,s.resolve)(e);let n;try{n=await(0,Os.realpath)(o)}catch{const e=this._extensionPluginOriginalPaths.get(t);n=e?.get(o)??o}const i=r.delete(n);return 0===r.size?(this._extensionPlugins.delete(t),this._extensionPluginOriginalPaths.delete(t)):i&&this._forgetExtensionPluginOriginalPath(t,n),i&&this.pluginLogger.log("info",`Unregistered extension plugin: ${n} (extension: ${t})`),i}async _loadExtensionPluginContent(e,t){const r=(0,s.basename)(e),o={name:r,localPath:e,extensionId:t},n=await qh(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},...void 0!==n.logoUrl&&{logoUrl:n.logoUrl},...void 0!==n.version&&{version:n.version},...void 0!==n.homepage&&{homepage:n.homepage},...void 0!==n.repository&&{repository:n.repository},skills:n.skills,rules:n.rules,agents:n.agents,commands:n.commands,mcpConfig:n.mcpConfig??void 0,capabilities:n.capabilities,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 t=(0,ce.q6)().withName("LocalPluginsService.load"),r=(function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var 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,i.VI)(t),!1),performance.now()),o=e=>{this.pluginLogger.increment(`local_plugins_service.load.${e}`,1),this.pluginLogger.distribution("local_plugins_service.load.duration",performance.now()-r,{outcome:e})},n=this.getSettings(),a=BC(this.marketplaceOptions,this.userHomeDirectory),c=n.importThirdPartyPlugins,l=n.loadUserLocalPlugins??!0,u=n.loadCursorFirstParty??a.length>0;if(!c&&!u&&!l)return this.pluginLogger.log("info","Skipping plugin loading, cursor 1p, 3p, and user-local plugins are disabled"),{plugins:[],failures:[],sourceUnavailable:!1};this.pluginLogger.increment("local_plugins_service.load.start",1);const d=(e,t)=>{this.pluginLogger.increment("local_plugins_service.load_plugin.error",1),this.pluginLogger.log("error",`Cursor plugin load error ${e.name}@${e.version}: ${t?.message??String(t)}`)};try{const e=await async function(e,t={}){const r=t.log??Jc,o=performance.now(),n=t.loadClaude??!0,i=t.loadUserLocal??!0,a=t.marketplaceSources??[],c=t.loadCursorFirstParty??a.length>0,l=[],u=[];let d;n&&l.push(Vh(e,0,{userHomeDir:t.userHomeDir,onError:t.onError,log:r})),c&&a.length>0&&(d=Promise.allSettled(a.map((e=>Jh({...e,userHomeDir:e.userHomeDir??t.userHomeDir,log:e.log??r}))))),i&&l.push(async function(e={}){const t=e.log??Jc,r=performance.now(),o=e.userHomeDir??process.env.HOME;if(!o)return t.log("info","loadUserLocalPlugins: no home directory available, skipping"),[];const n=(0,s.join)(o,".cursor","plugins","local");let i;try{i=await(0,Os.readdir)(n,{withFileTypes:!0})}catch{return t.log("info",`loadUserLocalPlugins: ${n} not found or not readable (${(performance.now()-r).toFixed(1)}ms)`),[]}const a=await(0,Os.realpath)(n).catch((()=>(0,s.resolve)(n))),c=[];for(const r of i){if(!r.isDirectory()&&!r.isSymbolicLink())continue;if(r.name.startsWith("."))continue;const o=(0,s.join)(n,r.name);try{if(r.isSymbolicLink()){let e;try{e=await(0,Os.realpath)(o)}catch(e){t.log("warn",`loadUserLocalPlugin ${r.name} rejected: failed to resolve symlink (${e instanceof Error?e.message:String(e)})`);continue}try{bd(a,e)}catch{t.log("warn",`loadUserLocalPlugin ${r.name} rejected: symlink target ${e} is outside ${n}`);continue}}if(!(await(0,Os.stat)(o)).isDirectory()){r.isSymbolicLink()&&t.log("warn",`loadUserLocalPlugin ${r.name} rejected: symlink target is not a directory`);continue}const s=performance.now(),i=await(e.localPluginVariablesLookup?.(r.name)),{displayName:l,description:u,authorName:d,logoUrl:h,version:p,homepage:f,repository:m,variablesSchema:g,skills:w,rules:y,agents:v,commands:b,mcpConfig:S,capabilities:k,hooks:E}=await qh(o,r.name,void 0,{configuredVariables:i,log:t}),C={source:"user-local",sourceInfo:{name:r.name,localPath:o}};c.push({identifier:C,installPath:o,...void 0!==l&&{displayName:l},...void 0!==u&&{description:u},...void 0!==d&&{authorName:d},...void 0!==h&&{logoUrl:h},...void 0!==p&&{version:p},...void 0!==f&&{homepage:f},...void 0!==m&&{repository:m},variablesSchema:g,skills:w,rules:y,agents:v,commands:b,mcpConfig:S??void 0,capabilities:k,hooks:E}),t.log("info",`loadUserLocalPlugin ${r.name} loaded in ${(performance.now()-s).toFixed(1)}ms`)}catch(e){t.log("error",`loadUserLocalPlugin ${r.name} failed: ${e instanceof Error?e.message:String(e)}`)}}return t.log("info",`loadUserLocalPlugins completed in ${(performance.now()-r).toFixed(1)}ms (${c.length} plugins loaded)`),c}({userHomeDir:t.userHomeDir,log:r,localPluginVariablesLookup:t.localPluginVariablesLookup}));const[h,p]=await Promise.all([Promise.allSettled(l),d??Promise.resolve([])]);let f=!1;const m=[];for(const e of p)"rejected"!==e.status?(e.value.sourceUnavailable&&(f=!0),m.push(...e.value.plugins),u.push(...e.value.failures)):(f=!0,r.log("error",`marketplace source threw while loading; treating it as unavailable: ${String(e.reason)}`));for(const e of h)"rejected"!==e.status?m.push(...e.value):(f=!0,r.log("error",`plugin source threw while loading; treating it as unavailable: ${String(e.reason)}`));const g=new Set,w=[];for(const e of m){if(!e.installPath){w.push(e);continue}const t=await(0,Os.realpath)(e.installPath).catch((()=>e.installPath));g.has(t)||(g.add(t),w.push(e))}const y=new Map,v=[];for(const e of w){const t=Kh(e);if(void 0!==t){const r=y.get(t),o=!e.loadError;if(!0===r)continue;if(!1===r&&o){const r=v.findIndex((e=>Kh(e)===t&&e.loadError));-1!==r&&v.splice(r,1),y.set(t,!0),v.push(e);continue}y.set(t,o)}v.push(e)}const b=performance.now()-o;return r.log("info",`loadAllPlugins completed in ${b.toFixed(1)}ms (claude=${n}, userLocal=${i}, marketplace=${a.length} sources, total=${v.length} plugins, failures=${u.length}, sourceUnavailable=${f})`),{plugins:v,failures:u,sourceUnavailable:f}}(this.workspacePaths,{userHomeDir:this.userHomeDirectory,loadClaude:c,loadUserLocal:l,loadCursorFirstParty:u&&a.length>0,marketplaceSources:a.length>0?a.map((e=>({...e,onCursorError:d}))):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 o("success"),this.pluginLogger.log("info",`Plugins loaded in ${(performance.now()-r).toFixed(1)}ms`),e}catch(e){return o("error"),this.pluginLogger.log("error",`Failed to load all plugins: ${e}`),{plugins:[],failures:[],sourceUnavailable:!0}}}catch(t){e.error=t,e.hasError=!0}finally{UC(e)}}}var HC=r("../proto/dist/generated/aiserver/v1/dashboard_pb.js");BigInt(0),BigInt(8),BigInt(16),BigInt(65535);function qC({failOpenWhenEmpty:e,server:t,settings:r}){if(!0!==r?.allowedMcpConfiguration?.requireMcpServersInTeamNetworkAllowlist||void 0===t.url)return{blocked:!1};const o=(r.networkAllowlist??[]).map((e=>e.trim())).filter((e=>e.length>0));return 0===o.length&&e||mS(t.url,o)?{blocked:!1}:{blocked:!0,reason:"teamNetworkAllowlist",message:"Not on the team network allowlist"}}class zC{constructor(e){this.dashboardClient=e}getTeamAdminSettings(){return this.dashboardClient.getTeamAdminSettingsOrEmptyIfNotInTeam(new HC.Byz({}))}getTeamRepos(){return this.dashboardClient.getTeamReposOrEmptyIfNotInTeam(new HC.aYW({}))}}function GC(e,t){if("workspace"!==e)return[];const r=[],o=new Set;for(const e of t??[]){const t=e.trim();0===t.length||o.has(t)||(o.add(t),r.push(t))}return r}class VC{constructor(e){this.fetch=e}get(){const e=this.cached,t=void 0===e?1/0:Date.now()-e.fetchedAt;return void 0===e||t>6e5?(this.cached=void 0,this.refresh()):(t>3e5&&this.refresh().catch((()=>{})),Promise.resolve(e.value))}invalidate(){this.cached=void 0,this.inFlight=void 0}refresh(){if(void 0===this.inFlight){const e=this.fetch().then((t=>(this.inFlight!==e||void 0===t&&void 0!==this.cached||(this.cached={value:t,fetchedAt:Date.now()}),t))).finally((()=>{this.inFlight===e&&(this.inFlight=void 0)}));this.inFlight=e}return this.inFlight}}class JC{constructor(e,t,r={}){this.teamAdminSettingsProvider=e,this.defaultAllowlistProvider=t,this.options=r,this.lastFetchSucceeded=!0,this.settings=new VC((()=>this.fetchSettings())),this.teamRepos=new VC((()=>this.teamAdminSettingsProvider.getTeamRepos())),this.defaultAllowlist=new VC((()=>this.fetchDefaultAllowlist())),this.getTeamAdminSettings(),this.prefetchTeamRepos()}async prefetchTeamRepos(){try{await this.teamRepos.get()}catch{}}invalidateCache(){this.settings.invalidate(),this.defaultAllowlist.invalidate()}async fetchSettings(){try{const e=await this.teamAdminSettingsProvider.getTeamAdminSettings();return this.lastFetchSucceeded=!0,this.lastFetchedSettings=e,e}catch(e){throw this.lastFetchSucceeded=!1,e}}getTeamAdminSettings(){return this.settings.get().catch((()=>{}))}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,o=await this.isMcpSettingsOverhaulEnabled({disableExposureLog:!0});if(!0===r?.disableAll)return{blocked:!0,reason:"teamPolicy",message:"Blocked by team policy"};if(o){if(function(e,t){return!(0,Fm.YaX)(e,t)}(e,r))return{blocked:!0,reason:"teamPolicy",message:"Blocked by team policy"};const o=await this.getMcpNetworkControlsConfig(e),n=void 0===e.url?{allowed:!0}:(0,Fm.MEY)(e.url,o);if(!n.allowed)return{blocked:!0,reason:"teamNetworkAllowlist",message:n.message};const s=qC({failOpenWhenEmpty:!1,server:e,settings:t});if(s.blocked)return s}if(!o){const r=function({isMcpAccessNetworkAllowlistEnabled:e,server:t,settings:r}){return e&&!0===r?.allowedMcpConfiguration?.requireMcpServersInTeamNetworkAllowlist?qC({failOpenWhenEmpty:!0,server:t,settings:r}):{blocked:!1}}({isMcpAccessNetworkAllowlistEnabled:await this.isMcpAccessNetworkAllowlistEnabled(),server:e,settings:t});if(r.blocked)return r}return{blocked:!1}}async getManagedSlackWorkspaceLists(){const e=await this.getTeamAdminSettings()??this.lastFetchedSettings;return void 0===e?[]:function(e){return e.memberSlackManagedWorkspacesUnreadable?"unconfirmed":[e.slackIntegrationSettings?.managedWorkspaces?.slackTeamIds??[],...e.memberSlackManagedWorkspaces.map((e=>e.slackTeamIds))].filter((e=>e.length>0))}(e)}async getMcpNetworkControlsConfig(e){const t=await this.getTeamAdminSettings(),r=t?.allowedMcpConfiguration;if(await this.isMcpSettingsOverhaulEnabled()){const o="win32"===process.platform&&await this.isWin32UserExtensionStdioUnsandboxEnabled();return(0,Fm._NE)({allowedMcpConfiguration:r,server:e,localAgentNetworkAllowlist:t?.networkAllowlist,blockMessage:"Not on the team network allowlist",aggregateManagedServerNetworkAllowlists:!1,stdioPlatform:process.platform,unsandboxUserExtensionStdio:o})}return{enabled:!1,localAgentNetworkAllowlist:t?.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 isReadControlEnabled(){try{return await(this.options.isReadControlEnabled?.())??!0}catch{return!1}}async isDenylistEnforcementKilled(){try{return!0===await(this.options.isAdminCommandDenylistEnforcementKilled?.())}catch{return!1}}async getAdminCommandDenylist(){if(await this.isDenylistEnforcementKilled())return{rules:[]};const e=await this.getTeamAdminSettings();return{rules:e?.autoRunControls?.adminCommandDenylist?.rules??[]}}async isMcpSettingsOverhaulEnabled(e){const t=this.options.isMcpSettingsOverhaulEnabled?.(e);return void 0!==t&&await t}async isWin32UserExtensionStdioUnsandboxEnabled(){try{const e=this.options.isWin32UserExtensionStdioUnsandboxEnabled?.();return void 0!==e&&await e}catch{return!1}}async getMcpToolControls(){const e=await this.getTeamAdminSettings(),t=e?.allowedMcpConfiguration;if(void 0===t)return;const r=(0,gS.BJ)({autoRunControls:e?.autoRunControls,allowedMcpServers:t?.allowedMcpServers});return r.policies.length>0||r.tools.length>0?{enabled:!0,mcpToolAllowlist:r.tools,allowUserOverride:t?.allowUserOverrideMcpServers??!1,serverPolicies:r.policies}:void 0}async getNetworkAccessControls(){const e=await this.getTeamAdminSettings();return void 0!==e||this.lastFetchSucceeded?{allowlist:e?.networkAllowlist??[],denylist:e?.networkDenylist??[],available:!0}:{allowlist:[],denylist:[],available:!1}}async getSandboxingControls(){const e=await this.getTeamAdminSettings(),t=e?.autoRunControls?.sandboxingControls,r=(o=t?.sandboxReadBoundary,o===HC.h0i.WORKSPACE?"workspace":"system");var o;return{sandboxingDisabled:t?.sandboxing===HC.faf.DISABLED,networkingDisabled:t?.sandboxNetworking===HC._mX.ALWAYS_DISABLED,gitDisabled:t?.sandboxGit===HC.i24.ALWAYS_DISABLED,readBoundary:r,readAllowlistPaths:GC(r,t?.sandboxReadAllowlistPaths),allowUserOverrideReadAllowlist:!1!==t?.allowUserOverrideSandboxReadAllowlist}}async isAttributionDisabledByAdmin(){const e=await this.getTeamAdminSettings();return void 0===e&&!this.lastFetchSucceeded||(e?.attributionControls?.disableAttribution??!1)}getDefaultNetworkAllowlist(){return this.defaultAllowlist.get().catch((()=>({allowlist:[],available:!1})))}async fetchDefaultAllowlist(){return this.defaultAllowlistProvider?{allowlist:await this.defaultAllowlistProvider.getDefaultNetworkAllowlist(),available:!0}:{allowlist:[],available:!0}}getTeamRepos(){return this.teamRepos.get()}async isMcpAccessNetworkAllowlistEnabled(){return await(this.options.isMcpAccessNetworkAllowlistEnabled?.())??!1}}const KC=new Rm,ZC={async resolveWorkspaceState(e){const t=e.workingDirectory??e.projectRoot??e.workspaceRoots?.[0],r=e.projectRoot??(void 0!==t?await Ba((0,ce.q6)(),KC,t)??t:void 0),o=e.workspaceRoots??(void 0!==r?[r]:void 0!==t?[t]:[]);return{workingDirectory:t,projectRoot:r,projectDirectory:e.projectDirectory??(void 0!==r?Ds(r):void 0),workspaceRoots:o,createdAt:new Date}}},XC=(0,m.h)("ControlledConversationActionManager");class QC{get signal(){return this.abortController.signal}get abortRequested(){return this.abortCalled}constructor(){this.abortCallbacks=[],this.abortController=new AbortController,this.acceptsActions=!0,this.disposed=!1,this.abortStarted=!1,this.abortCalled=!1,this.runActive=!1,this.unprocessedUserMessages=[],this.clientStream=(0,y.Jt)()}addAbortCallback(e){this.abortCallbacks.push(e)}abort(e,t){if(this.abortCalled=!0,this.abortController.signal.aborted||this.abortStarted)return;const r=t?.interruptedPendingToolCallResolutions;if(this.abortStarted=!0,!this.runActive){this.abortController.abort(e);for(const e of this.abortCallbacks)e();return void(this.abortCallbacks.length=0)}const o=this.abortController,n=[...this.abortCallbacks];this.abortCallbacks.length=0,this.submitConversationAction(new Nr.QFf({action:{case:"cancelAction",value:new Nr.TTG({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(!this.acceptsActions)throw new y.W2("ControlledConversationActionManager is not accepting actions");if("userMessageAction"===e.action.case){const t=e.action.value.userMessage;t&&this.unprocessedUserMessages.push(t)}await this.clientStream.write(e)}queueFollowUpUserMessage(e){if(this.disposed||this.abortStarted)throw new y.W2("ControlledConversationActionManager run was aborted or disposed");this.unprocessedUserMessages.push(e)}async enqueueReplayableConversationAction(e){if("asyncAskQuestionCompletionAction"!==e.action.case)throw new TypeError("Only asyncAskQuestionCompletionAction can use enqueue acknowledgement");if(!this.acceptsActions)throw new y.W2("ControlledConversationActionManager is not accepting actions");this.clientStream.write(e).catch((()=>{}))}markMessageAsProcessed(e){this.unprocessedUserMessages=this.unprocessedUserMessages.filter((t=>t.messageId!==e.messageId))}requeueMessage(e){this.unprocessedUserMessages.some((t=>t.messageId===e.messageId))||this.unprocessedUserMessages.unshift(e)}getUnprocessedUserMessages(){return[...this.unprocessedUserMessages]}hasUnprocessedMessages(){return this.unprocessedUserMessages.length>0}close(){this.acceptsActions=!1,this.clientStream.close()}reopen(){this.disposed||this.acceptsActions||this.resetStream()}resetStream(){if(this.disposed)throw new y.W2("ControlledConversationActionManager disposed");this.acceptsActions=!1,this.clientStream.close(),this.clientStream=(0,y.Jt)(),this.acceptsActions=!0,this.abortController=new AbortController,this.abortStarted=!1;for(const e of this.unprocessedUserMessages)this.clientStream.write(new Nr.QFf({action:{case:"userMessageAction",value:new Nr.Vtf({userMessage:e})}})).catch((()=>{}))}async run(e,t){const r=this.clientStream;this.runActive=!0;try{for await(const o of r)try{await t.write(o)}catch(t){XC.error(e,"Error writing conversation action",t)}}catch(e){if(!(e instanceof y.W2))throw e}finally{this.clientStream===r&&(this.runActive=!1)}}dispose(){this.disposed||(this.disposed=!0,this.abortCallbacks.length=0,this.acceptsActions=!1,this.clientStream.throw(new y.W2("ControlledConversationActionManager disposed")))}}var YC=r("../cursor-sdk-local-runtime/dist/utils/logger.js");const ex="x-blob-encryption-key";function tx(e,t){const r={...t};return void 0!==r[ex]||(0,So.TU)(e)&&(r[ex]=e),r}const rx=new Map;function ox(e){if("userMessageAction"===e.action.case)return e.action.value.userMessage?.text}function nx(e,t,r){const o=e.runOptions?.requestedModel;return{conversationId:e.conversationId,generationId:e.conversationId,model:o?.modelId??"unknown",modelId:o?.modelId,modelParams:o?.parameters.map((e=>({id:e.id,value:e.value}))),loopCount:t,promptText:r}}function sx(e){return new Nr.QFf({action:{case:"userMessageAction",value:new Nr.Vtf({userMessage:new Nr.RGk({text:e})})}})}function ix(e){return e instanceof DOMException&&"AbortError"===e.name||e instanceof Error&&("AbortError"===e.name||"The operation was aborted"===e.message)}function ax(e){e?.catch((e=>{YC.Jz.warn("[agent-session-runner] fire-and-forget hook failed:",e)}))}var cx=r("../mcp-core/dist/oauth/resolved-oauth-client-id.js"),lx=r("../mcp-core/dist/oauth/rest-mcp-provider-metadata.js");const ux=new Set(["mcp.slack.com","setup.shopify.com"]);class dx{constructor(e,t){this.inner=e,this.resolver=t}async getDefinitions(e,t=!0){const r=await this.inner.getDefinitions(e,t);return Promise.all(r.map((async e=>{const t=await async function(e,t){if(!("url"in e)||!e.url)return e;const r=await async function(e,t,r,o=fetch){let n;try{n=new URL(e).hostname}catch{return t}const s=void 0!==(0,cg.Di)(e,r.restMcpHost);if(!ux.has(n)&&!s)return t;let i=await r.resolve(e);if(!i&&s){const t=(await(0,lx.Ez)(e,o))?.clientId;void 0!==t&&(i={CLIENT_ID:t})}return i?t?void 0===(0,cx.qF)(t.CLIENT_ID)?{...i,...t,CLIENT_ID:i.CLIENT_ID}:{...i,...t}:i:t}(e.url,e.auth,t);return r===e.auth?e:{...e,auth:r}}(e.serverConfig,this.resolver);return t===e.serverConfig?e:{...e,serverConfig:t}})))}clearCache(){this.inner.clearCache?.()}}class hx{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 px{constructor(e,t){this.storage=e,this.prefix=t}async isServerApproved(e,t,r){return this.storage.isServerApproved(this.prefix+e,t,r)}}class fx{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 Wg(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){for(const{loader:t,prefix:r}of this.loaders){if(!e.startsWith(r))continue;const o=e.slice(r.length);t.clearClient?.(o)}}clearAllMcpCaches(){for(const{loader:e}of this.loaders)e.clearAllMcpCaches?.()}}class mx{constructor(e,t,r,o,i=!1,a,c,l=s.join((0,n.homedir)(),".cursor","mcp.json"),u){const d=Array.isArray(e)?e:[e],h=[];for(let e=0;e<d.length;e++){const t=d[e],r=s.join(t,".cursor","mcp.json"),o=`project-${e}-${s.basename(t)}-`;h.push({path:r,prefix:o})}h.push({path:l,prefix:"user-"});const p=new Map;for(const{path:e,prefix:t}of h)p.has(e)&&"user-"!==t||p.set(e,t);const f=[];for(const[e,n]of p){const s=i?"":n,d=new hx(t,s),h=new px(o,s),p=e===l,m=[new Gm,...p?[]:[new Wm(h)],new iw(r),...c?[new Bm(c)]:[]],g=u?new ow(new dx(new rw(e),u),d,m,{authRedirectUrlGenerator:a}):new aw(e,d,m,a);f.push({prefix:s,loader:g})}this.loader=new fx(f)}static init(e,t,r,o=!1,n,i){const a=new lw(s.join(r,"mcp-auth.json"));(async function(e){await(0,Os.rm)(s.join(e,"mcp-cache.json"),{force:!0})})(r).catch((()=>{}));const c=o?{isServerApproved:()=>Promise.resolve(!0)}:new Hm(s.join(r,"mcp-approvals.json"),t);return new mx(t,a,e,c,!0,void 0,n,void 0,i)}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 gx="cursor-plugins/local";function wx(e){var t;if(e)for(const r of e)if("object"==typeof(t=r)&&null!==t&&t.kind===gx)return r}class yx extends Bg{constructor(e){super(e),this.runtimeManager=e,this.disposed=!1}async dispose(){this.disposed||(this.disposed=!0,await this.runtimeManager.closeAllClients())}}class vx{constructor(e){this.storagePath=e}async isServerDisabled(e){try{const t=await(0,Os.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,Os.mkdir)((0,s.dirname)(this.storagePath),{recursive:!0}),await(0,Os.writeFile)(this.storagePath,JSON.stringify(e,null,2))}}class bx{constructor(e,t){this.pluginMcpService=e,this.importThirdPartyPlugins=t}async getDefinitions(){let e;try{e=await this.pluginMcpService.getPluginMcpServers()}catch(e){return YC.Jz.warn("[cursor-config-mcp] Failed to enumerate plugin MCP servers:",e),[]}const t=[];for(const r of e){if(!this.importThirdPartyPlugins&&xx(r))continue;const e=cw(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}}):YC.Jz.warn("[cursor-config-mcp] Failed to initialize plugin MCP client:",{identifier:r.identifier,pluginName:r.pluginName,pluginSource:r.pluginSource,result:"invalid-config",errorMessage:"pluginMcpDescriptorToServerConfig returned undefined"})}return t}}class Sx{constructor(e){this.servers=e}async getDefinitions(){return Object.entries(this.servers).map((([e,t])=>({identifier:e,authStorageKey:`inline:${e}`,serverConfig:Cx(e,t),source:"inline",metadata:{source:"cursor-sdk"}})))}}function kx(e={}){const t=e.teamSettingsService??{getDotCursorProtection:async()=>!1,getShouldBlockMcp:async()=>!1,getDeleteFileProtection:async()=>!1,getIsHeadlessDisabled:async()=>!1,isServerBlocked:async()=>!1,getTeamRepos:async()=>{},getAutoRunControls:async()=>({enabled:!1,allowed:[],blocked:[],enableAllowlistMode:!0,enableRunEverything:!1,enableSmartAuto:!0,mcpToolAllowlist:[]}),getAdminCommandDenylist:async()=>({rules:[]}),getMcpToolControls:async()=>{},getNetworkAccessControls:async()=>({allowlist:[],denylist:[],available:!0}),getMcpNetworkControlsConfig:async()=>({enabled:!1}),getDefaultNetworkAllowlist:async()=>({allowlist:[],available:!0}),getSandboxingControls:async()=>({sandboxingDisabled:!1,networkingDisabled:!1,gitDisabled:!1}),isAttributionDisabledByAdmin:async()=>!1,invalidateCache:()=>{}},r=e.ignoreApprovals??!1,o=e.importThirdPartyPlugins??!1;return{async createLease(i){const a=i.workspaceState,c=a.projectRoot??a.workingDirectory,l=a.projectDirectory;if(!c||!l)return new Ug;const u=new vx((0,s.join)(l,"mcp-disabled.json")),d=function(e){const{teamSettingsService:t,projectRoot:r,projectDirectory:o,ignoreApprovals:i,disabledStore:a,includeProjectMcp:c,includeUserMcp:l}=e;if(c&&l)return mx.init(t,r,o,i,a);if(!c&&!l)return;const u=new lw((0,s.join)(o,"mcp-auth.json")),d=i?{isServerApproved:()=>Promise.resolve(!0)}:new Hm((0,s.join)(o,"mcp-approvals.json"),r),h=[new Gm,new Wm(d),new iw(t),new Bm(a)],p=[];return c&&p.push({prefix:"",loader:new aw((0,s.join)(r,".cursor","mcp.json"),u,h)}),l&&p.push({prefix:"",loader:new aw((0,s.join)((0,n.homedir)(),".cursor","mcp.json"),u,h)}),Ex(p)}({teamSettingsService:t,projectRoot:c,projectDirectory:l,ignoreApprovals:r,disabledStore:u,includeProjectMcp:e.includeProjectMcp??!0,includeUserMcp:e.includeUserMcp??!0}),h=[],p=e.inlineMcpServers??{};if(Object.keys(p).length>0){const e=new lw((0,s.join)(l,"mcp-auth.json")),r=[new Gm,new iw(t)];h.push({prefix:"",loader:new ow(new Sx(p),e,r)})}const f=wx(i.services.pluginBootstrapOutputs);if(f&&(e.includePluginMcp??1)){const e=new Hm((0,s.join)(l,"mcp-approvals.json"),c),n=new lw((0,s.join)(l,"mcp-auth.json")),i=[new Gm];r||i.push(new Wm(e)),i.push(new iw(t),new Bm(u));const a=new LC(f.pluginsService),d=new ow(new bx(a,o),n,i);h.push({prefix:"",loader:d})}if(d&&h.push({prefix:"",loader:d}),0===h.length)return new Ug;const m=Ex(h),g=await m.load(e.initializationCtx??(0,ce.q6)(),e.cache);return new yx(g)}}}function Ex(e){return 1===e.length?e[0].loader:new fx(e)}function Cx(e,t){if("command"in t){if(void 0!==t.type&&"stdio"!==t.type)throw new Error(`Unsupported MCP server type "${String(t.type)}" for "${e}"`);return{command:t.command,args:t.args?[...t.args]:void 0,env:t.env,cwd:t.cwd,startupTimeoutSec:t.startupTimeoutSec}}if("url"in t){if(void 0!==t.type&&"http"!==t.type&&"sse"!==t.type)throw new Error(`Unsupported MCP server type "${String(t.type)}" for "${e}"`);const r={url:t.url,headers:t.headers,auth:t.auth?{CLIENT_ID:t.auth.CLIENT_ID,CLIENT_SECRET:t.auth.CLIENT_SECRET,scopes:t.auth.scopes?[...t.auth.scopes]:void 0}:void 0};return"sse"===t.type?{...r,type:"sse"}:r}throw new Error(`Invalid inline MCP server config for "${e}"`)}function xx(e){return"claude-plugin"===e.pluginSource}function _x(e){if("object"!=typeof e||null===e)return!1;const t=e.event;return"backgrounded"===t?.case}function Px(e){if("object"!=typeof e||null===e)return;const t=e.path;return"string"==typeof t&&t.length>0?t:void 0}class Ix{cacheCarriersForExecId(e,t){const r=this.carriersByExecId.get(e);if(!(void 0!==r&&r.length>0&&0===t.length))for(this.carriersByExecId.has(e)&&this.carriersByExecId.delete(e),this.carriersByExecId.set(e,t);this.carriersByExecId.size>Ix.CARRIERS_BY_EXEC_ID_MAX;){const e=this.carriersByExecId.keys().next().value;if(void 0===e)break;this.carriersByExecId.delete(e)}}constructor(e,t,r,o){this.inner=e,this.wake=r,this.carriersByExecId=new Map,this.inFlightByExecId=new Map,this.resolveDrain="function"==typeof t?t:e=>t,this.skipPathWriteDrain=o?.skipPathWriteDrain,this.onWakeWrittenPath=o?.onWakeWrittenPath,this.forceWrittenPathBeforeDrain=o?.forceWrittenPathBeforeDrain,this.writeBarrierTimeoutMs=o?.writeBarrierTimeoutMs??2e3,this.resolveWriteBarrierTimeoutMs=o?.resolveWriteBarrierTimeoutMs,this.onWriteBarrier=o?.onWriteBarrier}resolveTimeoutMs(){if(void 0!==this.resolveWriteBarrierTimeoutMs)try{const e=this.resolveWriteBarrierTimeoutMs();if("number"==typeof e&&Number.isFinite(e))return e}catch{}return this.writeBarrierTimeoutMs}get(e){return this.wrapImpl(e.symbol,this.inner.get(e))}*entries(){for(const[e,t]of this.inner.entries())yield[e,this.wrapImpl(e.symbol,t)]}wrapImpl(e,t){if(!function(e){return"object"==typeof e&&null!==e&&"execute"in e&&"function"==typeof e.execute}(t))return t;const r=function(e){return e===kr.symbol||e===ie.symbol||e===mr.symbol||e===ur.symbol?{kind:"path"}:e===br.symbol||e===Sr.symbol||e===ee.symbol||e===lr.symbol?{kind:"exposed"}:void 0}(e),o=this.resolveDrain,n=this.wake,s=this.skipPathWriteDrain,i=this.forceWrittenPathBeforeDrain,a=()=>this.resolveTimeoutMs(),c=this.onWriteBarrier,l=this.onWakeWrittenPath,u=(e,t)=>{if(void 0!==r&&void 0!==n)try{if("path"===r.kind){const r=Px(e);void 0!==r&&(n.wakeForWrittenPath(r),l?.(r,t))}else n.wakeExposedMounts()}catch{}},d=this.cacheCarriersForExecId.bind(this),h=this.carriersByExecId,p=this.inFlightByExecId,f=async(e,t)=>{const r=t?.hookContextCollector;if(void 0===r)return[];if(!1===t?.deliverAgentStoreConflictNotices)return[];const n=void 0!==t?.execId&&t.execId.length>0?t.execId:void 0;if(void 0!==n){const e=h.get(n);if(void 0!==e)return e.length>0&&r.push(...e),e;const t=p.get(n);if(void 0!==t){const e=await t;return e.length>0&&r.push(...e),e}}const s=async t=>{const r=o(e);let s=[];try{const e=await r.peek();if(s=e.eventIds,e.carriers.length>0)return t.push(...e.carriers),r.ack(e.eventIds),void 0!==n&&d(n,e.carriers),e.carriers;s.length>0&&r.ack(s);const o=[];return void 0!==n&&d(n,o),o}catch{return s.length>0&&r.release(s),[]}};if(void 0===n)return await s(r);const i=s(r);p.set(n,i);try{return await i}finally{p.get(n)===i&&p.delete(n)}};return new Proxy(t,{get:(t,o,n)=>"execute"!==o?Reflect.get(t,o,n):(o,n,l)=>{const d=t.execute.call(t,o,n,l);return"object"==typeof(h=d)&&null!==h&&Symbol.asyncIterator in h&&"function"==typeof h[Symbol.asyncIterator]?async function*(){let t=!1,r=!1,s=!1;try{for await(const r of d)if(e===Sr.symbol&&_x(r)){if(!t){u(n,o);const e=await f(o,l);t=!0,e.length>0&&(yield new yr.FI({event:{case:"hookContext",value:new yr.Ng({hookAdditionalContexts:[...e]})}}))}yield r}else yield r;s=!0}catch(e){throw r=!0,e}finally{u(n,o),t||r||!s||await f(o,l)}}():function(e){return"object"==typeof e&&null!==e&&"then"in e&&"function"==typeof e.then}(d)?(async()=>{try{const t=await d;return u(n,o),e===kr.symbol&&!0===s?.()&&!0===l?.enableAgentStoreConflictNotices||(await async function(e,t,r,o){const n=e=>{try{o.onWriteBarrier?.(e)}catch{}};if(void 0===e||"path"!==r?.kind)return;const s=Px(t);if(void 0===s)return;if(!(o.timeoutMs>0))return void n({durationMs:0,outcome:"skipped"});const i=Date.now(),a=e(s).then((e=>e),(()=>"error")),c=await Promise.race([a,(0,Ht.cb)(o.timeoutMs).then((()=>"timeout"))]);"not_store_path"!==c&&n({durationMs:Date.now()-i,outcome:c})}(i,n,r,{timeoutMs:a(),onWriteBarrier:c}),await f(o,l)),t}catch(e){throw u(n,o),e}})():(u(n,o),d);var h}})}}function Rx(e){return new RegExp(`<${e}(?:\\s[^>]*)?>[\\s\\S]*?</${e}>`,"gi")}Ix.CARRIERS_BY_EXEC_ID_MAX=32,Error,Iu.execFileSync,new Map,$s.constants.O_NOFOLLOW,new Set(["write_conflict","create_conflict","truncate_conflict_failed","conflict_fallback_failed","quota_exceeded","gap"]),new Set(["write_conflict","create_conflict","truncate_conflict_failed","conflict_fallback_failed","quota_exceeded"]),Math.max(1,Math.floor(8192));const Tx=["user_info","project_layout","rules","always_applied_workspace_rules","agent_requestable_workspace_rules","user_rules","agent_skills","available_skills","cloud_instructions","cloud_task_instructions","open_and_recently_viewed_files","system_reminder","system-reminder","instructions_update","mcp_instructions","mcp_file_system","mcp_file_system_servers","git_status","agent_transcripts","cursor_rules_context","attached_files","system_notification","task_notification","agent_notification"].map(Rx);function Ax(e){return function(e,t){let r=e;if(r.includes("<"))for(const e of t)r=r.replace(e,"");return(r.includes("\n\n\n")?r.replace(Mx,"\n\n"):r).trim()}(e,Tx)}["system_reminder","system-reminder"].map(Rx);const Mx=/\n{3,}/g;function Dx(e){const t=(0,As.sh)(e.conversationId);if("subagent"===e.kind&&e.parentConversationId){const r=(0,As.sh)(e.parentConversationId);return`${As.O2}/${r}/subagents/${t}.${e.ext}`}return`${As.O2}/${t}/${t}.${e.ext}`}function Ox(e){const t=(0,As.sh)(e.conversationId);return`${As.O2}/${t}.${e.ext}`}function Nx(e){const t=e.exts??["jsonl","txt"],r=e.includeLegacy??!0,o=[],n=e=>{o.includes(e)||o.push(e)};for(const o of t)n(Dx({conversationId:e.conversationId,ext:o,kind:e.kind,parentConversationId:e.parentConversationId})),"subagent"===e.kind&&e.parentConversationId&&n(Dx({conversationId:e.conversationId,ext:o,kind:"primary"})),r&&n(Ox({conversationId:e.conversationId,ext:o}));return o}var $x;(()=>{const e=globalThis.Intl?.Segmenter;e&&new e(void 0,{granularity:"grapheme"})})(),function(e){e.INTERNAL="INTERNAL",e.EXTERNAL="EXTERNAL",e.NO_PREAMBLE="NO_PREAMBLE"}($x||($x={}));var Fx=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},jx=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 Lx(e){switch(e){case Nr.xyI.AGENT:return"agent";case Nr.xyI.ASK:return"ask";case Nr.xyI.PLAN:return"plan";case Nr.xyI.DEBUG:return"debug";case Nr.xyI.TRIAGE:return"triage";case Nr.xyI.MULTITASK:return"multitask";case Nr.xyI.CUSTOM:return"custom";case Nr.xyI.UNSPECIFIED:default:return"agent"}}function Ux(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 Bx(e,t){return function(e){return"object"==typeof e&&null!==e&&"__type"in e&&"Uint8Array"===e.__type&&"hex"in e&&"string"==typeof e.hex}(t)?function(e){return`[Binary data omitted from transcript: ${e} bytes]`}(t.hex.length/2):t}const Wx=new TextEncoder,Hx=new TextDecoder,qx=new class{serialize(e){const t=JSON.stringify(e,Ux);return Wx.encode(t)}deserialize(e){const t=Hx.decode(e);return t.includes('"__type":"Uint8Array"')?JSON.parse(t,Bx):JSON.parse(t)}};function zx(e){const t=e.providerOptions;return!0===t?.cursor?.isSummary}function Gx(e){return"system"!==e.role&&!zx(e)}function Vx(e,t){return"user"===e.role&&"user"===t.role}async function Jx(e,t,r){const o=await t.getBlob(e,r);return o?Nr.Anz.fromBinary(o).summarizedMessages:[]}async function Kx(e,t,r,o){const n=await t.getBlob(e,r);if(n){if(n.length>5e6)return o.omittedOversizeBlobCount++,o.omittedOversizeBlobBytes+=n.length,o.largestOmittedOversizeBlobBytes=Math.max(o.largestOmittedOversizeBlobBytes,n.length),{role:"assistant",content:`[Oversize transcript blob omitted: ${s=n.length,`${(s/1e6).toFixed(1)} MB`}]`};var s;try{const e=performance.now(),t=qx.deserialize(n);return o.totalDeserializeDurationMs+=performance.now()-e,o.hydratedBlobCount++,o.hydratedBlobBytes+=n.length,o.largestHydratedBlobBytes=Math.max(o.largestHydratedBlobBytes,n.length),t}catch{return}}}async function Zx(e,t,r){const o={messages:[],hydratedBlobCount:0,hydratedBlobBytes:0,largestHydratedBlobBytes:0,totalDeserializeDurationMs:0,omittedOversizeBlobCount:0,omittedOversizeBlobBytes:0,largestOmittedOversizeBlobBytes:0};for(const n of r){const r=await Kx(e,t,n,o);r&&o.messages.push(r)}return o}async function Xx(e,t,r,o,n){const s=[];let i=0;const a=()=>{const n=Kx(e,t,r[i++],o);n.catch((()=>{})),s.push(n)};for(;i<r.length&&s.length<8;)a();for(let e=s.shift();e;e=s.shift()){let t;try{t=await e}catch(e){if(!n.skipFailedReads)throw e}i<r.length&&a(),t&&await n.visit(t)}}function Qx(e,t){switch(e.type){case"text":return t?Yx(e.text):e.text;case"image":return"[Image]";case"file":return e.filename?`[File: ${e.filename}]`:"[File]";case"reasoning":return`[Thinking] ${e.text}`;case"redacted-reasoning":return"[Thinking]";case"tool-call":return`[Tool call] ${e.toolName}${function(e){if(null==e)return"";switch(typeof e){case"string":return e;case"number":case"boolean":case"bigint":case"symbol":case"function":return e.toString()}const t=Object.entries(e);return 0===t.length?"":`\n${t.map((([e,t])=>{let r;return r="string"==typeof t?t:"object"==typeof t&&null!==t?JSON.stringify(t):String(t),` ${e}: ${r}`})).join("\n")}`}(e.args)}`;case"tool-result":return`[Tool result] ${e.toolName}`;default:return""}}function Yx(e){return Ax(e)}const e_=/<think>[\s\S]*?<\/think>/gi,t_=/<thinking>[\s\S]*?<\/thinking>/gi,r_=/\n{3,}/g;function o_(e){let t=e;return t.includes("<")&&(t=t.replace(e_,"").replace(t_,"")),(t.includes("\n\n\n")?t.replace(r_,"\n\n"):t).trim()}function n_(e,t,r){if(void 0===e)return"";if("string"==typeof e){const o=t?Yx(e):e;return r?o_(o):o}return e.map((e=>{if(r&&"text"===e.type){const r=o_(t?Yx(e.text):e.text);return Qx({...e,text:r},!1)}return Qx(e,t)})).filter(Boolean).join("\n")}function s_(e,t){const r={role:e.role},o=e.content;if("string"==typeof o){const n=t?Yx(o):o,s="assistant"===e.role?o_(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?Yx(r.text):r.text,s="assistant"===e.role?o_(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 i_(e){return e.endsWith("\n")?e:`${e}\n`}function a_(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({type:"turn_ended",...t}))),{textSuffixes:r,jsonFields:o,jsonlLines:n}}function c_(e){if("system"===e.role||zx(e))return;const t=s_(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 l_{constructor(e,t,r,o={}){this.projectDir=e,this.blobStore=t,this.writeFile=r,this.options={writeText:o.writeText??!0,writeJson:o.writeJson??!1,writeJsonl:o.writeJsonl??!1,pathResolver:o.pathResolver,appendFile:o.appendFile,streamFullJsonlWrites:o.streamFullJsonlWrites??!1,fallbackToFullWriteOnIncrementalFailure:o.fallbackToFullWriteOnIncrementalFailure??!0}}resolveFilePath(e,t){if(this.options.pathResolver)return this.options.pathResolver(e,t);const r=Dx({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=Fx(n,(0,i.VI)(e.withName("writeFromState")),!1);try{const{overviewFactory:e}=o,n=a_(o),{appendFile:a,streamFullJsonlWrites:c,writeJsonl:l,writeText:u,writeJson:d}=this.options;if(a&&c&&l&&!u&&!d&&!e)try{return await this.writeJsonlStreamed(s,{state:t,filePath:this.resolveFilePath(r,"jsonl"),appendFile:a,terminalLines:n.jsonlLines}),!0}catch(e){console.error("[TranscriptStore] Streamed transcript write failed, retrying as a single write:",e)}const h=await async function(e,t,r){const o={stack:[],error:void 0,hasError:!1};try{const n=Fx(o,(0,i.VI)(e.withName("hydrateSummaryArchives")),!1);let s=0;const a=(0,i.OA)(n.ctx),c=[];let l=0,u=0,d=0,h=0,p=0,f=0,m=0;const g=await Promise.all(r.summaryArchives.map((async e=>{s++;try{const r=await Jx(a,t,e);return s+=r.length,await Zx(a,t,r)}catch{return{messages:[],hydratedBlobCount:0,hydratedBlobBytes:0,largestHydratedBlobBytes:0,totalDeserializeDurationMs:0,omittedOversizeBlobCount:0,omittedOversizeBlobBytes:0,largestOmittedOversizeBlobBytes:0}}})));for(const e of g)c.push(...e.messages),l+=e.hydratedBlobCount,u+=e.hydratedBlobBytes,d=Math.max(d,e.largestHydratedBlobBytes),h+=e.totalDeserializeDurationMs,p+=e.omittedOversizeBlobCount,f+=e.omittedOversizeBlobBytes,m=Math.max(m,e.largestOmittedOversizeBlobBytes);n.span.setAttribute("getBlobCount",s),n.span.setAttribute("hydratedBlobCount",l),n.span.setAttribute("hydratedBlobBytes",u),n.span.setAttribute("largestHydratedBlobBytes",d),n.span.setAttribute("totalDeserializeDurationMs",h),n.span.setAttribute("omittedOversizeBlobCount",p),n.span.setAttribute("omittedOversizeBlobBytes",f),n.span.setAttribute("largestOmittedOversizeBlobBytes",m);const w=Fx(o,(0,i.VI)(e.withName("hydratePromptMessages")),!1),y=await Zx(a,t,r.rootPromptMessagesJson);w.span.setAttribute("getBlobCount",r.rootPromptMessagesJson.length),w.span.setAttribute("hydratedBlobCount",y.hydratedBlobCount),w.span.setAttribute("hydratedBlobBytes",y.hydratedBlobBytes),w.span.setAttribute("largestHydratedBlobBytes",y.largestHydratedBlobBytes),w.span.setAttribute("totalDeserializeDurationMs",y.totalDeserializeDurationMs),w.span.setAttribute("omittedOversizeBlobCount",y.omittedOversizeBlobCount),w.span.setAttribute("omittedOversizeBlobBytes",y.omittedOversizeBlobBytes),w.span.setAttribute("largestOmittedOversizeBlobBytes",y.largestOmittedOversizeBlobBytes);const v=y.messages.filter(Gx);return c.push(...v),c}catch(e){o.error=e,o.hasError=!0}finally{jx(o)}}(s.ctx,this.blobStore,t);if(0===h.length&&0===n.jsonlLines.length)return!0;let p;if((this.options.writeText||e)&&(p=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=n_(e.content,t,o);n.trim()&&("tool"===e.role?r.push(n):r.push(`${e.role}:\n${n}`))}return r.join("\n\n")}(h)),this.options.writeText){const e=p??"",t=n.textSuffixes.length>0?e.trim().length>0?`${e}\n\n${n.textSuffixes.join("\n")}`:n.textSuffixes.join("\n"):e;t.trim()&&await this.writeFile(this.resolveFilePath(r,"txt"),t)}if(this.options.writeJson){const e=function(e){let t=e.filter((e=>"system"!==e.role));t.length>=2&&"user"===t[0].role&&"user"===t[1].role&&(t=t.slice(1));const r=[];for(const e of t){const t=s_(e,"user"===e.role);(t.text||t.thinking||t.toolCalls||t.toolResult)&&r.push(t)}return 0===r.length?"":JSON.stringify(r,null,2)}(h);if(e||n.jsonlLines.length>0){const o={mode:Lx(t.mode),messages:e?JSON.parse(e):[],...n.jsonFields};await this.writeFile(this.resolveFilePath(r,"json"),JSON.stringify(o,null,2))}}if(this.options.writeJsonl){const t=function(e){let t=e.filter((e=>"system"!==e.role));t.length>=2&&Vx(t[0],t[1])&&(t=t.slice(1));const r=[];for(const e of t){const t=c_(e);t&&r.push(t)}return r.join("\n")}(h);let o=[t,...n.jsonlLines].filter((e=>e.length>0)).join("\n");if(o&&e&&p?.trim())try{const t=(await e(p)).trim();t&&(o=function(e,t){const r={type:"metadata",metadata:{overview:t}};return`${JSON.stringify(r)}\n${e}`}(o,t))}catch(e){console.error("[TranscriptStore] Failed to generate transcript overview:",e)}o&&await this.writeFile(this.resolveFilePath(r,"jsonl"),i_(o))}return!0}catch(e){return console.error("[TranscriptStore] Failed to write transcript:",e),!1}}catch(e){n.error=e,n.hasError=!0}finally{jx(n)}}async writeJsonlStreamed(e,t){const{filePath:r,appendFile:o}=t;let n=[],s=0,a=0,c=0;const l=async()=>{if(0===n.length)return;const e=`${n.join("\n")}\n`;n=[],s=0,0===a?await this.writeFile(r,e):await o(r,e),a++,c+=e.length},u=async e=>{e&&(n.push(e),s+=e.length+1,s>=1e6&&await l())};let d,h=0;const p=await async function(e,t,r,o){const n={hydratedBlobCount:0,hydratedBlobBytes:0,largestHydratedBlobBytes:0,totalDeserializeDurationMs:0,omittedOversizeBlobCount:0,omittedOversizeBlobBytes:0,largestOmittedOversizeBlobBytes:0};for(const s of r.summaryArchives){let r;try{r=await Jx(e,t,s)}catch{continue}await Xx(e,t,r,n,{skipFailedReads:!0,visit:o})}return await Xx(e,t,r.rootPromptMessagesJson,n,{skipFailedReads:!1,visit:async e=>{Gx(e)&&await o(e)}}),n}((0,i.OA)(e.ctx),this.blobStore,t.state,(async e=>{"system"!==e.role&&(h++,1!==h?(2===h&&d&&(Vx(d,e)||await u(c_(d)),d=void 0),await u(c_(e))):d=e)}));d&&await u(c_(d));for(const e of t.terminalLines)await u(e);await l(),e.span.setAttribute("streamed",!0),e.span.setAttribute("chunkCount",a),e.span.setAttribute("writtenChars",c),e.span.setAttribute("hydratedBlobCount",p.hydratedBlobCount),e.span.setAttribute("hydratedBlobBytes",p.hydratedBlobBytes),e.span.setAttribute("largestHydratedBlobBytes",p.largestHydratedBlobBytes),e.span.setAttribute("totalDeserializeDurationMs",p.totalDeserializeDurationMs),e.span.setAttribute("omittedOversizeBlobCount",p.omittedOversizeBlobCount),e.span.setAttribute("omittedOversizeBlobBytes",p.omittedOversizeBlobBytes),e.span.setAttribute("largestOmittedOversizeBlobBytes",p.largestOmittedOversizeBlobBytes)}async writeFromStateIncremental(e,t,r,o,n={}){const s={stack:[],error:void 0,hasError:!1};try{const a=t.rootPromptMessagesJson.length,c=a_(n),l=c.jsonlLines.length>0;if(a===o&&!l&&!n.overviewFactory)return a;const u=this.options.appendFile;if(!(u&&this.options.writeJsonl&&!this.options.writeText&&!this.options.writeJson&&o>0&&a>=o&&(a>o||l))||n.overviewFactory)return await this.writeFromStateFull(e,t,r,n)?a:0;const d=Fx(s,(0,i.VI)(e.withName("writeFromStateIncremental")),!1);if(a===o&&l)try{return await u(this.resolveFilePath(r,"jsonl"),i_(c.jsonlLines.join("\n"))),a}catch(o){return console.error(this.options.fallbackToFullWriteOnIncrementalFailure?"[TranscriptStore] Failed to append transcript, falling back to full write:":"[TranscriptStore] Failed to append transcript:",o),this.options.fallbackToFullWriteOnIncrementalFailure?await this.writeFromStateFull(e,t,r,n)?a:0:0}try{const e=t.rootPromptMessagesJson.slice(o),n=await Zx(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=c_(e);t&&s.push(t)}if(s.push(...c.jsonlLines),s.length>0){const e=i_(s.join("\n"));await u(this.resolveFilePath(r,"jsonl"),e)}return a}catch(o){return console.error(this.options.fallbackToFullWriteOnIncrementalFailure?"[TranscriptStore] Failed to append transcript, falling back to full write:":"[TranscriptStore] Failed to append transcript:",o),this.options.fallbackToFullWriteOnIncrementalFailure?await this.writeFromStateFull(e,t,r,n)?a:0:0}}catch(e){s.error=e,s.hasError=!0}finally{jx(s)}}}class u_ extends Error{constructor(e){super(`Hook denied: ${e}`),this.failureType="permission_denied",this.name="HookDeniedError",this.reason=e}}class d_ extends Error{constructor(e,t){super(`Hook failed (fail-closed): ${e}`),this.failureType="error",this.name="FailClosedError",this.reason=e,this.cause=t}}const h_="To view or modify configured hooks, go to Cursor Settings > Hooks.";function p_(e){return`Tool blocked because this hook is configured to fail closed (block when it fails). ${e}`}function f_(e,t){return Re(`${t?`${e} was blocked by a hook: ${t}`:`${e} was blocked by a hook.`}\n\n${h_}`)}function m_(e){return function(e){return e instanceof u_}(e)||function(e){return e instanceof d_}(e)}const g_=(0,m.h)("cli-hooks-executor");function w_(e){try{return(0,$s.statSync)(e).isFile()}catch{return!1}}class y_{constructor(e,t,r,o,n,s,i,a){this.workspacePath=t,this.globalContext=r,this.shellExecutor=o,this.promptHookClient=n,this.onHookExecution=i,this.options=a,this.sessionEnvById=new Map,this.sessionUserEmailById=new Map,this.activeSessionIdsByConversationId=new Map,this.transcriptParentConversationIdById=new Map,this.configReadyPromises=[],this.config=e,s&&this.addConfigReadyPromise(s)}addConfigReadyPromise(e){this.configReadyPromises.push(e.catch((()=>{})))}reportCommandFailure(e,t){if(void 0!==e)try{e(t)}catch{}}emitHookExecution(e){const t={...e,transportMode:e.transportMode??("prompt"===e.hookType?"prompt":this.getCommandHookPayloadTransportMode())};try{this.onHookExecution?.(t)}catch{}}getCommandHookPayloadTransportMode(){return"stdin"===this.options?.commandHookPayloadTransport?"win32"===process.platform?"windows_temp_file":"stdin":"argv_heredoc"}shouldUseCommandHookDirectStdinTransport(){return"stdin"===this.getCommandHookPayloadTransportMode()}async writeCommandHookStdinPayload(e,t){if(!e)throw new Error("Hook stdin transport was requested, but the executor did not provide stdin");try{e.end(Buffer.from(t,"utf8"))}catch(e){const t=e instanceof Error&&"code"in e?e.code:void 0;if("EPIPE"===t||"ERR_STREAM_DESTROYED"===t||"ERR_STREAM_PREMATURE_CLOSE"===t)return;throw e}try{await(0,vu.finished)(e)}catch(e){const t=e instanceof Error&&"code"in e?e.code:void 0;if("EPIPE"===t||"ERR_STREAM_DESTROYED"===t||"ERR_STREAM_PREMATURE_CLOSE"===t)return;throw e}}updateConfig(e){this.config=e}beginSessionEnvironment(e,t){this.sessionEnvById.delete(e.sessionId),this.sessionUserEmailById.delete(e.sessionId);const r=this.activeSessionIdsByConversationId.get(e.conversationId)??[];this.activeSessionIdsByConversationId.set(e.conversationId,r.filter((t=>t!==e.sessionId)).concat(e.sessionId));const o=t?.userEmail?.trim()??"";o.length>0&&this.sessionUserEmailById.set(e.sessionId,o)}setSessionUserEmail(e,t){const r=t?.trim()??"";0!==r.length&&this.sessionUserEmailById.set(e.sessionId,r)}setSessionEnvironment(e,t){void 0===t?this.sessionEnv={...this.sessionEnv,...e}:this.sessionEnvById.set(t.sessionId,{...this.sessionEnvById.get(t.sessionId),...e})}clearSessionEnvironment(e){if(void 0===e)this.sessionEnv=void 0;else{this.sessionEnvById.delete(e.sessionId),this.sessionUserEmailById.delete(e.sessionId);const t=(this.activeSessionIdsByConversationId.get(e.conversationId)??[]).filter((t=>t!==e.sessionId));0===t.length?this.activeSessionIdsByConversationId.delete(e.conversationId):this.activeSessionIdsByConversationId.set(e.conversationId,t)}}resolveUserEmail(e){const{conversation_id:t,session_id:r}=e;if(void 0!==r&&this.sessionUserEmailById.has(r))return this.sessionUserEmailById.get(r)??null;if(void 0!==t){const e=this.activeSessionIdsByConversationId.get(t)?.at(-1);if(void 0!==e){const t=this.sessionUserEmailById.get(e);if(void 0!==t)return t}}return this.globalContext.user_email}setTranscriptParentConversationId(e,t){this.transcriptParentConversationIdById.set(e,t)}async getTranscriptPathIfExists(e){try{const t=(0,As.Rv)((0,n.homedir)(),this.workspacePath),r=this.transcriptParentConversationIdById.get(e),o=Nx(r?{conversationId:e,kind:"subagent",parentConversationId:r}:{conversationId:e,kind:"primary"}).map((e=>(0,s.join)(t,e)));for(const e of o)try{return await(0,Os.access)(e),e}catch{}return null}catch{return null}}async getSubagentTranscriptPathIfExists(e){const{subagentId:t,parentConversationId:r}=e;try{const e=(0,As.Rv)((0,n.homedir)(),this.workspacePath),o=Nx({conversationId:t,kind:"subagent",parentConversationId:r}).map((t=>(0,s.join)(e,t)));for(const e of o)try{return await(0,Os.access)(e),e}catch{}return null}catch{return null}}hasHooksForStep(e){return[this.config.enterpriseHooks,this.config.teamHooks,this.config.userHooks,this.config.projectHooks,this.options?.runtimeHooks,this.config.claudeUserHooks,this.config.claudeProjectHooks,this.config.claudeProjectLocalHooks,...(this.config.pluginHooks??[]).map((e=>e.config))].some((t=>{const r=t?.hooks[e];return void 0!==r&&r.length>0}))}hasFailClosedHooksForStep(e,t){const r=[this.config.enterpriseHooks,this.config.teamHooks,this.config.projectHooks,this.config.userHooks,this.options?.runtimeHooks];for(const o of r){const r=o?.hooks[e];if(r&&(t?Ae(r,t):r).some((e=>!0===e.failClosed)))return!0}for(const r of this.config.pluginHooks??[]){const o=r.config.hooks[e];if(o&&(t?Ae(o,t):o).some((e=>Fe(e)&&!0===e.failClosed)))return!0}return!1}configuredHookDirectory(e){const t=this.config.configDirs;switch(e){case"enterprise":return t?.enterprise;case"team":return t?.team;case"user":return t?.user;case"claude-user":return t?.claudeUser;default:return}}cwdForHookSource(e,t){if(void 0!==e?.cwd&&e.cwd.length>0)return e.cwd;const r=this.configuredHookDirectory(t.source);if(void 0!==r&&r.length>0)return r;const o=e?.cwdForSource?.(t.source);return void 0!==o&&o.length>0?o:t.fallback}getCwdForSource(e){const t=this.config.configDirs;switch(e){case"enterprise":return t?.enterprise??this.workspacePath;case"team":return t?.team??this.workspacePath;case"project":case"claude-project":case"claude-project-local":case"claude-plugin":case"runtime":default:return this.workspacePath;case"user":return t?.user??this.workspacePath;case"claude-user":return t?.claudeUser??this.workspacePath}}buildHookEnvironment(e){const{transcriptPath:t,sessionId:r,conversationId:o,executionEnv:n}=e,s=this.resolveUserEmail({conversation_id:o,session_id:r});return{CURSOR_PROJECT_DIR:this.workspacePath,CURSOR_VERSION:this.globalContext.cursor_version,...s&&{CURSOR_USER_EMAIL:s},...t&&{CURSOR_TRANSCRIPT_PATH:t},CLAUDE_PROJECT_DIR:this.workspacePath,...this.sessionEnv,...void 0!==r?this.sessionEnvById.get(r):void 0,...n}}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,r){this.configReadyPromises.length>0&&await Promise.all(this.configReadyPromises);const o=function(e){return Be.includes(e)}(e),n=t,s=o?null:n.conversation_id?await this.getTranscriptPathIfExists(n.conversation_id):null;let i;if(e===he.subagentStop){const e=t;i=e.subagent_id?await this.getSubagentTranscriptPathIfExists({subagentId:e.subagent_id,parentConversationId:e.parent_conversation_id}):null}const a=o?void 0:n.session_id??n.conversation_id,c={...t,...void 0!==a&&{session_id:a},hook_event_name:e,cursor_version:this.globalContext.cursor_version,workspace_roots:[this.workspacePath],user_email:this.resolveUserEmail(n),...!o&&{transcript_path:s},...e===he.subagentStop&&{agent_transcript_path:i??null}},l=function(e,t){switch(e){case"beforeShellExecution":case"afterShellExecution":return Te(t,"command");case"beforeMCPExecution":case"afterMCPExecution":{const e=Te(t,"tool_name");return e?`MCP:${e}`:void 0}case"beforeReadFile":return"Read";case"afterFileEdit":return"Write";case"beforeTabFileRead":return"TabRead";case"afterTabFileEdit":return"TabWrite";case"beforeSubmitPrompt":return"UserPromptSubmit";case"stop":return"Stop";case"afterAgentResponse":return"AgentResponse";case"afterAgentThought":return"AgentThought";case"subagentStart":case"subagentStop":return Te(t,"subagent_type");case"preToolUse":case"postToolUse":case"postToolUseFailure":return Te(t,"tool_name");default:return}}(e,c),u=[],d=(e,t)=>{if(!e)return;const o=Ae(e,l),n=this.cwdForHookSource(r,{source:t,fallback:this.getCwdForSource(t)});for(const e of o)$e(e)?this.promptHookClient&&u.push({type:"prompt",script:e,source:t}):Fe(e)&&u.push({type:"command",script:e,cwd:n,env:r?.env,source:t})};d(this.config.enterpriseHooks?.hooks[e],"enterprise"),d(this.config.teamHooks?.hooks[e],"team"),d(this.config.projectHooks?.hooks[e],"project"),d(this.config.userHooks?.hooks[e],"user"),d(this.options?.runtimeHooks?.hooks[e],"runtime"),d(this.config.claudeProjectLocalHooks?.hooks[e],"claude-project-local"),d(this.config.claudeProjectHooks?.hooks[e],"claude-project"),d(this.config.claudeUserHooks?.hooks[e],"claude-user");for(const t of this.config.pluginHooks??[]){const o=t.config.hooks[e];if(!o?.length)continue;const n=r?.cwd??(e===he.stop||e===he.subagentStop?this.workspacePath:t.installPath),s={...void 0!==t.plugin&&{plugin:t.plugin},...void 0!==t.marketplace&&{marketplace:t.marketplace},...void 0!==t.pluginId&&{pluginId:t.pluginId},...void 0!==t.marketplaceId&&{marketplaceId:t.marketplaceId}};for(const e of Ae(o,l))Fe(e)&&u.push({type:"command",script:e,cwd:n,env:r?.env,source:"claude-plugin",attribution:s,pluginInstallPath:t.installPath})}if(0!==u.length)return this.executeAllAndMerge(e,u,c,r?.onCommandFailure)}async executeAllAndMerge(e,t,r,o){let n;const s=()=>n??=function(e){const t=JSON.stringify(e);return{json:t,payloadSizeBytes:Buffer.byteLength(t,"utf8")}}(r),i=t.map((async(t,n)=>{const{source:i,attribution:a}=t;try{return"prompt"===t.type?await this.executePromptHook(e,t.script,r,i,n,s,a):await this.executeCommandHook(e,t.script,t.cwd,t.env,r,i,n,s,a,t.pluginInstallPath,o)}catch(r){const o=r instanceof Error?r.message:String(r);if(!0===t.script.failClosed){const t=p_(`Hook execution failed: ${o}`),r=Ve(e,t);if(r)return{success:!0,data:r,source:i,index:n}}return g_.warn((0,ce.q6)(),`${e} hook error`,{source:i,index:n,error:o}),{success:!1,source:i,index:n}}})),a=await Promise.all(i),c=[];for(const e of a)e.success&&void 0!==e.data&&c.push(e.data);return function(e,t){if(0===t.length)return;if(1===t.length)return t[0];const r=Ue.includes(e),o=e===he.sessionStart,n=e===he.workspaceOpen,s=Ne.has(e),i={};for(const e of t){const t=e;for(const[e,l]of Object.entries(t))if(void 0!==l)if(n&&"pluginPaths"===e&&Array.isArray(l)){const t=i[e],r=Array.isArray(t)?t:[],o=new Set(r),n=[...r];for(const e of l)"string"!=typeof e||o.has(e)||(o.add(e),n.push(e));i[e]=n}else"permission"===e&&r?i[e]=(c=l,"deny"===(a=i[e])||"deny"===c?"deny":"ask"===a||"ask"===c?"ask":"allow"===a||"allow"===c?"allow":void 0):"user_message"!==e&&"agent_message"!==e?s&&"additional_context"===e&&"string"==typeof l?i[e]=We(i[e],l):"continue"!==e||"boolean"!=typeof l?i[e]=o&&"env"===e&&"object"==typeof l&&null!==l?He(i[e],l):l:void 0===i[e]?i[e]=l:i[e]=i[e]&&l:i[e]=We(i[e],l)}var a,c;return i}(e,c)}async executeCommandHook(e,t,r,o,n,s,i,a,c,l,u){if(this.shouldSkipHookDueToLoopLimit(e,t,n))return{success:!1,source:s,index:i};const d=Date.now(),h=a(),p=h.payloadSizeBytes;let f;try{f=await this.executeCommandScript({script:t,cwd:r,request:n,jsonPayload:h.json,env:o,...void 0!==l&&{pluginInstallPath:l}})}catch(r){const o=r instanceof Error?r.message:String(r),n=o.toLowerCase().includes("timed out");this.reportCommandFailure(u,{command:t.command,source:s,exitCode:null,stderr:"",errorMessage:o});const a=Date.now()-d,l=n?"timeout":"spawn_error";if(!0===t.failClosed){const r=Ve(e,p_(`Hook "${t.command}" execution failed: ${o}`));if(r)return this.emitHookExecution({hookStep:e,hookSource:s,hookType:"command",status:n?"timeout":"blocked",latencyMs:a,payloadSizeBytes:p,errorClass:l,failClosed:!0,timedOut:n,...c}),{success:!0,data:r,source:s,index:i}}return this.emitHookExecution({hookStep:e,hookSource:s,hookType:"command",status:n?"timeout":"failed",latencyMs:a,payloadSizeBytes:p,errorClass:l,failClosed:!0===t.failClosed,timedOut:n,...c}),{success:!1,source:s,index:i}}if(2===f.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.`)}(f.stdout,f.stderr,t.command),o=Ve(e,r);return o?(this.emitHookExecution({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:f.duration,payloadSizeBytes:p,failClosed:!0===t.failClosed,exitCode:f.exitCode,...c}),{success:!0,data:o,source:s,index:i}):(this.emitHookExecution({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:f.duration,payloadSizeBytes:p,failClosed:!0===t.failClosed,exitCode:f.exitCode,...c}),{success:!1,source:s,index:i})}if(0!==f.exitCode&&null!==f.exitCode){if(this.reportCommandFailure(u,{command:t.command,source:s,exitCode:f.exitCode,stderr:f.stderr}),!0===t.failClosed){const r=Ve(e,p_(`Hook "${t.command}" failed with exit code ${f.exitCode}${f.stderr?`: ${f.stderr.trim()}`:""}`));if(r)return this.emitHookExecution({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:f.duration,payloadSizeBytes:p,errorClass:"exit_nonzero",failClosed:!0,exitCode:f.exitCode,...c}),{success:!0,data:r,source:s,index:i}}return this.emitHookExecution({hookStep:e,hookSource:s,hookType:"command",status:"failed",latencyMs:f.duration,payloadSizeBytes:p,errorClass:"exit_nonzero",failClosed:!0===t.failClosed,exitCode:f.exitCode,...c}),{success:!1,source:s,index:i}}const m=f.stdout.trim();if(!m){if(!0===t.failClosed){const r=Ve(e,p_(`Hook "${t.command}" returned no output.`));if(r)return this.emitHookExecution({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:f.duration,payloadSizeBytes:p,errorClass:"empty_stdout",failClosed:!0,exitCode:f.exitCode??void 0,...c}),{success:!0,data:r,source:s,index:i}}return this.emitHookExecution({hookStep:e,hookSource:s,hookType:"command",status:"failed",latencyMs:f.duration,payloadSizeBytes:p,errorClass:"empty_stdout",failClosed:!0===t.failClosed,exitCode:f.exitCode??void 0,...c}),{success:!1,source:s,index:i}}const g=function(e){const t=e.trim();if(0===t.length)return;const r=Je(t);if(void 0!==r)return r.value;if(t.endsWith("}"))for(let e=t.length-1;e>=0;e--){if("{"!==t[e])continue;const r=Je(t.slice(e));if(void 0!==r)return r.value}}(m);if(void 0===g){const r=ze({step:e,command:t.command,failClosed:!0===t.failClosed,kind:"invalid_json"});return r.blockResponse?(this.emitHookExecution({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:f.duration,payloadSizeBytes:p,errorClass:"invalid_json",failClosed:!0===t.failClosed,exitCode:f.exitCode??void 0,...c}),{success:!0,data:r.blockResponse,source:s,index:i}):(this.emitHookExecution({hookStep:e,hookSource:s,hookType:"command",status:"failed",latencyMs:f.duration,payloadSizeBytes:p,errorClass:"invalid_json",failClosed:!0===t.failClosed,exitCode:f.exitCode??void 0,...c}),{success:!1,source:s,index:i})}const w=Le(e,g,{enableClaudeNestedHookSpecificOutputCompatibility:this.options?.enableClaudeNestedHookSpecificOutputCompatibility});if(w.success){const r=w.data,o="deny"===r.permission||"ask"===r.permission;return this.emitHookExecution({hookStep:e,hookSource:s,hookType:"command",status:o?"blocked":"success",latencyMs:f.duration,payloadSizeBytes:p,failClosed:!0===t.failClosed,exitCode:f.exitCode??void 0,...c}),{success:!0,data:w.data,source:s,index:i}}const y=ze({step:e,command:t.command,failClosed:!0===t.failClosed,kind:"invalid_response"});return y.blockResponse?(this.emitHookExecution({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:f.duration,payloadSizeBytes:p,errorClass:"invalid_response",failClosed:!0===t.failClosed,exitCode:f.exitCode??void 0,...c}),{success:!0,data:y.blockResponse,source:s,index:i}):(this.emitHookExecution({hookStep:e,hookSource:s,hookType:"command",status:"failed",latencyMs:f.duration,payloadSizeBytes:p,errorClass:"invalid_response",failClosed:!0===t.failClosed,exitCode:f.exitCode??void 0,...c}),{success:!1,source:s,index:i})}async executePromptHook(e,t,r,o,n,s,i){if(this.shouldSkipHookDueToLoopLimit(e,t,r))return{success:!1,source:o,index:n};if(!this.promptHookClient)return{success:!1,source:o,index:n};const a=1e3*(t.timeout??60),c=Date.now(),l=s(),u=l.payloadSizeBytes,d=(0,ce.q6)(),[h,p]=d.withTimeoutAndCancel(a);try{const r=JSON.parse(l.json),s=await this.promptHookClient.evaluatePromptHook(h,{prompt:t.prompt,hookInputJson:r,modelName:t.model});if(s.ok){const r=function(e){return qe(e)?Ge(0,{permission:"allow"}):e===he.beforeSubmitPrompt||e===he.sessionStart?Ge(0,{continue:!0}):e===he.stop?Ge(0,{}):void 0}(e);return this.emitHookExecution({hookStep:e,hookSource:o,hookType:"prompt",status:"success",latencyMs:Date.now()-c,payloadSizeBytes:u,failClosed:!0===t.failClosed,...i}),r?{success:!0,data:r,source:o,index:n}:{success:!1,source:o,index:n}}{const r=Ve(e,s.reason??"Prompt hook blocked this action");return this.emitHookExecution({hookStep:e,hookSource:o,hookType:"prompt",status:"blocked",latencyMs:Date.now()-c,payloadSizeBytes:u,failClosed:!0===t.failClosed,...i}),r?{success:!0,data:r,source:o,index:n}:{success:!1,source:o,index:n}}}catch(r){const s=r instanceof Error?r.message:String(r),a=s.toLowerCase().includes("abort")||s.toLowerCase().includes("timed out"),l=a?"timeout":"prompt_error";if(!0===t.failClosed){const t=Ve(e,p_(`Prompt hook failed: ${s}`));if(t)return this.emitHookExecution({hookStep:e,hookSource:o,hookType:"prompt",status:a?"timeout":"blocked",latencyMs:Date.now()-c,payloadSizeBytes:u,errorClass:l,failClosed:!0,timedOut:a,...i}),{success:!0,data:t,source:o,index:n}}return this.emitHookExecution({hookStep:e,hookSource:o,hookType:"prompt",status:a?"timeout":"failed",latencyMs:Date.now()-c,payloadSizeBytes:u,errorClass:l,failClosed:!0===t.failClosed,timedOut:a,...i}),{success:!1,source:o,index:n}}finally{p()}}async executeCommandScript(e){const{script:t,cwd:r,request:o,env:i,pluginInstallPath:a,jsonPayload:c}=e,l=1e3*(t.timeout??60),u=Date.now();let d;const h=new AbortController,p=setTimeout((()=>{h.abort()}),l);try{const e="win32"===process.platform,f=this.getCommandHookPayloadTransportMode(),m=this.shouldUseCommandHookDirectStdinTransport(),g=e?function(e,t){const r=function(e){let t=0;for(;t<e.length&&/\s/.test(e.charAt(t));)t++;if("&"===e.charAt(t))for(t++;t<e.length&&/\s/.test(e.charAt(t));)t++;const r=e.slice(0,t),o=e.charAt(t);if("'"===o||'"'===o){let n=e.indexOf(o,t+1);for(;"'"===o&&-1!==n&&"'"===e.charAt(n+1);)n=e.indexOf("'",n+2);if(-1===n)return;return{prefix:r,quote:o,rawPath:e.slice(t+1,n),rest:e.slice(n+1)}}const n=/^\S+/.exec(e.slice(t));if(n)return{prefix:r,quote:"",rawPath:n[0],rest:e.slice(t+n[0].length)}}(e);if(!r)return e;const{prefix:o,quote:n,rawPath:s,rest:i}=r;if(0===s.length||!/[\\/]/.test(s))return e;if(i.length>0&&!/^\s/.test(i))return e;if(/[$`{}()|;,<>]/.test(s)||""===n&&/['"]/.test(s))return e;const a=s.slice(Math.max(s.lastIndexOf("\\"),s.lastIndexOf("/"))+1);if(0===a.length||a.includes("."))return e;const c="'"===n?s.replace(/''/g,"'"):s,l=/^[A-Za-z]:[\\/]/.test(u=c)||u.startsWith("\\")||u.startsWith("/")?c:`${t.cwd.replace(/[\\/]+$/,"")}\\${c}`;var u;const d=it.find((e=>t.isFile(l+e)));return void 0===d?e:""!==n?`${o}${n}${s}${d}${n}${i}`:`${o}'${s}${d}'${i}`}(t.command,{cwd:r,isFile:w_}):t.command;let w;if(m)w=e?at(g):g;else if("windows_temp_file"===f){d=await(0,Os.mkdtemp)((0,s.join)((0,n.tmpdir)(),"cursor-hooks-"));const e=(0,s.join)(d,"payload.json");await(0,Os.writeFile)(e,c,{encoding:"utf8",flag:"wx"}),w=function(e,t){return`$OutputEncoding = [System.Text.UTF8Encoding]::new($false); try { $global:cursorHookConsoleInputEncoding = [Console]::InputEncoding; $null = Register-EngineEvent -SourceIdentifier PowerShell.Exiting -Action { try { [Console]::InputEncoding = $global:cursorHookConsoleInputEncoding } catch { } }; [Console]::InputEncoding = $OutputEncoding } catch { }; Get-Content -LiteralPath '${e.replace(/'/g,"''")}' -Raw -Encoding UTF8 | & { $input | ${at(t)} }`+st(t)}(e,g)}else w=e?`@'\n${c.replace(/'/g,"''")}\n'@ | & ${g}`+st(g):`${t.command} <<'CURSOR_HOOK_EOF'\n${c}\nCURSOR_HOOK_EOF`;const y=o,{conversation_id:v,session_id:b}=y,S=void 0===v?void 0:this.activeSessionIdsByConversationId.get(v),k=void 0===b||b===v&&!this.sessionEnvById.has(b)?void 0===v?void 0:S?.at(-1)??v:b,E=this.buildHookEnvironment({transcriptPath:y.transcript_path,sessionId:k,conversationId:v,executionEnv:i}),C={};for(const[e,t]of Object.entries(E))void 0!==t&&(C[e]=t);void 0!==a&&(C.CURSOR_PLUGIN_ROOT=a,C.CLAUDE_PLUGIN_ROOT=a);const x=(0,ce.q6)();let _="",P="",I=null,R=!1;for await(const e of this.shellExecutor.execute(x,w,{workingDirectory:r,signal:h.signal,sandboxPolicy:{perUser:{type:"insecure_none"}},env:C,pipeStdin:m}))switch(e.type){case"stdin_ready":m&&(await this.writeCommandHookStdinPayload(e.stdin,c),R=!0);break;case"stdout":_+=e.data.toString("utf8");break;case"stderr":P+=e.data.toString("utf8");break;case"exit":I=e.code}if(m&&!R)throw new Error("Hook stdin transport was requested, but the executor did not signal stdin readiness");clearTimeout(p);const T=Date.now()-u;if(h.signal.aborted)throw new Error(`Hook script timed out after ${l}ms`);return{stdout:_,stderr:P,exitCode:I,duration:T}}catch(e){if(clearTimeout(p),Date.now(),h.signal.aborted)throw new Error(`Hook script timed out after ${l}ms`);throw e}finally{if(d)try{await(0,Os.rm)(d,{recursive:!0,force:!0})}catch{}}}}function v_(e){switch(e??(0,n.platform)()){case"darwin":return s.default.join("/Library","Application Support","Cursor","hooks.json");case"win32":return s.default.join("C:\\","ProgramData","Cursor","hooks.json");default:return s.default.join("/etc","cursor","hooks.json")}}class b_{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=this.paths.projectConfigPath??this.paths.claudeProjectConfigPath??this.paths.claudeProjectLocalConfigPath,n=o?s.default.dirname(s.default.dirname(o)):void 0,i=(e,t)=>{if(!e||!n)return;if(t)return n;const r=s.default.relative(s.default.resolve(n),s.default.resolve(e));return".."===r||r.startsWith(`..${s.default.sep}`)||s.default.isAbsolute(r)?void 0:n},a=async(e,t,o,n,i,a,c,l)=>{if(e)try{if(!await this.fileReader.exists(e))return;if(c&&this.fileReader.pathContainsSymlink&&await this.fileReader.pathContainsSymlink(e,c))return r.errors.push({source:t,message:`${i} at ${e}: refusing to load config path that contains a symlink`}),void this.logger.warn(`Refusing to load ${a} config via symlink path: ${e}`);const u=await this.fileReader.readFile(e);if(!u)return;const{config:d,error:h}=l(u);d?(r[o]=d,((e,t)=>{r.configDirs[e]=s.default.dirname(t)})(n,e)):h&&r.errors.push({source:t,message:`${i} at ${e}: ${h}`})}catch(e){r.errors.push({source:t,message:`Error accessing ${a} config file: ${String(e)}`})}},c=[{path:this.paths.enterpriseConfigPath,source:"enterprise",resultKey:"enterpriseHooks",configDirKey:"enterprise",parsePrefix:"Enterprise hooks.json",accessLabel:"enterprise",symlinkCheckRoot:i(this.paths.enterpriseConfigPath,!1)},{path:this.paths.teamConfigPath,source:"team",resultKey:"teamHooks",configDirKey:"team",parsePrefix:"Team hooks.json",accessLabel:"team",symlinkCheckRoot:i(this.paths.teamConfigPath,!1)},{path:this.paths.userConfigPath,source:"user",resultKey:"userHooks",configDirKey:"user",parsePrefix:"User hooks.json",accessLabel:"user",symlinkCheckRoot:i(this.paths.userConfigPath,!1)},{path:t?this.paths.projectConfigPath:void 0,source:"project",resultKey:"projectHooks",configDirKey:"project",parsePrefix:"Project hooks.json",accessLabel:"project",symlinkCheckRoot:i(this.paths.projectConfigPath,!0)}];for(const e of c)await a(e.path,e.source,e.resultKey,e.configDirKey,e.parsePrefix,e.accessLabel,e.symlinkCheckRoot,(t=>this.parseAndValidate(t,e.source)));const l=[{path:this.paths.claudeUserConfigPath,source:"claude-user",resultKey:"claudeUserHooks",configDirKey:"claudeUser",label:"user",symlinkCheckRoot:i(this.paths.claudeUserConfigPath,!1)},{path:t?this.paths.claudeProjectConfigPath:void 0,source:"claude-project",resultKey:"claudeProjectHooks",configDirKey:"claudeProject",label:"project",symlinkCheckRoot:i(this.paths.claudeProjectConfigPath,!0)},{path:t?this.paths.claudeProjectLocalConfigPath:void 0,source:"claude-project-local",resultKey:"claudeProjectLocalHooks",configDirKey:"claudeProjectLocal",label:"project local",symlinkCheckRoot:i(this.paths.claudeProjectLocalConfigPath,!0)}];for(const e of l)await a(e.path,e.source,e.resultKey,e.configDirKey,`Claude ${e.label} settings.json`,`Claude ${e.label}`,e.symlinkCheckRoot,(t=>this.parseClaudeConfig(t,e.source)));return this.dedupeClaudeHooksAgainstCursorHooks(r),r}getHookKey(e){return $e(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(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(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(!Se(e))return!1;if(!("hooks"in e))return!1;const r=e.hooks;if(!Se(r))return!1;const o=r;for(const[e,r]of Object.entries(o))if(e in pe&&Array.isArray(r)){const o=!0===t.allowMatcherlessStop&&"Stop"===e;for(const e of r)if(Se(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=Pe(r,this.logger),n=ut(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=ut(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(e?.hooks)for(const r of Object.keys(e.hooks))t.add(r);for(const r of e.pluginHooks??[])for(const e of Object.keys(r.config.hooks))t.add(e);return t}}class S_{constructor(e){this.config=e,this.configuredSteps=b_.getConfiguredSteps(e)}getConfig(){return this.config}hasHookForStep(e){return this.configuredSteps.has(e)}getConfiguredSteps(){return new Set(this.configuredSteps)}}var k_=r("node:perf_hooks");function E_(e,t){void 0!==e&&t.length>0&&e.push(...t)}class C_ extends Error{constructor(e){super(`Hook additional_context for ${e.hookEventName} is ${e.actualLength} chars (max ${e.maxLength}).`),this.name="HookAdditionalContextTooLargeError",this.hookEventName=e.hookEventName,this.actualLength=e.actualLength,this.maxLength=e.maxLength}}var x_=r("../proto/dist/generated/agent/v1/hook_additional_context_pb.js");function __({hookEventName:e,additionalContext:t}){const r=function(e){const t=e?.trim();return void 0!==t&&t.length>0?t:void 0}(t);if(void 0===r)return[];if(r.length>1e4)throw new C_({hookEventName:e,actualLength:r.length,maxLength:1e4});return[new x_.C({hookEventName:e,content:r})]}Object.fromEntries(Array.from(Ne).map((e=>{if(!function(e){return e===he.sessionStart||e===he.beforeSubmitPrompt||e===he.preToolUse||e===he.postToolUse||e===he.postToolUseFailure}(e))throw new Error(`HOOK_STEPS_SUPPORTING_ADDITIONAL_CONTEXT lists ${e} but HookStepAdditionalContextEventName does not include it. Extend the Extract<> union in spec.ts.`);return[e,{hookEventName:e}]})));const P_=(0,m.h)("generic-hooks");function I_(e,t,r,o){try{return __({hookEventName:r,additionalContext:o})}catch(o){if(o instanceof C_)return P_.warn(e,`${r} additional_context exceeded max size; dropping carrier`,{toolName:t,hookEventName:r,actualLength:o.actualLength,maxLength:o.maxLength}),[];throw o}}const R_=e=>Math.round(1e3*e)/1e3;function T_(e,t,r,o,n,s){const i=o(e),a=n.getToolCallId?.(t)??(0,Ts.randomUUID)(),c=n.getExtraHookFields?.(t)??{},l={baseHookRequest:i,toolUseId:a,toolInput:n.createToolInput(t),extraHookFields:c,hookContextCollector:s?.hookContextCollector??n.getHookContextCollector?.(t)??[]},u=function(e,t,r,o){let{toolInput:n,extraHookFields:s,hookContextCollector:i}=o;const{baseHookRequest:a,toolUseId:c}=o;return{fireFailureAsync:async(o,l,u,d=!1)=>{try{const h=await ic(e.signal,(()=>t.executeHookForStep(he.postToolUseFailure,{...a,tool_name:r,tool_input:n,error_message:l,failure_type:u,duration:o,tool_use_id:c,is_interrupt:d,...s})));E_(i,I_(e,r,he.postToolUseFailure,h?.additional_context))}catch(t){P_.warn(e,"postToolUseFailure hook error",{toolName:r,error:t instanceof Error?t.message:String(t)})}},fireSuccessAsync:async(o,l)=>{try{const u=await ic(e.signal,(()=>t.executeHookForStep(he.postToolUse,{...a,tool_name:r,tool_input:n,tool_output:l,duration:o,tool_use_id:c,...s})));E_(i,I_(e,r,he.postToolUse,u?.additional_context))}catch(t){P_.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,n.toolName,l);return{hookContext:l,helpers:u}}async function A_(e,t,r,o,n,s,i,a){const{baseHookRequest:c,toolUseId:l,extraHookFields:u}=o;try{const a=await ic(e.signal,(()=>r.executeHookForStep(he.preToolUse,{...c,tool_name:s.toolName,tool_input:n.getToolInput(),tool_use_id:l,...u})));if("deny"===a?.permission){const r=a.user_message||`${s.toolName} blocked by preToolUse hook`,c=Re(r);try{E_(o.hookContextCollector,__({hookEventName:he.preToolUse,additionalContext:a.additional_context}))}catch(t){if(!(t instanceof C_))throw t;P_.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,c),reason:c}}a?.updated_input&&s.applyUpdatedInput&&(s.applyUpdatedInput(t,a.updated_input),n.setToolInput(s.createToolInput(t)),s.getExtraHookFields&&n.setExtraHookFields(s.getExtraHookFields(t))),E_(o.hookContextCollector,__({hookEventName:he.preToolUse,additionalContext:a?.additional_context}))}catch(o){const a=r.hasFailClosedHooksForStep?.(he.preToolUse,s.toolName)??!1,c=o instanceof C_;if(a){const e=p_(`${c?"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}}P_.warn(e,c?"preToolUse additional_context exceeded max size; dropping carrier":"preToolUse hook error",{toolName:s.toolName,error:o instanceof Error?o.message:String(o),...c?{actualLength:o.actualLength,maxLength:o.maxLength}:{}})}if(a)try{const s=await a({ctx:e,args:t,baseHookRequest:c,hookExecutor:r,toolInput:n.getToolInput(),toolUseId:l,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(m_(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 M_(e){return e.toolCallId}function D_(e,t,r,o){return{async execute(n,s,i){const{hookContext:a,helpers:c}=T_(n,s,t,r,o,i);let l;try{l=await A_(n,s,t,a,c,o,o.createRejectedResult,o.runPreExecutionHooks)}catch(e){throw o.runCleanup?.(a.toolUseId),e}if("rejected"===l.type)return o.runCleanup?.(a.toolUseId),l.result;const u=k_.performance.now();try{const r=await e.execute(n,s,i),l=R_(k_.performance.now()-u);if(o.runPostExecutionHooks)try{const e=await o.runPostExecutionHooks({ctx:n,args:s,result:r,baseHookRequest:a.baseHookRequest,hookExecutor:t,toolInput:c.getToolInput(),toolUseId:a.toolUseId,executionDurationMs:l,extraHookFields:a.extraHookFields});if(void 0!==e)return await c.fireSuccessAsync(l,JSON.stringify(o.createSuccessOutput(s,e))),o.runCleanup?.(a.toolUseId),e}catch(e){if(m_(e))return await c.fireFailureAsync(l,e.reason,e.failureType),o.runCleanup?.(a.toolUseId),o.createRejectedResult(s,e.reason);P_.warn(n,"postExecutionHooks error",{toolName:o.toolName,error:e instanceof Error?e.message:String(e)})}return o.isSuccess(r)?await c.fireSuccessAsync(l,JSON.stringify(o.createSuccessOutput(s,r))):await c.fireFailureAsync(l,o.getErrorMessage(r),o.getFailureType?.(r)??"error",o.isInterrupt?.(r)??!1),o.runCleanup?.(a.toolUseId),r}catch(e){const t=R_(k_.performance.now()-u);throw await c.fireFailureAsync(t,e instanceof Error?e.message:String(e),"error"),o.runCleanup?.(a.toolUseId),e}}}}function*O_(e,t){const r=t.hookContextCollector;e.createHookContextEvent&&void 0!==r&&0!==r.length&&(yield e.createHookContextEvent(r))}function N_(e){const t=e.code;return"ENOENT"===t||"ENOTDIR"===t}class $_{async readFile(e){try{return await Os.readFile(e,"utf-8")}catch(e){if("ENOENT"===e?.code)return;throw e}}async exists(e){try{return await Os.access(e),!0}catch{return!1}}async pathContainsSymlink(e,t){return async function(e,t){const r=function(e,t){const r=s.default.resolve(e),o=s.default.resolve(t),n=s.default.relative(o,r);if(0===n.length||".."===n||n.startsWith(`..${s.default.sep}`)||s.default.isAbsolute(n))return"unsafe";const i=n.split(s.default.sep).filter((e=>e.length>0)),a=[];let c=o;for(const e of i)c=s.default.join(c,e),a.push(c);return a}(e,t);if("unsafe"===r)return!0;for(const e of r)try{if((await(0,Os.lstat)(e)).isSymbolicLink())return!0}catch(e){if(N_(e))return!0;throw e}return!1}(e,t)}}class F_{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 Rr.Jy({configuredSteps:Array.from(this.hooksConfigLease.getConfiguredSteps())}):void 0;if("success"===o.result.case&&(n||s)){const e=o.result.value.requestContext,t=new Rr.bb({...e,...n&&{hooksAdditionalContext:n},...s&&{hooksConfig:s}});return new Rr._G({result:{case:"success",value:new Rr.yW({requestContext:t,servedFromDiskCache:o.result.value.servedFromDiskCache})}})}return o}}function j_(e){return!!e&&e.type!==pi.vc.INSECURE_NONE&&e.type!==pi.vc.UNSPECIFIED}const L_="Shell";async function U_({hookExecutor:e,baseHookRequest:t,toolUseId:r,command:o,cwd:n,sandbox:s}){const i=await e.executeHookForStep(he.beforeShellExecution,{...t,command:o,cwd:n,sandbox:s,tool_use_id:r});if("deny"===i?.permission){const e=f_("Command execution",i.user_message);throw new u_(e)}if("ask"===i?.permission)return a=i.user_message,new yr.In({kind:yr.b.FORCE_PROMPT,reason:a});var a}const B_={toolName:L_,getToolCallId:M_,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 gr.Lt({result:{case:"rejected",value:new yr.pZ({command:e.command,workingDirectory:e.workingDirectory,reason:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"BackgroundShell error";case"rejected":return e.result.value.reason||"BackgroundShell rejected";case"permissionDenied":return"Permission denied";case"sandboxUnsupported":return`Sandbox policy unsupported on this host: ${e.result.value.reason}`;default:return"Unknown error"}},createSuccessOutput:(e,t)=>"success"===t.result.case?{shell_id:t.result.value.shellId,pid:t.result.value.pid}:{success:!0},getExtraHookFields:e=>({cwd:e.workingDirectory||""}),runPreExecutionHooks:async e=>{const{args:t,baseHookRequest:r,hookExecutor:o,toolUseId:n}=e,s=t.workingDirectory||"",i=j_(t.sandboxPolicy);Mr(t,await U_({hookExecutor:o,baseHookRequest:r,toolUseId:n,command:t.command,cwd:s,sandbox:i}))}};class W_{constructor(e,t,r){this.wrappedExecutor=D_(e,t,r,B_)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const H_={toolName:"WriteShellStdin",createToolInput:e=>({shell_id:e.shellId,chars_length:e.chars.length}),createRejectedResult:(e,t)=>new gr.nt({result:{case:"error",value:new gr.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 q_{constructor(e,t,r){this.wrappedExecutor=D_(e,t,r,H_)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const z_={toolName:"ComputerUse",getToolCallId:M_,createToolInput:e=>({actions_count:e.actions.length}),createRejectedResult:(e,t)=>new Mf.ks({result:{case:"error",value:new Mf.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 G_{constructor(e,t,r){this.wrappedExecutor=D_(e,t,r,z_)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const V_={toolName:"Delete",getToolCallId:M_,createToolInput:e=>({file_path:e.path}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new wr.Pi({result:{case:"rejected",value:new wr.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 J_{constructor(e,t,r){this.wrappedExecutor=D_(e,t,r,V_)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const K_={toolName:"ReadLints",getToolCallId:M_,createToolInput:e=>({file_path:e.path}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new gb.Ek({result:{case:"rejected",value:new gb.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 Z_{constructor(e,t,r){this.wrappedExecutor=D_(e,t,r,K_)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const X_={toolName:"Fetch",getToolCallId:M_,createToolInput:e=>({url:e.url}),applyUpdatedInput:(e,t)=>{"string"==typeof t.url&&(e.url=t.url)},createRejectedResult:(e,t)=>new Cm.uN({result:{case:"error",value:new Cm.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 Q_{constructor(e,t,r){this.wrappedExecutor=D_(e,t,r,X_)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const Y_={toolName:"Grep",getToolCallId:M_,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 Tm.Ud({result:{case:"error",value:new Tm.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 eP{constructor(e,t,r){this.wrappedExecutor=D_(e,t,r,Y_)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const tP={toolName:"List",getToolCallId:M_,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 dv.fv({result:{case:"rejected",value:new dv.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 rP{constructor(e,t,r){this.wrappedExecutor=D_(e,t,r,tP)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const oP=(0,m.h)("hooks-exec:mcp");function nP(e,t,r,o){try{return __({hookEventName:r,additionalContext:o})}catch(o){if(o instanceof C_)return oP.warn(e,`${r} additional_context exceeded max size; dropping carrier`,{toolName:t,hookEventName:r,actualLength:o.actualLength,maxLength:o.maxLength}),[];throw o}}class sP{constructor(e,t,r,o,n){this.innerExecutor=e,this.hookExecutor=t,this.baseHookRequestExtractor=r,this.mcpLease=o,this.hooksConfigLease=n}async execute(e,t,r){if(t.smartModeApprovalOnly)return this.innerExecutor.execute(e,t,r);if(t.symbolicPathArguments.length>0&&(!0===this.hooksConfigLease?.hasHookForStep(he.preToolUse)||!0===this.hooksConfigLease?.hasHookForStep(he.beforeMCPExecution)))return new Lt.iz({result:{case:"error",value:new Lt.Nh({error:`"${Zt}" arguments can't be used on this computer: hooks that inspect MCP calls are configured here, and they would not see the file's contents. Read the file and pass its contents instead.`})}});const o=this.baseHookRequestExtractor(e),n=(0,Ts.randomUUID)(),s=r?.hookContextCollector??[];let i=Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t?.toJson()])));const a=`MCP:${t.toolName}`;try{const r=await this.hookExecutor.executeHookForStep(he.preToolUse,{...o,tool_name:a,tool_input:i,tool_use_id:n});if("deny"===r?.permission){const t=r.user_message||"MCP tool blocked by preToolUse hook";try{E_(s,__({hookEventName:he.preToolUse,additionalContext:r.additional_context}))}catch(t){if(!(t instanceof C_))throw t;oP.warn(e,"preToolUse deny additional_context exceeded max size; dropping carrier",{toolName:a,actualLength:t.actualLength,maxLength:t.maxLength})}return await this.firePostToolUseFailureAsync(e,o,a,i,t,"permission_denied",0,n,!1,s),new Lt.iz({result:{case:"permissionDenied",value:new Lt.HQ({error:f_("MCP tool execution",t),isReadonly:!1})}})}if(r?.updated_input)try{for(const[e,o]of Object.entries(r.updated_input))void 0!==o&&(t.args[e]=qt.Value.fromJson(o));i=Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t?.toJson()])))}catch(t){oP.warn(e,"Failed to merge updated_input for MCP",{error:t instanceof Error?t.message:String(t)})}E_(s,__({hookEventName:he.preToolUse,additionalContext:r?.additional_context}))}catch(t){const r=this.hookExecutor.hasFailClosedHooksForStep?.(he.preToolUse,a)??!1,c=t instanceof C_;if(r){const r=p_(`${c?"preToolUse additional_context exceeded max size":"preToolUse hook failed"}: ${t instanceof Error?t.message:"preToolUse hook error"}`);return await this.firePostToolUseFailureAsync(e,o,a,i,r,"error",0,n,!1,s),new Lt.iz({result:{case:"permissionDenied",value:new Lt.HQ({error:f_("MCP tool execution",r),isReadonly:!1})}})}oP.warn(e,c?"preToolUse additional_context exceeded max size; dropping carrier":"preToolUse hook error in MCP executor",{toolName:a,error:t instanceof Error?t.message:String(t),...c?{actualLength:t.actualLength,maxLength:t.maxLength}:{}})}const c=await(this.mcpLease?.getClient(e,t.providerIdentifier)),l=c?.config;let u;const d=l&&"url"in l&&l.url?l.url:void 0;u=void 0!==d?{url:d}:l&&"command"in l?{command:[l.command,...l.args??[]].filter(Boolean).join(" ")}:{command:t.providerIdentifier};const h={mcp_server_name:t.providerIdentifier,...void 0!==d?{mcp_server_url:d}:{}},p={...o,tool_name:t.toolName,tool_input:JSON.stringify(i),tool_use_id:n,...h,...u},f=await this.hookExecutor.executeHookForStep(he.beforeMCPExecution,p);if("deny"===f?.permission){const t=f_("MCP tool execution",f.user_message);return await this.firePostToolUseFailureAsync(e,o,a,i,t,"permission_denied",0,n,!1,s),new Lt.iz({result:{case:"permissionDenied",value:new Lt.HQ({error:t,isReadonly:!1})}})}const m=k_.performance.now();try{const c=await this.innerExecutor.execute(e,t,r),l=R_(k_.performance.now()-m);let u="{}";if("success"===c.result.case)try{const e=c.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"}));u=JSON.stringify({content:e,isError:c.result.value.isError})}catch(t){oP.warn(e,"Failed to serialize MCP result",{error:t instanceof Error?t.message:String(t)}),u=JSON.stringify({error:"Failed to serialize result"})}else"error"===c.result.case?u=JSON.stringify({error:c.result.value.error}):"rejected"===c.result.case?u=JSON.stringify({rejected:!0,reason:c.result.value.reason}):"permissionDenied"===c.result.case&&(u=JSON.stringify({permissionDenied:!0,error:c.result.value.error}));const d={...o,tool_name:t.toolName,tool_input:JSON.stringify(i),result_json:u,duration:l,tool_use_id:n,...h};await this.hookExecutor.executeHookForStep(he.afterMCPExecution,d);const p=await this.firePostToolUse(e,o,a,i,u,l,n,s);if(void 0!==p?.updated_mcp_tool_output)try{const e=p.updated_mcp_tool_output,t=[];if("string"==typeof e)t.push(new Lt._Z({content:{case:"text",value:new Lt.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 Lt._Z({content:{case:"text",value:new Lt.zN({text:String(e.text)})}})):t.push(new Lt._Z({content:{case:"text",value:new Lt.zN({text:JSON.stringify(e)})}}))}else t.push(new Lt._Z({content:{case:"text",value:new Lt.zN({text:JSON.stringify(e)})}}));const r="object"==typeof e&&null!==e&&"isError"in e&&Boolean(e.isError);return new Lt.iz({result:{case:"success",value:new Lt.QW({content:t,isError:r})}})}catch(t){return oP.warn(e,"Failed to process updated_mcp_tool_output",{error:t instanceof Error?t.message:String(t)}),c}return c}catch(t){const r=R_(k_.performance.now()-m),c=t instanceof Error?t.message:String(t);throw await this.firePostToolUseFailureAsync(e,o,a,i,c,"error",r,n,!1,s),t}}async firePostToolUse(e,t,r,o,n,s,i,a){try{const c=await this.hookExecutor.executeHookForStep(he.postToolUse,{...t,tool_name:r,tool_input:o,tool_output:n,duration:s,tool_use_id:i});return E_(a,nP(e,r,he.postToolUse,c?.additional_context)),c}catch(t){return void oP.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,c,l){try{const u=await this.hookExecutor.executeHookForStep(he.postToolUseFailure,{...t,tool_name:r,tool_input:o,error_message:n,failure_type:s,duration:i,tool_use_id:a,is_interrupt:c});E_(l,nP(e,r,he.postToolUseFailure,u?.additional_context))}catch(t){oP.warn(e,"postToolUseFailure hook error in MCP executor",{error:t instanceof Error?t.message:String(t)})}}}const iP={toolName:"ListMcpResources",createToolInput:e=>({server:e.server}),applyUpdatedInput:(e,t)=>{"string"==typeof t.server&&(e.server=t.server)},createRejectedResult:(e,t)=>new Lt.kP({result:{case:"error",value:new Lt.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 aP{constructor(e,t,r){this.wrappedExecutor=D_(e,t,r,iP)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const cP={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 Lt.ZD({result:{case:"error",value:new Lt.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 lP{constructor(e,t,r){this.wrappedExecutor=D_(e,t,r,cP)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const uP={toolName:"Read",getToolCallId:M_,createToolInput:e=>({file_path:e.path}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new Ut.sV({result:{case:"rejected",value:new Ut.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,toolUseId:s}=e;if("success"!==r.result.case)return;const i="content"===r.result.value.output.case?r.result.value.output.value:"",a=await async function(e,t){try{return await e()}catch(e){const r=function(e,t){return`${e??"Action"} was blocked because a configured hook failed to execute${t?`: ${t}`:"."}\n\nThis is a safety measure (fail-closed) - when hooks cannot be evaluated, the action is blocked to prevent potentially unsafe operations.\n\n${h_}`}(t,e instanceof Error?e.message:String(e));throw new d_(r,e)}}((()=>n.executeHookForStep(he.beforeReadFile,{...o,content:i,file_path:t.path,attachments:[],tool_use_id:s})),"File read");if("deny"===a?.permission){const e=f_("File read",a.user_message);throw new u_(e)}}};class dP{constructor(e,t,r){this.wrappedExecutor=new Vt(D_(e,t,r,uP))}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const hP={toolName:"RecordScreen",getToolCallId:M_,createToolInput:e=>({mode:e.mode,save_as_filename:e.saveAsFilename}),createRejectedResult:(e,t)=>new nE.Tj({result:{case:"failure",value:new nE.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 pP{constructor(e,t,r){this.wrappedExecutor=D_(e,t,r,hP)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}function fP(e){return"success"===e.result.case||"failure"===e.result.case?e.result.value.stdout+e.result.value.stderr:""}const mP={toolName:L_,createToolInput:e=>{const t=e.workingDirectory||"",r=e.timeout;return{command:e.command,cwd:t,..."number"==typeof r&&r>0&&{timeout:r}}},applyUpdatedInput:(e,t)=>{"string"==typeof t.command&&(e.command=t.command),"string"==typeof t.cwd&&(e.workingDirectory=t.cwd),"number"==typeof t.timeout&&t.timeout>=0&&(e.timeout=t.timeout)},createRejectedResult:(e,t)=>new yr.W4({result:{case:"rejected",value:new yr.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:fP(t),exitCode:"success"===t.result.case?0:1}),getExtraHookFields:e=>({cwd:e.workingDirectory||""}),runPreExecutionHooks:async e=>{const{args:t,baseHookRequest:r,hookExecutor:o,toolUseId:n}=e,s=t.workingDirectory||"";Mr(t,await U_({hookExecutor:o,baseHookRequest:r,toolUseId:n,command:t.command,cwd:s,sandbox:j_(t.requestedSandboxPolicy)}))},runPostExecutionHooks:async e=>{const{args:t,result:r,baseHookRequest:o,hookExecutor:n,executionDurationMs:s,toolUseId:i}=e,a=fP(r);await n.executeHookForStep(he.afterShellExecution,{...o,command:t.command,output:a,duration:s,sandbox:j_(t.requestedSandboxPolicy),tool_use_id:i})}};class gP{constructor(e,t,r){this.wrappedExecutor=D_(e,t,r,mP)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}class wP{constructor(){this.output=""}onEvent(e){"stdout"===e.event.case||"stderr"===e.event.case?this.output+=e.event.value.data:"exit"===e.event.case&&(this.exitEvent=e.event.value)}getOutput(){return this.output}isAborted(){return this.exitEvent?.aborted??!1}getExitCode(){return this.exitEvent?.code??0}}const yP={toolName:L_,createToolInput:e=>{const t=e.workingDirectory||"",r=e.timeout;return{command:e.command,cwd:t,..."number"==typeof r&&r>0&&{timeout:r}}},applyUpdatedInput:(e,t)=>{"string"==typeof t.command&&(e.command=t.command),"string"==typeof t.cwd&&(e.workingDirectory=t.cwd),"number"==typeof t.timeout&&t.timeout>=0&&(e.timeout=t.timeout)},createRejectedEvent:(e,t)=>new yr.FI({event:{case:"rejected",value:new yr.pZ({command:e.command,workingDirectory:e.workingDirectory,reason:t})}}),createHookContextEvent:e=>new yr.FI({event:{case:"hookContext",value:new yr.Ng({hookAdditionalContexts:[...e]})}}),getExtraHookFields:e=>({cwd:e.workingDirectory||""}),createResultCollector:()=>new wP,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,toolUseId:n}=e,s=t.workingDirectory||"",i=j_(t.requestedSandboxPolicy);Mr(t,await U_({hookExecutor:o,baseHookRequest:r,toolUseId:n,command:t.command,cwd:s,sandbox:i}))},runPostExecutionHooks:async e=>{const{args:t,baseHookRequest:r,hookExecutor:o,collector:n,executionDurationMs:s,toolUseId:i}=e,a=j_(t.requestedSandboxPolicy);await o.executeHookForStep(he.afterShellExecution,{...r,command:t.command,output:n.getOutput(),duration:s,sandbox:a,tool_use_id:i})}};class vP{constructor(e,t,r){this.wrappedExecutor=function(e,t,r,o){return{async*execute(n,s,i){const{hookContext:a,helpers:c}=T_(n,s,t,r,o,i),l=o.runPreExecutionHooks?async e=>{await o.runPreExecutionHooks(e)}:void 0,u=await A_(n,s,t,a,c,o,((e,t)=>o.createRejectedEvent(e,t)),l);if("rejected"===u.type){yield u.result;for(const e of O_(o,a))yield e;return}const d=k_.performance.now(),h=o.createResultCollector();let p=!1;try{for await(const t of e.execute(n,s,i))h.onEvent(t),yield t}catch(e){p=!0;const t=R_(k_.performance.now()-d),r=e instanceof Error?e.message:String(e);await c.fireFailureAsync(t,r,"error");for(const e of O_(o,a))yield e;throw e}const f=R_(k_.performance.now()-d);if(o.runPostExecutionHooks)try{await o.runPostExecutionHooks({ctx:n,args:s,baseHookRequest:a.baseHookRequest,hookExecutor:t,toolInput:c.getToolInput(),toolUseId:a.toolUseId,extraHookFields:a.extraHookFields,collector:h,executionDurationMs:f})}catch(e){P_.warn(n,"postExecutionHooks error",{toolName:o.toolName,error:e instanceof Error?e.message:String(e)})}if(!p)if(h.isAborted())await c.fireFailureAsync(f,"Command was aborted","error",!0);else if(o.isStreamSuccess?.(h)??1)await c.fireSuccessAsync(f,JSON.stringify(o.createSuccessOutput(s,h)));else{const e=o.getStreamErrorMessage?.(s,h)??`Command failed with exit code ${h.getExitCode()}`;await c.fireFailureAsync(f,e,"error")}for(const e of O_(o,a))yield e}}}(e,t,r,yP)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}class bP{constructor(e,t,r){const o=new Map;this.wrappedExecutor=D_(e,t,r,function(e,t){return{toolName:"Write",getToolCallId:M_,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 vr.v3({result:{case:"error",value:new vr.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 r=>{const{args:o,toolUseId:n}=r;if(!1===e.hasHooksForStep?.(he.afterFileEdit))return;let s,i=!1;try{(await(0,Os.stat)(o.path)).size>262144?i=!0:s=await ua(o.path)}catch(e){}t.set(n,{contentBeforeWrite:s,fileTooLarge:i})},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||!1===e.hasHooksForStep?.(he.afterFileEdit))return;const{contentBeforeWrite:c,fileTooLarge:l}=a??{fileTooLarge:!1};let u;u=l||void 0===c?[{old_string:"",new_string:o.fileText}]:c===o.fileText?[]:function(e,t){const r=(0,Nv.YB)("","",e,t,"","",{context:0,timeout:50});return void 0===r?[{old_string:"",new_string:t}]:0===r.hunks.length?[]:r.hunks.map((e=>{const t=[],r=[];for(const 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")}}))}(c,o.fileText);const d={...s,file_path:o.path,edits:u},h=await e.executeHookForStep(he.afterFileEdit,d);if(o.returnFileContentAfterWrite&&void 0!==h){const e=n.result.value.path;try{const t=await ua(e),r=Bi(t),o=Buffer.byteLength(t,"utf8");return new vr.v3({result:{case:"success",value:new vr.j6({...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)}}class SP{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){if(e.symbol===ht.symbol)return new wt(this.hookExecutor);const t=this.innerAccessor.get(e);return e.symbol===br.symbol?new gP(t,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===Sr.symbol?new vP(t,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===kr.symbol?new bP(t,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===At.symbol?new sP(t,this.hookExecutor,this.baseHookRequestExtractor,this.mcpLease,this.hooksConfigLease):e.symbol===Jt.symbol||e.symbol===Kt.symbol?new dP(t,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===vt.symbol?new rP(t,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===de.symbol?new eP(t,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===le.symbol?new Q_(t,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===ie.symbol?new J_(t,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===ae.symbol?new Z_(t,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===Mt.symbol?new aP(t,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===Dt.symbol?new lP(t,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===ee.symbol?new W_(t,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===te.symbol?new q_(t,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===se.symbol?new G_(t,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===Pr.symbol?new pP(t,this.hookExecutor,this.baseHookRequestExtractor):e.symbol===Ir.symbol&&(this.hooksAdditionalContextPromise||this.hooksConfigLease)?new F_(t,this.hooksAdditionalContextPromise??Promise.resolve(void 0),this.teamHooksReadyPromise,this.hooksConfigLease):t}*entries(){for(const[e,t]of this.innerAccessor.entries())e.symbol===br.symbol?yield[e,new gP(t,this.hookExecutor,this.baseHookRequestExtractor)]:e.symbol===Sr.symbol?yield[e,new vP(t,this.hookExecutor,this.baseHookRequestExtractor)]:e.symbol===kr.symbol?yield[e,new bP(t,this.hookExecutor,this.baseHookRequestExtractor)]:e.symbol===At.symbol?yield[e,new sP(t,this.hookExecutor,this.baseHookRequestExtractor,this.mcpLease,this.hooksConfigLease)]:e.symbol===Jt.symbol||e.symbol===Kt.symbol?yield[e,new dP(t,this.hookExecutor,this.baseHookRequestExtractor)]:e.symbol===vt.symbol?yield[e,new rP(t,this.hookExecutor,this.baseHookRequestExtractor)]:e.symbol===de.symbol?yield[e,new eP(t,this.hookExecutor,this.baseHookRequestExtractor)]:e.symbol===le.symbol?yield[e,new Q_(t,this.hookExecutor,this.baseHookRequestExtractor)]:e.symbol===ie.symbol?yield[e,new J_(t,this.hookExecutor,this.baseHookRequestExtractor)]:e.symbol===ae.symbol?yield[e,new Z_(t,this.hookExecutor,this.baseHookRequestExtractor)]:e.symbol===Mt.symbol?yield[e,new aP(t,this.hookExecutor,this.baseHookRequestExtractor)]:e.symbol===Dt.symbol?yield[e,new lP(t,this.hookExecutor,this.baseHookRequestExtractor)]:e.symbol===ee.symbol?yield[e,new W_(t,this.hookExecutor,this.baseHookRequestExtractor)]:e.symbol===te.symbol?yield[e,new q_(t,this.hookExecutor,this.baseHookRequestExtractor)]:e.symbol===se.symbol?yield[e,new G_(t,this.hookExecutor,this.baseHookRequestExtractor)]:e.symbol===Pr.symbol?yield[e,new pP(t,this.hookExecutor,this.baseHookRequestExtractor)]:e.symbol===Ir.symbol&&(this.hooksAdditionalContextPromise||this.hooksConfigLease)?yield[e,new F_(t,this.hooksAdditionalContextPromise??Promise.resolve(void 0),this.teamHooksReadyPromise,this.hooksConfigLease)]:yield[e,t];yield[ht,new wt(this.hookExecutor)]}}const kP={cursor_version:process.env.AGENT_CLI_STATIC_VERSION??"1.0.0",user_email:null};function EP(e=process.cwd()){let t=e;return{getCwd:async()=>t,clone:e=>EP(e??t),async*execute(e,r,o={}){const n=o.workingDirectory??t;t=n;const s=function(e){return"win32"===process.platform?{executable:(0,Fs.oG)(),args:[...et,"-Command",e]}:{executable:process.env.SHELL||"/bin/sh",args:["-lc",e]}}(r),i=(0,Iu.spawn)(s.executable,[...s.args],{cwd:n,env:{...process.env,...o.env??{}},signal:o.signal,stdio:[!0===o.pipeStdin?"pipe":"ignore","pipe","pipe"]}),a=[];let c,l,u=!1;const d=()=>{c?.(),c=void 0},h=e=>{a.push(e),d()};for(i.on("spawn",(()=>{!0===o.pipeStdin&&h({type:"stdin_ready",stdin:i.stdin??void 0})})),i.stdout?.setEncoding("utf8"),i.stdout?.on("data",(e=>{h({type:"stdout",data:String(e)})})),i.stderr?.setEncoding("utf8"),i.stderr?.on("data",(e=>{h({type:"stderr",data:String(e)})})),i.on("error",(e=>{l=e,u=!0,d()})),i.on("close",(e=>{h({type:"exit",code:e}),u=!0}));!u||a.length>0;)0!==a.length?yield a.shift():await new Promise((e=>{c=e}));if(void 0!==l)throw l}}}function CP(e,t,...r){for(const o of r){const r=t(e[o]);if(void 0!==r)return r}}function xP(e){return"string"==typeof e&&e.length>0?e:void 0}function _P(e){return"object"==typeof e&&null!==e&&"string"==typeof e.id&&"string"==typeof e.value}function PP(e){if(Array.isArray(e)&&e.every(_P))return e.map((e=>({id:e.id,value:e.value})))}class IP{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 RP(e,t={}){const r=await new b_(new $_,function(e,t){const r=e.projectRoot??e.workingDirectory??e.workspaceRoots[0],o=t.includeProjectHooks??!0,i=t.includeUserHooks??!0;return{enterpriseConfigPath:t.includeEnterpriseHooks??1?v_():void 0,userConfigPath:i?(0,s.join)((0,n.homedir)(),".cursor","hooks.json"):void 0,claudeUserConfigPath:i?(0,s.join)((0,n.homedir)(),".claude","settings.json"):void 0,projectConfigPath:o&&void 0!==r?(0,s.join)(r,".cursor","hooks.json"):void 0,claudeProjectConfigPath:o&&void 0!==r?(0,s.join)(r,".claude","settings.json"):void 0,claudeProjectLocalConfigPath:o&&void 0!==r?(0,s.join)(r,".claude","settings.local.json"):void 0}}(e,t)).load(),o=new S_(r),i=function(e){return e.projectRoot??e.workingDirectory??e.workspaceRoots[0]??process.cwd()}(e),a=function(e){return Object.freeze({...kP,...e.globalContext??{}})}(t);return{projectDir:e.projectRoot,workspacePath:i,hooksConfig:r,hooksConfigLease:o,globalContext:a,createSessionRuntime(){const e=new y_(r,i,a,(t.createTerminalExecutor??EP)(),t.promptHookClient,void 0,void 0,{enableClaudeNestedHookSpecificOutputCompatibility:!0,commandHookPayloadTransport:(n=t.useCommandHookStdinTransport,!0===n?"stdin":"legacy")});var n;return{hookExecutor:e,hooksConfigLease:o,async dispose(){e.clearSessionEnvironment()}}},async dispose(){}}}function TP(e={}){return{createHooksRuntime:t=>RP(t.workspaceState,e)}}var AP=r("../proto/dist/generated/aiserver/v1/dashboard_connect.js");async function MP(e){(function(e){return"object"==typeof e&&null!==e&&"dispose"in e&&"function"==typeof e.dispose})(e)&&await e.dispose()}function DP(e={}){const t=e.getThirdPartyExtensibilityEnabled??(()=>!0),r=e.importThirdPartyPlugins??!1,o=e.includeProjectExtensibility??!0,s=e.includeUserExtensibility??!0,i=e.includeManagedSkills??!0,a=e.includePluginExtensibility??!0,c=new Rm,l=(0,n.homedir)(),u=Sp(l).dirPath;let d,h=!0;return{async prepareLocalExtensibility(){h=i&&await async function(e){if(!e)return!1;const t=(0,xo.createClient)(AP.I,e);return"synced"===(await async function(e,t){try{const r=await t.getManagedSkills()??[],o=await NC(e,{managedSkills:[...r]});return{status:"synced",managedSkillsCount:r.length,syncResult:o}}catch(t){return FC.warn(e,"Failed to sync managed skills from source",{error:t}),{status:"fetch_failed",error:t}}}((0,ce.q6)(),{getManagedSkills:async()=>(await t.getManagedSkills(new HC.X8g({}))).skills??[]})).status}(e.dashboardTransport)},async loadLocalExtensibility(n){const i=function(e){if(e.workspaceRoots.length>0)return[...e.workspaceRoots];const t=e.projectRoot??e.workingDirectory;return void 0!==t?[t]:[]}(n.workspaceState);if(0===i.length)return d=void 0,{cursorRulesService:UP(),getAgentSkills:async e=>[]};const p=(0,ce.q6)(),f=e.loadNestedRules??!0,m=o?i.map((e=>new wf(p,c,e,f,t,void 0))):[],g=function(e,t){const r=OP(t);return{getAllCursorRules:async t=>NP(await e.getAllCursorRules(t),r),reload(t){e.reload(t)},onDidChangeRules:t=>e.onDidChangeRules(t),dispose(){e.dispose()}}}(0===m.length?UP():1===m.length?m[0]:new gf(m,(()=>Np)),{allowedRoots:o?i:[],excludedRoots:[]}),w=function(e,t){const r=OP(t);return{getAllCursorRules:async t=>NP(await e.getAllCursorRules(t),r),getAllAgentSkills:async t=>NP(await e.getAllAgentSkills(t),r),reload(t){e.reload(t)},onDidChangeRules:t=>e.onDidChangeRules(t),onDidChangeSkills:t=>e.onDidChangeSkills(t),dispose(){e.dispose()}}}(new yf(p,o?i:[],l,c,f,void 0,t,Promise.resolve(),"sdk"),{allowedRoots:[...o?i:[],...s?[l]:[],...h?[u]:[]],excludedRoots:h?[]:[u]}),y=o?i.map((e=>new If(e,t))):[],v=0===y.length?new kf:1===y.length?y[0]:new Tf(y),b=wx(n.services.pluginBootstrapOutputs),S=b&&a?new bf(p,(()=>({importThirdPartyPlugins:r})),void 0,b.pluginsService):void 0,k=b&&a?new Af((()=>({importThirdPartyPlugins:r})),b.pluginsService):void 0,E=new gf([g,w,...S?[S]:[]],(()=>Np)),C=new bC([w,...S?[S]:[]],(()=>[]),(()=>({workspacePaths:o?i:[],userHomeDirectory:l,agentStoreSkillsDirs:[]}))),x=new Tf([v,...k?[k]:[]]);return d={localRulesService:g,localSkillsService:w,localSubagentsService:v,pluginSkillsService:S,pluginSubagentsService:k,mergedCursorRulesService:E,mergedAgentSkillsService:C,mergedSubagentsService:x},{cursorRulesService:E,getAgentSkills:e=>C.getAllAgentSkills(e),subagentsService:x}},async disposeLocalExtensibility(){if(!d)return;const e=d;d=void 0,await async function(e){let t;const r=[e.mergedSubagentsService,e.mergedAgentSkillsService,e.mergedCursorRulesService,e.pluginSubagentsService,e.pluginSkillsService,e.localSubagentsService,e.localSkillsService,e.localRulesService];for(const e of r)try{await MP(e)}catch(e){t??=e}if(void 0!==t)throw t}(e)}}}function OP(e){const t=Promise.all(e.allowedRoots.map(jP)),r=Promise.all(e.excludedRoots.map(jP));return async e=>{const[o,n,s]=await Promise.all([LP(e.fullPath),t,r]);return void 0!==o&&!s.some((e=>$P(o,e)))&&n.some((e=>$P(o,e)))}}async function NP(e,t){const r=await Promise.all(e.map(t));return e.filter(((e,t)=>r[t]))}function $P(e,t){if(e===t)return!0;const r=`${t}/`;return e.startsWith(r)}function FP(e){return e.replace(/\\/g,"/").replace(/\/+$/,"")}async function jP(e){try{return FP(await(0,Os.realpath)(e))}catch{return FP(e)}}async function LP(e){try{return FP(await(0,Os.realpath)(e))}catch{return}}function UP(){return{getAllCursorRules:async()=>[],reload(){},onDidChangeRules:()=>()=>{},dispose(){}}}function BP(e={}){const t=e.userHomeDirectory??(0,n.homedir)(),r=e.importThirdPartyPlugins??!1,o=e.pluginLogger??{log(e,t,r){switch(e){case"warn":YC.Jz.warn("[local-plugins-bootstrap]",t,r??{});break;case"error":YC.Jz.error("[local-plugins-bootstrap]",t,r??{})}},increment(){},distribution(){},captureException(e,t){YC.Jz.error("[local-plugins-bootstrap] Unexpected plugin exception:",e,t??{})}},i=WP(e.marketplaceOptions),a=void 0!==e.dashboardTransport,c=e.loadCursorFirstParty??(i||a);return{async loadPluginBootstrapOutputs(n){const i=(a=n.workspaceState).projectRoot??a.workspaceRoots[0]??a.workingDirectory;var a;const{discoveredEntries:l,failures:u}=await async function(e){if(void 0===e)return{discoveredEntries:[],failures:[]};try{return{discoveredEntries:(await up(e)).map((({key:t,entry:r})=>({source:"project-settings",workspacePath:e,key:t,entry:r}))),failures:[]}}catch(e){return{discoveredEntries:[],failures:[{stage:"discovery",source:"project-settings",message:e instanceof Error?`Failed to read project plugin settings: ${e.message}`:`Failed to read project plugin settings: ${String(e)}`,detail:e}]}}}(i),d=e.marketplaceOptions??(e.dashboardTransport?function(e){const t=(0,s.join)(e.userHomeDirectory,".cursor","plugins","marketplaces"),r=(0,xo.createClient)(AP.I,e.dashboardTransport),o=eh((async()=>{try{return await r.getEffectiveUserPlugins(new HC.EwF({}))}catch{return{plugins:[]}}}),t,void 0,void 0,{allowedMarketplaceNames:["cursor-public"]}),n=e.workspacePath,i=eh((async()=>{if(void 0===n)return{plugins:[]};try{const e=await up(n);if(0===e.length)return{plugins:[]};const t=e.filter((e=>e.entry.gitUrl)),o=e.filter((e=>!e.entry.gitUrl)),s=t.filter((({entry:e})=>{const t=e.gitUrl;return!t||ip(t)})).map((({key:e,entry:t})=>{const r=dp(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 i=[];if(o.length>0)try{const e=o.map((e=>{const t=dp(e.key);return new HC.vwy({name:t.name,marketplaceName:t.marketplaceName})})),t=await r.resolvePluginsByRef(new HC.WvV({refs:e}));i=t.plugins?.map((e=>({plugin:e,isEnabled:!0})))??[]}catch{}return{plugins:[...s,...i]}}catch{return{plugins:[]}}}),t,void 0,void 0,{allowedMarketplaceNames:["cursor-public"]});return[{client:o,userId:"",cacheManager:new _u(e.userHomeDirectory),pruneOldVersions:!0},{client:i,userId:"",cacheManager:new _u(e.userHomeDirectory),pruneOldVersions:!0}]}({dashboardTransport:e.dashboardTransport,workspacePath:i,userHomeDirectory:t}):void 0),h=WP(d),p=new WC(void 0!==i?[i]:[],t,(()=>({importThirdPartyPlugins:r,loadCursorFirstParty:c})),d,o);let f=[];const m=[...u];try{f=await p.getAllEnabledPlugins()}catch(e){m.push({stage:"resolution",source:"plugin-loader",message:e instanceof Error?`Failed to load plugins: ${e.message}`:`Failed to load plugins: ${String(e)}`,detail:e})}l.length>0&&!h&&m.push({stage:"resolution",source:"plugin-loader",message:"Project plugin entries were discovered, but no marketplace-backed project plugin source was configured. Those entries remain available through discoveredEntries only.",detail:{workspacePath:i,discoveredEntryCount:l.length}});const g={kind:gx,discoveredEntries:l,loadedPlugins:f,loadFailures:p.getLoadFailures(),bootstrapFailures:m,pluginsService:p,async dispose(){}};for(const e of m)YC.Jz.warn("[local-plugins-bootstrap] Plugin bootstrap failure:",{workspacePath:i,stage:e.stage,source:e.source,message:e.message,detail:e.detail});for(const e of g.loadFailures)YC.Jz.warn("[local-plugins-bootstrap] Plugin load failure:",{workspacePath:i,pluginName:e.pluginName,pluginId:e.pluginId,marketplaceName:e.marketplaceName,errorType:e.errorType,errorMessage:e.errorMessage});return[g]}}}function WP(e){return void 0!==e&&(!Array.isArray(e)||e.length>0)}class HP{async getAllCursorRules(e){return[]}reload(e){}dispose(){}onDidChangeRules(e){return()=>{}}}const qP=["projectFolder","terminalsFolder","agentSharedNotesFolder","agentConversationNotesFolder","agentTranscriptsFolder","processWorkingDirectory","artifactsFolder"];function zP(e){if(e.length<=1)return e;let t=e.length;for(;t>1&&("/"===(r=e[t-1])||"\\"===r)&&(3!==t||":"!==e[1]);)t-=1;var r;return e.slice(0,t)}function GP(e){const t=zP(e).replaceAll("\\","/");return/^[A-Za-z]:\/$/.test(t)?t.slice(0,-1):t}function VP(e){const t=zP(e.reportedWorkspacePath);if(""===e.suffix)return t;const r=t.replaceAll("\\","/"),o="/"===r?e.suffix:`${r}${e.suffix}`;return t.includes("\\")?o.replaceAll("/","\\"):o}function JP(e){const t=GP(e.value),r=[...new Set(e.hostRoots.filter((e=>e.length>0)))].sort(((e,t)=>GP(t).length-GP(e).length));for(const o of r){const r=GP(o);if(t===r)return VP({reportedWorkspacePath:e.reportedWorkspacePath,suffix:""});const n="/"===r?"/":`${r}/`;if(t.startsWith(n)){const o="/"===r?t:t.slice(r.length);return VP({reportedWorkspacePath:e.reportedWorkspacePath,suffix:o})}}}class KP extends hC{constructor(e,t){super(e),this.sessionMcpLease=t}async dispose(){try{await super.dispose()}finally{await MP(this.sessionMcpLease)}}}function ZP(e){const t=new Rm;return{async createResources(r){const o=e.createSessionDependencies?.(r)??{pendingDecisionStore:e.pendingDecisionStore,fileChangeTracker:e.fileChangeTracker,permissionsService:e.permissionsService};if(!o.pendingDecisionStore||!o.fileChangeTracker||!o.permissionsService)throw new Error("Local resource provider factory requires either shared dependencies or a per-session dependency factory.");const n=r.workspaceServices.cursorRulesService??new HP,s=r.workspaceServices.subagentsService??new kf,i=r.workspaceServices.mcpLease??new Ug,a=void 0!==r.options.mcpServersOverride&&void 0!==e.createSessionMcpLease?await e.createSessionMcpLease(r,r.options.mcpServersOverride):void 0,c=(l=a??i,0===(u=r.options.extraMcpTools??[]).length?l:"onDidChange"in(d=l)&&"function"==typeof d.onDidChange?new Em(l,u):new km(l,u));var l,u,d;try{const i=await async function(e,t){return void 0===e?{}:"function"==typeof e?await e({sessionId:t.sessionState.sessionId,metadata:t.metadata}):e}(r.options.localResourceProviderOptions,r),l={pendingDecisionStore:o.pendingDecisionStore,fileChangeTracker:o.fileChangeTracker,gitExecutor:t,ignoreService:e.ignoreService,grepProvider:e.grepProvider,permissionsService:o.permissionsService,workspacePaths:e.workspacePaths,diagnosticsProvider:e.diagnosticsProvider,mcpLease:c,mcpStateAccessor:e.createMcpStateAccessor?.(c),cursorRulesService:n,subagentsService:s,repositoryProvider:e.repositoryProvider,projectDir:e.projectDir,shellManager:e.shellManager,_defaultSandboxPolicy:e.defaultSandboxPolicy??{type:"insecure_none"},_defaultSandboxPolicySources:e.defaultSandboxPolicySources,getSandboxEnabled:e.getSandboxEnabled,getSandboxSupported:e.getSandboxSupported,getNetworkAllowlistInfo:e.getNetworkAllowlistInfo,getSmartModeClassifierAutoModeEnabled:e.getSmartModeClassifierAutoModeEnabled,devForceNextSmartModeClassifierBlockToken:e.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:e.getMockPromptTime,mcpFileOutputThresholdBytes:e.mcpFileOutputThresholdBytes,mcpMetaToolEnabled:e.mcpMetaToolEnabled,getAgentSkills:r.workspaceServices.getAgentSkills,...i},u=void 0===a?new hC(l):new KP(l,a);return void 0!==r.options.reportedWorkspacePath&&function(e,t,r){const o=e.get(Ir);void 0!==o&&e.register(Ir,{execute:async(e,n,s)=>function(e,t,r){if("success"!==e.result.case||void 0===e.result.value.requestContext?.env)return e;const o=e.clone();if("success"!==o.result.case)return e;const n=o.result.value.requestContext?.env;if(void 0===n)return o;n.workspacePaths=n.workspacePaths.map((e=>JP({value:e,hostRoots:r,reportedWorkspacePath:t})??e));for(const e of qP){const o=n[e];if(void 0===o||""===o)continue;const s=JP({value:o,hostRoots:r,reportedWorkspacePath:t});n[e]="processWorkingDirectory"===e?s??zP(t):s??o}return o}(await o.execute(e,n,s),t,r)})}(u,r.options.reportedWorkspacePath,[...l.workspacePaths,l.projectDir]),u}catch(e){throw await MP(a),e}}}}const XP=["cursorRulesService","getAgentSkills","subagentsService"],QP=new WeakSet;function YP(e){("object"==typeof e&&null!==e||"function"==typeof e)&&QP.add(e)}function eI(e){return("object"==typeof e&&null!==e||"function"==typeof e)&&QP.has(e)}function tI(e,t){const r=Object.keys(t).filter((e=>!XP.includes(e)));if(r.length>0)throw new Error(`Workspace service contributors may only provide ${XP.join(", ")}. Received unsupported service keys: ${r.join(", ")}.`);for(const r of XP)Object.hasOwn(t,r)&&(e[r]=t[r])}async function rI(e,t,r){const o={config:void 0,plugins:[],pluginBootstrapOutputs:[],cursorRulesService:void 0,getAgentSkills:void 0,subagentsService:void 0,mcpLease:void 0,hooksRuntime:void 0};try{o.config=e.config?await e.config.loadConfig(t):void 0,o.plugins=e.plugins?await e.plugins.loadPlugins(t):[];const n=()=>({workspaceState:t,policy:r,services:o});o.pluginBootstrapOutputs=e.pluginBootstrap?await e.pluginBootstrap.loadPluginBootstrapOutputs(n()):o.pluginBootstrapOutputs,o.mcpLease=e.mcp?await e.mcp.createLease(n()):void 0,o.hooksRuntime=e.hooks?await e.hooks.createHooksRuntime(n()):void 0,e.localExtensibility?.prepareLocalExtensibility&&await e.localExtensibility.prepareLocalExtensibility(n());const s=e.localExtensibility?await e.localExtensibility.loadLocalExtensibility(n()):void 0;void 0!==s&&(YP(s.cursorRulesService),YP(s.subagentsService),Object.assign(o,s));for(const t of e.workspaceServicesContributors??[]){const e=await t.contributeServices(n());void 0!==e&&tI(o,e)}return o}catch(t){try{await oI(o,{disposeLocalExtensibility:e.localExtensibility?.disposeLocalExtensibility})}catch(e){throw function(e,t){return new AggregateError([t],"Workspace service loading failed and resource cleanup also failed.",{cause:e})}(t,e)}throw t}}async function oI(e,t){const r=t?.preserveSharedContributorsFrom;let o;const n=async e=>{try{await MP(e)}catch(e){o??=e}};if(e.subagentsService===r?.subagentsService||eI(e.subagentsService)||await n(e.subagentsService),e.cursorRulesService===r?.cursorRulesService||eI(e.cursorRulesService)||await n(e.cursorRulesService),t?.disposeLocalExtensibility)try{await t.disposeLocalExtensibility()}catch(e){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 MP(e[r])}catch(e){t??=e}if(void 0!==t)throw t}(e.pluginBootstrapOutputs)}catch(e){o??=e}if(void 0!==o)throw o}const nI=["project","user","team","mdm","plugins"],sI=new Set([...nI,"all"]);function iI(e){if(void 0===e||0===e.length)return cI([]);for(const t of e)if(!sI.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{...cI(nI),all:!0}}return cI(e)}function aI(e,t){return e[t]}function cI(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 lI=Object.freeze({}),uI=Object.freeze({allowMcpServers:!0,allowPlugins:!0,allowBackgroundSessions:!0,requireMcpApproval:!1,maxParallelSessions:void 0,sandboxMode:void 0,metadata:lI});async function dI(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 MP(n)}catch(e){r??=e}}}if(void 0!==r)throw r}async function hI(e={}){const t=function(e={}){return{workspace:e.workspace??ZC,config:e.config,plugins:e.plugins,pluginBootstrap:e.pluginBootstrap,mcp:e.mcp,hooks:e.hooks,localExtensibility:e.localExtensibility,resourceFactory:e.resourceFactory,resourceWrappers:e.resourceWrappers,workspaceServicesContributors:e.workspaceServicesContributors,lifecycle:e.lifecycle}}(e.adapters),r=await t.workspace.resolveWorkspaceState({workingDirectory:e.workingDirectory,projectRoot:e.projectRoot,projectDirectory:e.projectDirectory,workspaceRoots:e.workspaceRoots}),o=await async function(e,t){return e.resolvePolicy(t)}(e.policyAdapter??function(e={}){const t=Object.freeze({...uI.metadata,...e.metadata}),r={...uI,...e,metadata:t};return{name:"permissive-sdk-local",resolvePolicy:()=>r}}(),{workspaceState:r});let n=await rI(t,r,o),s=!1,i=Promise.resolve();const a=e=>{const t=i.then(e);return i=t.catch((()=>{})),t},c=t.localExtensibility?.disposeLocalExtensibility;return{state:r,get services(){return n},policy:o,async createSessionRuntime(e={}){if(s)throw new Error("Cannot create a session runtime after the workspace runtime has been disposed.");return async function(e){const t={sessionId:e.options?.sessionId??(0,Co.C)(),createdAt:new Date},r=Object.freeze({...e.options?.metadata??{}}),o={options:e.options??{},workspaceState:e.workspaceState,workspaceServices:e.workspaceServices,policy:e.policy,sessionState:t,metadata:r,getAgentSkills:e.workspaceServices.getAgentSkills};let n,s;const i=[];try{n=e.adapters.resourceFactory?await e.adapters.resourceFactory.createResources(o):void 0,s=n,i.push(n);for(const t of e.adapters.resourceWrappers??[])s=await t.wrapResources({...o,baseResources:n,resources:s}),i.push(s);await(e.adapters.lifecycle?.onSessionCreated?.(t))}catch(e){try{await dI(i)}catch(t){throw function(e,t){return new AggregateError([t],"Session creation failed and resource cleanup also failed.",{cause:e})}(e,t)}throw e}let a=!1;return{state:t,resources:{base:n,wrapped:s},metadata:r,workspaceServices:e.workspaceServices,policy:e.policy,async dispose(){if(!a){a=!0;try{await dI(i)}finally{await(e.adapters.lifecycle?.onSessionDisposed?.(t))}}}}}({options:e,workspaceState:r,workspaceServices:n,policy:o,adapters:t})},async reload(){s||await a((async()=>{if(s)return;const e=n,i=await rI(t,r,o);s?await oI(i,{disposeLocalExtensibility:c}):(n=i,await oI(e,{preserveSharedContributorsFrom:i,disposeLocalExtensibility:c}),await(t.lifecycle?.onWorkspaceReload?.(r)))}))},async dispose(){s||(s=!0,await a((async()=>{try{await oI(n,{disposeLocalExtensibility:c})}finally{await(t.lifecycle?.dispose())}})))}}}class pI{async requestApproval(e){return{approved:!0}}}class fI{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 mI{async open(e,t){}async getDiagnostics(e,t){return[]}}class gI{async getCodebaseReference(e,t){}}class wI{constructor(e){this.inner=e}async getState(e){const t=await this.inner.getState(e);return{...t,servers:t.servers.filter((e=>"needsAuth"!==e.status))}}}class yI{constructor(e){this.subagents=e.map((e=>new io.zz({fullPath:`sdk-inline://${e.name}`,name:e.name,description:e.description,tools:[],model:e.model,prompt:e.prompt,permissionMode:io.b$.DEFAULT,isBackground:!1,source:"sdk"})))}async getAllSubagents(){return this.subagents}async reload(){return this.subagents}}let vI;function bI(e){const t=process.env.CURSOR_DATA_DIR;if(t?.trim())return Ds(e);let r;try{r=(0,n.homedir)()}catch{r=void 0}return function(e){const t=e.cursorDataDir?.trim();return t?(0,s.join)(t,"projects",(0,As.r_)(e.workspacePath)):void 0!==e.homeDir&&function(e){if(""===e.trim())return!1;try{return!!(0,$s.statSync)(e).isDirectory()&&((0,$s.accessSync)(e,$s.constants.W_OK),!0)}catch{return!1}}(e.homeDir)?(0,s.join)(e.homeDir,".cursor","projects",(0,As.r_)(e.workspacePath)):(0,s.join)(e.ensureFallbackRoot(e.tempDir),(0,As.r_)(e.workspacePath))}({workspacePath:e,homeDir:r,tempDir:(0,n.tmpdir)(),ensureFallbackRoot:e=>(void 0===vI&&(vI=function(e){return(0,$s.mkdtempSync)((0,s.join)(e,"cursor-transcripts-"))}(e)),vI)})}async function SI(e,t){const r=(0,s.dirname)(e);await(0,Os.mkdir)(r,{recursive:!0}),await(0,Os.writeFile)(e,t,"utf-8")}class kI{constructor(e){this.writeChain=Promise.resolve(),this.workspacePath=e.workspacePath,this.conversationId=e.conversationId,this.parentConversationId=e.parentConversationId,this.blobStore=e.blobStore,this.projectDir=bI(this.workspacePath);const t=this.parentConversationId?(e,t)=>{const r=Dx({conversationId:e,ext:t,kind:"subagent",parentConversationId:this.parentConversationId});return(0,s.join)(this.projectDir,r)}:void 0;this.transcriptStore=new l_(this.projectDir,e.blobStore,SI,{writeText:!1,writeJsonl:!0,...t?{pathResolver:t}:{}}),this.nestedSubagentTranscriptStore=new l_(this.projectDir,e.blobStore,SI,{writeText:!1,writeJsonl:!0,pathResolver:(e,t)=>{const r=Dx({conversationId:e,ext:t,kind:"subagent",parentConversationId:this.conversationId});return(0,s.join)(this.projectDir,r)}})}enqueueWrite(e,t){const r=this.writeChain;return this.writeChain=r.then((async()=>{try{await e()}catch(e){YC.Jz.warn(`${t} ${e instanceof Error?e.message:String(e)}`)}})),this.writeChain}async writeFromState(e,t){return this.enqueueWrite((async()=>{await this.transcriptStore.writeFromStateFull(e,t,this.conversationId);const r=await(0,So.Vn)(e,t,this.blobStore);for(const[t,o]of Object.entries(r))o?.conversationState&&await this.nestedSubagentTranscriptStore.writeFromStateFull(e,o.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=Dx({conversationId:this.conversationId,ext:"jsonl",kind:"subagent",parentConversationId:this.parentConversationId});return(0,s.join)(this.projectDir,e)}return function(e,t){const r=Dx({conversationId:t,ext:"jsonl",kind:"primary"});return(0,s.join)(bI(e),r)}(this.workspacePath,this.conversationId)}getProjectDir(){return this.projectDir}}const EI=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,CI="User aborted/interrupted manually.";class xI{constructor(e){this.sessions=new Map,this.backgroundRuns=new Map,this.activeForegroundExecutions=new Map,this.backgroundPromises=new Set,this.pendingReleaseSessions=new Set,this.childParentIds=new Map,this.parentChildIds=new Map,this.queuedChildCompletions=new Map,this.childCompletionWaiters=new Map,this.agentClient=e.agentClient,this.getResources=e.getResources,this.mcpTools=e.mcpTools??[],this.workspacePath=e.workspacePath,this.parentConversationId=e.parentConversationId,this.headers=e.headers,this.endlessRetries=e.endlessRetries,this.onSessionCreated=e.onSessionCreated,this.onInteractionUpdate=e.onInteractionUpdate,this.onSessionCompleted=e.onSessionCompleted,this.onSessionReleased=e.onSessionReleased,this.onSubagentTokenDelta=e.onSubagentTokenDelta,this.lifecycleStore=new ho}async createOrResumeSession(e,t){if(t.forkAgentId)throw new Error("forkAgentId is not supported in local subagents.");const r=t.resumeAgentId;if(r&&function(e){if(!EI.test(e))throw new Error(`Invalid resumeAgentId format: ${e}`)}(r),r&&!t.prompt)return r;if(r&&po(t.prompt)&&this.isBackgroundRunBusy(r))throw new Error("Sub-agent is currently running. You may send the follow-up message when it has completed.");if(r&&this.sessions.get(r))return r;const o=r??(0,Co.C)(),n=function(e){const t=new So.We,r=(0,So.sh)(e),o=new So.pH(new So.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.setMetadata("subagentInfo",r.subagentInfo),o.setMetadata("blobEncryptionKey",r.blobEncryptionKey),o}(o),s=new kI({workspacePath:this.workspacePath,conversationId:o,parentConversationId:this.parentConversationId,blobStore:n.getBlobStore()});return this.sessions.set(o,{agentStore:n,transcriptWriter:s,toolCallId:t.toolCallId}),this.onSessionCreated?.({agentId:o,toolCallId:t.toolCallId,subagentType:t.subagentType,parentAgentId:t.parentConversationId}),o}async runSession(e,t,r,o){if(this.isAwaitBackgroundMode(r))return this.awaitBackgroundRun(r.resumeAgentId,e.signal);const n=this.sessions.get(t);if(!n)return{status:"error",error:`Subagent session not found: ${t}`};if(r.runInBackground){const[o,s]=e.withDetached().withCancel();return this.registerBackgroundRun(t,this.executeSubagent(o,t,r,n),r.parentConversationId,s),{status:"background",backgroundReason:io.qL.AGENT_REQUEST,toolCallCount:0}}const[s,i]=e.withDetached().withCancel();let a=!1;const c=()=>{a||i()};e.signal.addEventListener("abort",c,{once:!0}),e.signal.aborted&&c();let l=()=>{};const u=new Promise((e=>{l=e})),d={requestBackground:()=>!!a||!s.signal.aborted&&(a=!0,e.signal.removeEventListener("abort",c),l(),!0)};this.activeForegroundExecutions.set(r.toolCallId,d),this.activeForegroundExecutions.set(t,d);try{const e=this.executeSubagent(s,t,r,n),o=await Promise.race([e.then((e=>({handedOff:!1,outcome:e}))),u.then((()=>({handedOff:!0})))]);return o.handedOff?(this.registerBackgroundRun(t,e,r.parentConversationId,i),{status:"background",backgroundReason:io.qL.USER_REQUEST,toolCallCount:0}):(this.onSessionCompleted?.(t,o.outcome),o.outcome)}finally{this.clearForegroundExecution(r.toolCallId,d),this.clearForegroundExecution(t,d),a||e.signal.removeEventListener("abort",c)}}forceBackgroundByToolCallId(e){const t=this.activeForegroundExecutions.get(e);return t?.requestBackground()?new so.a3({status:so.jh.ACCEPTED}):new so.a3({status:so.jh.NOT_FOUND})}clearForegroundExecution(e,t){this.activeForegroundExecutions.get(e)===t&&this.activeForegroundExecutions.delete(e)}releaseSession(e){this.lifecycleStore.release(e),this.isBackgroundRunBusy(e)?this.pendingReleaseSessions.add(e):this.cleanupSession(e)}async awaitBackgroundWorkers(){for(;this.backgroundPromises.size>0;)await Promise.allSettled([...this.backgroundPromises])}async waitForBackgroundCompletions(e,t){return this.collectAvailableChildCompletions(e,t)}isBackgroundRunBusy(e){return this.lifecycleStore.isBusy(e)||this.backgroundRuns.has(e)}registerBackgroundRun(e,t,r,o){this.registerParentChildLink(e,r);const n=this.lifecycleStore.startRun(e,{abort:o}),s=t.catch((e=>({status:"error",error:e instanceof Error?e.message:String(e)}))),i={runId:n,promise:s};this.backgroundRuns.set(e,i),this.backgroundPromises.add(s),s.then((t=>{this.lifecycleStore.finishRun(e,n);const r=this.backgroundRuns.get(e);if(r?.runId===n){this.backgroundRuns.delete(e),this.enqueueChildCompletion(e,n,t),this.maybeCleanupReleasedSession(e);try{this.onSessionCompleted?.(e,t)}catch(t){YC.Jz.error("[LocalSubagentHostAdapter] onSessionCompleted threw after background run",{agentId:e,error:t instanceof Error?t.message:String(t)})}}return t})).finally((()=>this.backgroundPromises.delete(s)))}maybeCleanupReleasedSession(e){this.pendingReleaseSessions.has(e)&&!this.isBackgroundRunBusy(e)&&this.cleanupSession(e)}cleanupSession(e){this.pendingReleaseSessions.delete(e);const t=this.sessions.get(e);if(!t)return;const r=this.parentChildIds.get(e);if(r)for(const e of r)this.childParentIds.delete(e);this.removeParentChildLink(e),this.parentChildIds.delete(e),this.queuedChildCompletions.delete(e),this.childCompletionWaiters.delete(e),t.transcriptWriter.waitForPendingWrites().catch((()=>{})),this.sessions.delete(e),this.onSessionReleased?.(e)}async executeSubagent(e,t,r,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{return{status:"error",error:"Subagent was aborted by the user"}}if(0===a.length)return i;const c=this.buildChildrenCompletedMessage(a,n.childrenCompletedMessageTemplate);if(i=await this.runContinuationLoop(e,t,new so.Pw({...r,prompt:c,resumeAgentId:t,runInBackground:!1}),o,n,s),"completed"!==i.status)return i}return i}async runContinuationLoop(e,t,r,o,n,s){let i,a,c=0;for(let l=0;l<s;l++){if(e.signal.aborted)return{status:"error",error:"Subagent was aborted by the user"};const s=0===l?r.prompt:this.computeContinuationNudge(n,c,i),u=0===l?new so.Pw({...r,runInBackground:!1}):new so.Pw({...r,prompt:s,resumeAgentId:t,runInBackground:!1});if(a=await this.executeSubagentOnce(e,t,u,o),"completed"!==a.status)return a;const d=a.toolCallCount??0,h=a.finalMessage??"";if(void 0!==i&&h.includes(i))return a;d>0?(c=0,i=void 0):(c+=1,i=c>=n.idleThreshold?`DONE_${(0,Co.C)().replace(/-/g,"").slice(0,8)}`:void 0)}return a??{status:"error",error:"Subagent continuation exited unexpectedly"}}computeContinuationNudge(e,t,r){return t>=e.idleThreshold&&void 0!==r?e.escapeMessageTemplate.replace("{idle_count}",String(t)).replace("{escape_token}",r):e.nudgeMessage}async executeSubagentOnce(e,t,r,o){let n,s=0;const i=new Nr.QFf({action:{case:"userMessageAction",value:new Nr.Vtf({userMessage:new Nr.RGk({text:r.prompt})})}}),a=new Nr.Gmx({modelId:r.modelId,displayModelId:r.modelId,displayName:r.modelId});void 0!==r.credentials.case&&(a.credentials=r.credentials);const c=new QC,l={sendUpdate:async(e,r)=>{"tokenDelta"===r.message.case&&this.onSubagentTokenDelta?.(t,r.message.value.tokens),"toolCallStarted"!==r.message.case&&"toolCallCompleted"!==r.message.case&&"partialToolCall"!==r.message.case||this.onInteractionUpdate?.(t,r),"toolCallCompleted"===r.message.case&&s++,"textDelta"===r.message.case&&(n=(n??"")+r.message.value.text)},query:async(e,t)=>function(e){const t=e.query.case;switch(t){case"webSearchRequestQuery":return zr(e.id,"Web search is not supported in local subagent");case"webFetchRequestQuery":return Vr(e.id,"Web fetch is not supported in local subagent");case"switchModeRequestQuery":return Zr(e.id,"Subagent mode switches are not supported in local subagent");case"askQuestionInteractionQuery":{const t=new kn.tz({result:{case:"rejected",value:new kn.ox({reason:"Interactive questions are not supported in local subagent mode"})}});return Jr(e.id,t)}default:throw new Error(`Unhandled interaction query type in local subagent: ${String(t)}`)}}(t)},u={handleCheckpoint:async(e,t)=>{await o.agentStore.handleCheckpoint(e,t),o.transcriptWriter.writeFromState(e,t)},getLatestCheckpoint:()=>o.agentStore.getLatestCheckpoint()};try{const d=r.rootParentConversationId?.trim(),h=r.parentConversationId?.trim(),p=void 0!==d&&""!==d?d:void 0!==h&&""!==h?h:t,f=await this.getResources({agentId:t,parentAgentId:r.parentConversationId}),m=r.readonly?new V(f,function(e){const t=[q(kr,Cr(e.errorMessage)),q(ie,xr(e.errorMessage)),q(At,_r(e.errorMessage))];return e.wrapShell&&t.push(q(br,function(e){return{execute:async(t,r)=>new yr.W4({result:{case:"permissionDenied",value:Er(e,r)}})}}(e.errorMessage)),q(Sr,function(e){return{async*execute(t,r){yield new yr.FI({event:{case:"permissionDenied",value:Er(e,r)}})}}}(e.errorMessage)),q(ee,function(e){return{execute:async(t,r)=>new gr.Lt({result:{case:"permissionDenied",value:Er(e,r)}})}}(e.errorMessage))),e.includeWriteBackgroundShellStdin&&t.push(q(te,function(e){return{execute:async(t,r)=>new gr.nt({result:{case:"error",value:new gr.Gv({error:e})}})}}(e.errorMessage))),t}({errorMessage:"This operation is not allowed in readonly mode. The subagent was launched with readonly: true, which restricts shell, write, delete, and MCP operations.",wrapShell:!0,includeWriteBackgroundShellStdin:!0})):f;return await this.agentClient.run(e,o.agentStore.getConversationStateStructure(),i,a,l,m,o.agentStore.getBlobStore(),c,u,[...this.mcpTools],{conversationGroupId:p,conversationId:t,...o.transcriptWriter.parentConversationId?{transcriptParentConversationId:o.transcriptWriter.parentConversationId}:{},subagentTypeName:r.subagentType||void 0,headers:tx(o.agentStore.getMetadata("blobEncryptionKey"),this.headers),endlessRetries:this.endlessRetries,subagentModelOverrides:[]}),await o.transcriptWriter.writeTurnEndedFromState(e,o.agentStore.getConversationStateStructure(),e.signal.aborted?{status:"aborted",error:CI}:{status:"success"}),{status:"completed",finalMessage:n,toolCallCount:s}}catch(r){const n=r instanceof Error?r.message:String(r);return YC.Jz.error("[LocalSubagentHostAdapter] Subagent session failed",{agentId:t,error:n}),await o.transcriptWriter.writeTurnEndedFromState(e,o.agentStore.getLatestCheckpoint()??o.agentStore.getConversationStateStructure(),this.getTurnEndedFromError(e,n)),e.signal.aborted?{status:"aborted",error:CI}:{status:"error",error:n}}}getTurnEndedFromError(e,t){return e.signal.aborted?{status:"aborted",error:CI}:{status:"error",error:t}}isAwaitBackgroundMode(e){if(!Boolean(e.resumeAgentId&&!po(e.prompt)&&!0===e.readonly&&!0!==e.runInBackground))return!1;if(0===(e.parentConversationId??"").trim().length)throw new Error(`Missing parentConversationId for subagent await/status check (subagentId: ${e.resumeAgentId})`);return!0}async awaitBackgroundRun(e,t){const r=this.backgroundRuns.get(e);return r?this.awaitBackgroundEntry(r,t):this.isBackgroundRunBusy(e)?this.awaitBusyLifecycleRun(e,t):{status:"error",error:`No background subagent found for id: ${e}`}}async awaitBackgroundRunBounded(e,t){const r=t.agentId;if(e.signal.aborted)return new so.zJ({result:{case:"stillRunning",value:new so.L5({agentId:r})}});const o=this.backgroundRuns.get(r);if(void 0===o){const e=this.takeQueuedChildCompletion(r);return void 0!==e?"success"===e.status?new so.zJ({result:{case:"complete",value:new so.bE({agentId:r,finalMessage:e.finalMessage,toolCallCount:e.toolCallCount??0})}}):new so.zJ({result:{case:"error",value:new so.Y({agentId:r,error:e.finalMessage||"Subagent was aborted"})}}):this.isBackgroundRunBusy(r)?new so.zJ({result:{case:"stillRunning",value:new so.L5({agentId:r})}}):new so.zJ({result:{case:"notFound",value:new so.Hq({agentId:r})}})}const[n,s]=e.withTimeoutAndCancel(Math.max(0,t.timeoutMs)),i=await new Promise((e=>{const t=()=>e(void 0);n.signal.addEventListener("abort",t,{once:!0}),o.promise.then(e).finally((()=>{n.signal.removeEventListener("abort",t),s()}))}));return void 0===i||"background"===i.status||e.signal.aborted?new so.zJ({result:{case:"stillRunning",value:new so.L5({agentId:r})}}):(this.takeQueuedChildCompletion(r,o.runId),"completed"===i.status?new so.zJ({result:{case:"complete",value:new so.bE({agentId:r,finalMessage:i.finalMessage,toolCallCount:i.toolCallCount??0})}}):new so.zJ({result:{case:"error",value:new so.Y({agentId:r,error:i.error??"Subagent was aborted"})}}))}takeQueuedChildCompletion(e,t){for(const[r,o]of this.queuedChildCompletions){const n=o.findIndex((r=>r.agentId===e&&(void 0===t||r.runId===t)));if(-1===n)continue;const[s]=o.splice(n,1);return 0===o.length&&this.queuedChildCompletions.delete(r),s}}async awaitBusyLifecycleRun(e,t){for(;this.isBackgroundRunBusy(e);){if(t.aborted)return{status:"error",error:"Await timed out while task is still running"};const r=this.backgroundRuns.get(e);if(r)return this.awaitBackgroundEntry(r,t);await new Promise((e=>setTimeout(e,50)))}return{status:"completed",toolCallCount:0}}async awaitBackgroundEntry(e,t){if(t.aborted)return{status:"error",error:"Await timed out while task is still running"};const r={status:"error",error:"Await timed out while task is still running"};return new Promise((o=>{const n=()=>{o(r)};t.addEventListener("abort",n,{once:!0}),e.promise.then(o).finally((()=>t.removeEventListener("abort",n)))}))}registerParentChildLink(e,t){const r=t?.trim();if(!r||r===e||!this.sessions.has(r)&&r!==this.parentConversationId)return;const o=this.childParentIds.get(e);if(o===r)return;o&&(this.parentChildIds.get(o)?.delete(e),0===(this.parentChildIds.get(o)?.size??0)&&this.parentChildIds.delete(o)),this.childParentIds.set(e,r);const n=this.parentChildIds.get(r)??new Set;n.add(e),this.parentChildIds.set(r,n)}removeParentChildLink(e){const t=this.childParentIds.get(e);if(!t)return;this.childParentIds.delete(e);const r=this.parentChildIds.get(t);r?.delete(e),0===(r?.size??0)&&this.parentChildIds.delete(t)}enqueueChildCompletion(e,t,r){const o=this.childParentIds.get(e);if(!o)return;const n=this.queuedChildCompletions.get(o)??[];n.push({agentId:e,runId:t,status:"completed"===r.status?"success":"error"===r.status?"error":"aborted",finalMessage:"completed"===r.status?r.finalMessage??"":"error"===r.status?r.error:"Subagent was aborted by the user",..."completed"===r.status&&void 0!==r.toolCallCount?{toolCallCount:r.toolCallCount}:{}}),this.queuedChildCompletions.set(o,n),this.removeParentChildLink(e);const s=this.childCompletionWaiters.get(o);if(s){this.childCompletionWaiters.delete(o);for(const e of s)e()}}async collectAvailableChildCompletions(e,t){const r=this.drainChildCompletions(e);return r.length>0?r:this.hasPendingChildSubagents(e)?(await this.waitForChildCompletion(e,t),this.drainChildCompletions(e)):[]}hasPendingChildSubagents(e){return(this.parentChildIds.get(e)?.size??0)>0}drainChildCompletions(e){const t=this.queuedChildCompletions.get(e)??[];return this.queuedChildCompletions.delete(e),t}async waitForChildCompletion(e,t){if(t.aborted)throw new Error("aborted");await new Promise(((r,o)=>{const n=this.childCompletionWaiters.get(e)??new Set,s=()=>{a(),r()},i=()=>{a(),o(new Error("aborted"))},a=()=>{n.delete(s),0===n.size&&this.childCompletionWaiters.delete(e),t.removeEventListener("abort",i)};n.add(s),this.childCompletionWaiters.set(e,n),t.addEventListener("abort",i,{once:!0})}))}buildChildrenCompletedMessage(e,t){const r=e.map((e=>{const t="success"===e.status?"SUCCESS":"FAILED";return`## Agent ${e.agentId} -- ${t}\n\n${e.finalMessage}`})).join("\n\n---\n\n");return t.replace("{summaries}",r)}}var _I=r("../proto/dist/generated/agent/v1/agent_service_connect.js"),PI=r("../proto/dist/generated/agent/v1/requested_model_pb.js"),II=r("../proto/dist/generated/agent/v1/selected_context_pb.js"),RI=r("./src/agent/analytics.ts"),TI=r("../proto/dist/generated/agent/v1/todo_tool_pb.js");const AI={[Mf.w3.UNSPECIFIED]:"unspecified",[Mf.w3.LEFT]:"left",[Mf.w3.RIGHT]:"right",[Mf.w3.MIDDLE]:"middle",[Mf.w3.BACK]:"back",[Mf.w3.FORWARD]:"forward"},MI={[Mf.Dh.UNSPECIFIED]:"unspecified",[Mf.Dh.UP]:"up",[Mf.Dh.DOWN]:"down",[Mf.Dh.LEFT]:"left",[Mf.Dh.RIGHT]:"right"},DI={[Mf.EB.UNSPECIFIED]:"unspecified",[Mf.EB.TAP]:"tap",[Mf.EB.DOWN]:"down",[Mf.EB.UP]:"up"};function OI(e){return AI[e]??"unspecified"}function NI(e){return void 0===e?void 0:{x:e.x,y:e.y}}function $I({result:e}){switch(e.case){case"success":return{status:"success",value:{actionCount:e.value.actionCount,durationMs:e.value.durationMs,settleMs:e.value.settleMs,screenshotPath:e.value.screenshotPath,cursorPosition:NI(e.value.cursorPosition),log:e.value.log}};case"error":return{status:"error",error:{message:e.value.error,actionCount:e.value.actionCount,durationMs:e.value.durationMs,screenshotPath:e.value.screenshotPath,log:e.value.log}};default:return}}function FI(e,t){switch(e.message.case){case"textDelta":return{type:"text-delta",text:e.message.value.text};case"thinkingDelta":return{type:"thinking-delta",text:e.message.value.text};case"thinkingCompleted":return{type:"thinking-completed",thinkingDurationMs:e.message.value.thinkingDurationMs};case"userMessageAppended":return{type:"user-message-appended",userMessage:{type:"user_message",session_id:t,text:e.message.value.userMessage?.text??""}};case"tokenDelta":return{type:"token-delta",tokens:e.message.value.tokens};case"summary":return{type:"summary",summary:e.message.value.summary};case"summaryStarted":return{type:"summary-started"};case"summaryCompleted":return{type:"summary-completed"};case"shellOutputDelta":return{type:"shell-output-delta",event:e.message.value.event.case?{case:e.message.value.event.case,value:e.message.value.event.value?.toJson?.()??e.message.value.event.value}:{}};case"toolCallStarted":return jI("tool-call-started",e.message.value);case"partialToolCall":return jI("partial-tool-call",e.message.value);case"toolCallCompleted":return jI("tool-call-completed",e.message.value);case"heartbeat":return null;case"turnEnded":{const t=e.message.value;return{type:"turn-ended",...(void 0!==t.inputTokens||void 0!==t.outputTokens||void 0!==t.cacheReadTokens||void 0!==t.cacheWriteTokens)&&{usage:{inputTokens:Number(t.inputTokens??BigInt(0)),outputTokens:Number(t.outputTokens??BigInt(0)),cacheReadTokens:Number(t.cacheReadTokens??BigInt(0)),cacheWriteTokens:Number(t.cacheWriteTokens??BigInt(0)),...t.reasoningTokens&&{reasoningTokens:Number(t.reasoningTokens)}}}}}case"toolCallDelta":{const r=e.message.value,o=r.toolCallDelta;if("taskToolCallDelta"!==o?.delta.case)return null;const n=o.delta.value.interactionUpdate;if(void 0===n)return null;const s=FI(n,t);return null!==s&&function(e){switch(e.type){case"text-delta":case"thinking-delta":case"thinking-completed":case"tool-call-started":case"tool-call-completed":case"partial-tool-call":case"step-started":case"step-completed":case"tool-requests-listed":return!0;default:return!1}}(s)?{type:"tool-call-delta",callId:r.callId,modelCallId:r.modelCallId,taskUpdate:s}:null}case"stepStarted":return{type:"step-started",stepId:Number(e.message.value.stepId)};case"toolRequestsListed":return{type:"tool-requests-listed",callCount:e.message.value.callCount};case"stepCompleted":return{type:"step-completed",stepId:Number(e.message.value.stepId),stepDurationMs:Number(e.message.value.stepDurationMs)};case"postRequestPrompt":case"activeBranchChange":case"feedbackRequest":case"responseComparison":case"contextInjectionState":case"routedModel":case"grokBotNudge":case"thinkingNote":case"voiceCallUtterance":case void 0:return null;default:return e.message,null}}function jI(e,t){const r=function(e){if(!e?.tool)return null;switch(e.tool.case){case"shellToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"shell",args:{command:t.command,...t.workingDirectory?{workingDirectory:t.workingDirectory}:{},...t.timeout?{timeout:t.timeout}:{}},...r?{result:qI(r)}:{}}:null}case"deleteToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"delete",args:{path:t.path},...r?{result:zI(r)}:{}}:null}case"globToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"glob",args:{globPattern:t.globPattern,...t.targetDirectory?{targetDirectory:t.targetDirectory}:{}},...r?{result:GI(r)}:{}}:null}case"grepToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"grep",args:{pattern:t.pattern,...t.path?{path:t.path}:{},...t.glob?{glob:t.glob}:{},...t.outputMode?{outputMode:t.outputMode}:{},...t.contextBefore?{contextBefore:t.contextBefore}:{},...t.contextAfter?{contextAfter:t.contextAfter}:{},...t.context?{context:t.context}:{},...t.caseInsensitive?{caseInsensitive:t.caseInsensitive}:{},...t.type?{type:t.type}:{},...t.headLimit?{headLimit:t.headLimit}:{},...void 0!==t.offset?{offset:t.offset}:{},...t.multiline?{multiline:t.multiline}:{},...t.sort?{sort:t.sort}:{},...t.sortAscending?{sortAscending:t.sortAscending}:{}},...r?{result:VI(r)}:{}}:null}case"readToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"read",args:{path:t.path},...r?{result:KI(r)}:{}}:null}case"editToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"edit",args:{path:t.path},...r?{result:ZI(r)}:{}}:null}case"lsToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"ls",args:{path:t.path,...t.ignore&&t.ignore.length>0?{ignore:t.ignore}:{}},...r?{result:XI(r)}:{}}:null}case"readLintsToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"readLints",args:{paths:t.paths},...r?{result:YI(r)}:{}}:null}case"mcpToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"mcp",args:{...t.providerIdentifier?{providerIdentifier:t.providerIdentifier}:{},...t.toolName?{toolName:t.toolName}:{},...t.args?{args:Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t.toJson()])))}:{}},...r?{result:eR(r)}:{}}:null}case"generateImageToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"generateImage",args:{description:t.description,...t.filePath?{filePath:t.filePath}:{}},...r?{result:rR(r)}:{}}:null}case"recordScreenToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"recordScreen",args:{mode:oR(t.mode)},...r?{result:nR(r)}:{}}:null}case"semSearchToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"semSearch",args:{query:t.query,...t.targetDirectories&&t.targetDirectories.length>0?{targetDirectories:t.targetDirectories}:{},...t.explanation?{explanation:t.explanation}:{}},...r?{result:tR(r)}:{}}:null}case"createPlanToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"createPlan",args:{plan:t.plan},...r?{result:sR(r)}:{}}:null}case"updateTodosToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"updateTodos",args:{todos:t.todos.map((e=>({content:e.content,status:aR(e.status)})))},...r?{result:iR(r)}:{}}:null}case"fetchToolCall":case"switchModeToolCall":return null;case"computerUseToolCall":return function({args:e,result:t}){return e?{type:"computerUse",args:{actions:e.actions.flatMap((e=>function({action:e}){switch(e.case){case"mouseMove":return{type:"mouseMove",coordinate:NI(e.value.coordinate)};case"click":return{type:"click",coordinate:NI(e.value.coordinate),button:OI(e.value.button),count:e.value.count,modifierKeys:e.value.modifierKeys};case"mouseDown":case"mouseUp":return{type:e.case,button:OI(e.value.button)};case"drag":return{type:"drag",path:e.value.path.map((e=>({x:e.x,y:e.y}))),button:OI(e.value.button),modifierKeys:e.value.modifierKeys};case"scroll":return{type:"scroll",coordinate:NI(e.value.coordinate),direction:MI[e.value.direction]??"unspecified",amount:e.value.amount,modifierKeys:e.value.modifierKeys};case"type":return{type:"type",text:e.value.text};case"key":return{type:"key",key:e.value.key,holdDurationMs:e.value.holdDurationMs,stroke:DI[e.value.stroke]??"unspecified"};case"wait":return{type:"wait",durationMs:e.value.durationMs};case"screenshot":case"cursorPosition":return{type:e.case};default:return}}(e)??[])),description:e.description},result:t?$I(t):void 0}:null}(e.tool.value);case"readTodosToolCall":case"webSearchToolCall":case"listMcpResourcesToolCall":case"readMcpResourceToolCall":return null;case"taskToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"task",args:LI(t),...r?{result:WI(r)}:{}}:null}case"applyAgentDiffToolCall":case"askQuestionToolCall":case"writeShellStdinToolCall":case"reflectToolCall":case"setupVmEnvironmentToolCall":case"replaceEnvToolCall":case"startGrindExecutionToolCall":case"startGrindPlanningToolCall":case"truncatedToolCall":case"webFetchToolCall":case"reportBugfixResultsToolCall":case"aiAttributionToolCall":case"prManagementToolCall":case"editPrLabelsToolCall":case"fetchCloudAgentDataToolCall":case"mcpAuthToolCall":case"connectScmToolCall":case"searchConversationsToolCall":case"awaitToolCall":case"blameByFilePathToolCall":case"getMcpToolsToolCall":case"reportBugToolCall":case"setActiveBranchToolCall":case"communicateUpdateToolCall":case"sendFinalSummaryToolCall":case"updateOriginPrCodeTourToolCall":case"getOriginPrCodeTourToolCall":case"recordCiInvestigationFindingsToolCall":case"sendMessageToolCall":case"sendToUserToolCall":case"createGoalToolCall":case"updateGoalToolCall":case"getAgentStatusToolCall":case"sendToAgentToolCall":case"readAgentTranscriptToolCall":case"createAgentToolCall":case"createProjectToolCall":case"stopAgentToolCall":case"listTrackedTasksToolCall":case"createTrackedTasksToolCall":case"updateTrackedTasksToolCall":case"deleteTrackedTasksToolCall":case"updateTrackedTaskStatusesToolCall":case"updateTrackedTaskTagsToolCall":case"piReadToolCall":case"piBashToolCall":case"piEditToolCall":case"piWriteToolCall":case"piGrepToolCall":case"piFindToolCall":case"piLsToolCall":case"writeCanvasToolCall":case"readCanvasToolCall":case"generateVideoToolCall":case"xSearchToolCall":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 LI(e){return{description:e.description??"",prompt:e.prompt??"",...e.subagentType?{subagentType:UI(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:BI(e.mode)}:{},...e.respondingToMessageIds&&e.respondingToMessageIds.length>0?{respondingToMessageIds:e.respondingToMessageIds}:{}}}function UI(e){const t=e.type.case;return t?"custom"===t?{kind:t,name:e.type.value.name}:{kind:t}:{kind:"unspecified"}}function BI(e){switch(e){case io.FL.AGENT:return"agent";case io.FL.PLAN:return"plan";default:return"unspecified"}}function WI(e){if(e.result?.case)switch(e.result.case){case"success":{const t=e.result.value;return{status:"success",value:{...t.conversationSteps&&t.conversationSteps.length>0?{conversationSteps:t.conversationSteps.map((e=>e.toJson?.()??e))}:{},...t.agentId?{agentId:t.agentId}:{},isBackground:t.isBackground??!1,...void 0!==t.durationMs?{durationMs:Number(t.durationMs)}:{},...t.resultSuffix?{resultSuffix:t.resultSuffix}:{},backgroundReason:HI(t.backgroundReason),...t.transcriptPath?{transcriptPath:t.transcriptPath}:{}}}}case"error":return{status:"error",error:{message:e.result.value.error??"Task failed"}};default:return}}function HI(e){switch(e){case io.qL.AGENT_REQUEST:return"agentRequest";case io.qL.USER_REQUEST:return"userRequest";case io.qL.QUEUED_FOLLOW_UP:return"queuedFollowUp";default:return"unspecified"}}function qI(e){if(e.result?.case)switch(e.result.case){case"success":case"failure":{const t=e.result.value;return{status:"success",value:{exitCode:t.exitCode??0,signal:t.signal??"",stdout:t.stdout??"",stderr:t.stderr??"",executionTime:t.executionTime??0}}}case"timeout":return{status:"error",error:{message:`Command timed out after ${e.result.value.timeoutMs}ms`,command:e.result.value.command,workingDirectory:e.result.value.workingDirectory}};case"rejected":return{status:"error",error:{message:e.result.value.reason??"Command rejected",command:e.result.value.command,workingDirectory:e.result.value.workingDirectory}};case"spawnError":return{status:"error",error:{message:e.result.value.error??"Failed to spawn command",command:e.result.value.command,workingDirectory:e.result.value.workingDirectory}};default:return}}function zI(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{fileSize:Number(e.result.value.fileSize??0)}}:{status:"error",error:{message:e.result.value.error??e.result.value.reason??e.result.value.clientVisibleError??e.result.case,path:e.result.value.path}}}function GI(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{files:e.result.value.files??[],totalFiles:e.result.value.totalFiles??0,clientTruncated:e.result.value.clientTruncated??!1,ripgrepTruncated:e.result.value.ripgrepTruncated??!1}}:{status:"error",error:{message:e.result.value.error??e.result.value.reason??e.result.case}}}function VI(e){if(e.result?.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]=JI(o);return{status:"success",value:{...Object.keys(r).length>0?{workspaceResults:r}:{},...t.activeEditorResult?{activeEditorResult:JI(t.activeEditorResult)}:{}}}}return{status:"error",error:{message:e.result.value.error??e.result.case}}}}function JI(e){if(e?.result?.case)switch(e.result.case){case"content":return{type:"content",output:{matches:e.result.value.matches?.map((e=>({file:e.file,...void 0!==e.lineNumber?{lineNumber:e.lineNumber}:{},line:e.line,...e.beforeContext?{beforeContext:e.beforeContext}:{},...e.afterContext?{afterContext:e.afterContext}:{}})))??[],totalMatches:e.result.value.totalMatches??0}};case"files":return{type:"files",output:{files:e.result.value.files??[],count:e.result.value.count??0}};case"count":return{type:"count",output:{counts:e.result.value.counts?.map((e=>({file:e.file,count:e.count})))??[],total:e.result.value.total??0}};default:return}}function KI(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{content:"content"===e.result.value.output.case?e.result.value.output.value:"",totalLines:e.result.value.totalLines??0,fileSize:Number(e.result.value.fileSize??0)}}:{status:"error",error:{message:e.result.value.error??e.result.value.reason??e.result.case,path:e.result.value.path}}}function ZI(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{...void 0!==e.result.value.linesAdded?{linesAdded:e.result.value.linesAdded}:{},...void 0!==e.result.value.linesRemoved?{linesRemoved:e.result.value.linesRemoved}:{},...e.result.value.diffString?{diffString:e.result.value.diffString}:{}}}:{status:"error",error:{message:e.result.value.error??e.result.value.reason??e.result.case,path:e.result.value.path}}}function XI(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{directoryTreeRoot:QI(e.result.value.directoryTreeRoot)}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function QI(e){if(e)return{absPath:e.absPath??"",childrenDirs:e.childrenDirs?.map(QI)??[],childrenFiles:e.childrenFiles?.map((e=>({name:e.name})))??[],childrenWereProcessed:e.childrenWereProcessed??!1,fullSubtreeExtensionCounts:e.fullSubtreeExtensionCounts??{},numFiles:e.numFiles??0}}function YI(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{fileDiagnostics:e.result.value.fileDiagnostics?.map((e=>({path:e.path,diagnostics:e.diagnostics?.map((e=>({severity:cR(e.severity),...e.range?{range:{...e.range.start?{start:{line:e.range.start.line,character:e.range.start.character}}:{},...e.range.end?{end:{line:e.range.end.line,character:e.range.end.character}}:{}}}:{},message:e.message,source:e.source,code:e.code})))??[],diagnosticsCount:e.diagnosticsCount??0})))??[],totalFiles:e.result.value.totalFiles??0,totalDiagnostics:e.result.value.totalDiagnostics??0}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function eR(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{content:e.result.value.content?.map((e=>{const t={};return"text"===e.content?.case?t.text={text:e.content.value.text}:"image"===e.content?.case&&(t.image={data:e.content.value.data,...e.content.value.mimeType?{mimeType:e.content.value.mimeType}:{}}),t}))??[],isError:e.result.value.isError??!1}}:{status:"error",error:{message:e.result.value.error??e.result.value.reason??e.result.case}}}function tR(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{results:e.result.value.results??""}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function rR(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{filePath:e.result.value.filePath??""}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function oR(e){switch(e){case nE.$u.START_RECORDING:return"START_RECORDING";case nE.$u.SAVE_RECORDING:return"SAVE_RECORDING";case nE.$u.DISCARD_RECORDING:return"DISCARD_RECORDING";default:throw new Error(`Unknown RecordingMode: ${e}`)}}function nR(e){if(e.result?.case)switch(e.result.case){case"startSuccess":return{status:"success",value:{wasPriorRecordingCancelled:e.result.value.wasPriorRecordingCancelled??!1}};case"saveSuccess":return{status:"success",value:{path:e.result.value.path??"",recordingDurationMs:Number(e.result.value.recordingDurationMs??0)}};case"discardSuccess":return{status:"success",value:{}};case"failure":return{status:"error",error:{message:e.result.value.error??"Unknown error"}};default:return}}function sR(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function iR(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{todos:e.result.value.todos?.map((e=>({content:e.content,status:aR(e.status)})))??[],totalCount:e.result.value.totalCount??0}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function aR(e){switch(e){case TI.Vj.UNSPECIFIED:case TI.Vj.PENDING:return"pending";case TI.Vj.IN_PROGRESS:return"inProgress";case TI.Vj.COMPLETED:return"completed";case TI.Vj.CANCELLED:return"cancelled";default:return"pending"}}function cR(e){switch(e){case gb.h_.UNSPECIFIED:case gb.h_.ERROR:return"error";case gb.h_.WARNING:return"warning";case gb.h_.INFORMATION:return"information";case gb.h_.HINT:return"hint";default:return"error"}}const lR={type:"object",properties:{},additionalProperties:!0};function uR(e){return"text"===e.type?new Lt._Z({content:{case:"text",value:new Lt.zN({text:e.text})}}):new Lt._Z({content:{case:"image",value:new Lt.do({data:o.Buffer.from(e.data,"base64"),mimeType:e.mimeType??""})}})}function dR(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var hR=r("./src/agent/errors.ts"),pR=r("./src/agent/executor-common.ts"),fR=r("./src/agent/native/vendored-tree-sitter.ts"),mR=r("./src/agent/platform-package-locator.ts"),gR=r("./src/agent/sdk-config.ts"),wR=r("../../node_modules/.pnpm/@statsig+js-client@3.31.0/node_modules/@statsig/js-client/src/index.js"),yR=r("./src/agent/utils/logger.ts");const vR={checkFeatureGate:()=>!1,getDynamicConfigValue:({defaultValue:e})=>e},bR=new Map;var SR=r("./src/agent/tools-option.ts");class kR{async requestApproval(){return{approved:!0}}}function ER(e,t){if(!function(e){return void 0!==e&&Object.keys(e).length>0}(t))return;const r=e.resources.base;if(!(r instanceof hC))throw new hR.j1("SDK custom tools require the default local workspace resource provider.",{isRetryable:!1});const o=r.getMcpExecutionPolicyDeps(),n=r.get(At),s=function(e,t){return{async execute(r,o,n){const s=o.toolName||function(e){const t=`${kt}-`;return e.startsWith(t)?e.slice(t.length):e}(o.name),i=e[s];if(void 0===i)return new Lt.iz({result:{case:"error",value:new Lt.Nh({error:`Unknown custom tool: ${s}`})}});try{return function(e){const t=function(e){return"object"==typeof(t=e)&&null!==t&&!Array.isArray(t)&&"content"in t&&Array.isArray(t.content)?{content:e.content,isError:e.isError,structuredContent:e.structuredContent}:"string"==typeof e?{content:[{type:"text",text:e}]}:{content:[{type:"text",text:JSON.stringify(e)}],structuredContent:dR(e)?e:void 0};var t}(e),r=void 0!==t.structuredContent?qt.Struct.fromJson(t.structuredContent):void 0;return new Lt.iz({result:{case:"success",value:new Lt.QW({content:t.content.map(uR),isError:t.isError??!1,structuredContent:r})}})}(await i.execute(function(e){return Object.fromEntries(Object.entries(e.args).map((([e,t])=>[e,t.toJson()])))}(o),{toolCallId:o.toolCallId||void 0,...void 0===t||""===t?{}:{sessionId:t}}))}catch(e){return new Lt.iz({result:{case:"error",value:new Lt.Nh({error:e instanceof Error?e.message:String(e)})}})}}}}(t,e.state.sessionId),i=new kR;e.resources.base.register(At,{async execute(e,t,r){if(function(e){return e.providerIdentifier===kt}(t)){const n=await _y(e,t,{...o,pendingDecisionProvider:i,toolDef:{source:"internal"}});return void 0!==n?n:s.execute(e,t,r)}return n.execute(e,t,r)}})}function CR(){const e=process.env.CURSOR_SDK_MOCK_PROMPT_TIME;if(void 0===e||""===e)return;const t=new Date(e);return Number.isNaN(t.getTime())?void 0:t}const xR={warn(){},error(){}},_R={log(){}};class PR{async requestApproval(e){return{approved:!1,reason:`Local SDK runs cannot request interactive approval for ${IR(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 IR(e){switch(e.type){case vm.Shell:return"this shell command";case vm.Mcp:return"this MCP tool call";case vm.Write:return"this file edit";case vm.Delete:return"this file deletion";default:return"this operation"}}function RR(e){return void 0!==e&&"insecure_none"!==e.type}async function TR(e,t){const r="string"==typeof e||void 0===e?{workingDirectory:e,apiKey:t}:e,a=(0,ce.q6)().with(m._O,_R);iI(r.settingSources),function(e){if(void 0!==e&&(!Number.isFinite(e)||e<=0))throw new Error(`Workspace scan cache TTL must be a positive number of milliseconds, got ${e}`);Ma=e}((0,gR.Mu)()),/:\/\/(localhost|127\.0\.0\.1)/.test(pR.EV)&&(process.env.NODE_TLS_REJECT_UNAUTHORIZED="0");const c=performance.now();let l=0;if(r.apiKey){const e=performance.now();await Promise.all([(0,pR.ly)(r.apiKey),(0,pR.mU)(r.apiKey)]),l=performance.now()-e}const u=r.workingDirectory||process.cwd();(0,fR.configureVendoredTreeSitterWorkspaceDir)(u);for(const e of r.dirs??[])(0,fR.configureVendoredTreeSitterWorkspaceDir)(e);const d=(0,As.Rv)((0,n.homedir)(),u);let h;const p="win32"===process.platform?"rg.exe":"rg",f=process.env.CURSOR_RIPGREP_PATH;h=f&&(0,s.isAbsolute)(f)?f:(0,mR.hQ)({binaryName:p,excludedWorkspaceDir:u}),h||(h=(0,Fs.xS)()),h&&(0,Fs.J)(h);let g,w={getDotCursorProtection:async()=>!1,getShouldBlockMcp:async()=>!1,getDeleteFileProtection:async()=>!1,getIsHeadlessDisabled:async()=>!1,isServerBlocked:async()=>!1,getTeamRepos:async()=>{},getAutoRunControls:async()=>({enabled:!1,allowed:[],blocked:[],enableAllowlistMode:!0,enableRunEverything:!1,enableSmartAuto:!0,mcpToolAllowlist:[]}),getAdminCommandDenylist:async()=>({rules:[]}),getMcpToolControls:async()=>{},getNetworkAccessControls:async()=>({allowlist:[],denylist:[],available:!0}),getMcpNetworkControlsConfig:async()=>({enabled:!1}),getDefaultNetworkAllowlist:async()=>({allowlist:[],available:!0}),getSandboxingControls:async()=>({sandboxingDisabled:!1,networkingDisabled:!1,gitDisabled:!1}),isAttributionDisabledByAdmin:async()=>!1,invalidateCache:()=>{}};if(r.apiKey)try{g=(0,pR.KU)(r.apiKey,r.teamId);const e=(0,xo.createClient)(AP.I,g),t=function(e){let t=bR.get(e);return t||(t=async function(e){try{const t=await async function(e){const t=await(0,pR.dC)(e,pR.EV);if(!t)return;const r=pR.EV.endsWith("/")?pR.EV.slice(0,-1):pR.EV,o=await fetch(`${r}/aiserver.v1.AnalyticsService/BootstrapStatsig`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json","x-cursor-client-type":"sdk","x-cursor-client-version":(0,pR.tF)(),"x-ghost-mode":(0,pR.U)(e)},body:JSON.stringify({})});if(!o.ok)return void yR.v.log(`Failed to bootstrap SDK Statsig: ${o.status} ${o.statusText}`);const n=await o.json();return"string"==typeof n.config&&n.config.length>0?n.config:void 0}(e);if(!t)return vR;const r=new wR.StatsigClient("client-Bm4HJ0aDjXHQVsoACMREyLNxm5p6zzuzhO50MgtoT5D",function(e){try{const t=JSON.parse(e);if(t.user)return{...t.user,custom:{...t.user.custom,clientType:"sdk",clientVersion:(0,pR.tF)()}}}catch(e){yR.v.log(`Failed to parse SDK Statsig bootstrap user: ${e instanceof Error?e.message:String(e)}`)}return{custom:{clientType:"sdk",clientVersion:(0,pR.tF)()}}}(t),{disableLogging:!0,disableStorage:!0,networkConfig:{preventAllNetworkTraffic:!0}});return r.dataAdapter.setData(t),r.initializeSync(),{checkFeatureGate:(e,t)=>{try{return r.checkGate(e,t)}catch{return!1}},getDynamicConfigValue({configName:e,paramName:t,defaultValue:o}){try{return r.getDynamicConfig(e).get(t,o)}catch{return o}}}}catch(e){return yR.v.log(`Failed to initialize SDK Statsig: ${e instanceof Error?e.message:String(e)}`),vR}}(e),bR.set(e,t),t.then((r=>{r===vR&&bR.get(e)===t&&bR.delete(e)}),(()=>{bR.get(e)===t&&bR.delete(e)}))),t}(r.apiKey),o={getDefaultNetworkAllowlist:async()=>(await t).getDynamicConfigValue({configName:"sandbox_default_network_allowlist",paramName:"allowlist",defaultValue:[]})};w=new JC(new zC(e),o,{isMcpAccessNetworkAllowlistEnabled:async()=>(await t).checkFeatureGate("mcp_access_network_allowlist"),isMcpSettingsOverhaulEnabled:async e=>(await t).checkFeatureGate("mcp_settings_overhaul",e),isWin32UserExtensionStdioUnsandboxEnabled:async e=>(await t).checkFeatureGate("mcp_user_extension_stdio_unsandboxed_win32",e),isAdminCommandDenylistEnforcementKilled:async()=>(await t).checkFeatureGate("admin_command_denylist_enforcement_killswitch")})}catch(e){yR.v.log(`Failed to initialize authenticated dashboard services: ${e instanceof Error?e.message:String(e)}`)}const y=performance.now(),v=r.apiKey?await(0,Fs.tv)(`${(0,n.homedir)()}/.cursor/sandbox.json`,(0,n.homedir)()):void 0,b=void 0!==r.apiKey?await async function(e){const{cwd:t,perUserSandboxPolicy:r,sandboxOptions:o}=e;if(!1===o?.enabled)return{defaultSandboxPolicy:{type:"insecure_none"},defaultSandboxPolicySources:void 0};const n=RR(r)?r:!0===o?.enabled?function(e,t={}){return{type:e,...t}}("workspace_readwrite",{networkPolicy:(0,Fs.Po)()}):void 0;if(void 0===n)return{defaultSandboxPolicy:{type:"insecure_none"},defaultSandboxPolicySources:void 0};if(function(e){const t="win32"===process.platform?"cursorsandbox.exe":"cursorsandbox",r=(0,mR.hQ)({binaryName:t,excludedWorkspaceDir:e});r&&(0,Fs.St)({sandboxBinaryPath:r})}(t),!(0,Fs.K3)(void 0,{ctx:e.initializationCtx}))throw new hR.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}=await(0,Fs.resolveSandboxPolicyForWorkspace)(t,s);return{defaultSandboxPolicy:i,defaultSandboxPolicySources:s}}({cwd:u,perUserSandboxPolicy:v,sandboxOptions:r.sandboxOptions,initializationCtx:a}):void 0,S=performance.now()-y,k=b?.defaultSandboxPolicy,E=b?.defaultSandboxPolicySources,C=RR(k),x=performance.now(),_=(()=>{const e=[],t=new Set;for(const o of[u,...r.dirs??[]]){const r=(0,s.resolve)(o);t.has(r)||(t.add(r),e.push(o))}return e.length>1?e:void 0})(),P=await async function(e){const{workingDirectory:t,projectDir:r}=e,o=function(e,t){const r=[],o=new Set;for(const n of[e,...t??[]]){const e=(0,s.resolve)(n);o.has(e)||(o.add(e),r.push(n))}return r}(t,e.dirs),n=o.length>1?o:void 0,i=iI(e.settingSources),a=e.teamSettingsService??{getDotCursorProtection:async()=>!1,getShouldBlockMcp:async()=>!1,getDeleteFileProtection:async()=>!1,getIsHeadlessDisabled:async()=>!1,isServerBlocked:async()=>!1,getTeamRepos:async()=>{},getAutoRunControls:async()=>({enabled:!1,allowed:[],blocked:[],enableAllowlistMode:!0,enableRunEverything:!1,enableSmartAuto:!0,mcpToolAllowlist:[]}),getAdminCommandDenylist:async()=>({rules:[]}),getMcpToolControls:async()=>{},getNetworkAccessControls:async()=>({allowlist:[],denylist:[],available:!0}),getMcpNetworkControlsConfig:async()=>({enabled:!1}),getDefaultNetworkAllowlist:async()=>({allowlist:[],available:!0}),getSandboxingControls:async()=>({sandboxingDisabled:!1,networkingDisabled:!1,gitDisabled:!1}),isAttributionDisabledByAdmin:async()=>!1,invalidateCache:()=>{}},c=e.defaultSandboxPolicy??{type:"insecure_none"},l=e.getSandboxSupported??(()=>(0,Fs.K3)(c,{ctx:e.initializationCtx})),u=e.getSandboxEnabled??(()=>"insecure_none"!==c.type&&l()),d=new Rm,h=new Ya(d,a,o),p=new mI,f=new gI,m=e.getSmartModeClassifierAutoModeEnabled?.(),g=new fI(m?"allowlist":e.approvalMode??"unrestricted",c,a,e.respectAdminControls??!1),w=e.pendingDecisionProvider,y={executeIndexedGrep:void 0},v=()=>!0,b=aI(i,"plugins"),S=e.importThirdPartyPlugins??!1,k=e.mcpMetaToolEnabled??!0,E=void 0!==e.mcpServers&&Object.keys(e.mcpServers).length>0,C=void 0!==e.customSubagents&&e.customSubagents.length>0,x=E||aI(i,"project")||aI(i,"user")||b,_=aI(i,"project")||aI(i,"user")||aI(i,"mdm"),P=aI(i,"team"),I=P&&void 0!==e.dashboardTransport,R=aI(i,"project")||aI(i,"user")||P||I||b,T={teamSettingsService:a,initializationCtx:e.initializationCtx,importThirdPartyPlugins:S,ignoreApprovals:!0,includeProjectMcp:aI(i,"project"),includeUserMcp:aI(i,"user"),includePluginMcp:b},A=s=>hI({workingDirectory:t,...void 0!==n?{workspaceRoots:n}:{},adapters:{...s.includeMcp?{mcp:kx({...T,inlineMcpServers:e.mcpServers})}:{},...b?{pluginBootstrap:BP({importThirdPartyPlugins:S,dashboardTransport:e.dashboardTransport})}:{},..._?{hooks:TP({includeProjectHooks:aI(i,"project"),includeUserHooks:aI(i,"user"),includeEnterpriseHooks:aI(i,"mdm"),useCommandHookStdinTransport:e.useCommandHookStdinTransport})}:{},...R?{localExtensibility:DP({includeProjectExtensibility:aI(i,"project"),includeUserExtensibility:aI(i,"user"),includeManagedSkills:I,includeTeamExtensibility:P,includePluginExtensibility:b,teamSettingsService:a,getThirdPartyExtensibilityEnabled:v,dashboardTransport:e.dashboardTransport,importThirdPartyPlugins:S})}:{},resourceFactory:ZP({ignoreService:h,grepProvider:y,workspacePaths:o,diagnosticsProvider:p,repositoryProvider:f,projectDir:r??t,shellManager:void 0,defaultSandboxPolicy:c,defaultSandboxPolicySources:e.defaultSandboxPolicySources,getSandboxEnabled:u,getSandboxSupported:l,getNetworkAllowlistInfo:e.getNetworkAllowlistInfo,getSmartModeClassifierAutoModeEnabled:e.getSmartModeClassifierAutoModeEnabled,devForceNextSmartModeClassifierBlockToken:e.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:e.getMockPromptTime,mcpFileOutputThresholdBytes:void 0,mcpMetaToolEnabled:k,createMcpStateAccessor:e=>new wI(new RE(e)),createSessionMcpLease:(e,t)=>kx({...T,inlineMcpServers:t}).createLease({workspaceState:e.workspaceState,services:e.workspaceServices,policy:e.policy}),createSessionDependencies:()=>{const r=w??new pI;return{pendingDecisionStore:r,fileChangeTracker:new Pm(t),permissionsService:new Mk(h,r,g,a,t,e.respectAdminControls??!1)}}}),resourceWrappers:_?[{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 IP(new SP(e.resources,o.hookExecutor,(()=>function(e,t){const r=CP(t,xP,"conversationId","conversation_id")??e.sessionId??"";return{conversation_id:r,generation_id:CP(t,xP,"generationId","generation_id")??r,model:CP(t,xP,"model")??"unknown",...Oe({modelId:CP(t,xP,"modelId","model_id"),modelParams:CP(t,PP,"modelParams","model_params")})}}(e.sessionState,e.metadata)),e.workspaceServices.mcpLease,void 0,void 0,t.hooksConfigLease),o)}}]:[],...C?{workspaceServicesContributors:[{contributeServices:t=>{const r=new yI(e.customSubagents??[]),o=t.services.subagentsService;return{subagentsService:void 0===o?r:new Tf([r,o])}}}]}:{}}});if(!x)return A({includeMcp:!1});try{return await A({includeMcp:!0})}catch(e){return YC.Jz.warn("[default-local-workspace-runtime] Failed to initialize MCP-enabled runtime, retrying without MCP:",{error:e,workingDirectory:t,projectDir:r,enablePlugins:b,importThirdPartyPlugins:S}),A({includeMcp:!1})}}({workingDirectory:u,...void 0!==_?{dirs:_}:{},projectDir:d,teamSettingsService:w,initializationCtx:a,dashboardTransport:g,settingSources:r.settingSources,mcpServers:r.mcpServers,customSubagents:r.customSubagents,defaultSandboxPolicy:k,defaultSandboxPolicySources:E,approvalMode:C?"allowlist":void 0,pendingDecisionProvider:C||!0===r.autoReview?new PR:void 0,getNetworkAllowlistInfo:C?()=>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,Fs.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,Fs.tv)(e,r);t&&"insecure_none"!==t.type&&t.networkPolicy?.allow&&s.push(...t.networkPolicy.allow)}const c=[...new Set(s)];return{hasDefaults:o.available&&o.allowlist.length>0,explicitEntries:c}}(w,(0,n.homedir)(),u):void 0,getSmartModeClassifierAutoModeEnabled:()=>!0===r.autoReview,devForceNextSmartModeClassifierBlockToken:r.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:CR,respectAdminControls:void 0!==r.apiKey,useCommandHookStdinTransport:!0}),I=performance.now()-x;let R,T;return(0,RI.ou)(r.apiKey,{runtime:"local",ensure_ghost_mode_ms:Math.round(l),bootstrap_statsig_ms:0,create_workspace_runtime_ms:Math.round(I),load_sandbox_policy_ms:Math.round(S),total_ms:Math.round(performance.now()-c)}),{run:async(e,t,n)=>(0,YC.ni)(xR,(async()=>{const s=(0,i.VI)((0,ce.q6)().withName("sdk.run").with(m._O,_R)),[a,c]=s.ctx.withCancel(),l=t.sessionId??(0,Co.C)(),d=t.mcpServersOverride,h=void 0===(p=t.customTools)?[]:Object.entries(p).map((([e,t])=>({clientKey:kt,providerIdentifier:kt,toolName:e,name:`${kt}-${e}`,description:t.description??"",inputSchema:t.inputSchema??lR,...void 0===t.outputSchema?{}:{outputSchema:t.outputSchema},...void 0===t.annotations?{}:{annotations:t.annotations},source:"internal"})));var p;let f;f=await P.createSessionRuntime({sessionId:l,mcpServersOverride:d,extraMcpTools:h});const g=new Map;try{const s=f.resources.wrapped;ER(f,t.customTools);const i=t.blobStore??new So.ve;let p=t.initialState??new Nr.Y9z({});const m=void 0!==t.model?new PI.G4({modelId:t.model.id,...!0===t.model.maxMode?{maxMode:!0}:{},parameters:(t.model.params??[]).map((e=>new PI.SR({id:e.id,value:e.value})))}):void 0,y=Array.isArray(e.images)?e.images.map((e=>{const t=(0,Co.C)(),r=new Uint8Array(o.Buffer.from(e.data,"base64")),n=(0,pR.v8)(r);return new II.d({uuid:t,...n?{mimeType:n}:{},dataOrBlobId:{case:"data",value:r}})})):[],v=y.length>0?new II.xv({selectedImages:y}):void 0,b=function(e){switch(e){case"agent":return Nr.xyI.AGENT;case"plan":return Nr.xyI.PLAN;default:return}}(t.mode),S=new Nr.QFf({action:{case:"userMessageAction",value:new Nr.Vtf({userMessage:new Nr.RGk({text:e.text,selectedContext:v,...void 0!==b?{mode:b}:{}})})}}),k={sendUpdate:async(e,t)=>{const r=FI(t,l);null!==r&&await n.sendUpdate(r)},query:async(e,t)=>function(e){switch(e.query.case){case"webSearchRequestQuery":return qr(e.id);case"webFetchRequestQuery":return Gr(e.id);case"switchModeRequestQuery":return Kr(e.id);case"askQuestionInteractionQuery":return Jr(e.id,new kn.tz({result:{case:"rejected",value:new kn.ox({reason:"Interactive questions are not supported in local SDK runs"})}}));case"createPlanRequestQuery":return Xr(e.id,new Fr.bK({result:{case:"success",value:new Fr.Jo},planUri:""}));case"setupVmEnvironmentArgs":return Qr(e.id,new xn.r$({result:{case:"success",value:new xn.JH}}));case"replaceEnvArgs":return Yr(e.id,new Cn.dV({result:{case:"failure",value:new Cn.uq({errorMessage:"Environment replacement is not supported in local SDK runs",setupLogs:""})}}));case"prManagementRequestQuery":return eo(e.id,new En.HL({result:{case:"error",value:new En.K$({error:"PR management is only available in cloud agents"})}}));case"mcpAuthRequestQuery":return to(e.id,"MCP authentication is not supported in local SDK runs");case"connectScmRequestQuery":return ro(e.id,"Connecting GitHub is not supported in local SDK runs");case"generateImageRequestQuery":return oo(e.id,e.query.value.args?.description);case void 0:throw new hR.j1("Missing interaction query type",{isRetryable:!1});default:throw e.query,new hR.j1("Unhandled interaction query type",{isRetryable:!1})}}(t)};if(R!==t.apiKey||!T){await Promise.all([(0,pR.ly)(t.apiKey),(0,pR.mU)(t.apiKey)]);const e=(0,pR.KU)(t.apiKey,r.teamId),o=Rs((0,xo.createClient)(_I.N,e),{injectTraceHeaders:!0});T=new Ss(o),R=t.apiKey}const E=(0,pR.Vh)(T,(()=>{const e=(0,pR.KU)(t.apiKey,r.teamId),o=Rs((0,xo.createClient)(_I.N,e),{injectTraceHeaders:!0}),n=new Ss(o);return T=n,R=t.apiKey,n})),C=function(e){return{...void 0!==e.allowedTools?{[SR.$$]:e.allowedTools.join(",")}:{},...void 0!==e.disallowedTools&&e.disallowedTools.length>0?{[SR.VJ]:e.disallowedTools.join(",")}:{}}}(t),x=new xI({agentClient:E,getResources:async({agentId:e})=>{let r=g.get(e);var o;return r||(r=await P.createSessionRuntime({sessionId:e,mcpServersOverride:d,extraMcpTools:h,...(o=t.subagentInherit,void 0===o?{}:{...void 0!==o.resourceProviderOptions?{localResourceProviderOptions:o.resourceProviderOptions}:{},...void 0!==o.reportedWorkspacePath?{reportedWorkspacePath:o.reportedWorkspacePath}:{}})}),ER(r,t.customTools),r.resources.base.register(co,_),r.resources.base.register(lo,I),r.resources.base.register(uo,A),g.set(e,r)),r.resources.wrapped},mcpTools:h,workspacePath:u,parentConversationId:l,...void 0!==t.subagentInherit&&Object.keys(C).length>0?{headers:C}:{},onSessionReleased:e=>{const t=g.get(e);t&&(t.dispose(),g.delete(e))}}),_=function(e){const t=new Map,r=new Map;async function o(t,r,o){let n;try{n=await e.createOrResumeSession(t,r);const s=await e.runSession(t,n,r,{execId:o?.execId});return"error"===s.status?new so.vS({result:{case:"error",value:new so.od({agentId:n,error:s.error})}}):"aborted"===s.status?new so.vS({result:{case:"error",value:new so.od({agentId:n,error:s.error??"Subagent was aborted by the user"})}}):"background"===s.status?new so.vS({result:{case:"success",value:new so.HJ({agentId:n,finalMessage:s.finalMessage,toolCallCount:s.toolCallCount??0,backgroundReason:s.backgroundReason,transcriptPath:s.transcriptPath})}}):new so.vS({result:{case:"success",value:new so.HJ({agentId:n,finalMessage:s.finalMessage,toolCallCount:s.toolCallCount??0})}})}catch(t){if(n&&e.releaseSession&&e.releaseSession(n),t instanceof Hr)throw t;const o=t instanceof Error?t.message:String(t),s=n??function(e){return e instanceof ao&&e.agentId||e&&"object"==typeof e&&"agentId"in e&&"string"==typeof e.agentId?e.agentId:void 0}(t)??r.resumeAgentId;return new so.vS({result:{case:"error",value:new so.od({...s?{agentId:s}:{},error:o})}})}}return{execute(e,n,s){const i=function(e){if(e.toolCallId&&e.parentConversationId)return[e.parentConversationId,e.toolCallId,e.resumeAgentId??"",e.forkAgentId??""].join("\0")}(n);if(void 0===i)return o(e,n,s);const a=r.get(i);if(void 0!==a)return Promise.resolve(a);const c=t.get(i);if(void 0!==c)return c;const l=o(e,n,s).then((e=>("success"===e.result.case&&(r.set(i,e),r.size>1e3&&r.delete(r.keys().next().value)),e))).finally((()=>{t.delete(i)}));return t.set(i,l),l}}}(x),I=(w=x,{execute:(e,t)=>w.awaitBackgroundRunBounded(e,t)}),A=function(e){return{execute:async(t,r)=>e.forceBackgroundByToolCallId(r.toolCallId)}}(x);f.resources.base.register(co,_),f.resources.base.register(lo,I),f.resources.base.register(uo,A);const M=P.services.hooksRuntime,D=M?function(e){const{workspaceRuntime:t}=e;if(!(t.hooksConfigLease.hasHookForStep(he.sessionStart)||t.hooksConfigLease.hasHookForStep(he.sessionEnd)||t.hooksConfigLease.hasHookForStep(he.stop)||t.hooksConfigLease.hasHookForStep(he.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(he.sessionStart))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...Oe(e),is_background_agent:!1},r=await o.executeHookForStep(he.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){YC.Jz.warn("[hooks-adapter] sessionStart hook failed:",e)}},async onSessionEnd(e,t){if(o.hasHooksForStep(he.sessionEnd))try{const r={conversation_id:n?.conversationId??"",generation_id:n?.generationId??"",model:n?.model??"unknown",...n?Oe(n):{},reason:e,duration_ms:t,is_background_agent:!1,final_status:e};await o.executeHookForStep(he.sessionEnd,r)}catch(e){YC.Jz.warn("[hooks-adapter] sessionEnd hook failed:",e)}finally{o.clearSessionEnvironment()}else o.clearSessionEnvironment()},async onBeforeSubmitPrompt(e){if(o.hasHooksForStep(he.beforeSubmitPrompt))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...Oe(e),prompt:e.promptText??"",attachments:[]};await o.executeHookForStep(he.beforeSubmitPrompt,t)}catch(e){YC.Jz.warn("[hooks-adapter] beforeSubmitPrompt hook failed:",e)}},async onTurnCompleted(e){if(!o.hasHooksForStep(he.stop))return;const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...Oe(e),status:"completed",loop_count:e.loopCount},r=await o.executeHookForStep(he.stop,t),n="string"==typeof r?.followup_message?r.followup_message.trim():"";return n.length>0?n:void 0},async onTurnError(e){if(o.hasHooksForStep(he.stop))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...Oe(e),status:"error",loop_count:e.loopCount};await o.executeHookForStep(he.stop,t)}catch(e){YC.Jz.warn("[hooks-adapter] onTurnError stop hook failed:",e)}},async onTurnAborted(e){if(o.hasHooksForStep(he.stop))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...Oe(e),status:"aborted",loop_count:e.loopCount};await o.executeHookForStep(he.stop,t)}catch(e){YC.Jz.warn("[hooks-adapter] onTurnAborted stop hook failed:",e)}},async dispose(){await r.dispose()}}}({workspaceRuntime:M,sessionState:f.state,metadata:f.metadata}):void 0,O=new kI({workspacePath:u,conversationId:l,blobStore:i}),N=function(e,t,r){const{hooks:o}=r,[n,s]=e.withCancel(),i=new QC;let a;const c=new Map,l=(e,t)=>{const r=c.get(e);void 0!==r&&(c.delete(e),clearTimeout(r.ackTimer),r.resolve(t))};let u;const d=[],h=e=>{for(const t of d.splice(0))t.resolve(e)},p=()=>{if(0===d.length)return;const e=d.map((e=>e.text)).join("\n\n");return h("complete_delivered"),sx(e)},f=r.interactionListener,m={async sendUpdate(e,t){const r=t.message;if("contextInjectionState"===r?.case){const e=r.value,t=e.injectionId,o=function(e){switch(e){case"queued":return"queued";case"delivered":return"delivered";case"queuedForNextTurn":return"queued_for_next_turn";case"cancelled":return"cancelled";default:return"rejected"}}(e.state?.state?.case),n=void 0===t?void 0:c.get(t);if(void 0!==n&&void 0!==t){const e=function(e){switch(e){case"queued":return"confirm_steering";case"delivered":return"complete_delivered";case"queued_for_next_turn":case"cancelled":case"rejected":return"revert_to_followup";default:throw new Error(`Unknown steer ack state: ${String(e)}`)}}(o);"confirm_steering"===e?clearTimeout(n.ackTimer):(c.delete(t),n.resolve(e))}}await f.sendUpdate(e,t)},query:(e,t)=>f.query(e,t),...void 0!==f.enqueuePostTurnEndedWork?{enqueuePostTurnEndedWork:e=>f.enqueuePostTurnEndedWork?.(e)}:{},...void 0!==f.flushPostTurnEndedWork?{flushPostTurnEndedWork:e=>f.flushPostTurnEndedWork?.(e)??Promise.resolve()}:{}};let g=r.initialState;const w={async handleCheckpoint(e,t){g=t,await(r.onCheckpoint?.(t))},getLatestCheckpoint:()=>g};let y="completed";const v=Date.now(),b=tx(function(e,t){if((0,So.TU)(t))return t;const r=rx.get(e);if(void 0!==r)return r;const o=(0,So.sh)(e).blobEncryptionKey;if(void 0===o)throw new Error("getDefaultAgentMetadata did not seed a blobEncryptionKey");return rx.set(e,o),o}(r.conversationId,r.blobEncryptionKey),r.runOptions?.headers);return{done:(async()=>{const e=nx(r,0,ox(t));try{const t=await(o?.onSessionStart?.(e));if(t?.blocked)throw y="error",new Error(t.blockedReason??"Session blocked by sessionStart hook")}catch(e){if("completed"!==y)throw e;YC.Jz.warn("[agent-session-runner] sessionStart hook failed:",e)}let s=t,d=0;for(;s;){const e=nx(r,d,ox(s));try{await(o?.onBeforeSubmitPrompt?.(e))}catch(e){YC.Jz.warn("[agent-session-runner] beforeSubmitPrompt hook failed:",e)}a=r.runOptions?.generationUUID??(0,Co.C)();try{await r.agentClient.run(n,g,s,void 0,m,r.resources,r.blobStore,i,w,r.mcpTools??[],{conversationId:r.conversationId,...r.runOptions,generationUUID:a,headers:b,subagentModelOverrides:r.runOptions?.subagentModelOverrides??[]})}catch(t){throw y=ix(t)?"aborted":"error",ax("aborted"===y?o?.onTurnAborted?.(e):o?.onTurnError?.(e)),t}finally{a=void 0;for(const e of[...c.keys()])l(e,"revert_to_followup")}let t;try{t=await(o?.onTurnCompleted?.(e))}catch(e){throw y="error",e}const f="string"==typeof t?t.trim():"";let v;if(f.length>0)v=sx(f);else{const t=new AbortController;u=t;try{v=await(r.nextAction?.(e,AbortSignal.any([n.signal,t.signal])))}catch(r){if(n.signal.aborted||!t.signal.aborted)throw y=n.signal.aborted||ix(r)?"aborted":"error",ax("aborted"===y?o?.onTurnAborted?.(e):o?.onTurnError?.(e)),r}finally{u=void 0}void 0===v?v=p():h("revert_to_followup")}void 0!==v?(d+=1,i.resetStream(),s=v):s=void 0}})().finally((async()=>{h("revert_to_followup");const e=Date.now()-v;try{await(o?.onSessionEnd?.(y,e))}catch(e){YC.Jz.warn("[agent-session-runner] sessionEnd hook failed:",e)}try{await(o?.dispose?.())}catch(e){YC.Jz.warn("[agent-session-runner] hooks dispose failed:",e)}})),abort(){s()},async steer(e){if(""===e.trim())return"revert_to_followup";const t=a;if(void 0===t){const t=u;if(void 0===t)return"revert_to_followup";const r=new Promise((t=>{d.push({text:e,resolve:t})}));return t.abort(),await r}const r=(0,Co.C)(),o=new Promise((e=>{const t=setTimeout((()=>{l(r,"revert_to_followup")}),15e3);t.unref?.(),c.set(r,{resolve:e,ackTimer:t})}));try{return await i.submitConversationAction(new Nr.QFf({action:{case:"injectContextAction",value:new Nr.hGJ({injectionId:r,expectedRunId:t,payload:{case:"userContext",value:new Nr.oW$({userMessage:new Nr.RGk({messageId:(0,Co.C)(),text:e})})}})}})),await o}catch(e){return l(r,"revert_to_followup"),YC.Jz.warn("[agent-session-runner] context injection failed:",e),"revert_to_followup"}}}}(a,S,{agentClient:E,interactionListener:k,resources:s,blobStore:i,initialState:p,conversationId:l,mcpTools:h,blobEncryptionKey:t.blobEncryptionKey,runOptions:{generationUUID:t.requestId,requestedModel:m,enableAgentRetries:!1!==r.enableAgentRetries,...Object.keys(C).length>0?{headers:C}:{},...void 0!==t.systemPrompt?{customSystemPrompt:t.systemPrompt}:{}},hooks:D,async nextAction(e,t){const r=await x.waitForBackgroundCompletions(l,t);return r.length>0?function(e){return new Nr.QFf({action:{case:"backgroundTaskCompletionAction",value:new Nr.Kwc({completions:e.map((e=>new Nr.KFq({taskId:e.agentId,kind:Nr.aZc.SUBAGENT,status:"success"===e.status?Nr.uHL.SUCCESS:"aborted"===e.status?Nr.uHL.ABORTED:Nr.uHL.ERROR,...e.finalMessage.length>0?{detail:e.finalMessage}:{}})))})}})}(r):void 0},async onCheckpoint(e){p=e,O.writeFromState(a,e),await(t.onCheckpoint?.(e))}}),$=N.done.finally((async()=>{try{await x.awaitBackgroundWorkers()}finally{await O.waitForPendingWrites().catch((()=>{}));for(const e of g.values())try{await e.dispose()}catch(e){yR.v.log(`Failed to dispose subagent session runtime: ${e instanceof Error?e.message:String(e)}`)}g.clear(),await f.dispose()}})).catch((e=>{throw e}));return{abort(){N.abort(),c()},done:$,steer:e=>N.steer(e)}}catch(e){for(const e of g.values())try{await e.dispose()}catch{}throw g.clear(),await f.dispose(),e}var w})),async reload(){await P.reload()},async dispose(){await P.dispose()}}}},"./src/agent/native/tree-sitter-bash.webpack.cjs"(e,r,o){const{loadVendoredTreeSitterModule:n}=o("./src/agent/native/vendored-tree-sitter.ts"),s=n({packageName:"tree-sitter-bash",nativeRequire:t});e.exports=s.available?s.module:{}},"./src/agent/native/tree-sitter.webpack.cjs"(e,r,o){const{createUnavailableParserClass:n,loadVendoredTreeSitterModule:s}=o("./src/agent/native/vendored-tree-sitter.ts"),i=s({packageName:"tree-sitter",nativeRequire:t});e.exports=i.available?i.module:n(i.reason)},"../constants/dist/mcp.js"(e,t,r){r.d(t,{G$:()=>C,tl:()=>I,TI:()=>o,Qy:()=>c,uS:()=>S,RJ:()=>D,Di:()=>l,sr:()=>u,NC:()=>k,OY:()=>M,U_:()=>b,vI:()=>d,TS:()=>E});const o="cursor/requiresConfirmation",n="https://grok.com/connectors-oauth-exchange-code/",s="https://x.com/i/connectors/oauth_callback",i={provider:"google-workspace",clientRegistration:"static",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!0,authorizationParams:{access_type:"offline",prompt:"select_account consent"}},a={provider:"x-money",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0,registeredAppRedirectUris:[n,s]},c="x-cursor-auth";function l(e,t){return function({serverUrl:e,restMcpHost:t}){if(void 0===e)return;let r;try{r=new URL(e)}catch{return}return"https:"===r.protocol&&r.hostname.toLowerCase()===t.toLowerCase()&&""===r.port?u(e):void 0}({serverUrl:e,restMcpHost:t})}function u(e){if(void 0===e)return;let t;try{t=new URL(e)}catch{return}const r=/^\/rest-mcp\/([^/]+)\/mcp\/?$/.exec(t.pathname);return r?.[1]}function d(e){if("object"!=typeof(t=e)||null===t)return{};var t;const r=e,o="string"==typeof r.cursor_client_id&&r.cursor_client_id.length>0?r.cursor_client_id:void 0;let n;if("object"==typeof r.cursor_authorization_params&&null!==r.cursor_authorization_params){const e=Object.entries(r.cursor_authorization_params).filter((e=>"string"==typeof e[1]));e.length>0&&(n=Object.fromEntries(e))}return{...void 0!==o?{clientId:o}:{},...!0===r.cursor_omit_resource_indicator?{omitResourceIndicator:!0}:{},...!0===r.cursor_omit_consent_prompt?{omitConsentPrompt:!0}:{},...void 0!==n?{authorizationParams:n}:{},...!0===r.cursor_rejects_custom_scheme_redirects?{rejectsCustomSchemeRedirects:!0}:{},...!0===r.cursor_unauthenticated_connect?{unauthenticatedConnect:!0}:{},...!0===r.cursor_loopback_ipv4?{loopbackIpv4:!0}:{},...!0===r.cursor_backend_only_token_exchange?{backendOnlyTokenExchange:!0}:{}}}new Set(Object.values({notConnected:"scm_not_connected",tokenUnavailable:"scm_token_unavailable",tokenRejected:"scm_token_rejected",repoNotAccessible:"scm_repo_not_accessible",orgBlocked:"scm_org_blocked"})),new Set(Object.values({originNotEnabled:"origin_not_enabled",teamDisabled:"team_disabled",admissionRejected:"admission_rejected"}));const h="https://mcp.shop.com",p={provider:"grok-connectors",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,scopes:["grok-plugins:access","offline_access"]},f=new Map([["gmailmcp.googleapis.com",{...i,scopes:["https://www.googleapis.com/auth/gmail.readonly","https://www.googleapis.com/auth/gmail.compose","https://www.googleapis.com/auth/gmail.modify"]}],["drivemcp.googleapis.com",{...i,scopes:["https://www.googleapis.com/auth/drive.readonly","https://www.googleapis.com/auth/drive.file"]}],["calendarmcp.googleapis.com",{...i,scopes:["https://www.googleapis.com/auth/calendar.events","https://www.googleapis.com/auth/calendar.calendarlist.readonly","https://www.googleapis.com/auth/calendar.events.readonly","https://www.googleapis.com/auth/calendar.events.freebusy"]}],["docsmcp.googleapis.com",{...i,scopes:["https://www.googleapis.com/auth/documents"]}],["sheetsmcp.googleapis.com",{...i,scopes:["https://www.googleapis.com/auth/spreadsheets"]}],["slidesmcp.googleapis.com",{...i,scopes:["https://www.googleapis.com/auth/presentations"]}],["bigquery.googleapis.com",{...i,scopes:["https://www.googleapis.com/auth/bigquery"]}],["api.x.com",{provider:"x",clientRegistration:"static",unauthenticatedConnect:!1,rejectsCustomSchemeRedirects:!1,pinsScopesOverConfiguredScopes:!0}],["mcp.money-dev.x.com",a],["mcp.money-staging.x.com",a],["mcp.money.x.com",a],["connectors-gateway.grok.gcp.mouseion.dev",p],["connectors-gateway.grok.com",p],["mcp.hubspot.com",{provider:"hubspot",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0}],["mcp.box.com",{provider:"box",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0}],["mcp.quickbooks.intuit.com",{provider:"quickbooks-online",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,requiresHostedCallback:!0,unauthenticatedConnect:!1,unauthenticatedEndpointBlocked:!0,backendOnlyTokenExchange:!0,scopes:["com.intuit.quickbooks.accounting","foundations.tools.businessreports.read","foundations.tools.bi-dashboard","foundations.tools.transactions.write","foundations.tools.companyprofile.read","foundations.tools.companyprofile.write","payroll.tools.tax.read","payroll.tools.employer.read","payroll.tools.employer.manage","payroll.tools.run.read","payroll.tools.run.manage","payroll.tools.employee.read","payroll.tools.employee.manage","worker-mgmt.tools.employee.read","worker-mgmt.tools.employee.manage","sales.tools.invoice.read","sales.tools.invoice","sales.tools.estimate.read","sales.tools.estimate","sales.tools.payment-link.read","sales.tools.payment-link","sales.tools.settings.read","sales.tools.settings","sales.tools.salesorder.read","sales.tools.salesorder","contact.tools.customer.read","contact.tools.customer","catalog.tools.item.read","catalog.tools.item","lending.tools.servicing.read","money-onboarding.tools.application"]}],["setup.shopify.com",{provider:"shopify",clientRegistration:"static",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!1}],["mcp.shop.com",{provider:"shop",clientRegistration:"static",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!0,requiresHostedCallback:!0,backendOnlyTokenExchange:!0,authorizationParams:{resource:h}}]]);function m(e){return e.endsWith("/")?e:`${e}/`}async function g(e,t){if(void 0===t)return;const r=new URL(e),o=new URL(t);if(r.origin!==o.origin||!m(r.pathname).startsWith(m(o.pathname)))throw new Error(`Protected resource ${t} does not match expected ${r.href} (or origin)`);return o}const w=/^\/shops\/[A-Za-z0-9-]+\/mcp$/;function y(e){if(void 0!==e)try{return new URL(e)}catch{return}}async function v(e,t){if(void 0===t)return;const r=new URL(e),o=y(t);if(void 0===o||o.origin!==r.origin||o.pathname!==r.pathname&&!w.test(o.pathname))throw new Error(`Protected resource ${t} does not match expected ${r.href} (or origin)`);return o}function b(e,t){if(function(e,t){const r=t.gtmApiOrigin;if(void 0===e||void 0===r)return!1;let o,n;try{o=new URL(e),n=new URL(r)}catch{return!1}return o.protocol===n.protocol&&o.hostname===n.hostname&&""===o.port&&"/mcp"===o.pathname}(e,t))return async()=>{};const r=y(e);return void 0!==r&&function(e){return"https:"===e.protocol&&e.hostname===new URL(h).hostname}(r)?async()=>{}:void 0!==r&&function(e){return"https:"===e.protocol&&"setup.shopify.com"===e.hostname&&""===e.port&&"/mcp"===e.pathname}(r)?v:g}function S(e,t){const r=function(e){if(void 0===e)return;let t;try{t=new URL(e).hostname}catch{return}return function(e){return f.get(e.toLowerCase())}(t)}(t)?.authorizationParams;if(void 0!==r)for(const[t,o]of Object.entries(r))e.searchParams.set(t,o)}function k(e){return"login.microsoftonline.com"===e.hostname}function E(e){const t=new Set(e.searchParams.getAll("prompt").flatMap((e=>e.split(" "))).filter((e=>""!==e&&"consent"!==e)));e.searchParams.delete("prompt"),t.size>0&&e.searchParams.set("prompt",[...t].join(" "))}new Set([...f].filter((([,e])=>"google-workspace"===e.provider)).map((([e])=>e)));const C="https://ptht05hbb1ssoooe.public.blob.vercel-storage.com/assets/uploads/cursorlogomcpv3.svg",x="https://www.cursor.com/bot/mcp/oauth/callback",_={portal:"https://www.cursor.com/agents/mcp/oauth/callback",grokBotBounce:x},P="grokbot://mcp/oauth/callback",I="http://localhost:8787/callback",R="gb";new Set(["outlook","outlook-calendar","onedrive","teams"]),new Set(["teams"]);function T(e){const t=new URL(I);return t.port=String(e),t.toString()}function A(e){try{const t=new URL(e);if("http:"!==t.protocol)return!1;const r=t.hostname;return"localhost"===r||"127.0.0.1"===r||"[::1]"===r}catch{return!1}}function M(e){const t=e.redirectUrl??I;if(!0!==e.loopbackIpv4||!A(t))return t;const r=new URL(t);return r.hostname="127.0.0.1",r.toString()}function D(e,t=_){const r=new Set,o=void 0!==e&&A(e);return e&&!o&&r.add(e),r.add(t.portal),e===P&&r.add(t.grokBotBounce),r.add(I),e&&o&&r.add(e),Array.from(r)}new Map([[R,P],["gw",n],["gd",I],["xa",s],...[18787,28787,31787].map((e=>[`gd${e}`,T(e)]))]),new Map([[P,R],[x,R],[n,"gw"],[s,"xa"]]),M({loopbackIpv4:!0})},"../mcp-agent-exec/dist/mcp-sandbox-policy.js"(e,t,r){r.d(t,{buildMcpSandboxPolicy:()=>o.Ico});var o=r("../mcp-core/dist/index.js")},"../mcp-core/dist/admin-mcp-tool-allowlist.js"(e,t,r){r.d(t,{BJ:()=>a,rh:()=>s});var o=r("../mcp-core/dist/mcp-tool-annotations.js");function n(e){return e.trim().toLowerCase()}function s(e,t){switch(e.mode){case"all":return!0;case"custom":return function(e,t){const r=n(e);return 0!==r.length&&t.some((e=>n(e)===r))}(t.name,e.tools);case"reads":return(0,o.NY)(t.annotations);default:return e}}function i(e,t){switch(t.mode){case"all":return[`${e}:*`];case"custom":return t.tools.map((t=>`${e}:${t}`));case"reads":return[];default:return t}}function a({autoRunControls:e,allowedMcpServers:t}){const r=!0===e?.enabled?e.mcpToolAllowlist??[]:[],o=function(e){return(e??[]).flatMap((e=>{const t=void 0===e.name?"":n(e.name);if(0===t.length)return[];const r=function({mode:e,tools:t}){const r=(t??[]).map(n).filter((e=>e.length>0)),o=void 0===e?void 0:n(e);return"all"===o?{mode:"all"}:"reads"===o?{mode:"reads"}:r.length>0?{mode:"custom",tools:r}:{mode:"all"}}({mode:e.toolAllowlistMode,tools:e.toolAllowlist});return[{name:t,policy:r,flattened:i(t,r)}]}))}(t);return{tools:(s=[...o.flatMap((e=>[...e.flattened])),...r],[...new Set(s)]),policies:o.map((e=>({name:e.name,policy:e.policy})))};var s}r("../mcp-core/dist/transport/mcp-url-utils.js")},"../mcp-core/dist/index.js"(e,t,r){r.d(t,{B1j:()=>a,fz:()=>h,c8u:()=>de,Tp_:()=>ke,uOd:()=>d,GSN:()=>Ee,Uod:()=>Ce,E_S:()=>ge,Ico:()=>ae,O3I:()=>E,tBH:()=>b,MEY:()=>o.ME,eod:()=>m,Fmf:()=>ue,jIB:()=>oe,VDJ:()=>L,X5z:()=>F,$HQ:()=>o.$H,YaX:()=>i,Gpm:()=>me,DEr:()=>xe,PKk:()=>Pe,iog:()=>Ue,bIe:()=>f,sfL:()=>p,_NE:()=>o._N,Ezk:()=>ye.Ez,qFm:()=>we.qF,eaG:()=>N,q2e:()=>y,mtU:()=>ve,Uuy:()=>ze,utF:()=>be,gD9:()=>_e});var o=r("../mcp-core/dist/transport/mcp-url-utils.js");function n(e){const t=e?.trim();return void 0===t||0===t.length?void 0:t}function s(e){const t=e?.trim();return void 0===t||0===t.length?void 0:t}function i(e,t,r){if(void 0===t)return!0;if(!0===t.disableAll)return!1;if(function(e){return!0===e.url?.startsWith("mcp-provider://")}(e))return!0;const i=t.allowedMcpServers??[];return 0===i.length&&!0!==t.allowUserOverrideMcpServers||!!function(e,t,r){return t.length>0&&function(e,t,r){const i=r?.matchesServerUrlPattern??o.vc;return t.some((t=>{const r=n(t.command),a=s(t.serverUrl);if(void 0===r&&void 0===a)return!1;const c=void 0===r||void 0!==e.command&&(0,o.mD)(r,e.command),l=void 0===a||void 0!==e.url&&i(a,e.url);return c&&l}))}(e,t,r)}(e,i,r)||!0===t.allowUserOverrideMcpServers&&!function(e,t,r){const i=r?.matchesServerUrlPattern??o.vc;return(t??[]).some((t=>{const r=n(t.command),a=s(t.serverUrl);if(void 0===r&&void 0===a)return!1;const c=void 0===r||void 0!==e.command&&(0,o.mD)(r,e.command),l=void 0===a||void 0!==e.url&&i(a,e.url);return c&&l}))}(e,t.deniedMcpServers,r)}r("../mcp-core/dist/admin-mcp-tool-allowlist.js");class a{constructor(e=864e5){this.ttl=e,this.staleDirty=!1,this.refreshGeneration=0}async get(e){const t=performance.now();if(this.state&&this.state.expiresAt>t&&!this.staleDirty)return this.state.value;if(this.staleDirty&&this.state){const t=this.state.value;if(!this.refreshInFlight){const t=this.refreshGeneration;let r;r=(async()=>{try{const r=await e();if(t!==this.refreshGeneration)return;this.state={expiresAt:performance.now()+this.ttl,value:r},this.staleDirty=!1}catch{}finally{r&&this.refreshInFlight===r&&(this.refreshInFlight=void 0)}})(),this.refreshInFlight=r}return t}const r=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)}}var c=r("../constants/dist/mcp.js");new Set(["EAI_AGAIN","ECONNABORTED","ECONNREFUSED","ECONNRESET","EHOSTUNREACH","ENETDOWN","ENETUNREACH","ENOTFOUND","EPIPE","ETIMEDOUT","EADDRNOTAVAIL","UND_ERR_CONNECT_TIMEOUT"]),new Set(["ECONNRESET","EPIPE"]);const l=new Set([429,502,503,504]);function u(e){const t=e.code,r=(e instanceof Error||"string"==typeof e.message?e.message:"").match(/\(HTTP (\d+)\)|Non-200 status code \((\d+)\)|\bHTTP\s+(\d{3})\b/i),o=r?.[1]??r?.[2]??r?.[3],n=void 0!==o?parseInt(o,10):void 0;if("number"==typeof t&&t>=100)return void 0!==n&&l.has(n)&&!l.has(t)?n:t;if("string"==typeof t&&/^\d{3}$/.test(t)){const e=Number.parseInt(t,10);return e>=100&&e<=599?e:n}return n}const d=8192;new Set(["ENOENT","EACCES","ENOTDIR","EPERM"]);const h="mcp_tool.attempt";function p(e){return void 0===e?"unknown":"url"in e&&e.url.length>0?void 0!==(0,c.sr)(e.url)?"rest_mcp":"streamable_http":"command"in e?"stdio":"unknown"}function f(e){const t=e.httpStatus??(void 0!==e.error?function(e){if(!e||"object"!=typeof e)return;const t=u(e);if(void 0!==t)return t;const r=e.cause;return r&&"object"==typeof r?u(r):void 0}(e.error):void 0);return void 0!==t&&Number.isInteger(t)&&t>=100&&t<=599?{error_class:"http",error_code:String(t),transport:e.transport}:void 0!==e.error||!0===e.failed?{error_class:"other",error_code:"exception",transport:e.transport}:!0===e.isError?{error_class:"payload",error_code:"is_error",transport:e.transport}:{error_class:"none",error_code:"none",transport:e.transport}}async function m(e){const t=[],r=new Set;let o;for(let n=1;;n++){const s=await e.fetchPage(o),i=e.itemsOf(s);t.push(...i);const a=e.nextCursorOf(s);if(!a||r.has(a))return t;if(n>=1e3)throw new Error("MCP list did not end after 1000 pages; refusing to keep paging");r.add(a),o=a}}function g(e){return Object.fromEntries(Object.entries(e).filter((([,e])=>void 0!==e)))}function w(e,t){const r=function(e){try{const t=new URL(e);return{host:t.host,origin:t.origin,pathname:t.pathname}}catch{return{host:null,origin:null,pathname:null}}}(e),o=!1!==t?.includePath;return{host:r.host,origin:r.origin,path:o?r.pathname:null}}function y(e,t){return w(e,t)}var v=r("crypto");function b(e,t){const r=e?.access_token,o="string"==typeof r?r.length:0,n=Boolean(e?.refresh_token),s="number"==typeof e?.expires_in&&Number.isFinite(e.expires_in)?e.expires_in:null;return{accessTokenLen:o,refreshTokenPresent:n,expiresAtTimestamp:t?.expiresInIsFresh&&null!==s?Date.now()+Math.round(1e3*s):null,grantedScope:"string"==typeof e?.scope&&e.scope.length>0?e.scope:null}}function S(e){if(e)return(0,v.createHash)("sha256").update(e).digest("hex").slice(0,12)}function k(e){if(e&&0!==e.length)return S(JSON.stringify([...e].sort()))}function E(e){return{clientIdHash:S(e?.client_id),hasClientSecret:(e?.client_secret??"").length>0,redirectUrisHash:k(e?.redirect_uris),redirectUriCount:e?.redirect_uris?.length??0}}function C(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 x(e,t){for(const r of t)if("string"==typeof C(e,r.split(".")))return C(e,r.split("."))}function _(e){if(!e||"object"!=typeof e)return;const t=e.errorCode;return"string"==typeof t?t:void 0}function P(e){if(!e)return;const t=e.match(/\(HTTP (\d+)\)|Non-200 status code \((\d+)\)|\bHTTP\s+(\d{3})\b/i),r=t?.[1]??t?.[2]??t?.[3];if(!r)return;const o=Number.parseInt(r,10);return Number.isNaN(o)?void 0:o}function I(e){if(e instanceof Error){const t=e.message;return t&&t!==e.name?N(t):void 0}if(null!=e){const t=String(e);return t?N(t):void 0}}function R(e){if(e&&"object"==typeof e)return e.cause}function T(e,t=4){const r=[];let o=e;for(let e=0;e<t&&null!=o;e++){if(!(o instanceof Error)){r.push(N(String(o)));break}{const e=I(o);r.push(e?`${o.name}: ${e}`:o.name),o=R(o)}}return r.length>1?r.join(" > "):void 0}const A="[REDACTED]",M=/(^|_|-)(token|secret|password|assertion|authorization|verifier|challenge|code)(_|-|$)/i;function D(e){return e.replace(/(authorization[^:=\r\n]{0,32}[:=]\s*["']?)(?:[A-Za-z][\w.~+/-]*[ \t]+)?[^"',\s&}]+/gi,`$1${A}`).replace(/((?:access_token|refresh_token|id_token|client_secret|code|password|assertion|token|secret)[^:=\r\n]{0,32}[:=]\s*["']?)([^"',\s&}]+)/gi,`$1${A}`).replace(/(\bBearer\s+)([A-Za-z0-9\-._~+/]+=*)/gi,`$1${A}`)}function O(e,t=256){return e.length>t?`${e.slice(0,Math.max(0,t-3))}...`:e}function N(e,t){return O(D(e),t?.maxLength)}function $(e){if("string"==typeof e)return O(D(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")||M.test(t)}(e)?A:"string"==typeof t?D(t):t));if(!t)return;return O(t)}catch{return}}function F(e){const t=R(e),r=e instanceof Error?e.name:null!=e?typeof e:void 0,o=t instanceof Error?t.name:void 0,n=I(t),s=I(e)??n,i=x(e,["code","cause.code"]),a=_(e)??_(t)??x(e,["errorCode","error","cause.errorCode","cause.error","body.error","response.body.error"]),c=function(e){for(const t of["status","statusCode","response.status","response.statusCode","cause.status","cause.statusCode","cause.response.status","cause.response.statusCode"]){const r=C(e,t.split("."));if("number"==typeof r&&Number.isFinite(r))return r}}(e)??P(s)??P(n),l=$(C(e,["response","body"])??C(e,["body"])??C(e,["data"])??C(e,["cause","body"])??C(e,["cause","response","body"])),u=function(e){const t=e.message?.toLowerCase(),r=e.code?.toLowerCase();return t?.includes("timed out")||t?.includes("timeout")||t?.includes("etimedout")||"etimedout"===r?"timeout":t?.includes("enotfound")||t?.includes("eai_again")||t?.includes("dns")||"enotfound"===r||"eai_again"===r?"dns":t?.includes("certificate")||t?.includes("tls")||t?.includes("ssl")?"tls":t?.includes("econnreset")||t?.includes("connection reset")||"econnreset"===r?"connection_reset":t?.includes("econnrefused")||t?.includes("connection refused")||"econnrefused"===r?"connection_refused":void 0}({message:s,code:i}),d=a?"oauth_error":u?"auth_transport_error":s?"generic_error":void 0;return g({errorName:r,errorMessage:s,errorType:null!=e?typeof e:void 0,httpStatus:c,oauthErrorCode:a,errorResponseSummary:l,networkClassification:u,causeName:o,causeMessage:n,causeChain:T(e),sdkErrorKind:d})}const j={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 L(e){const t=e.message??j[e.event],r={event:e.event,cursorMcp:{oauth:g({...e.metadata})}},o=e.level??"info";"error"!==o?"warn"!==o?"debug"!==o?e.logger.info?.(t,r):e.logger.debug?.(t,r):e.logger.warn?.(t,r):e.logger.error?.(t,e.error,r)}const U=new Map(["AWS4-HMAC-SHA256","Api-Key","ApiKey","Basic","Bearer","Bot","DPoP","Digest","GNAP","HOBA","Key","Mutual","NTLM","Negotiate","OAuth","PrivateToken","SCRAM-SHA-1","SCRAM-SHA-256","Token","vapid"].map((e=>[e.toLowerCase(),e]))),B=4096;function W(e){return"object"==typeof e&&null!==e&&"url"in e&&"string"==typeof e.url}function H(e){return"string"==typeof e?e:e instanceof URL?e.toString():e.url}function q(e){const t=[];return e.forEach(((e,r)=>{t.push(r)})),t.sort()}function z(e){if(null===e)return null;const t=Number.parseInt(e,10);return Number.isNaN(t)?null:t}function G(e,t){if(null==e)return{kind:"none",bytes:0,contentLength:z(t.get("content-length"))};if("string"==typeof e){const r=(new TextEncoder).encode(e).length;return{kind:"text",bytes:r,contentLength:z(t.get("content-length"))??r}}if(e instanceof URLSearchParams){const r=e.toString(),o=(new TextEncoder).encode(r).length;return{kind:"text",bytes:o,contentLength:z(t.get("content-length"))??o}}return e instanceof Blob?{kind:"blob",bytes:e.size,contentLength:z(t.get("content-length"))??e.size}:e instanceof ArrayBuffer||ArrayBuffer.isView(e)?{kind:"binary",bytes:e.byteLength,contentLength:z(t.get("content-length"))??e.byteLength}:"object"==typeof e&&null!==e&&("getReader"in e||Symbol.asyncIterator in e)?{kind:"stream",bytes:null,contentLength:z(t.get("content-length"))}:{kind:"unknown",bytes:null,contentLength:z(t.get("content-length"))}}function V(e,t){if(null===e||!e.toLowerCase().startsWith("application/x-www-form-urlencoded"))return;const r="string"==typeof t?function(e){for(const t of e.split("&")){const e=t.indexOf("="),r=e>=0?t.slice(0,e):t;let o;try{o=decodeURIComponent(r.replaceAll("+"," "))}catch{return}if("grant_type"!==o)continue;const n=e>=0?t.slice(e+1):"";try{return decodeURIComponent(n.replaceAll("+"," "))}catch{return}}}(t):t instanceof URLSearchParams?t.get("grant_type")??void 0:void 0;return r?function(e){switch(e){case"authorization_code":case"refresh_token":case"client_credentials":case"urn:ietf:params:oauth:grant-type:jwt-bearer":case"urn:ietf:params:oauth:grant-type:token-exchange":return e;default:return"other"}}(r):void 0}function J(e){const{input:t,init:r}=e,o=w(H(t)),n=function(e,t){const r=new Headers(W(e)?e.headers:void 0);return new Headers(t?.headers).forEach(((e,t)=>{r.set(t,e)})),r}(t,r),s=q(n),i=n.get("content-type"),a=S(n.get("mcp-session-id")??void 0),c=function(e){if(!e)return null;const t=e.trim().split(/\s+/,1)[0]??"";return U.get(t.toLowerCase())??"unrecognized"}(n.get("authorization"));return{method:(r?.method??(W(t)?t.method:void 0)??"GET").toUpperCase(),url:o,headers:{names:s,count:s.length},contentType:i,body:G(r?.body,n),sessionIdHash:a??null,authorizationScheme:c}}function K(e,t){const r=q(e.headers),o=z(e.headers.get("content-length"));return{status:e.status,ok:e.ok,headers:{names:r,count:r.length},contentType:e.headers.get("content-type"),body:{kind:null===e.body?"none":"stream",bytes:null===e.body?0:o,contentLength:o,...void 0!==t?{errorSummary:t}:{}},sessionIdHash:S(e.headers.get("mcp-session-id")??void 0)??null,wwwAuthenticateHash:S(e.headers.get("www-authenticate")??void 0)??null,mcpProtocolVersion:e.headers.get("mcp-protocol-version")??null,requestId:e.headers.get("x-request-id")??null,retryAfter:Z(e.headers,"retry-after"),slackRateLimitType:Z(e.headers,"x-slack-ratelimit-type")}}function Z(e,t){return e.get(t)?.slice(0,64)??null}function X(e){const t={};return void 0!==e.errorName&&(t.name=e.errorName),void 0!==e.errorMessage&&(t.message=e.errorMessage),void 0!==e.errorType&&(t.type=e.errorType),void 0!==e.oauthErrorCode&&(t.oauthErrorCode=e.oauthErrorCode),void 0!==e.errorResponseSummary&&(t.responseSummary=e.errorResponseSummary),void 0!==e.networkClassification&&(t.networkClassification=e.networkClassification),void 0!==e.sdkErrorKind&&(t.sdkErrorKind=e.sdkErrorKind),t}function Q(e,t){const r=J({input:e,init:t});if(void 0!==V(r.contentType,t?.body))return!0;const o=r.url.path?.toLowerCase()??"";return o.endsWith("/token")||o.includes("/oauth/token")||o.includes("/connect/token")}async function Y(e,t){try{const r=await e.clone().text();return r.length>t?r.slice(0,t):r}catch{return}}async function ee(e){if(!Q(e.input,e.init))return;const t=await Y(e.response,B);if(void 0!==t)try{return $(JSON.parse(t))}catch{return N(t,{maxLength:B})}}async function te(e){const t=await async function(e,t){try{if(t.ok)return;const r=t.headers.get("content-type")?.toLowerCase()??"";if(!r.includes("json")&&!r.includes("text"))return;const o=await Y(t,B);if(void 0===o)return;return function(e){if("/mcp"!==(t=w(H(e.input)).path)&&!0!==t?.endsWith("/mcp"))return N(e.rawText,{maxLength:B});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?N(r.message,{maxLength:B}):void 0;return void 0!==o||void 0!==n?JSON.stringify({...void 0!==o?{code:o}:{},...void 0!==n?{message:n}:{}}):void 0}(t):void 0}catch{return}}({input:e,rawText:o})}catch{return}}(e.input,e.response);return{responseErrorSummary:t,oauthTokenErrorBodySummary:void 0===t?await ee({input:e.input,response:e.response,init:e.init}):void 0}}function re(e,t,r){try{e()}catch{t.warn?.("MCP HTTP exchange logging failed",{event:"mcp_http_exchange_logging_failure",phase:r})}}function oe(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:c,oauthTokenErrorBodySummary:l}=a.ok?{}:await te({input:e,init:s,response:a});return!n&&a.ok||re((()=>{!function(e){const{logger:t,response:r}=e,o=function(e){const{input:t,init:r,response:o,durationMs:n,metadata:s,responseErrorSummary:i,oauthTokenErrorBodySummary:a}=e,c=J({input:t,init:r}),l=V(c.contentType,r?.body);return{event:"mcp_http_exchange",outcome:o.ok?"success":"http_error",durationMs:n,cursorMcp:{transport:{...s,request:c,response:K(o,i),...void 0!==l?{oauth:{grantType:l}}:{},...void 0!==a?{oauthTokenErrorBodySummary:a}:{}}}}}(e);r.ok?t.info?.("MCP HTTP exchange completed",o):function(e){return 401===e.response.status&&null===e.request.authorizationScheme&&e.response.headers.has("www-authenticate")&&!Q(e.input,e.init)}({response:r,request:o.cursorMcp.transport.request,input:e.input,init:e.init})?t.debug?.("MCP HTTP exchange completed",o):t.warn?.("MCP HTTP exchange completed",o)}({logger:r,input:e,init:s,response:a,durationMs:Date.now()-i,metadata:o,responseErrorSummary:c,oauthTokenErrorBodySummary:l})}),r,"success"),a}catch(t){const n=function(e){if(!e||"object"!=typeof e)return;const t=[e.response,e.cause?.response];for(const e of t)if(e&&"object"==typeof e&&"status"in e&&"number"==typeof e.status&&"headers"in e&&"function"==typeof e.headers?.get)return e}(t),{responseErrorSummary:a,oauthTokenErrorBodySummary:c}=n?await te({input:e,init:s,response:n}):{};throw re((()=>{!function(e){const{logger:t}=e;t.warn?.("MCP HTTP exchange failed",function(e){const{input:t,init:r,error:o,durationMs:n,metadata:s,responseFromError:i,responseErrorSummary:a,oauthTokenErrorBodySummary:c}=e,l=F(o),u=J({input:t,init:r}),d=V(u.contentType,r?.body);return{event:"mcp_http_exchange",outcome:"error",durationMs:n,cursorMcp:{transport:{...s,request:u,response:void 0!==i?K(i,a):{status:l.httpStatus??null,ok:null,headers:{names:[],count:0},contentType:null,body:{kind:"none",bytes:null,contentLength:null,...void 0!==a?{errorSummary:a}:{}},requestId:null,sessionIdHash:null,wwwAuthenticateHash:null,mcpProtocolVersion:null,retryAfter:null,slackRateLimitType:null},...void 0!==d?{oauth:{grantType:d}}:{},...void 0!==c?{oauthTokenErrorBodySummary:c}:{},error:X(l)}}}}(e))}({logger:r,input:e,init:s,error:t,durationMs:Date.now()-i,metadata:o,responseFromError:n,responseErrorSummary:a,oauthTokenErrorBodySummary:c})}),r,"failure"),t}}}new Set(["admin_policy_enforced","policy_enforced"]),new Set(["invalid_grant","interaction_required","unauthorized_client","invalid_resource"]),new Set(["50105","53000","53001","53002","53003","53004","530032","90094","7000112","500014"]),new Map([["50173","refresh_token_revoked"],["50076","mfa_required"],["50078","mfa_required"],["50079","mfa_required"],["50057","account_disabled"],["500341","account_disabled"],["65001","consent_required"],["70043","refresh_token_expired"],["70045","refresh_token_expired"],["70000","refresh_token_invalid"],["135010","refresh_token_invalid"]]),new Set(["InvalidGrantError","InvalidRequestError"]);const ne=["0.0.0.0/0","::/0"];function se(e){const t=(e??[]).filter((e=>e.trim().length>0)),r=t.flatMap((e=>{const t=(0,o.bi)(e);return void 0===t?[]:[t]}));return{hasConfiguredEntries:t.length>0,hasInvalidEntries:r.length!==t.length,entries:r}}function ie(e){const t=se(e.mcpNetworkAllowlist),r=se(e.mcpNetworkDenylist),o=e.mcpNetworkMode;if("deny_all"===o||r.entries.includes("*")||r.hasInvalidEntries)return{version:1,default:"deny"};if("allow_all"===o)return{version:1,default:"deny",allow:[...ne],...r.entries.length>0?{deny:r.entries}:{}};if("allowlist"===o||t.hasConfiguredEntries){const e=function(e){return e.entries.includes("*")?[...ne]:e.entries}(t);return e.length>0?{version:1,default:"deny",allow:e,...r.entries.length>0?{deny:r.entries}:{}}:{version:1,default:"deny"}}return{version:1,default:"deny",allow:[...ne],...r.entries.length>0?{deny:r.entries}:{}}}async function ae(e,t){const{resolveSandboxPolicyForWorkspace:o}=await Promise.resolve().then(r.bind(r,"../shell-exec/dist/api/index.js")),n={type:"workspace_readwrite",sandboxWorkspaceRoot:t,networkPolicy:ie(e),networkPolicyStrict:!0},{policy:s}=await o(t,{perUser:n});return s}const ce=["0.0.0.0/0","::/0"];function le(e){const t=(e??[]).filter((e=>e.trim().length>0)),r=t.flatMap((e=>{const t=(0,o.bi)(e);return void 0===t?[]:[t]}));return{hasInvalidEntries:r.length!==t.length,entries:r}}function ue(e){const t=!0===e.enabled,r=le(e.mcpNetworkDenylist),n="deny_all"===e.mcpNetworkMode||r.entries.includes("*")||r.hasInvalidEntries,s=t?function(e){if("allow_all"===e.mcpNetworkMode)return[...ce];const t=le(e.mcpNetworkAllowlist);if("allowlist"===e.mcpNetworkMode)return t.entries.includes("*")?[...ce]:t.entries;if(!function(e){return(e.mcpNetworkAllowlist??[]).some((e=>e.trim().length>0))}(e))return[...ce];const r=(0,o.b6)(e);return r.includes("*")?[...ce]:r}(e):[],i=t?n?["*"]:r.entries:[];return JSON.stringify({enabled:t,mode:e.mcpNetworkMode,allow:n?[]:s,deny:i})}class de extends Error{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)}}new Map,new Set,new Set(["connection_attempt"]),new Set(["health_probe"]),r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=d6585ecc3ef25fb368c06a7be3232df8c0e9380e7f3_9fbb579d5110d1faa52af09926f676f7/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js"),r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=d6585ecc3ef25fb368c06a7be3232df8c0e9380e7f3_9fbb579d5110d1faa52af09926f676f7/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/errors.js"),Error,Error;const he=new Set(["UnauthorizedError","InvalidGrantError","InvalidTokenError","InvalidClientError","UnauthorizedClientError"]),pe=new Set(["invalid_grant","invalid_token","invalid_client","unauthorized_client"]),fe=[/\btoken (?:has |is )?expired\b/i,/\btoken (?:was|is) invalid\b/i,/\binvalid (?:refresh[ _]?)?token\b/i,/\btoken (?:has been |was )?revoked\b/i];function me(e){if(null===e||"object"!=typeof e)return!1;const t=e.name;if("string"==typeof t&&he.has(t))return!0;const r=e.errorCode;return!("string"!=typeof r||!pe.has(r.toLowerCase()))||function(e){if(null===e||"object"!=typeof e)return!1;const t=e.name,r=e.errorCode;if("InvalidRequestError"!==t&&("string"!=typeof r||"invalid_request"!==r.toLowerCase()))return!1;const o=e.message;return"string"==typeof o&&fe.some((e=>e.test(o)))}(e)}function ge(e,t){void 0!==t&&t.length>0&&e.searchParams.set("scope",t.join(" "))}new Set(["invalid_refresh_token","token_revoked","token_expired"]);var we=r("../mcp-core/dist/oauth/resolved-oauth-client-id.js"),ye=r("../mcp-core/dist/oauth/rest-mcp-provider-metadata.js");function ve(e,t){if(void 0===t)return{headers:t,cursorAuthHeaderValue:void 0,cursorAuthOrigin:void 0};const r=Object.entries(t),o=r.find((([e])=>e.toLowerCase()===c.Qy));if(void 0===o)return{headers:t,cursorAuthHeaderValue:void 0,cursorAuthOrigin:void 0};let n;try{n=new URL(e).origin}catch{n=void 0}return{headers:Object.fromEntries(r.filter((([e])=>e.toLowerCase()!==c.Qy))),cursorAuthHeaderValue:o[1],cursorAuthOrigin:n}}function be(e,t,r){return async(o,n)=>{let s;try{s=new URL("string"==typeof o?o:o.toString()).origin}catch{return r(o,n)}if(s!==t)return r(o,n);const i=await e();if(void 0===i||0===i.length)return r(o,n);const a=new Headers(n?.headers);return a.set(c.Qy,i),r(o,{...n,headers:a,redirect:"manual"})}}Error;const Se=new Set(["invalid_auth","not_authed","account_inactive","token_revoked","token_expired"]),ke="Your team admin only allows Slack workspaces your company manages. Connect your company Slack workspace instead.";class Ee extends Error{constructor(){super(ke),this.name="SlackWorkspaceNotManagedError"}}class Ce extends Error{constructor(){super("Slack couldn't confirm which workspace this connection is for, and your team admin only allows the Slack workspaces your company manages. Try again in a moment."),this.name="SlackWorkspaceUnconfirmedError"}}function xe(e){return URL.canParse(e)&&"mcp.slack.com"===new URL(e).hostname.toLowerCase()}function _e(e,t){const r=new Map,o=t.lookUpWorkspace??(t=>async function(e,t){let r;try{const o=await e("https://slack.com/api/auth.test",{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/x-www-form-urlencoded"},signal:AbortSignal.timeout(5e3)});r=await o.json()}catch{return{kind:"unavailable"}}if("object"!=typeof r||null===r)return{kind:"unavailable"};const o=r;return!0!==o.ok?"string"==typeof o.error&&Se.has(o.error)?{kind:"dead"}:{kind:"unavailable"}:"string"!=typeof o.team_id||0===o.team_id.length?{kind:"unavailable"}:"string"==typeof o.enterprise_id&&o.enterprise_id.length>0?{kind:"found",slackTeamId:o.team_id,slackEnterpriseId:o.enterprise_id}:{kind:"found",slackTeamId:o.team_id}}(e,t));let n,s=[];return async(i,a)=>{if(!xe(function(e){return"string"==typeof e?e:e instanceof URL?e.href:e.url}(i)))return e(i,a);const c=function(e,t){const r=new Headers(t?.headers??(e instanceof Request?e.headers:void 0)),o=/^Bearer\s+(.+)$/i.exec(r.get("authorization")??"");return o?.[1]?.trim()||void 0}(i,a);if(void 0===c)return e(i,a);const l=await((void 0===n||Date.now()-n.atMs>=3e4)&&(n={atMs:Date.now(),lists:t.managedSlackWorkspaceLists().then((e=>"unconfirmed"===e?e:(s=e.filter((e=>e.length>0)).map((e=>e.map((e=>e.toUpperCase())))),s)),(()=>s))}),n.lists);if("unconfirmed"===l)throw new Ce;if(0===l.length)return e(i,a);let u=r.get(c);if(void 0===u){const t=await o(c);if("dead"===t.kind)return e(i,a);if("unavailable"===t.kind)throw new Ce;r.size>=64&&r.clear(),r.set(c,t),u=t}const d=[u.slackTeamId,u.slackEnterpriseId].flatMap((e=>void 0===e?[]:[e.toUpperCase()]));if(!l.every((e=>d.some((t=>e.includes(t))))))throw new Ee;return e(i,a)}}function Pe(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(!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){if(!(e instanceof Error))return!1;const t=e,r=e.cause?.code;return"ECONNREFUSED"===t.code||"ECONNREFUSED"===r||e.message.includes("ECONNREFUSED")}(e)}var Ie=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=d6585ecc3ef25fb368c06a7be3232df8c0e9380e7f3_9fbb579d5110d1faa52af09926f676f7/node_modules/@modelcontextprotocol/sdk/dist/esm/types.js");const Re="2026-07-28",Te=-32022,Ae="io.modelcontextprotocol/protocolVersion",Me="io.modelcontextprotocol/clientCapabilities",De="io.modelcontextprotocol/clientInfo",Oe="io.modelcontextprotocol/serverInfo",Ne={name:"cursor",version:"1.0.0"},$e=new Map;function Fe(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function je(e){const t=new URL(String(e));return t.hash="",t.href}function Le(e,t){const r=$e.get(e);return!(void 0===r||r<=t()&&($e.delete(e),1))}function Ue(e,t=Date.now){return Le(je(e),t)}function Be(e,t){try{return je(e)===t}catch{return!1}}function We(e){return(e.headers.get("content-type")??"").toLowerCase().includes("application/json")}function He(e,t,r,o,n=t.message){const s=new Headers(e?.headers);if(s.set("mcp-protocol-version",Re),s.set("mcp-method",r),s.delete("mcp-session-id"),!t.isRequest&&n===t.message)return{...e,headers:s};const i=Fe(n.params)?n.params:{},a=Fe(i._meta)?i._meta:{},c=function(e,t){const r="tools/call"===e||"prompts/get"===e?"name":"resources/read"===e?"uri":void 0,o=void 0===r?void 0:t[r];return"string"==typeof o?o:void 0}(r,i);void 0!==c&&s.set("mcp-name",c);const l=JSON.stringify({...n,params:{...i,_meta:{...a,[Ae]:Re,[Me]:o.capabilities,[De]:o.clientInfo}}});return{...e,headers:s,body:l}}function qe(e){return new Response(JSON.stringify({jsonrpc:"2.0",...e}),{status:200,headers:{"content-type":"application/json"}})}function ze(e,t){const r=je(t.serverUrl),o=t.now??Date.now;let n={capabilities:{},clientInfo:{...Ne}},s=!1;const i=()=>s||Le(r,o),a=async(t,i,a)=>{const{method:c,message:l}=t;if(void 0===c)return e(i,a);if("notifications/initialized"===c)return new Response(null,{status:202});if(t.isRequest&&"initialize"===c){const c={jsonrpc:"2.0",id:l.id,method:"server/discover",params:{}},u=await e(i,He(a,t,"server/discover",n,c)),d=await async function(e,t,r){if(!e.ok||!We(e))return e;let o;try{o=await e.clone().json()}catch{return e}if(!Fe(o)||!Fe(o.result))return e;const n=o.result,s=n.supportedVersions;if(!Array.isArray(s)||!s.includes(Re))return qe({id:t,error:{code:Te,message:"Unsupported protocol version",data:{requested:Re,supported:s??[]}}});const i=Fe(n._meta)?n._meta:{},a=Fe(i[Oe])?i[Oe]:{name:new URL(r).hostname,version:"unknown"};return qe({id:t,result:{protocolVersion:Ie.aE,capabilities:Fe(n.capabilities)?n.capabilities:{},serverInfo:a,..."string"==typeof n.instructions?{instructions:n.instructions}:{}}})}(u,l.id,r);return d!==u&&(s=!0,function(e,t){$e.set(e,t()+6e5)}(r,o)),d}return e(i,He(a,t,c,n))};return async(t,c)=>{const l=function(e,t,r){if("POST"!==(t?.method??"GET").toUpperCase()||"string"!=typeof t?.body||!Be(e,r))return;let o;try{o=JSON.parse(t.body)}catch{return}if(!Fe(o)||"2.0"!==o.jsonrpc)return;const n="string"==typeof o.method?o.method:void 0;return{message:o,method:n,isRequest:void 0!==n&&"id"in o}}(t,c,r);if(void 0===l)return function(e,t,r){return"GET"===(t?.method??"GET").toUpperCase()&&Be(e,r)}(t,c,r)&&i()?new Response(null,{status:405}):e(t,c);if(l.isRequest&&"initialize"===l.method){const e=Fe(l.message.params)?l.message.params:{};n={capabilities:Fe(e.capabilities)?e.capabilities:{},clientInfo:Fe(e.clientInfo)?e.clientInfo:n.clientInfo}}const u=l.isRequest&&"initialize"===l.method;if(u?Le(r,o):i())return a(l,t,c);if(u&&(s=!1),!l.isRequest)return e(t,c);const d=await e(t,c);if(u&&await async function(e){if(e.status>=500||!We(e))return!1;const t=Number(e.headers.get("content-length"));if(Number.isFinite(t)&&t>4096)return!1;let r;try{r=await e.clone().json()}catch{return!1}if(!Fe(r)||!Fe(r.error))return!1;const o=r.error;if(o.code!==Te||!Fe(o.data))return!1;const n=o.data.supported;return Array.isArray(n)&&n.includes(Re)}(d)){const e=await a(l,t,c);return s?e:d}return d}}},"../mcp-core/dist/mcp-tool-annotations.js"(e,t,r){r.d(t,{NY:()=>n,hT:()=>i,yC:()=>s});var o=r("../constants/dist/mcp.js");function n(e){return void 0!==e&&!0!==e.destructiveHint&&!0===e.readOnlyHint}function s(e){if(void 0!==e&&0!==e.length)try{const t=JSON.parse(e);if("object"==typeof t&&null!==t&&!Array.isArray(t))return t}catch{}}function i(e){if(void 0===e)return{};const t={};"string"==typeof e.title&&e.title.length>0&&(t.title=e.title.slice(0,256));for(const r of["readOnlyHint","destructiveHint","idempotentHint","openWorldHint"])"boolean"==typeof e[r]&&(t[r]=e[r]);return function(e){return!0===e?.[o.TI]}(e)&&(t[o.TI]=!0),0===Object.keys(t).length?{}:{annotationsJson:JSON.stringify(t)}}},"../mcp-core/dist/oauth/resolved-oauth-client-id.js"(e,t,r){r.d(t,{qF:()=>n});const o=/\$\{[^}]*\}/;function n(e){if(void 0!==function(e){if(void 0===e)return;const t=e.trim();return 0!==t.length&&o.test(t)?t:void 0}(e))return;const t=e?.trim();return t&&t.length>0?t:void 0}},"../mcp-core/dist/oauth/rest-mcp-provider-metadata.js"(e,t,r){r.d(t,{Ez:()=>i});var o=r("../constants/dist/mcp.js"),n=r("../utils/dist/test-resets.js");const s=new Map;async function i(e,t=fetch){if(void 0===(0,o.sr)(e))return;const r=new URL(e),n=`${r.origin}/.well-known/oauth-protected-resource${r.pathname.replace(/\/+$/,"")}`,i=s.get(n);if(void 0!==i&&i.expiresAtMs>Date.now())return i.metadata;let a;try{const e=await t(n);if(!e.ok)return;a=(0,o.vI)(await e.json())}catch{return}return s.set(n,{metadata:a,expiresAtMs:Date.now()+3e5}),a}(0,n.J)((function(){s.clear()}))},"../mcp-core/dist/transport/mcp-url-utils.js"(e,t,r){r.d(t,{$H:()=>q,ME:()=>L,_N:()=>H,b6:()=>j,bi:()=>P,mD:()=>A,vc:()=>N});const o=BigInt(0),n=BigInt(8),s=BigInt(16),i=BigInt(65535);function a(e){const t=e.split(".");if(4!==t.length)return;let r=o;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<<n|BigInt(t)}return{version:4,value:r}}function c(e){if(0===e.length)return[];const t=[],r=e.split(":");for(let e=0;e<r.length;e++){const o=r[e];if(0===o.length)return;if(o.includes(".")){if(e!==r.length-1)return;const n=a(o);if(!n)return;t.push(Number(n.value>>s&i)),t.push(Number(n.value&i))}else{if(!/^[0-9a-f]{1,4}$/i.test(o))return;t.push(Number.parseInt(o,16))}}return t}function l(e){return a(e)??function(e){const t=$(e);if(0===t.length||t.includes(":::"))return;const r=t.indexOf("::");if(-1===r){const e=c(t);if(!e||8!==e.length)return;return{version:6,value:e.reduce(((e,t)=>e<<s|BigInt(t)),o)}}if(-1!==t.indexOf("::",r+1))return;const n=t.slice(0,r),i=t.slice(r+2),a=c(n),l=c(i);if(!a||!l)return;const u=a.length+l.length;return u>7?void 0:{version:6,value:[...a,...new Array(8-u).fill(0),...l].reduce(((e,t)=>e<<s|BigInt(t)),o)}}(e)}const u=new Map,d=new Map;function h(e,t){return function(e,t){switch(t.kind){case"matchAll":return!0;case"invalidCidr":return!1;case"cidr":{const r=function(e){if(d.has(e))return d.get(e);d.size>=I&&d.clear();const t=l(e);return d.set(e,t),t}(e);return void 0!==r&&r.version===t.version&&r.value>>t.shift===t.shiftedNetwork}case"subdomainOrBase":return e===t.suffix||e.endsWith(`.${t.suffix}`);case"exact":return e===t.value}}($(e),function(e){const t=u.get(e);if(t)return t;u.size>=I&&u.clear();const r=function(e){const t=$(e);if("*"===t)return{kind:"matchAll"};if(t.includes("/")){const e=t.lastIndexOf("/");if(e<=0||e===t.length-1)return{kind:"invalidCidr"};const r=l(t.slice(0,e));if(!r)return{kind:"invalidCidr"};const o=Number(t.slice(e+1)),n=4===r.version?32:128;if(!Number.isInteger(o)||o<0||o>n)return{kind:"invalidCidr"};const s=BigInt(n-o);return{kind:"cidr",version:r.version,shift:s,shiftedNetwork:r.value>>s}}return t.startsWith("*.")?{kind:"subdomainOrBase",suffix:t.slice(2)}:{kind:"exact",value:t}}(e);return u.set(e,r),r}(t))}new Set(["airtable.com","anysphere.co","api.aws","apify.com","asana.com","ashbyhq.com","atlassian.com","atlassian.net","azuredatabricks.net","box.com","buildkite.com","calendly.com","canva.com","clickhouse.cloud","clickup.com","cloudflare.com","composio.dev","context7.com","cursor.com","cursor.sh","cursorapi.com","databricks.com","datadoghq.com","datadoghq.eu","ddog-gov.com","dropbox.com","elevenlabs.io","exa.ai","figma.com","firecrawl.dev","github.com","githubcopilot.com","gitlab.com","google.com","googleapis.com","granola.ai","hex.tech","hubspot.com","huggingface.co","intercom.com","linear.app","monday.com","neon.tech","notion.com","plain.com","posthog.com","prisma.io","railway.com","ramp.com","render.com","salesforce.com","sentry.dev","sentry.io","slack.com","snowflakecomputing.com","spacelift.io","statsig.com","stripe.com","supabase.com","todoist.net","vercel.com","workos.com","x.ai","x.com","zapier.com"]);const p="Blocked by MCP Network Admin Server Controls";function f(e){return/\s/.test(e)}const m="[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?",g=new RegExp(`^(?:${m}\\.)*${m}$`),w=new RegExp(`^\\*\\.(?:${m}\\.)*${m}$`),y="(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)",v=new RegExp(`^${y}(?:\\.${y}){3}$`),b=/^[0-9a-f:]+$/,S=new RegExp(`^(?:${y}(?:\\.${y}){3}|[0-9a-f:]+)\\/\\d{1,3}$`);function k(e){const t=$(e);return t.length>0&&t.length<=253&&g.test(t)}function E(e){const t=$(e);return v.test(t)||function(e){const t=$(e);if(!b.test(t))return!1;try{return new URL(`https://[${t}]`),!0}catch{return!1}}(t)}function C(e,t){return""===t||"http:"===e&&"80"===t||"https:"===e&&"443"===t}function x(e){const t=new URL(e.pathname||"/",e.origin);if(t.search=e.search,t.pathname.endsWith("/")&&t.pathname.length>1&&(t.pathname=t.pathname.slice(0,-1)),"/"===t.pathname&&""===t.search){const t=e.protocol.toLowerCase();let r=`${t}//${e.hostname.toLowerCase()}`;return C(t,e.port)||(r+=`:${e.port}`),r}const r=e.protocol.toLowerCase();let o=`${r}//${e.hostname.toLowerCase()}`;return C(r,e.port)||(o+=`:${e.port}`),`${o}${t.pathname}${t.search}`}function _(e){if(e.includes("://"))return function(e){try{const t=new URL(e);return("http:"===t.protocol||"https:"===t.protocol)&&!(0===t.hostname.length||t.username.length>0||t.password.length>0)&&""===t.hash&&function(e){const t=e.toLowerCase();return!t.includes("*")&&(k(t)||E(t))}(t.hostname)}catch{return!1}}(e);const t=$(e);return"*"===t||!!w.test(t)||(t.includes("/")?function(e){const t=$(e);if(!S.test(t))return!1;const[r]=t.split("/");return void 0!==r&&h(r,t)}(t):k(t)||E(t))}function P(e){if(R.has(e))return R.get(e);R.size>=I&&R.clear();const t=function(e){const t=e.trim();if(0===t.length)return;const r=t.lastIndexOf("/");if(!t.includes("://")&&r>0&&/^\d+$/.test(t.slice(r+1).trim())){const e=`${$(t.slice(0,r))}/${t.slice(r+1).trim()}`;return _(e)?e:void 0}if(f(t)||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;if(e.hostname.includes("*"))return;if(r||o){const t=x(e);if(!_(t))return;return t}{const t=x(e);if(!_(t))return;return t}}catch{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||!_(s)||s!==n&&"*"===s?void 0:s}(e);return R.set(e,t),t}const I=2048,R=new Map,T=new Map;function A(e,t){if(!e.includes("*"))return e===t;const r=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${r}$`).test(t)}function M(e){return e.endsWith("/")&&e.length>1?e.slice(0,-1):e}function D(e,t){return function(e,t,r){const o=O(t);if(!o)return!1;let n;try{n=new URL(e)}catch{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("*")&&$(s)===$(i)&&(A(a=n.pathname,c=o.pathname)||A(M(a),M(c)))&&function(e,t,r){return""===e?r.allowRequestQueryWhenPatternOmitsQuery||""===t:A(e,t)}(n.search,o.search,r));var s,i,a,c}(e,t,{allowRequestQueryWhenPatternOmitsQuery:!0})}function O(e){const t=e.trim();if(0===t.length||f(t))return;if(function(e){const t=e.indexOf("[");return-1!==t&&-1===e.indexOf("]",t)}(t))return;const r=F(t);if(r&&("http:"===r.protocol||"https:"===r.protocol)&&""===r.username&&""===r.password&&0!==r.hostname.length&&(!$(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($(r.hostname)!==$(n))return}return r}}function N(e,t){if(A(e,t))return!0;let r;return T.has(t)?r=T.get(t):(T.size>=I&&T.clear(),r=F(t),T.set(t,r)),!!r&&h(r.hostname,e)}function $(e){const t=e.trim().toLowerCase();return t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t}function F(e){const t=e.trim();if(0===t.length)return;const r=t.includes("://")?t:`https://${t}`;try{return new URL(r)}catch{return}}function j(e){return(e.mcpNetworkAllowlist??[]).flatMap((e=>{const t=P(e);return void 0===t?[]:[t]}))}function L(e,t){if(!0!==t.enabled)return{allowed:!0};if("no_sandbox"===t.mcpNetworkMode)return{allowed:!0};if(!O(e))return{allowed:!1,message:t.blockMessage??p};const r=j(t);return r.length>0&&r.some((t=>function(e,t){const r=O(t);if(!r)return!1;if(!e.includes("://"))return h($(r.hostname),e);if(D(e,t))return!0;const o=function(e){try{const t=new URL(e);if(""!==t.username||""!==t.password||"/"!==t.pathname||""!==t.search||""!==t.hash)return;return`${t.protocol}//${t.host}/*`}catch{return}}(e);return void 0!==o&&D(o,t)}(t,e)))?{allowed:!0}:{allowed:!1,message:t.blockMessage??p}}function U(e){const t=e?.trim();return t&&t.length>0?t:void 0}function B(e){return U(e)?.toLowerCase()}function W(e,t,r){return void 0!==r?.command&&void 0===r.url&&void 0===t&&!0===e?.allowUserOverrideMcpServers}function H({allowedMcpConfiguration:e,server:t,localAgentNetworkAllowlist:r,blockMessage:o,unmatchedServerAllowlist:n,aggregateManagedServerNetworkAllowlists:s=!0,stdioPlatform:i,unsandboxUserExtensionStdio:a}){const c=e?.allowedMcpServers,l=function(e){if(!0!==e?.allowUserOverrideMcpServers)return;const t=(e.deniedMcpServers??[]).flatMap((e=>{const t=U(e.serverUrl),r=void 0===t?void 0:function(e){const t=e.trim();if(0===t.length)return;if(function(e){const t=e.indexOf("://");if(-1===t)return!1;const r=e.slice(t+3),o=r.indexOf("/");return-1===o?r.includes("?"):r.slice(o).includes("*")}(t)){const e=t.indexOf("://");if(-1!==e){const r=t.slice(e+3).split(/[/?#]/,1)[0];if(r?.includes("*")){const e=P(r.replace(/:\d+$/,""));if(void 0!==e)return e}}return}if(!t.includes("://")&&t.includes("*")&&"*"!==t&&!t.startsWith("*."))return;const r=P(e);if(void 0!==r)return r;const o=e.indexOf("://");if(-1===o)return;const n=e.slice(0,o).toLowerCase();if("http"!==n&&"https"!==n)return;const s=e.slice(o+3).split(/[/?#]/,1)[0];if(void 0===s||s.includes("@"))return;const i=P(s.replace(/:\d+$/,""));if(void 0!==i)return i;try{return P(new URL(e).hostname)}catch{return}}(t);return void 0===r?[]:[r]}));return t.length>0?t:void 0}(e),u=void 0===t?void 0:function(e,t){return e?.find((e=>function(e,t){const r=B(e.builtinServer),o=B(t.builtinServer);if(void 0!==r||void 0!==o)return void 0!==r&&r===o;const n=U(e.command),s=U(e.serverUrl);if(void 0===n&&void 0===s)return!1;const i=void 0===n||void 0!==t.command&&A(n,t.command),a=void 0===s||void 0!==t.url&&N(s,t.url);return i&&a}(e,t)))}(c,t),d=W(e,u,t),h=function({allowedMcpConfiguration:e,matchedServer:t,server:r}){return void 0===r?(e?.allowedMcpServers?.length??0)>0:void 0!==t||W(e,t,r)}({allowedMcpConfiguration:e,matchedServer:u,server:t})||void 0===t&&void 0!==l,p=void 0===t?s?c?.flatMap((e=>e.networkAllowlist??[])):void 0:d?[]:function(e,t,r){return void 0===e?r:[...e.networkAllowlist??[],...void 0!==U(e.serverUrl)&&void 0!==t.url?[t.url]:[]]}(u,t,n),f=d&&"win32"===i&&!0===a;let m;m=void 0===t?void 0:f?"no_sandbox":d?"allow_all":function(e,t){var r;if(void 0!==U(e?.command)&&void 0!==t.command&&void 0===t.url)return r=e?.networkMode,("allow_all"===r||"allowlist"===r||"deny_all"===r||"no_sandbox"===r?r:void 0)??"no_sandbox"}(u,t);const g=void 0===t||d?l:void 0;return{enabled:h,mcpNetworkAllowlist:p,...void 0!==m?{mcpNetworkMode:m}:{},...void 0!==g?{mcpNetworkDenylist:g}:{},...void 0!==r?{localAgentNetworkAllowlist:r}:{},...void 0!==o?{blockMessage:o}:{},...f?{win32UserExtensionUnsandbox:!0}:{}}}function q(e){if(!0===e?.enabled&&"no_sandbox"!==e.mcpNetworkMode)return e}},"../shell-exec/dist/api/index.js"(e,t,r){function o(e){const t=e||process.env,{ELECTRON_RUN_AS_NODE:r,...o}=t;for(const e of Object.keys(o))e.startsWith("AGENT_HOST_DAEMON_")&&delete o[e];return o}r.d(t,{BM:()=>Dr,Ls:()=>c,SandboxUnsupportedError:()=>kt,J:()=>b,St:()=>Ct,Fn:()=>Mr,r5:()=>ee,oG:()=>ur,Ko:()=>C,CG:()=>_e,W1:()=>$,G6:()=>Ar,_B:()=>ge,OK:()=>fe,$b:()=>me,K3:()=>Pt,tv:()=>Ee,wG:()=>Me,fZ:()=>Oe,s9:()=>Ie,XX:()=>Ae,T6:()=>ye,Po:()=>we,$6:()=>Se,l7:()=>Ce,xS:()=>v,resolveSandboxPolicyForWorkspace:()=>Fe,spawnInSandbox:()=>xt,Xw:()=>E});const n=["SSH_AUTH_SOCK","DBUS_SESSION_BUS_ADDRESS","XDG_RUNTIME_DIR","WAYLAND_DISPLAY"];function s(e){const t={...e};for(const e of n)delete t[e];return t}var i,a=r("node:perf_hooks");!function(e){e[e.SampleIntervalMs=250]="SampleIntervalMs",e[e.EventLoopResolutionMs=20]="EventLoopResolutionMs"}(i||(i={})),a.monitorEventLoopDelay;const c="\n[This shell is producing too much output to stream. The command will still run.]\n";var l=r("node:path"),u=r("node:fs"),d=r("../utils/dist/lru-cache.js");const h="undefined"!=typeof process&&"win32"===process.platform,p=new d.q({max:512});function f(e){try{return u.statSync(e)}catch{return null}}function m(e,t){if(e.match(/[\\/]/))return e;const r=t?`${e}\0${t.source}\0${t.flags}`:e,o=p.get(r);if(void 0!==o)return o;const n=l.join(".",e);if(f(n))return p.set(r,n),n;const s=process.env.PATH.split(h?";":":");for(const o of s){const n=l.join(o,e);if(f(n)&&(!t||t.test(n)))return p.set(r,n),n}return p.set(r,e),e}function g(e,t,r){if("win32"!==process.platform)return{cmd:m(e),args:t};if(!u.existsSync(e)){const o=[".exe",".bat",".cmd",".ps1"],n=e.toLowerCase();if(o.some((e=>n.endsWith(e)))){const o=m(e,r);if(u.existsSync(o))return g(o,t,r)}for(const n of o){const o=m(`${e}${n}`,r);if(u.existsSync(o))return g(o,t,r)}}return e.match(/\.ps1$/i)?{cmd:l.join(process.env.SYSTEMROOT,"System32","WindowsPowerShell","v1.0","PowerShell.exe"),args:["-ExecutionPolicy","Unrestricted","-NoLogo","-NonInteractive","-File",e].concat(t)}:e.match(/\.(bat|cmd)$/i)?{cmd:l.join(process.env.SYSTEMROOT,"System32","cmd.exe"),args:["/C",e,...t]}:e.match(/\.(js)$/i)?{cmd:process.execPath,args:[e].concat(t)}:{cmd:e,args:t}}let w;const y=["/usr/local/bin","/usr/bin","/bin"];function v(){const e=g("rg",[]).cmd;return"rg"!==e?e:void 0}function b(e){if(!e)throw new Error("configureRipgrepPath: path must not be empty");w=e}function S(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 k(e,t){const r=(0,l.dirname)(t);if(!r||"."===r)return e;let o=function(e){const t=S(e);return void 0!==t?e[t]??"":""}(e).split(l.delimiter).filter(Boolean);return 0===o.length&&"win32"!==process.platform&&(o=y),function(e,t){const r=S(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,...o.filter((e=>e!==r))].join(l.delimiter))}function E(e){return w&&(0,l.isAbsolute)(w)?{...k(e,w),CURSOR_RIPGREP_PATH:w}:e}function C(){if(!w)throw new Error("Ripgrep path not configured. Call configureRipgrepPath() at startup.");return w}const x="win32"===process.platform;function _(e){return!x&&!!e?.SUDO_ASKPASS}function P(e){return _(e)?"alias sudo='sudo -A'; ":""}function I(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 R=r("node:crypto?8af2"),T=r("node:os"),A=r("../utils/dist/workspace-paths.js"),M=r("../utils/dist/test-resets.js");let D;function O(e,t){const r=(0,u.lstatSync)(e);return r.isDirectory()&&r.uid===t&&!(18&r.mode)}function N(e){try{(0,u.mkdirSync)(e,{mode:448})}catch(e){if(!(e instanceof Error&&"code"in e&&"EEXIST"===e.code))throw e}}function $(e){return F(e,{create:!1})}function F(e,{create:t}){const r=process.getuid?.();if(void 0===r)return;const o=(0,l.join)((0,T.tmpdir)(),`cursor-sandbox-${(0,A.r_)((0,l.resolve)(e))}`);try{for(const e of[o,(0,l.join)(o,"tmp")])if(t&&N(e),!O(e,r))return;return o}catch{return}}(0,M.J)((function(){D=void 0}));const j='builtin eval "${__CURSOR_SANDBOX_TEMP_RESTORE:-}" 2>/dev/null; ';function L(e=(0,l.join)((0,T.tmpdir)(),"cursor-sandbox-cache",function(){return D||(D=(0,R.randomBytes)(16).toString("hex")),D}())){return{NPM_CONFIG_CACHE:(0,l.join)(e,"npm"),PNPM_STORE_PATH:(0,l.join)(e,"pnpm-store"),GOCACHE:(0,l.join)(e,"go-build"),GOMODCACHE:(0,l.join)(e,"go-mod"),CARGO_TARGET_DIR:(0,l.join)(e,"cargo-target"),PIP_CACHE_DIR:(0,l.join)(e,"pip"),UV_CACHE_DIR:(0,l.join)(e,"uv"),BUN_INSTALL_CACHE_DIR:(0,l.join)(e,"bun"),YARN_CACHE_FOLDER:(0,l.join)(e,"yarn"),npm_config_devdir:(0,l.join)(e,"node-gyp"),PLAYWRIGHT_BROWSERS_PATH:(0,l.join)(e,"playwright"),PUPPETEER_CACHE_DIR:(0,l.join)(e,"puppeteer"),TURBO_CACHE_DIR:(0,l.join)(e,"turbo"),GRADLE_USER_HOME:(0,l.join)(e,"gradle"),CONDA_PKGS_DIRS:(0,l.join)(e,"conda"),POETRY_CACHE_DIR:(0,l.join)(e,"poetry"),GEM_SPEC_CACHE:(0,l.join)(e,"gem-specs"),BUNDLE_PATH:(0,l.join)(e,"bundle"),COMPOSER_HOME:(0,l.join)(e,"composer"),HOMEBREW_CACHE:(0,l.join)(e,"homebrew"),CYPRESS_CACHE_FOLDER:(0,l.join)(e,"cypress"),NX_CACHE_DIRECTORY:(0,l.join)(e,"nx"),NUGET_PACKAGES:(0,l.join)(e,"nuget"),CCACHE_DIR:(0,l.join)(e,"ccache"),CP_HOME_DIR:(0,l.join)(e,"cocoapods")}}var U=r("node:fs/promises"),B=r("node:child_process"),W=r("../../node_modules/.pnpm/rxjs@8.0.0-alpha.14/node_modules/rxjs/dist/cjs/index.js"),H=r("../../node_modules/.pnpm/rxjs@8.0.0-alpha.14/node_modules/rxjs/dist/cjs/operators/index.js");class q extends Error{constructor(e,t,r,o,n,s){super(e),this.name="SpawnError",this.exitCode=t,this.code=t,this.stdout=n,this.stderr=s,this.command=r,this.args=o,Error.captureStackTrace&&Error.captureStackTrace(this,q)}}function z(e,t,r){r=r??{};let o=new W.Observable((o=>{const{encoding:n,timeout:s,...i}=r,{cmd:a,args:c}=g(e,t),l=i.stdin;l&&(delete i.stdin,i.stdio??=["pipe","pipe","pipe"]),i.stdio??=["ignore","pipe","pipe"];const u=(0,B.spawn)(a,c,i);r.processInfo&&void 0!==u.pid&&(r.processInfo.pid=u.pid);let d=null;s&&s>0&&(d=setTimeout((()=>{u.killed||u.kill();const e=new q(`Process timed out after ${s}ms`,-1,a,c);o.error(e)}),s));const h=t=>s=>{if(s.length<1)return;r.echoOutput&&("stdout"===t?process.stdout:process.stderr).write(s);let i="<< String sent back was too long >>";try{i="string"==typeof s?s.toString():s.toString(n||"utf8")}catch{i=`<< Lost chunk of process output for ${e} - length was ${s.length}>>`}o.next({source:t,text:i})},p=new W.Subscription;if(l)if(u.stdin){const e=u.stdin;p.add(l.subscribe({next:t=>e.write(t),error:o.error.bind(o),complete:()=>e.end()}))}else o.error(new Error("opts.stdio conflicts with provided spawn opts.stdin observable, 'pipe' is required"));let f=null,m=null,w=!1;return u.stdout?(m=new W.AsyncSubject,u.stdout.on("data",h("stdout")),u.stdout.on("close",(()=>{m.next(!0),m.complete()}))):m=(0,W.of)(!0),u.stderr?(f=new W.AsyncSubject,u.stderr.on("data",h("stderr")),u.stderr.on("close",(()=>{f.next(!0),f.complete()}))):f=(0,W.of)(!0),u.on("error",(e=>{w=!0,d&&clearTimeout(d),o.error(e)})),u.on("close",(e=>{w=!0,d&&clearTimeout(d);const t=(0,W.merge)(m,f).pipe((0,H.TS)((e=>!0),!0));0===e?t.subscribe((()=>o.complete())):t.subscribe((()=>{const t=new q(`Process failed with exit code: ${e}`,e,a,c);o.error(t)}))})),p.add(new W.Subscription((()=>{w||(d&&clearTimeout(d),u.kill())}))),p}));if(r.retries&&r.retries>0){const e=r.retries,t=r.retryDelay??1e3;o=o.pipe((0,H.L5)({count:e,delay:(e,r)=>{if(e instanceof q&&0!==e.exitCode)return(0,W.timer)(t);throw e}}))}return r.split?o:o.pipe((0,H.Tj)((e=>e?.text)))}function G(e,t,r){return r?.split?(o=z(e,t,{...r??{},split:!0}),new Promise(((e,t)=>{let r="",n="";o.subscribe({next:e=>{"stdout"===e.source?r+=e.text:n+=e.text},error:e=>{if(e instanceof q){const o=new q(`${r}\n${e.message}`,e.exitCode,e.command,e.args,r,n);t(o)}else{const o=new Error(`${r}\n${e instanceof Error?e.message:String(e)}`);t(o)}},complete:()=>e([r,n])})}))):function(e){return new Promise(((t,r)=>{let o="";e.subscribe({next:e=>{o+=e},error:e=>{if(e instanceof q){const t=new q(`${o}\n${e.message}`,e.exitCode,e.command,e.args,o,e.stderr);r(t)}else{const t=new Error(`${o}\n${e instanceof Error?e.message:String(e)}`);r(t)}},complete:()=>t(o)})}))}(z(e,t,{...r??{},split:!1}));var o}var V=r("../../node_modules/.pnpm/ignore@7.0.5/node_modules/ignore/index.js");const J=[".local/bin",".local/share/mise",".local/share/pnpm",".nvm",".volta",".asdf",".pyenv",".rbenv",".rustup",".cargo/bin",".cargo/registry",".cargo/git"],K=["bin","sbin","lib","opt","Cellar","share","Frameworks","etc/gitconfig","etc/openssl@3/cert.pem","etc/openssl@3/openssl.cnf","etc/ca-certificates"],Z=(e,t)=>t.flatMap((t=>K.map((r=>({platform:e,scope:"global",path:`${t}/${r}`}))))),X={linux:[".cache/node",".cache/yarn"],darwin:[".cache/node","Library/Caches/Yarn"]},Q=e=>[...J,...X[e]].map((t=>({platform:e,scope:"home-dir",path:t}))),Y=[{platform:"linux",scope:"global",path:"/bin"},{platform:"linux",scope:"global",path:"/sbin"},{platform:"linux",scope:"global",path:"/usr/bin"},{platform:"linux",scope:"global",path:"/usr/sbin"},{platform:"linux",scope:"global",path:"/lib"},{platform:"linux",scope:"global",path:"/lib64"},{platform:"linux",scope:"global",path:"/usr/lib"},{platform:"linux",scope:"global",path:"/usr/lib64"},{platform:"linux",scope:"global",path:"/usr/libexec"},{platform:"linux",scope:"global",path:"/usr/share"},{platform:"linux",scope:"global",path:"/etc/ld.so.cache"},{platform:"linux",scope:"global",path:"/etc/ld.so.conf"},{platform:"linux",scope:"global",path:"/etc/ld.so.conf.d"},{platform:"linux",scope:"global",path:"/etc/ssl/certs"},{platform:"linux",scope:"global",path:"/etc/ssl/openssl.cnf"},{platform:"linux",scope:"global",path:"/etc/ssl/cert.pem"},{platform:"linux",scope:"global",path:"/etc/ssl/ca-bundle.pem"},{platform:"linux",scope:"global",path:"/etc/ssl/certs/ca-certificates.crt"},{platform:"linux",scope:"global",path:"/etc/pki/tls/certs"},{platform:"linux",scope:"global",path:"/etc/pki/tls/openssl.cnf"},{platform:"linux",scope:"global",path:"/etc/pki/ca-trust/extracted"},{platform:"linux",scope:"global",path:"/etc/resolv.conf"},{platform:"linux",scope:"global",path:"/etc/hosts"},{platform:"linux",scope:"global",path:"/etc/nsswitch.conf"},{platform:"linux",scope:"global",path:"/etc/gai.conf"},{platform:"linux",scope:"global",path:"/etc/alternatives"},{platform:"linux",scope:"global",path:"/etc/mime.types"},{platform:"linux",scope:"global",path:"/etc/profile"},{platform:"linux",scope:"global",path:"/etc/bash.bashrc"},{platform:"linux",scope:"global",path:"/etc/zsh/zshenv"},{platform:"linux",scope:"global",path:"/etc/zsh/zprofile"},{platform:"linux",scope:"global",path:"/etc/zsh/zshrc"},{platform:"linux",scope:"global",path:"/etc/zsh/zlogin"},{platform:"linux",scope:"global",path:"/etc/gitconfig"},{platform:"linux",scope:"home",path:".bashrc"},{platform:"linux",scope:"home",path:".bash_profile"},{platform:"linux",scope:"home",path:".profile"},{platform:"linux",scope:"home",path:".zshenv"},{platform:"linux",scope:"home",path:".zprofile"},{platform:"linux",scope:"home",path:".zshrc"},{platform:"linux",scope:"home",path:".zlogin"},{platform:"linux",scope:"home",path:".gitconfig"},{platform:"linux",scope:"home",path:".ssh/known_hosts"},{platform:"linux",scope:"home",path:".config/mise/config.toml"},{platform:"linux",scope:"home-dir",path:".cache/dotslash"},...Q("linux"),...Z("linux",["/usr/local","/home/linuxbrew/.linuxbrew"]),{platform:"linux",scope:"global",path:"/usr/local/go"},{platform:"linux",scope:"global",path:"/nix/store"},{platform:"linux",scope:"global",path:"/nix/var/nix/profiles"},{platform:"linux",scope:"bundled",path:"ripgrep"},{platform:"darwin",scope:"global",path:"/bin"},{platform:"darwin",scope:"global",path:"/usr/bin"},{platform:"darwin",scope:"global",path:"/usr/lib"},{platform:"darwin",scope:"global",path:"/usr/libexec"},{platform:"darwin",scope:"global",path:"/usr/share"},{platform:"darwin",scope:"global",path:"/System/Library"},{platform:"darwin",scope:"global",path:"/System/Cryptexes"},{platform:"darwin",scope:"global",path:"/Library/Apple"},{platform:"darwin",scope:"global",path:"/Library/Developer/CommandLineTools"},{platform:"darwin",scope:"global",path:"/Applications/Xcode.app"},{platform:"darwin",scope:"global",path:"/Library/Preferences/com.apple.dt.Xcode.plist"},{platform:"darwin",scope:"global",path:"/private/etc/ssl/cert.pem"},{platform:"darwin",scope:"global",path:"/private/etc/ssl/certs"},{platform:"darwin",scope:"global",path:"/private/etc/ssl/openssl.cnf"},{platform:"darwin",scope:"global",path:"/private/etc/hosts"},{platform:"darwin",scope:"global",path:"/private/etc/resolv.conf"},{platform:"darwin",scope:"global",path:"/private/etc/apache2/mime.types"},{platform:"darwin",scope:"global",path:"/etc/profile"},{platform:"darwin",scope:"global",path:"/etc/bashrc"},{platform:"darwin",scope:"global",path:"/etc/zshenv"},{platform:"darwin",scope:"global",path:"/etc/zprofile"},{platform:"darwin",scope:"global",path:"/etc/zshrc"},{platform:"darwin",scope:"global",path:"/etc/zlogin"},{platform:"darwin",scope:"global",path:"/etc/gitconfig"},{platform:"darwin",scope:"home",path:".bashrc"},{platform:"darwin",scope:"home",path:".bash_profile"},{platform:"darwin",scope:"home",path:".profile"},{platform:"darwin",scope:"home",path:".zshenv"},{platform:"darwin",scope:"home",path:".zprofile"},{platform:"darwin",scope:"home",path:".zshrc"},{platform:"darwin",scope:"home",path:".zlogin"},{platform:"darwin",scope:"home",path:".gitconfig"},{platform:"darwin",scope:"home",path:".ssh/known_hosts"},{platform:"darwin",scope:"home",path:"Library/Preferences/.GlobalPreferences.plist"},{platform:"darwin",scope:"home",path:".config/mise/config.toml"},{platform:"darwin",scope:"home-dir",path:"Library/Python"},{platform:"darwin",scope:"home-dir",path:"Library/Caches/dotslash"},...Q("darwin"),...Z("darwin",["/opt/homebrew","/usr/local"]),{platform:"darwin",scope:"global",path:"/nix/store"},{platform:"darwin",scope:"global",path:"/nix/var/nix/profiles"},{platform:"darwin",scope:"bundled",path:"ripgrep"},{platform:"darwin",scope:"global",path:"/dev/null"},{platform:"darwin",scope:"global",path:"/dev/zero"},{platform:"darwin",scope:"global",path:"/dev/random"},{platform:"darwin",scope:"global",path:"/dev/urandom"}];function ee(e=process.platform,t=T.default.homedir(),r={}){const o=[];for(const n of Y){if(n.platform!==e)continue;if("global"===n.scope){o.push(n.path);continue}const s="bundled"===n.scope?r[n.path]:(0,l.join)(t,n.path);if(s)try{let e;switch(n.scope){case"home":e=(0,u.lstatSync)(s).isFile();break;case"home-dir":e=(0,u.lstatSync)(s).isDirectory();break;case"bundled":e=(0,u.statSync)(s).isFile()}e&&o.push(s)}catch{}}return o}const te=[{type:"workspace",pattern:"**/.cursor/*.json"},{type:"workspace",pattern:"**/.cursor/**/*.json"},{type:"workspace",pattern:"**/.cursor/.workspace-trusted"},{type:"workspace",pattern:"!**/.cursor/rules"},{type:"workspace",pattern:"!**/.cursor/rules/**"},{type:"workspace",pattern:"!**/.cursor/commands"},{type:"workspace",pattern:"!**/.cursor/commands/**"},{type:"workspace",pattern:"!**/.cursor/worktrees"},{type:"workspace",pattern:"!**/.cursor/worktrees/**"},{type:"workspace",pattern:"!**/.cursor/skills"},{type:"workspace",pattern:"!**/.cursor/skills/**"},{type:"workspace",pattern:"!**/.cursor/agents"},{type:"workspace",pattern:"!**/.cursor/agents/**"},{type:"workspace",pattern:"**/.claude/*.json"},{type:"workspace",pattern:"**/.claude/**/*.json"},{type:"workspace",pattern:"**/.vscode/**"},{type:"workspace",pattern:"**/.idea/**"},{type:"workspace",pattern:"**/.venv/"},{type:"workspace",pattern:"**/venv/"},{type:"workspace",pattern:"**/*.code-workspace"},{type:"workspace",pattern:"**/.cursorignore"},{type:"workspace",pattern:"**/.workspace-trusted"},{type:"workspace",pattern:"**/.cursor/**/cli.json"},{type:"workspace",pattern:"**/.cursor/**/cli-config.json"},{type:"workspace",pattern:"**/.cursor/**/mcp.json"},{type:"workspace",pattern:"**/.cursor/**/mcp-approvals.json"},{type:"workspace",pattern:"**/.cursor/**/permissions.json"},{type:"git",pattern:"**/.git/hooks/**"},{type:"git",pattern:"**/.git/config"},{type:"git",pattern:"**/.git/config.worktree"},{type:"git",pattern:"**/.git/info/attributes"},{type:"git",pattern:"**/.git/commondir"},{type:"git",pattern:"**/.git/worktrees/*/commondir"},{type:"worktree",pattern:".git"},{type:"absolute",pattern:"/etc/ssl/cert.pem"},{type:"absolute",pattern:"/etc/ssl/ca-bundle.pem"},{type:"absolute",pattern:"/private/etc/ssl/cert.pem"},{type:"absolute",pattern:"/etc/ssl/certs/ca-certificates.crt"},{type:"absolute",pattern:"/etc/pki/tls/certs/ca-bundle.crt"},{type:"absolute",pattern:"/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem"},{type:"home",pattern:".cursor/sandbox-policies"}];function re(e){const t=te.filter((e=>"workspace"===e.type)).map((e=>e.pattern));return{[e]:t}}function oe(e){const t=te.filter((e=>"worktree"===e.type)).map((e=>e.pattern));return{[e]:t}}te.filter((e=>"git"===e.type)).map((e=>e.pattern)),te.filter((e=>"workspace"===e.type&&e.pattern.startsWith("!")&&!e.pattern.endsWith("/**"))).map((e=>e.pattern.replace(/^!(\*\*\/)?/,"")));const ne=[];let se=null,ie=null;let ae=null;const ce=new Map;const le="win32"===process.platform||"darwin"===process.platform;function ue(e){if(!e.endsWith(l.sep))return e;const t=e.slice(0,-1);return""===t||"win32"===process.platform&&/^[a-zA-Z]:$/.test(t)?e:t}function de(e){return e.endsWith(l.sep)?e:e+l.sep}function he(e,t){const r=ue(t);if(le){const t=e.toLowerCase(),o=r.toLowerCase();return t===o||t.startsWith(de(o))}return e===r||e.startsWith(de(r))}function pe(e,t){const r=ue(e);return le?(0,l.relative)(r.toLowerCase(),t.toLowerCase()).replace(/\\/g,"/"):(0,l.relative)(r,t).replace(/\\/g,"/")}async function fe(e,t){if(he(e,t)){const r=pe(t,e);if((null===se&&(se=V({ignoreCase:!0}),se.add(te.filter((e=>"workspace"===e.type)).map((e=>e.pattern)))),se).ignores(r))return!0}const{isWorktree:r,gitDirParent:o}=await async function(e){const t=ce.get(e);if(t)return t;const r=await(0,U.stat)((0,l.join)(e,".git")).catch((()=>null));if(!r?.isFile()){const t={isWorktree:!1,gitDirParent:e};return ce.set(e,t),t}const o=await async function(e){try{const t=await G("git",["rev-parse","--git-common-dir"],{cwd:e});return(0,l.dirname)((0,l.resolve)(e,t.trim()))}catch{return null}}(e),n={isWorktree:!0,gitDirParent:o??e};return ce.set(e,n),n}(t);if(he(e,o)){const t=pe(o,e);if((null===ie&&(ie=V({ignoreCase:!0}),ie.add(te.filter((e=>"git"===e.type)).map((e=>e.pattern)))),ie).ignores(t))return!0}if(r&&he(e,t)&&".git"===pe(t,e))return!0;for(const t of function(){if(null!==ae)return ae;const e=T.default.homedir(),t=[];for(const r of te)switch(r.type){case"absolute":t.push(r.pattern);break;case"home":e.length>0&&t.push((0,l.join)(e,r.pattern))}return ae=t,t}())if(he(e,t))return!0;return!1}function me(e){return void 0!==e&&("allow"===e.default||void 0!==e.allow&&e.allow.length>0)}function ge(e){return void 0!==e&&"allow"===e.default}function we(){return{version:1,default:"deny"}}function ye(){return{version:1,default:"allow"}}var ve=r("../utils/dist/path-utils.js");function be(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 Se(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:be(e.networkPolicy),networkPolicyStrict:e.networkPolicyStrict,additionalReadonlyPaths:o,readBoundary:e.readBoundary,additionalReadPaths:Array.isArray(e.additionalReadPaths)?e.additionalReadPaths:void 0,disableTmpWrite:e.disableTmpWrite};return"workspace_readonly"===t?{type:"workspace_readonly",...n}:{type:"workspace_readwrite",...n,additionalReadwritePaths:e.additionalReadwritePaths}}function ke(e){if("object"!=typeof e||null===e)return"Expected an object";const t=Object.fromEntries(Object.entries(e));if(void 0!==t.type){const e=["insecure_none","workspace_readwrite","workspace_readonly"];if("string"!=typeof t.type||!e.includes(t.type))return`Invalid type: expected one of ${e.join(", ")}`}const r=["networkAccess","networkPolicyStrict","disableTmpWrite","enableSharedBuildCache","captureDenies"];for(const e of r)if(void 0!==t[e]&&"boolean"!=typeof t[e])return`Invalid ${e}: expected boolean`;const o=["debugOutputDir"];for(const e of o)if(void 0!==t[e]&&"string"!=typeof t[e])return`Invalid ${e}: expected string`;const n=["additionalReadwritePaths","additionalReadonlyPaths","additionalReadPaths"];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.readBoundary&&"system"!==t.readBoundary&&"workspace"!==t.readBoundary)return'Invalid readBoundary: expected "system" or "workspace"';if(void 0!==t.networkPolicy){if("object"!=typeof t.networkPolicy||null===t.networkPolicy)return"Invalid networkPolicy: expected object";const e=Object.fromEntries(Object.entries(t.networkPolicy));if(void 0!==e.default&&"allow"!==e.default&&"deny"!==e.default)return'Invalid networkPolicy.default: expected "allow" or "deny"';if(void 0!==e.allow&&!Array.isArray(e.allow))return"Invalid networkPolicy.allow: expected array";if(void 0!==e.deny&&!Array.isArray(e.deny))return"Invalid networkPolicy.deny: expected array"}}async function Ee(e,t){const r=await async function(e,t){try{const r=await(0,U.readFile)(e,"utf-8"),o=JSON.parse(r);if(void 0!==ke(o))return{success:!1,error:`Invalid sandbox policy: ${ke(o)??""}`};let n=Se(o);return t&&(n=Ce(n,t)),{success:!0,policy:n}}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 Ce(e,t){if("insecure_none"===e.type)return e;const r=e.additionalReadonlyPaths?.map((e=>(0,ve.o1)(e,t))),o=e.additionalReadPaths?.map((e=>(0,ve.o1)(e,t)));if("workspace_readonly"===e.type)return{...e,additionalReadonlyPaths:r,additionalReadPaths:o};const n=e.additionalReadwritePaths?.map((e=>(0,ve.o1)(e,t)));return{...e,additionalReadonlyPaths:r,additionalReadPaths:o,additionalReadwritePaths:n}}var xe=r("../utils/dist/safe-spawn-cwd.js");function _e(e){return e.teamAdmin?.type??e.perRepo?.type??e.perUser?.type??"insecure_none"}function Pe(...e){return e.some((e=>!0===e))}function Ie(...e){const t=new Set;for(const r of e)if(r)for(const e of r)t.add(De(e));return[...t]}const Re=function({defaultValue:e,rank:t}){return{defaultValue:e,merge:(...r)=>{const o=r.filter((e=>void 0!==e));return 0===o.length?e:o.reduce(((e,r)=>t[r]<t[e]?r:e))}}}({defaultValue:"system",rank:{workspace:0,system:1}}),Te=(...e)=>function(...e){const t=e.filter((e=>void 0!==e));if(0===t.length)return[];if(t.some((e=>0===e.length)))return[];if(1===t.length)return function(e){const t=new Set,r=[];for(const o of e){const e=De(o);t.has(e)||(t.add(e),r.push(o))}return r}(t[0]).map(De);let r=new Set(t[0].map(De));for(let e=1;e<t.length;e++){const o=new Set(t[e].map(De));r=new Set([...r].filter((e=>o.has(e))))}return[...r]}(...e);function Ae(...e){return Re.merge(...e)}function Me(...e){return Te(...e)}function De(e){const t=e.replace(/\\/g,"/").replace(/\/+$/,"");return""===t?"/":/^[a-zA-Z]:$/.test(t)?`${t}/`:t}function Oe(...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 Ne(...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 $e(...e){for(let t=e.length-1;t>=0;t--)if(void 0!==e[t])return e[t]}async function Fe(e,t,r={}){if(!t)return{policy:{type:"insecure_none"}};if((0,xe.$f)(e))return je(t,{workspaceDir:e});const o=r.stat??U.stat,n=r.spawnPromise??G,s=await o((0,l.join)(e,".git")).then((e=>e),(()=>null)),i=s?.isFile()??!1,a=null!==s;if("workspace_readwrite"===_e(t)){let r=e;if(i){const o=await n("git",["rev-parse","--git-common-dir"],{cwd:e}).then((t=>(0,l.resolve)(e,t.trim())),(()=>null));if(o){r=(0,l.dirname)(o);const n=t.perRepo,s=n?.ignoreMapping;t={...t,perRepo:{...n,type:"workspace_readwrite",additionalReadwritePaths:[...n?.additionalReadwritePaths??[],o],ignoreMapping:s,writeProtectionMapping:Ne(n?.writeProtectionMapping,oe(e))}}}}if(a)return je(t,{workspaceDir:e,gitDirParent:r})}return je(t,{workspaceDir:e})}function je(e,t){return function(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 He({},t);switch(r){case"workspace_readwrite":return He(Ue(e,r),t);case"workspace_readonly":return function(e,t){const r=t?.debug,o=Be(e,t),n={policy:We({type:"workspace_readonly",disableTmpWrite:o.disableTmpWrite,networkPolicyStrict:o.networkPolicyStrict,readBoundary:o.readBoundary,additionalReadPaths:o.additionalReadPaths,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}(Ue(e,r),t);case"insecure_none":return function(e,t){const{perUser:r,perRepo:o,teamAdmin:n}=e,s=t?.debug,i={policy:We({type:"insecure_none",allowlistEscalated:Pe(r?.allowlistEscalated,o?.allowlistEscalated,n?.allowlistEscalated)||void 0,debugOutputDir:$e(r?.debugOutputDir,o?.debugOutputDir,n?.debugOutputDir),captureDenies:Pe(r?.captureDenies,o?.captureDenies,n?.captureDenies)||void 0,enableSharedBuildCache:$e(r?.enableSharedBuildCache,o?.enableSharedBuildCache,n?.enableSharedBuildCache)},"insecure_none")};return s&&(i.debug={fieldSources:{}}),i}(Ue(e,r),t);default:throw new Error(`Unknown policy type: ${String(r)}`)}}(e,t)}function Le(e,t){return e?.type===t}function Ue(e,t){const{perUser:r,perRepo:o,teamAdmin:n}=e;return{perUser:Le(r,t)?r:void 0,perRepo:Le(o,t)?o:void 0,teamAdmin:Le(n,t)?n:void 0}}function Be(e,t){const r=t?.debug,{perUser:o,perRepo:n,teamAdmin:s}=e,i=t?.workspaceDir??process.cwd(),a=function(e){const t=function(){if(0!==ne.length)return{version:1,deny:[...ne]}}(),r=T.default.homedir(),o=[];for(const e of te)switch(e.type){case"workspace":case"git":case"worktree":break;case"absolute":o.push(e.pattern);break;case"home":r.length>0&&o.push((0,l.join)(r,e.pattern));break;default:{const t=e.type;throw new Error(`Unknown entry type: ${String(t)}`)}}return{type:"workspace_readwrite",additionalReadonlyPaths:o,writeProtectionMapping:re(e),...t&&{networkPolicy:t},networkPolicyStrict:!0}}(i),c={},u=[o,n,s],d=["perUser","perRepo","teamAdmin","hardcoded"],h=(e,t)=>{r&&(c[e]=d[t]??"unknown")},p=Pe(o?.disableTmpWrite,n?.disableTmpWrite,s?.disableTmpWrite);for(let e=u.length-1;e>=0;e--)if(!0===u[e]?.disableTmpWrite){h("disableTmpWrite",e);break}const f=Pe(o?.networkPolicyStrict,n?.networkPolicyStrict,s?.networkPolicyStrict,a.networkPolicyStrict);a.networkPolicyStrict&&h("networkPolicyStrict",3);const m=$e(o?.readBoundary,n?.readBoundary,s?.readBoundary)??"system",g=$e(o?.additionalReadPaths,n?.additionalReadPaths),w=!1===s?.allowUserOverrideReadPaths?Ie(s.additionalReadPaths):Ie(g,s?.additionalReadPaths),y="workspace"===m?w:void 0,v=Ie(o?.additionalReadonlyPaths,n?.additionalReadonlyPaths,s?.additionalReadonlyPaths,a.additionalReadonlyPaths),b=v.length>0?v:void 0;let S=Oe(o?.networkPolicy,n?.networkPolicy,s?.networkPolicy,a.networkPolicy);const k=s?.networkPolicy?.allow;void 0!==k&&k.length>0&&void 0!==S&&(S={...S,allow:[...k]},r&&(c["networkPolicy.allow"]="teamAdmin (replace)"));const E=void 0!==(C=S)?C:{version:1,default:"deny"};var C;const x=$e(o?.debugOutputDir,n?.debugOutputDir,s?.debugOutputDir),_=Pe(o?.captureDenies,n?.captureDenies,s?.captureDenies),P=$e(o?.enableSharedBuildCache,n?.enableSharedBuildCache,s?.enableSharedBuildCache),I=Ne(o?.ignoreMapping,n?.ignoreMapping,s?.ignoreMapping,a.ignoreMapping),R=function(e){const t=te.filter((e=>"git"===e.type)).map((e=>e.pattern));return{[e]:t}}(t?.gitDirParent??i);return{disableTmpWrite:p||void 0,networkPolicyStrict:f,readBoundary:m,additionalReadPaths:y,additionalReadonlyPaths:b,networkPolicy:E,debugOutputDir:x,captureDenies:_||void 0,enableSharedBuildCache:P,ignoreMapping:I,writeProtectionMapping:Ne(o?.writeProtectionMapping,n?.writeProtectionMapping,s?.writeProtectionMapping,a.writeProtectionMapping,R),fieldSources:c}}function We(e,t){const r={...e,type:t};for(const[e,t]of Object.entries(r))void 0===t&&Reflect.deleteProperty(r,e);return r}function He(e,t){const{perUser:r,perRepo:o,teamAdmin:n}=e,s=t?.debug,i=Be(e,t),a=Ie(r?.additionalReadwritePaths,o?.additionalReadwritePaths,n?.additionalReadwritePaths),c={policy:We({type:"workspace_readwrite",disableTmpWrite:i.disableTmpWrite,networkPolicyStrict:i.networkPolicyStrict,readBoundary:i.readBoundary,additionalReadPaths:i.additionalReadPaths,additionalReadwritePaths:a.length>0?a:void 0,additionalReadonlyPaths:i.additionalReadonlyPaths,networkPolicy:i.networkPolicy,debugOutputDir:i.debugOutputDir,captureDenies:i.captureDenies,enableSharedBuildCache:i.enableSharedBuildCache,ignoreMapping:i.ignoreMapping,writeProtectionMapping:i.writeProtectionMapping},"workspace_readwrite")};return s&&(c.debug={fieldSources:i.fieldSources}),c}var qe=r("../utils/dist/workload-spawn.js"),ze=r("../context/dist/logger.js"),Ge=r("../context/dist/core.js");const Ve=B.execFile,Je=new WeakMap;function Ke(e,t,r){return e===t?"related":r?.has(e)?"probably_unrelated":"maybe_related"}let Ze=0;function Xe(){const e=function(){const e=process.env.CURSOR_SANDBOX_POLICY_DIR?.trim();return e?l.resolve(e):l.resolve(l.join(T.homedir(),".cursor","sandbox-policies"))}();u.mkdirSync(e,{recursive:!0,mode:448});try{u.chmodSync(e,448)}catch{}const t=Date.now();return t-Ze>=9e5&&(Ze=t,function(e){let t;try{t=u.readdirSync(e)}catch{return}const r=Date.now();for(const o of t){if(!o.startsWith("sandbox-policy-"))continue;const t=l.join(e,o);try{const e=u.statSync(t);if(!e.isFile())continue;r-e.mtimeMs>36e5&&u.unlinkSync(t)}catch{}}}(e)),e}function Qe(e){const t=Xe(),r=R.randomBytes(8).toString("hex"),o=l.join(t,`sandbox-policy-${r}`);return u.writeFileSync(o,e,{encoding:"utf-8",mode:384}),o}const Ye="darwin"===process.platform,et="linux"===process.platform,tt=(0,ze.h)("shell-exec:sandbox");function rt(e){const t=Xe();return e&&0!==e.length?e.includes(t)?e:[...e,t]:[t]}let ot,nt=!0;function st(){return ot}function it(e){"linux"===process.platform&&Object.assign(e,E(e))}let at=null,ct=null,lt=null,ut=null,dt=!1,ht=null;function pt(e){return{...e,additionalReadonlyPaths:rt(e.additionalReadonlyPaths)}}function ft(e,t,r){let o;e.ignoreMapping&&(o=function(e){return vt(e)}(e.ignoreMapping));const n=function(e,t,r){const o=e&&e.length>0?function(...e){const t={};for(const r of e){let e=!1;try{e=(0,u.existsSync)(r)&&(0,u.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):{},n=function(e,t=e=>u.existsSync(e)){if((0,xe.$f)(e))return!0;let r=l.resolve(e);for(;;){try{if(t(l.join(r,".git")))return!0}catch{}const e=l.dirname(r);if(e===r)return!1;r=e}}(r),s=!et||n?t??{}:{},i={...o};for(const[e,t]of Object.entries(s))i[e]?i[e]=[...i[e],...t]:i[e]=t;if(0!==Object.keys(i).length)return vt(i)}(e.additionalReadonlyPaths,e.writeProtectionMapping,t),s=(i=e.readBoundary,r?.workspaceReadEnabled??function(){const e=nt;return"function"==typeof e?e():e}()?i??"system":"system");var i;const a=function(e=process.platform){const t=[],r=new Set,o={};try{o.ripgrep=C()}catch{}for(const n of ee(e,T.homedir(),o))r.has(n)||(r.add(n),t.push(n));return t}(),c="workspace"===s?function(e){const t=[],r=new Set;for(const o of e){let e=o.trim();if(!e)continue;"~"===e?e=T.homedir():(e.startsWith("~/")||e.startsWith("~\\"))&&(e=l.join(T.homedir(),e.slice(2))),e=e.replace(/\/\*\*$/,"").replace(/\/\*$/,""),e=e.replace(/\\\*\*$/,"").replace(/\\\*$/,"");const n=l.basename(e);if((n.includes("*")||n.includes("?"))&&(e=l.dirname(e)),!e||"."===e)continue;const s=l.normalize(e);r.has(s)||(r.add(s),t.push(s))}return t}(e.additionalReadPaths??[]):[],d=[...a],h=new Set(a);for(const e of c)h.has(e)||(h.add(e),d.push(e));const p={cwd:t,readBoundary:s,hardcodedReadPaths:d,additionalReadonlyPaths:n,networkAccess:me(e.networkPolicy),ignoreMapping:o};return"workspace_readonly"===e.type?{type:e.type,...p}:{type:e.type,...p,additionalReadwritePaths:e.additionalReadwritePaths||[],disableTmpWrite:e.disableTmpWrite||!1}}function mt(e){if(null!==at)return at;try{const t=st();return tt.info(e,`[checkBinaryAvailable] Resolved binary path: ${t}`),t?(at=u.existsSync(t),at?tt.info(e,`[checkBinaryAvailable] Binary path exists: ${String(at)}`):(ct=new Error(`Sandbox binary not found at ${t}`),tt.info(e,`[checkBinaryAvailable] Binary not found at: ${t}`)),at):(ct=new Error("Sandbox binary path was not configured"),at=!1,tt.info(e,"[checkBinaryAvailable] Binary path not set, returning false"),!1)}catch(t){return ct=t instanceof Error?t:new Error(String(t)),at=!1,tt.info(e,`[checkBinaryAvailable] Exception checking binary: ${String(t)}`),!1}}function gt(e){if(null!==ut)return ut;const t=e??(0,Ge.q6)();if(tt.info(t,"[isSandboxHelperSupported] Starting sandbox support check..."),!mt(t)){const e=ct?.message||"Binary check failed";return lt=e,tt.info(t,`[isSandboxHelperSupported] Binary not available, returning false. Reason: ${e}`),ut=!1,ut}if("win32"===process.platform)return lt="Windows sandbox helper only provides network proxy, not filesystem isolation",tt.info(t,"[isSandboxHelperSupported] win32: returning false (proxy-only, no filesystem sandbox)"),ut=!1,ut;if("darwin"===process.platform)return lt=null,tt.info(t,`[isSandboxHelperSupported] ${process.platform} platform, binary available, sandbox supported!`),ut=!0,ut;const{binaryPath:r,args:o,env:n}=function(e,t){const r={sandbox:ft(pt({type:"workspace_readwrite"}),t)},o=String(st());tt.info(e,`[sandboxPreflight] Running preflight with binary: ${o}`),tt.info(e,`[sandboxPreflight] CWD: ${t}`);const n={...process.env};return it(n),{binaryPath:o,args:["--policy",Qe(JSON.stringify(r)),"--preflight-only","--","/bin/true"],env:n}}(t,process.cwd());try{const e=Date.now();(0,qe.D9)(B.execFileSync,r,o,{stdio:["ignore","ignore","pipe"],timeout:wt,env:n,shell:!1});const s=Date.now()-e;return lt=null,tt.info(t,`[isSandboxHelperSupported] Preflight succeeded in ${s}ms, sandbox supported!`),ut=!0,ut}catch(e){return function(e,t){const{message:r,status:o,stderrText:n}=t;return tt.error(e,`[sandboxPreflight] Preflight failed: ${r}`),tt.error(e,`[sandboxPreflight] Exit status: ${o}`),n&&tt.error(e,`[sandboxPreflight] Stderr: ${n}`),lt=2===o?`Linux preflight failed with exit code 2 (unsupported kernel features). stderr: ${n||"none"}`:`Linux preflight failed: ${r||"unknown error"}. Exit status: ${o}. stderr: ${n||"none"}`,ut=!1,!1}(t,function(e){if("object"!=typeof e||null===e)return{stderrText:""};const t="message"in e&&"string"==typeof e.message?e.message:void 0,r=!("status"in e)||"number"!=typeof e.status&&null!==e.status?void 0:e.status,o="stderr"in e?e.stderr:void 0;return{message:t,status:r,stderrText:Buffer.isBuffer(o)||"string"==typeof o?o.toString():""}}(e))}}(0,M.J)((function(){ut=null,dt=!1,ht=null,lt=null,at=null,ct=null}));const wt=15e3;function yt(e,t=[],r={},n){const i=(0,Ge.q6)();if(r.env=o(r.env),!mt(i))throw new Error(`Sandbox binary not available: ${ct?.message||"binary not configured"}. Please build the binary or use 'insecure_none' policy.`);if("insecure_none"===n.type)return(0,qe.D9)(B.spawn,e,t,{...r,windowsHide:!0});if("workspace_readwrite"===n.type||"workspace_readonly"===n.type)return function(e,t,r,o){if("workspace_readwrite"!==o.type&&"workspace_readonly"!==o.type)throw new Error("Expected workspace_readwrite or workspace_readonly policy");const n=String(r.cwd??process.cwd()),i=o.sandboxWorkspaceRoot??n;let a=e,c=t;r.shell&&("win32"===process.platform?(a="string"==typeof r.shell?r.shell:"cmd.exe",c=["/c",`${e} ${t.join(" ")}`]):(a="string"==typeof r.shell?r.shell:"/bin/sh",c=["-c",`${e} ${t.join(" ")}`]));const u=ft(pt(o),i),d=function(e){if(!("workspace"!==e.readBoundary||"workspace_readwrite"===e.type&&e.disableTmpWrite||"win32"===process.platform))return F(e.cwd,{create:!0})}(u);d&&(u.additionalReadwritePaths=[...u.additionalReadwritePaths??[],d]);const h=function(e){if("insecure_none"===e.type)return;const t=e.networkPolicy;if(void 0===t)return;if(!me(t))return;const r=void 0!==t.deny&&t.deny.length>0;return"allow"!==t.default||r?{version:1,...t}:void 0}(o),p={sandbox:u};void 0!==h&&(p.networkPolicy=h),!1===o.networkPolicyStrict&&(p.networkPolicyStrict=!1);const f=["--policy",Qe(JSON.stringify(p)),"--",a,...c],m={..."linux"===process.platform?s(process.env):process.env,..."linux"===process.platform&&r.env?s(r.env):r.env,CURSOR_SANDBOX:"native"};if(it(m),d){const e=function(e,t,r){const o=function(e){const t=(0,l.join)(e,"tmp");return{TMPDIR:t,TMP:t,TEMP:t,TMPPREFIX:(0,l.join)(t,"sh-")}}(e);if(r){const r=L();for(const[n,s]of Object.entries(L(e)))t[n]===r[n]&&(o[n]=s)}return o}(d,m,o.enableSharedBuildCache);Object.assign(m,e),m.__CURSOR_SANDBOX_OWNED_ENV=Object.keys(e).join(" "),m.__CURSOR_SANDBOX_TEMP_RESTORE=Object.entries(e).map((([e,t])=>`builtin export ${e}='${t.replace(/'/g,"'\\''")}'`)).join("; ")}const g={cwd:r.cwd||n,env:m,stdio:r.stdio||["pipe","pipe","pipe"],detached:r.detached,windowsHide:!0};try{const e=new Date,t=(0,qe.D9)(B.spawn,String(st()),f,g);return Ye&&t.pid&&function(e,t){Je.set(e,t)}(t,{startTime:e,pid:t.pid}),t}catch(e){throw new Error(`Failed to spawn sandboxed process: ${String(e)}`)}}(e,t,r,n);throw new Error(`Unsupported sandbox policy: ${String(n)}`)}function vt(e,t,r,o){const n={};for(const[t,r]of Object.entries(e)){const e=t.startsWith("file://")?bt(t):t;n[e]=r;const o=St(e);o!==e&&(n[o]=r)}return n}function bt(e){let t=e.replace(/^file:\/\//,"");return t=decodeURIComponent(t),t.length>1&&t.endsWith("/")&&(t=t.slice(0,-1)),t}function St(e,t){if((0,xe.$f)(e))return e;try{return(t??u.realpathSync)(e)}catch{return e}}class kt extends Error{reason;constructor(e,t){super(e),this.reason=t,this.name="SandboxUnsupportedError"}}const Et="darwin"===process.platform;function Ct(e){!function(e){C();const{sandboxBinaryPath:t,workspaceReadEnabled:r}=e;ot||(ot=t),void 0!==r&&(nt=r)}(e)}function xt(e,t=[],r={},n){if(r.env=o(r.env),n.enableSharedBuildCache&&(r={...r,env:{...o(process.env),...L(),...r.env}}),"insecure_none"!==n.type){if(gt())return yt(e,t,r,n);const o=lt;throw new kt(`Sandbox policy '${n.type}' is not supported on this system. Ensure the sandbox helper binary is available, or use 'insecure_none'. Reason: ${o||"unknown"}`,o??void 0)}return function(e,t,r,o={spawn:B.spawn,spawnWorkload:qe.D9}){return o.spawnWorkload(o.spawn,e,t,{...r,windowsHide:!0})}(e,t,r)}function _t(e){return Et?async function(e){const t=Je.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,qe.D9)(Ve,"/usr/bin/log",s,((t,o)=>{if(t)return void e([{raw:t.message}]);const s=o.split(/\r?\n/).filter((e=>e.trim().length>0)),i=[];for(const e of s)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,a,c,l,u,d]=s,h=Number(a);i.push({timestamp:t.timestamp,processName:e.trim(),pid:h,decision:c.toLowerCase(),decisionCode:Number(l),operation:u,target:d,duplicateCount:1,raw:o,relationship:Ke(h,r,n)});continue}const a=/^(\d+) duplicate report for Sandbox: (.+)$/.exec(o);if(a){const e=Number(a[1]),s=a[2],c=/^([^(]+)\((\d+)\)\s+([a-zA-Z-]+)\((\d+)\)\s+([^\s]+)\s+(.+)$/.exec(s);if(c){const[,s,a,l,u,d,h]=c,p=Number(a);i.push({timestamp:t.timestamp,processName:s.trim(),pid:p,decision:l.toLowerCase(),decisionCode:Number(u),operation:d,target:h,duplicateCount:e,raw:o,relationship:Ke(p,r,n)})}else i.push({timestamp:t.timestamp,duplicateCount:e,raw:o});continue}i.push({timestamp:t.timestamp,raw:o})}catch{}e(i)}))}catch(t){e([{raw:String(t)}])}}))):(console.log("No sandbox metadata found on child process"),[]);var r,o,n}(e):Promise.resolve([])}function Pt(e,t){if(Et)try{(0,u.accessSync)("/usr/bin/sandbox-exec",u.constants.X_OK)}catch{return!1}return gt(t?.ctx)}var It=r("node:stream"),Rt=r("../context/dist/otel.js"),Tt=r("../utils/dist/writable-iterable.js");const At="--",Mt='builtin eval "$1"',Dt=50,Ot=262144;class Nt{writable;pending=[];pendingBytes=0;flushTimeout;flushPromise;flushIntervalMs;maxBufferedBytes;constructor(e,t){this.writable=e,this.flushIntervalMs=t?.flushIntervalMs??Dt,this.maxBufferedBytes=t?.maxBufferedBytes??Ot}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 $t(e){const t=new xe.Zv;if(!e.bufferOutputEvents){const r=(t,r)=>{e.writable.write({type:t,data:r}).catch((()=>{}))};return e.stdout?.on("data",(e=>{const o=t.note(e);void 0!==o&&o.length>0&&r("stdout",o)})),e.stderr?.on("data",(e=>{r("stderr",e)})),{get stdoutBytes(){return t.bytes},get stdoutPrefix(){return t.stdoutPrefix},async waitForOutput(){},async releaseHeldStdout(){const e=t.takeHeld();void 0!==e&&e.length>0&&r("stdout",e)},dropHeldStdout(){t.takeHeld()},async flush(){await this.releaseHeldStdout()}}}const r=new Nt(e.writable,e.outputLimiterOptions);let o;const n=Promise.all([Ft(e.stdout,r,t),jt(e.stderr,"stderr",r)]).then((()=>{})).catch((e=>{o=e}));return{get stdoutBytes(){return t.bytes},get stdoutPrefix(){return t.stdoutPrefix},async waitForOutput(){if(await n,void 0!==o)throw(e=o)instanceof Error?e:new Error(String(e));var e},async releaseHeldStdout(){const e=t.takeHeld();void 0!==e&&e.length>0&&await r.push("stdout",e)},dropHeldStdout(){t.takeHeld()},async flush(){await this.releaseHeldStdout(),await r.flush()}}}async function Ft(e,t,r){if(e)for await(const o of e){const e=r.note(o);void 0!==e&&e.length>0&&await t.push("stdout",e)}}async function jt(e,t,r,o){if(e)for await(const n of e)o?.(n),await r.push(t,n)}var Lt;!function(e){e.Zsh="zsh",e.ZshLight="zsh-light",e.Bash="bash",e.PowerShell="powershell",e.Naive="naive"}(Lt||(Lt={}));const Ut={TERM:"dumb",NO_COLOR:"1",FORCE_COLOR:"0",_ZO_DOCTOR:"0"};function Bt(e,t,r,o={spawn:B.spawn,killPid:process.kill.bind(process)}){const n=e.pid;if(void 0===n)return;const s=()=>{try{e.kill(r)}catch{}};switch(t){case"process_group":try{o.killPid(-n,r)}catch{s()}return;case"windows_tree":try{o.spawn("taskkill",["/pid",String(n),"/t","/f"],{stdio:"ignore",windowsHide:!0}).on("error",s)}catch{s()}return;case"single_process":return void s();default:throw new Error(`Unknown process tree kill mode: ${String(t)}`)}}function Wt(e,t=[],r={},o,n){const s=xt(e,t,{...r,env:E(r.env??process.env)},o);if(n){const e=function(e){return"win32"===e.platform?"windows_tree":e.detached?"process_group":"single_process"}({platform:process.platform,detached:!0===r.detached}),t=()=>{if(!s.pid)return;Bt(s,e,"SIGTERM");const t=setTimeout((()=>{!s.killed&&s.pid&&Bt(s,e,"SIGKILL")}),1e3);"process_group"!==e&&s.once("exit",(()=>{clearTimeout(t)}))};n.aborted?t():(n.addEventListener("abort",t,{once:!0}),s.once("exit",(()=>{n.removeEventListener("abort",t)})))}return s}function Ht(e){e?.on("error",(()=>{}))}const qt="IFS= builtin read -r -d '' __cursor_command <&5 2>/dev/null || { builtin printf '%s\\n' 'The command did not run: a shell startup file ($BASH_ENV or .zshenv) closed or replaced file descriptor 5, which carries the command. Run it again; this shell now passes commands as arguments.' >&2; builtin exit 126; }; exec 5<&-; builtin set -- \"$__cursor_command\"; builtin unset __cursor_command; ";function zt(e,t){return 126===e&&""===t}function Gt(){return"win32"!==process.platform}function Vt(e,t){const r=e.stdio.at(5);r instanceof It.default.Writable&&(Ht(r),r.end(`${t}\0`))}function Jt(e,t){e&&(Ht(e),e.write(t),e.end())}function Kt(e,t){e&&(Ht(e),e.on("data",(e=>{t(e.toString())})))}function Zt(e){const t=e.indexOf("\n");return{cwd:e.substring(0,t),rest:e.substring(t)}}function Xt(e,t){const r=`${t}\n`,o=e.indexOf(r);return o>=0?e.slice(o+r.length):e}function Qt(e,t,r){const o=`${t}\n`;if(!e.startsWith(o))return;const n=e.indexOf(`\n${r}\n`,o.length-1);return n<0?void 0:e.slice(o.length,n+1)}const Yt="__CURSOR_BASH_STATE_START__",er="__CURSOR_BASH_STATE_END__";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});function rr(e){if("win32"===process.platform){const t=/git.*bash/i;if(e&&t.test(e))return e;const r=g("bash",[],t).cmd;return t.test(r)?r:null}const t=process.env.SHELL;return t?.includes("bash")?t:g("bash",[]).cmd}function or(e){if("win32"!==process.platform)return e;const t=l.default.normalize(e),r=t[0]?.toLowerCase();return r&&":"===t[1]&&t[2]===l.default.sep?`/${r}${t.slice(2).replace(/\\/g,"/")}`:t.replace(/\\/g,"/")}function nr(e){const t=e.pipeStdin?Mt:`${Mt} < /dev/null`,r=e.useFileTransport?'snap=$(command cat "$CURSOR_STATE_INPUT_FILE")':"snap=$(command cat <&3)",o=e.useFileTransport?'mkdir -p "$(dirname "$CURSOR_STATE_OUTPUT_FILE")" 2>/dev/null; dump_bash_state > "$CURSOR_STATE_OUTPUT_FILE"':"dump_bash_state >&4";return(e.pipeCommand?qt:"")+`${r} && builtin shopt -s extglob && builtin eval -- "$snap"; { builtin set +u 2>/dev/null || true; builtin eval "\${__CURSOR_SANDBOX_ENV_RESTORE:-}" 2>/dev/null; `+j+`builtin export PWD="$(builtin pwd)"; builtin shopt -s expand_aliases 2>/dev/null; ${e.sudoAliasInjection}${t}; }; `+`COMMAND_EXIT_CODE=$?; ${o}; builtin exit $COMMAND_EXIT_CODE`}class sr{cwd;state;userTerminalHint;useFileStateTransport;commandPipeUnreadable;constructor(e,t,r,o=!1,n=!1){this.cwd=e,this.state=t,this.userTerminalHint=r,this.useFileStateTransport=o,this.commandPipeUnreadable=n}async getCwd(){return this.cwd}clone(e){return new sr(e??this.cwd,this.state,this.userTerminalHint,this.useFileStateTransport,this.commandPipeUnreadable)}resetSessionCwdAfterHopCdFailure(e){const{cwd:t,sandboxWorkspaceRoot:r}=e;l.default.resolve(t)===l.default.resolve(this.cwd)&&(this.cwd=void 0===r||l.default.resolve(r)===l.default.resolve(t)||(0,xe.A)(r)?(0,xe.D1)():r)}async*execute(e,t,r){const o={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}(o,(0,Rt.VI)(e.withName("BashState.execute")),!1),s=r?.pipeStdin??!1,i=(0,Tt.Jt)(),a=r?.workingDirectory??this.cwd,c={...process.env,...Ut,...r?.env},u=P(c),d=this.useFileStateTransport,h=!d&&!this.commandPipeUnreadable;let p,f,m;if(d){p=await(0,U.mkdtemp)(l.default.join(T.default.tmpdir(),"cursor-bash-state-")),f=l.default.join(p,"state-in"),m=l.default.join(p,"state-out"),await(0,U.writeFile)(f,this.state,"utf8"),await(0,U.writeFile)(m,"","utf8").catch((()=>{}));const e=or(f),t=or(m);c.CURSOR_STATE_INPUT_FILE=e,c.CURSOR_STATE_OUTPUT_FILE=t}const g=function(e){return["-O","extglob","-c",e.script,At,...void 0===e.command?[]:[e.command]]}({script:nr({pipeCommand:h,useFileTransport:d,sudoAliasInjection:u,pipeStdin:s}),command:h?void 0:t}),w=rr(this.userTerminalHint);if(!w)throw new Error("Can't find Bash");const y=r?.sandboxWorkspaceRoot??a,v=(await Fe(y,r?.sandboxPolicy)).policy,b="insecure_none"!==v.type?{...v,sandboxWorkspaceRoot:y}:v;let S="";const k=async()=>{if(d){if(!m)return void(S=this.state);try{S=await(0,U.readFile)(m,"utf8")}catch(e){console.warn("[shell-exec] Failed to read bash state file",e),S=this.state}}},E=async()=>{if(p)try{await(0,U.rm)(p,{recursive:!0,force:!0})}catch{}};let C;(0,xe.$Y)(a)&&(0,Rt.HF)(n.ctx,xe.yo);try{C=Wt(w,g,{env:c,stdio:[s?"pipe":"ignore","pipe","pipe","pipe","pipe",h?"pipe":"ignore"],cwd:a,detached:!0},b,r?.signal)}catch(e){throw await E(),e}C.on("spawn",(async()=>{try{await i.write({type:"stdin_ready",stdin:C.stdin??void 0,pid:C.pid})}catch(e){}}));const x=$t({stdout:C.stdout,stderr:C.stderr,writable:i,bufferOutputEvents:r?.bufferOutputEvents,outputLimiterOptions:r?.outputLimiterOptions});C.on("error",(async e=>{if((0,xe.fK)(e,a)){this.resetSessionCwdAfterHopCdFailure({cwd:a,sandboxWorkspaceRoot:r?.sandboxWorkspaceRoot}),(0,Rt.HF)(n.ctx,xe.Gq);const e=(0,xe.iA)(a);console.warn(`[shell-exec] working directory is not accessible (${e.cwdKind}:${e.cwdHash})`)}await E(),i.throw(e)}));let _=null,I=null,R=null,A=!1;const M=async e=>{if(A)return;if(A=!0,R&&(clearTimeout(R),R=null),(0,Rt.HF)(n.ctx,"exit"),e)try{await x.waitForOutput()}catch(e){return await E(),void i.throw(e instanceof Error?e:new Error(String(e)))}const t=(0,xe.wz)({exitCode:_,stdoutBytes:x.stdoutBytes,stdoutPrefix:x.stdoutPrefix,cwd:a})&&""===S;if(t&&x.dropHeldStdout(),await x.flush(),h&&zt(_,S)&&(this.commandPipeUnreadable=!0),t){this.resetSessionCwdAfterHopCdFailure({cwd:a,sandboxWorkspaceRoot:r?.sandboxWorkspaceRoot}),await E(),(0,Rt.HF)(n.ctx,xe.Gq);const e=(0,xe.iA)(a);return console.warn(`[shell-exec] working directory is not accessible (${e.cwdKind}:${e.cwdHash})`),void i.throw((0,xe.Vn)(a))}if(!r?.signal?.aborted){await k();const e=`${Yt}\n`,t=`${er}\n`;if(S.startsWith(e)&&S.endsWith(t)){let t=S.slice(e.length);t=t.slice(0,-26);const{cwd:r,rest:o}=Zt(t);this.state=o,"win32"!==process.platform&&r?.startsWith("/")&&(this.cwd=r)}}if(b.captureDenies)try{const e=await _t(C);e&&e.length>0&&await i.write({type:"sandbox_denies",events:e})}catch{}try{await i.write({type:"exit",code:_,signal:I??void 0,data:"",aborted:r?.signal?.aborted??!1}),i.close()}catch{i.close()}await E()};C.on("exit",((e,t)=>{_=e,I=t;const o=r?.closeTimeout??5e3;o>0&&(R=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.`),M(!1)}),o))})),C.on("close",(async()=>{await M(!0)}));const D=C.stdio[3],O=C.stdio[4],N=D instanceof It.default.Writable?D:null,$=O instanceof It.default.Readable?O:null;h&&Vt(C,t),d||(Jt(N,this.state),Kt($,(e=>{S+=e}))),yield*i}catch(e){o.error=e,o.hasError=!0}finally{tr(o)}}}async function ir(e){const t={...process.env,...Ut,...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 # Helper to log timing, only if DUMP_BASH_STATE_TIMING is set\n if [[ -n "\${DUMP_BASH_STATE_TIMING:-}" ]]; then\n # Timing setup\n if [[ "\${BASH_VERSION%%.*}" -ge 5 ]]; then\n # Use EPOCHREALTIME if available (bash 5+)\n local start_time=\${EPOCHREALTIME}\n local step_start=\${EPOCHREALTIME}\n _log_timing() {\n local step_name="$1"\n local now=\${EPOCHREALTIME}\n local step_duration=$(command awk "BEGIN {printf "%.3f", $now - $step_start}")\n local total_duration=$(command awk "BEGIN {printf "%.3f", $now - $start_time}")\n builtin printf "[TIMING] %-20s: %6.3fs (total: %6.3fs)\n" "$step_name" "$step_duration" "$total_duration" >&2\n step_start=$now\n }\n else\n # Fallback for older bash versions\n local start_time=$(command date +%s.%N)\n local step_start=$(command date +%s.%N)\n _log_timing() {\n local step_name="$1"\n local now=$(command date +%s.%N)\n local step_duration=$(command awk "BEGIN {printf "%.3f", $now - $step_start}")\n local total_duration=$(command awk "BEGIN {printf "%.3f", $now - $start_time}")\n builtin printf "[TIMING] %-20s: %6.3fs (total: %6.3fs)\n" "$step_name" "$step_duration" "$total_duration" >&2\n step_start=$now\n }\n fi\n else\n _log_timing() { :; }\n fi\n\n # Helper to append a line to output file\n _emit() {\n builtin printf '%s\n' "$1"\n }\n\n # Helper to safely encode and emit unsafe values. printf %q quotes the value for eval\n # without starting a process, and every command pays this dump and its restore.\n _emit_encoded() {\n local content="$1"\n local var_name="$2"\n if [[ -n "$content" ]]; then\n local quoted\n builtin printf -v quoted '%q' "$content"\n builtin printf 'cursor_snap_%s=%s\n' "$var_name" "$quoted"\n builtin printf 'builtin eval "$cursor_snap_%s"\n' "$var_name"\n fi\n }\n\n # Aliases replay after the functions, so a user function named alias would run in place of\n # each alias line. Only a line that starts an alias gets builtin: a quoted value can span\n # lines, and a continuation line can start with "alias ". awk reads bytes under LC_ALL=C, so a\n # value that is not valid UTF-8 does not make it warn. Without awk the lines stay as they are.\n _builtin_alias_lines() {\n [[ -n "$1" ]] || return 0\n builtin printf '%s\n' "$1" | LC_ALL=C command awk -v sq="'" '\n !q && /^alias / { $0 = "builtin " $0 }\n {\n print\n for (i = 1; i <= length($0); i++) {\n c = substr($0, i, 1)\n if (q == 1) { if (c == sq) q = 0 }\n else if (q == 2) { if (c == "\\\\") i++; else if (c == sq) q = 0 }\n else if (c == "\\\\") i++\n else if (c == "$" && substr($0, i + 1, 1) == sq) { q = 2; i++ }\n else if (c == sq) q = 1\n }\n }' 2>/dev/null ||\n builtin printf '%s\n' "$1"\n }\n\n # Start fresh\n _log_timing "file_init"\n\n # Emit start marker at the very beginning of the output\n _emit "__CURSOR_BASH_STATE_START__"\n\n # Working directory\n _emit "$PWD"\n _log_timing "working_dir"\n\n # The shell starts in POSIX mode when it inherits POSIXLY_CORRECT. POSIX_MODE\n # turns it back on after the functions if the session had it on.\n _emit "builtin set +o posix; builtin unset POSIXLY_CORRECT"\n\n # Drop ELECTRON_RUN_AS_NODE by exact name so one command exporting it can't\n # bake it into the snapshot that every later command re-evals (IDE-2911:\n # Cypress boots as plain Node until a new chat). Exact unset rather than the\n # line-based grep below, which would also eat vars whose name or multiline\n # value merely contains the token. The shell exits right after the dump.\n builtin unset ELECTRON_RUN_AS_NODE 2>/dev/null || true\n\n # Environment variables (export statements)\n # Filter out: proxy settings plus request/session-scoped vars that must not\n # leak across shell executions.\n local env_vars\n env_vars=$(builtin export -p 2>/dev/null | command grep -viE '_proxy=|CURSOR_SANDBOX|SUDO_ASKPASS|CURSOR_ASKPASS|CURSOR_CONVERSATION_ID|CURSOR_REQUEST_ID|CURSOR_AGENT_STORE' | command grep -vE '^(declare|export)( -[a-zA-Z]+)* POSIXLY_CORRECT(=|$)' || true)\n if [[ -n "\${__CURSOR_SANDBOX_OWNED_ENV:-}" ]]; then\n env_vars=$(builtin printf '%s\n' "$env_vars" | command grep -vE "^(export|declare|typeset)( -[a-zA-Z]+)* (\${__CURSOR_SANDBOX_OWNED_ENV// /|})=" || true)\n fi\n _emit_encoded "$env_vars" "ENV_VARS"\n _log_timing "environment"\n\n # POSIX shell options (replayable as set +/-o lines). Exclude the errexit/nounset/\n # pipefail this function force-enables above, so they are not baked into the restored\n # snapshot and leaked onto every subsequent command (a stray pipefail makes a\n # successful 'cmd | head' report exit 141).\n local posix_opts\n posix_opts=$(builtin shopt -po 2>/dev/null | command grep -vE '^set [-+]o (errexit|nounset|pipefail|posix)$' || true)\n _emit_encoded "$posix_opts" "POSIX_OPTS"\n _log_timing "posix_options"\n\n # Bash shopt options (replayable as shopt -s/-u lines)\n local bash_opts\n bash_opts=$(builtin shopt -p 2>/dev/null || true)\n _emit_encoded "$bash_opts" "BASH_OPTS"\n _log_timing "bash_options"\n\n # Functions: capture all functions\n local all_functions\n all_functions=$(builtin declare -f 2>/dev/null || true)\n _emit_encoded "$all_functions" "FUNCTIONS"\n _log_timing "functions"\n\n # Aliases\n local aliases\n aliases=$(_builtin_alias_lines "$(builtin alias -p 2>/dev/null || true)" || true)\n _emit_encoded "$aliases" "ALIASES"\n _log_timing "aliases"\n\n # POSIX mode makes a function name that is not a POSIX identifier, such as my-fn, a\n # fatal error, so it is replayed after the functions. Turning it on resets shopt\n # options such as inherit_errexit, so the shopt state is replayed again after it.\n local posix_mode=""\n if builtin shopt -qo posix; then\n posix_mode=$(builtin printf 'builtin set -o posix\n'; builtin export -p | command grep -E '^(declare|export)( -[a-zA-Z]+)* POSIXLY_CORRECT=' || true; command sed 's/^shopt /builtin shopt /' <<<"$bash_opts")\n fi\n _emit_encoded "$posix_mode" "POSIX_MODE"\n _log_timing "posix_mode"\n\n # Done\n _emit "# end of bash state dump"\n _emit "__CURSOR_BASH_STATE_END__"\n _log_timing "finalize"\n}\n builtin printf '${r}\\n'; dump_bash_state`],n=rr(e?.userTerminalHint);if(!n)throw new Error("Can't find Bash");const s=Wt(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()})),s.on("error",(e=>{console.warn(`[shell-exec] bash state init spawn failed; falling back to empty state: ${e instanceof Error?e.message:String(e)}`)})),await new Promise((e=>{s.on("close",(()=>{e(void 0)}))}));const a=Qt(Xt(i,r),Yt,er)??`${process.cwd()}\n`,{cwd:c,rest:l}=Zt(a),u="win32"===process.platform,d="win32"===process.platform?process.cwd():c;return new sr(d,l,e?.userTerminalHint,u)}var ar=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var 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 cr{initializer;promise;constructor(e){this.initializer=e}getExecutor(){return void 0===this.promise&&(this.promise=this.initializer()),this.promise}async getCwd(){return(await this.getExecutor()).getCwd()}clone(e){return new cr((async()=>(await this.getExecutor()).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,Rt.VI)(e.withName("LazyTerminalExecutor.execute")),!1);const n=await this.getExecutor();for await(const o of n.execute(e,t,r))yield o}catch(e){o.error=e,o.hasError=!0}finally{ar(o)}}}var lr=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 ur(){if("win32"!==process.platform){const e=process.env.SHELL;if(e?.includes("pwsh")||e?.includes("powershell"))return e}let e=g("pwsh",[]).cmd;if("pwsh"!==e)return e;if(e=g("powershell",[]).cmd,"powershell"!==e)return e;if("win32"===process.platform&&(e=l.join(process.env.SYSTEMROOT,"System32","WindowsPowerShell","v1.0","powershell.exe"),(0,u.existsSync)(e)))return e;throw new Error("Neither 'pwsh' (PowerShell Core) nor 'powershell' (Windows PowerShell) found in PATH")}class dr{cwd;state;constructor(e,t){this.cwd=e,this.state=t}async getCwd(){return this.cwd}clone(e){return new dr(e??this.cwd,this.state)}async*execute(e,t,r){const o={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}(o,(0,Rt.VI)(e.withName("PowerShellState.execute")),!1),s=r?.pipeStdin??!1,i=r?.workingDirectory??this.cwd,a=(0,Tt.Jt)(),c=function(e,t=process.platform,r=process.env){const o={...r,...Ut,...e?.env};return"win32"!==t||!0!==e?.powershellUtf8ChildEnv||Object.entries(o).some((([e,t])=>void 0!==t&&"PYTHONIOENCODING"===e.toUpperCase()))||(o.PYTHONIOENCODING="utf-8"),o}(r),u=_(c)?I(t):t,d=T.tmpdir(),h=l.join(d,`ps-state-out-${(0,R.randomUUID)()}.txt`),p="win32"===process.platform,f=((e,t,r,o,n)=>{return`\n${n?.utf8Console?"\ntry { [Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false) } catch { }\ntry { [Console]::InputEncoding = [System.Text.UTF8Encoding]::new($false) } catch { }\ntry { $global:OutputEncoding = [System.Text.UTF8Encoding]::new($false) } catch { }\n":""}\n${e}\n\nSet-Location ${s=t,`'${s.replace(/['\u2018\u2019\u201A\u201B]/g,"$&$&")}'`}\n\n# PowerShell 5.1 does not treat \\" as an escaped quote, so cmd /c "rmdir /s /q \\"D:\\dir\\""\n# hands cmd a bare \\ (the drive root). Refuse double-quoted args that end in \\ and touch the next arg.\n$__cursorCommand = {\n${r}\n}\n$__cursorBrokenQuote = $__cursorCommand.Ast.Find({\n param($node)\n if ($node -isnot [System.Management.Automation.Language.CommandAst]) { return $false }\n $elements = $node.CommandElements\n for ($i = 0; $i -lt $elements.Count - 1; $i++) {\n $element = $elements[$i]\n if (($element -is [System.Management.Automation.Language.StringConstantExpressionAst] -or\n $element -is [System.Management.Automation.Language.ExpandableStringExpressionAst]) -and\n $element.StringConstantType -eq 'DoubleQuoted' -and\n $element.Value.EndsWith('\\') -and\n $elements[$i + 1].Extent.StartOffset -eq $element.Extent.EndOffset) {\n return $true\n }\n }\n return $false\n}, $true)\nif ($__cursorBrokenQuote) {\n [Console]::Error.WriteLine('Command refused: PowerShell does not treat \\" as an escaped quote, so a double-quoted string ends at \\" and the rest runs as separate arguments, near: ' + $__cursorBrokenQuote.Extent.Text)\n [Console]::Error.WriteLine('Quote the outer string with single quotes instead, or write a double quote inside a double-quoted string as \`".')\n exit 1\n}\n# Out-Default writes held-back table output before exit, dot-sourcing keeps the command's state for the dump\n. $__cursorCommand | Out-Default\n$COMMAND_EXIT_CODE = $LASTEXITCODE\n\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 function ShouldPersistEnvVar {\n param([string]$Name)\n if ($Name -eq 'CURSOR_CONVERSATION_ID') {\n return $false\n }\n if ($Name -eq 'CURSOR_REQUEST_ID') {\n return $false\n }\n if ($Name -like 'CURSOR_AGENT_STORE*') {\n return $false\n }\n if ($Name -like '*CURSOR_SANDBOX*') {\n return $false\n }\n if ($Name -eq 'ELECTRON_RUN_AS_NODE') {\n return $false\n }\n return $true\n }\n\n $envVars = Get-ChildItem Env: | Sort-Object Name\n foreach ($var in $envVars) {\n if (-not (ShouldPersistEnvVar -Name $var.Name)) {\n continue\n }\n $encoded = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes([string]$var.Value))\n Emit ('Set-Item -LiteralPath ''Env:{0}'' -Value ([System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String(''{1}'')))' -f $var.Name, $encoded)\n }\n #Log-Timing "environment"\n\n $aliases = Get-Alias | Sort-Object Name\n foreach ($alias in $aliases) {\n $definition = $alias.Definition\n\n if ($alias.Options -band [System.Management.Automation.ScopedItemOptions]::ReadOnly) {\n }\n elseif ($alias.Options -band [System.Management.Automation.ScopedItemOptions]::Constant) {\n }\n elseif ($alias.Options -band [System.Management.Automation.ScopedItemOptions]::AllScope) {\n }\n else {\n Emit ('Set-Alias -Name "{0}" -Value "{1}"' -f $alias.Name, $definition)\n }\n }\n\n #Log-Timing "finalize"\n}\n\nDump-PowerShellState -OutputFile "${o}"\n\nexit $COMMAND_EXIT_CODE\n`;var s})(this.state,i,u,h,{utf8Console:p&&!0===r?.powershellUtf8Console}),m=l.join(d,`ps-script-${(0,R.randomUUID)()}.ps1`);await async function(e,t){await U.writeFile(e,"\ufeff"+t,{encoding:"utf8"})}(m,f);const g=["-ExecutionPolicy","Bypass"];s||g.push("-NonInteractive"),g.push("-File",m);const w=ur(),y=r?.sandboxWorkspaceRoot??i,v=(await Fe(y,r?.sandboxPolicy)).policy,b=Wt(w,g,{env:c,stdio:[s?"pipe":"ignore","pipe","pipe"],cwd:i,detached:!p},"insecure_none"!==v.type?{...v,sandboxWorkspaceRoot:y}:v,r?.signal);b.on("spawn",(async()=>{try{await a.write({type:"stdin_ready",stdin:b.stdin??void 0,pid:b.pid})}catch(e){}}));const S=$t({stdout:b.stdout,stderr:b.stderr,writable:a,bufferOutputEvents:r?.bufferOutputEvents,outputLimiterOptions:r?.outputLimiterOptions}),k=async()=>{try{const e=await U.readFile(h,"utf8"),{cwd:t,rest:r}=Zt(e);this.state=r,this.cwd=t.trim(),await(0,U.rm)(h).catch((()=>{}))}catch(e){}await(0,U.rm)(m,{recursive:!0,force:!0,maxRetries:5}).catch((e=>{console.warn(`[shell-exec] Could not remove PowerShell script ${m}`,e)}))};let E=null,C=null,x=null,P=!1;const A=async e=>{if(!P){if(P=!0,x&&(clearTimeout(x),x=null),(0,Rt.HF)(n.ctx,"exit"),e)try{await S.waitForOutput()}catch(e){return await k(),void a.throw(e instanceof Error?e:new Error(String(e)))}await S.flush();try{await a.write({type:"exit",code:E,signal:C??void 0,data:"",aborted:r?.signal?.aborted??!1})}catch(e){}await k(),a.close()}};b.on("exit",((e,t)=>{E=e,C=t;const o=r?.closeTimeout??5e3;o>0&&(x=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))})),b.on("close",(async()=>{await A(!0)})),b.on("error",(e=>{k().catch((()=>{})),a.throw(e)})),yield*a}catch(e){o.error=e,o.hasError=!0}finally{lr(o)}}}async function hr(){return new dr(process.cwd(),"")}var pr=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 fr{cwd;options;deps;constructor(e,t,r){this.cwd=e,this.options=t,this.deps=r}async getCwd(){return this.cwd}clone(e){return new fr(e??this.cwd,this.options,this.deps)}async*execute(e,t,r){const o={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}(o,(0,Rt.VI)(e.withName("NaiveTerminalExecutor.execute")),!1),s=(0,Tt.Jt)(),i=r?.pipeStdin??!1,a={...process.env,...Ut,...r?.env},c=_(a)?I(t):t,l=r?.workingDirectory??this.cwd,u=r?.sandboxWorkspaceRoot??l,d=this.deps?.resolveSandboxPolicyForWorkspace??Fe,h=(await d(u,r?.sandboxPolicy)).policy,p="insecure_none"!==h.type?{...h,sandboxWorkspaceRoot:u}:h,f="win32"===process.platform,m=(this.deps?.spawnWithSignal??Wt)(this.options?.shell||process.env.SHELL||"/bin/sh",[...this.options?.shellArgs??[],"-c",c],{env:a,cwd:l,stdio:[i?"pipe":"ignore","pipe","pipe"],detached:!f},p,r?.signal);m.on("spawn",(async()=>{try{await s.write({type:"stdin_ready",stdin:m.stdin??void 0,pid:m.pid})}catch(e){}}));const g=(this.deps?.attachShellOutputStreams??$t)({stdout:m.stdout,stderr:m.stderr,writable:s,bufferOutputEvents:r?.bufferOutputEvents,outputLimiterOptions:r?.outputLimiterOptions});m.on("error",(e=>{s.throw(e)})),m.on("exit",(async(e,t)=>{if((0,Rt.HF)(n.ctx,"exit"),await g.flush(),p.captureDenies)try{const e=await _t(m);e&&e.length>0&&await s.write({type:"sandbox_denies",events:e})}catch{}try{await s.write({type:"exit",code:e,signal:t??void 0,data:"",aborted:r?.signal?.aborted??!1}),s.close()}catch(e){s.close()}})),yield*s}catch(e){o.error=e,o.hasError=!0}finally{pr(o)}}}const mr="__CURSOR_ZSH_STATE_START__",gr="__CURSOR_ZSH_STATE_END__",wr=' local tool\n for tool in base64 tr; do\n if ! builtin whence -p "$tool" >/dev/null 2>&1; then\n builtin print -ru2 -- "Shell state not saved: $tool is not on PATH"\n return 0\n fi\n done\n if ! command base64 </dev/null >/dev/null 2>&1; then\n builtin print -ru2 -- "Shell state not saved: the environment is too large to run commands"\n return 0\n fi\n',yr=`#!/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 # Builtin printf, not a here-document: no argument length limit, and no temp file\n builtin printf 'cursor_snap_%s=$(builtin printf %%s '"'"'%s'"'"' | command base64 -d)\n' "$var_name" "$(command base64 <<<"$content" | command tr -d '\n')"\n builtin printf 'builtin eval "$cursor_snap_%s"\n' "$var_name"\n fi\n }\n\n # Aliases replay after the functions, so a user function named alias would run in place of\n # each alias line. Only a line that starts an alias gets builtin: a quoted value can span\n # lines, and a continuation line can start with "alias ". awk reads bytes under LC_ALL=C, so a\n # value that is not valid UTF-8 does not make it warn. Without awk the lines stay as they are.\n _builtin_alias_lines() {\n [[ -n "$1" ]] || return 0\n builtin printf '%s\n' "$1" | LC_ALL=C command awk -v sq="'" '\n !q && /^alias / { $0 = "builtin " $0 }\n {\n print\n for (i = 1; i <= length($0); i++) {\n c = substr($0, i, 1)\n if (q == 1) { if (c == sq) q = 0 }\n else if (q == 2) { if (c == "\\\\") i++; else if (c == sq) q = 0 }\n else if (c == "\\\\") i++\n else if (c == "$" && substr($0, i + 1, 1) == sq) { q = 2; i++ }\n else if (c == sq) q = 1\n }\n }' 2>/dev/null ||\n builtin printf '%s\n' "$1"\n }\n\n _log_timing "init"\n\n${wr}\n # Emit start marker at the very beginning of the output\n _emit "__CURSOR_ZSH_STATE_START__"\n\n # Header\n _emit "$PWD"\n\n _emit "# zsh state dump generated on $(command date +'%Y-%m-%d %H:%M:%S %z')"\n _log_timing "header"\n\n # Working directory\n _log_timing "working_dir"\n\n # Drop ELECTRON_RUN_AS_NODE by exact name so one command exporting it can't\n # bake it into the snapshot that every later command re-evals (IDE-2911:\n # Cypress boots as plain Node until a new chat). Exact unset rather than the\n # line-based grep below, which would also eat vars whose name or multiline\n # value merely contains the token. The shell exits right after the dump.\n builtin unset ELECTRON_RUN_AS_NODE 2>/dev/null || true\n\n # Environment variables (exported)\n # Filter out: proxy settings plus request/session-scoped vars that must not\n # leak across shell executions.\n # Under a non-UTF-8 locale zsh writes byte 0xa7 inside $'...' as M-', which\n # its own parser reads as the closing quote (zsh 5.9 Src/utils.c quotestring,\n # https://github.com/zsh-users/zsh/blob/zsh-5.9/Src/utils.c); the sed rewrites\n # that one escape to the § form so the restore eval can parse it. It runs\n # only on scalar $'...' lines: a plain-quoted value can hold the same four\n # characters literally, and there they must stay.\n local env_vars\n env_vars=$(builtin typeset -xp 2>/dev/null | command grep -viE '_proxy=|CURSOR_SANDBOX|SUDO_ASKPASS|CURSOR_ASKPASS|CURSOR_CONVERSATION_ID|CURSOR_REQUEST_ID|CURSOR_AGENT_STORE' | command sed "/^export[^=]*=[\\$]'/ s/\\\\\\\\M-'/\\\\\\\\xa7/g" || true)\n if [[ -n "\${__CURSOR_SANDBOX_OWNED_ENV:-}" ]]; then\n env_vars=$(builtin printf '%s\n' "$env_vars" | command grep -vE "^(export|declare|typeset)( -[a-zA-Z]+)* (\${__CURSOR_SANDBOX_OWNED_ENV// /|})=" || true)\n fi\n _emit_encoded "$env_vars" "ENV_VARS_B64"\n _log_timing "env_variables"\n\n # Options (replayable as setopt lines). Exclude the errreturn/nounset/pipefail this\n # function force-enables above, so they are not baked into the restored snapshot and\n # leaked onto every subsequent command (a stray pipefail makes a successful\n # 'cmd | head' report exit 141).\n local zsh_opts\n zsh_opts=$(setopt 2>/dev/null | command grep -vE '^(errreturn|nounset|pipefail)$' | command awk '{printf "builtin setopt %s 2>/dev/null || true\\n", $0}' || true)\n _emit_encoded "$zsh_opts" "ZSH_OPTS_B64"\n _log_timing "options"\n\n # 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 local alias_lines\n alias_lines=$({\n builtin alias -L 2>/dev/null || true\n builtin alias -gL 2>/dev/null || true\n builtin alias -sL 2>/dev/null || true\n })\n _builtin_alias_lines "$alias_lines" || true\n _log_timing "aliases"\n\n # Done\n _emit "# end of zsh state dump"\n _emit "__CURSOR_ZSH_STATE_END__"\n _log_timing "finalize"\n}\n`,vr="__CURSOR_ZSH_STATE_LIGHT_VALID__",br=`#!/usr/bin/env zsh\n\n# Usage:\n# source dump_zsh_state_light.zsh\n# dump_zsh_state_light\n# Or execute directly (captures a subshell's state):\n# ./dump_zsh_state_light.zsh\n\n# Lightweight version that skips function tracking for better performance\n\n# Define a function so sourcing won't alter caller state; emulate locally inside\nfunction dump_zsh_state_light() {\n emulate -L zsh -o errreturn -o pipefail\n set -u\n\n\n # Helper to log timing, only if DUMP_ZSH_STATE_TIMING is set\n if [[ -n "\${DUMP_ZSH_STATE_TIMING:-}" ]]; then\n # Timing setup\n typeset start_time=\${EPOCHREALTIME}\n typeset step_start=\${EPOCHREALTIME}\n _log_timing() {\n typeset step_name="$1"\n typeset now=\${EPOCHREALTIME}\n typeset step_duration=$((now - step_start))\n typeset total_duration=$((now - start_time))\n builtin printf "[TIMING] %-20s: %6.3fs (total: %6.3fs)\n" "$step_name" "$step_duration" "$total_duration" >&2\n step_start=$now\n }\n else\n _log_timing() { :; }\n fi\n\n # Ensure parameter arrays are available\n builtin zmodload -F zsh/parameter p:parameters p:options p:aliases p:galiases p:saliases 2>/dev/null || true\n _log_timing "zmodload"\n\n # Helper to print a line to stdout\n _emit() {\n builtin print -r -- "$1"\n }\n\n # Helper to safely encode and emit unsafe values\n _emit_encoded() {\n local content="$1"\n local var_name="$2"\n if [[ -n "$content" ]]; then\n # Builtin printf, not a here-document: no argument length limit, and no temp file\n builtin printf 'cursor_snap_%s=$(builtin printf %%s '"'"'%s'"'"' | command base64 -d)\n' "$var_name" "$(command base64 <<<"$content" | command tr -d '\n')"\n builtin printf 'eval "$cursor_snap_%s"\n' "$var_name"\n fi\n }\n\n _log_timing "init"\n\n${wr}\n # Emit validity marker so we can detect if dump_zsh_state_light completed\n _emit "__CURSOR_ZSH_STATE_LIGHT_VALID__"\n\n # Header\n _emit "$PWD"\n\n _emit "# zsh state dump (light) generated on $(command date +'%Y-%m-%d %H:%M:%S %z')"\n _log_timing "header"\n\n # Working directory\n _log_timing "working_dir"\n\n # Drop ELECTRON_RUN_AS_NODE by exact name so one command exporting it can't\n # bake it into the snapshot that every later command re-evals (IDE-2911:\n # Cypress boots as plain Node until a new chat). Exact unset rather than the\n # line-based grep below, which would also eat vars whose name or multiline\n # value merely contains the token. The shell exits right after the dump.\n builtin unset ELECTRON_RUN_AS_NODE 2>/dev/null || true\n\n # Environment variables (exported)\n # Filter out: proxy settings plus request/session-scoped vars that must not\n # leak across shell executions.\n # Under a non-UTF-8 locale zsh writes byte 0xa7 inside $'...' as M-', which\n # its own parser reads as the closing quote (zsh 5.9 Src/utils.c quotestring,\n # https://github.com/zsh-users/zsh/blob/zsh-5.9/Src/utils.c); the sed rewrites\n # that one escape to the § form so the restore eval can parse it. It runs\n # only on scalar $'...' lines: a plain-quoted value can hold the same four\n # characters literally, and there they must stay.\n local env_vars\n env_vars=$(builtin typeset -xp 2>/dev/null | command grep -viE '_proxy=|CURSOR_SANDBOX|SUDO_ASKPASS|CURSOR_ASKPASS|CURSOR_CONVERSATION_ID|CURSOR_REQUEST_ID|CURSOR_AGENT_STORE' | command sed "/^export[^=]*=[\\$]'/ s/\\\\\\\\M-'/\\\\\\\\xa7/g" || true)\n if [[ -n "\${__CURSOR_SANDBOX_OWNED_ENV:-}" ]]; then\n env_vars=$(builtin printf '%s\n' "$env_vars" | command grep -vE "^(export|declare|typeset)( -[a-zA-Z]+)* (\${__CURSOR_SANDBOX_OWNED_ENV// /|})=" || true)\n fi\n _emit_encoded "$env_vars" "ENV_VARS_B64"\n _log_timing "env_variables"\n\n # Options (replayable as setopt lines). Exclude the errreturn/nounset/pipefail this\n # function force-enables above, so they are not baked into the restored snapshot and\n # leaked onto every subsequent command (a stray pipefail makes a successful\n # 'cmd | head' report exit 141).\n local zsh_opts\n zsh_opts=$(setopt 2>/dev/null | command grep -vE '^(errreturn|nounset|pipefail)$' | command awk '{printf "builtin setopt %s 2>/dev/null || true\\n", $0}' || true)\n _emit_encoded "$zsh_opts" "ZSH_OPTS_B64"\n _log_timing "options"\n\n # SKIP FUNCTIONS - this is the key difference for performance\n\n # Aliases (regular, global, and suffix)\n {\n builtin alias -L 2>/dev/null || true\n builtin alias -gL 2>/dev/null || true\n builtin alias -sL 2>/dev/null || true\n }\n _log_timing "aliases"\n\n # Done\n _emit "# end of zsh state dump (light)"\n _log_timing "finalize"\n}\n`;var Sr=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 kr(){const e=process.env.SHELL;return e?.includes("zsh")?e:g("zsh",[]).cmd}class Er{cwd;state;commandPipeUnreadable;constructor(e,t,r=!1){this.cwd=e,this.state=t,this.commandPipeUnreadable=r}async getCwd(){return this.cwd}clone(e){return new Er(e??this.cwd,this.state,this.commandPipeUnreadable)}async*execute(e,t,r){const o={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}(o,(0,Rt.VI)(e.withName("ZshLightState.execute")),!1),s=r?.pipeStdin??!1,i=(0,Tt.Jt)(),a=r?.workingDirectory??this.cwd,c={...process.env,...Ut,...r?.env};let l='builtin eval "$1"';s||(l+=" < /dev/null");const u=P(c),d=Gt()&&!this.commandPipeUnreadable,h=["-c",(d?qt:"")+"builtin export PATH=\"/usr/bin:/bin:/usr/sbin:/sbin${PATH:+:$PATH}\"; snap=$(command cat <&3); builtin unsetopt aliases 2>/dev/null; builtin unalias -m '*' 2>/dev/null || true; "+`${br} builtin eval "$snap"; { builtin unsetopt nounset 2>/dev/null || true; builtin eval "\${__CURSOR_SANDBOX_ENV_RESTORE:-}" 2>/dev/null; `+j+`builtin export PWD="$(builtin pwd)"; builtin setopt aliases 2>/dev/null; ${u}${l}; }; COMMAND_EXIT_CODE=$?; dump_zsh_state_light >&4; builtin exit $COMMAND_EXIT_CODE`,At,...d?[]:[t]],p=r?.sandboxWorkspaceRoot??a,f=(await Fe(p,r?.sandboxPolicy)).policy,m="insecure_none"!==f.type?{...f,sandboxWorkspaceRoot:p}:f,g=Wt(kr(),h,{env:c,stdio:[s?"pipe":"ignore","pipe","pipe","pipe","pipe",d?"pipe":"ignore"],cwd:a,detached:!0},m,r?.signal);let w="";g.on("spawn",(async()=>{try{await i.write({type:"stdin_ready",stdin:g.stdin??void 0,pid:g.pid})}catch(e){}}));const y=$t({stdout:g.stdout,stderr:g.stderr,writable:i,bufferOutputEvents:r?.bufferOutputEvents,outputLimiterOptions:r?.outputLimiterOptions});g.on("error",(e=>{i.throw(e)}));let v=null,b=null,S=null,k=!1;const E=async e=>{if(!k){if(k=!0,S&&(clearTimeout(S),S=null),(0,Rt.HF)(n.ctx,"exit"),e)try{await y.waitForOutput()}catch(e){return void i.throw(e instanceof Error?e:new Error(String(e)))}if(await y.flush(),d&&zt(v,w)&&(this.commandPipeUnreadable=!0),!r?.signal?.aborted){const e=`${vr}\n`;if(w.startsWith(e)){const t=w.slice(e.length),{cwd:r,rest:o}=Zt(t);r?.startsWith("/")&&(this.state=o,this.cwd=r)}}if(m.captureDenies)try{const e=await _t(g);e&&e.length>0&&await i.write({type:"sandbox_denies",events:e})}catch{}try{await i.write({type:"exit",code:v,signal:b??void 0,data:"",aborted:r?.signal?.aborted??!1}),i.close()}catch(e){i.close()}}};g.on("exit",((e,t)=>{v=e,b=t;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))})),g.on("close",(async()=>{await E(!0)}));const C=g.stdio[3],x=g.stdio[4],_=C instanceof It.default.Writable?C:null,I=x instanceof It.default.Readable?x:null;d&&Vt(g,t),Jt(_,this.state),Kt(I,(e=>{w+=e})),yield*i}catch(e){o.error=e,o.hasError=!0}finally{Sr(o)}}}async function Cr(e){const t={...process.env,...Ut,...e?.env},r="__CURSOR_STATE_MARKER__",o=["-o","extendedglob","-ilc",`${br} builtin printf '${r}\\n'; dump_zsh_state_light`],n=Wt(kr(),o,{env:t,stdio:["ignore","pipe","pipe"],detached:!0},{type:"insecure_none"},e?.signal);let s="";n.stdout?.on("data",(e=>{s+=e.toString()})),n.on("error",(e=>{console.warn(`[shell-exec] zsh-light state init spawn failed; falling back to empty state: ${e instanceof Error?e.message:String(e)}`)})),await new Promise((e=>{n.on("close",(()=>{e(void 0)}))}));const i=Xt(s,r),a=`${vr}\n`,c=i.startsWith(a)?i.slice(a.length):`${process.cwd()}\n`,{cwd:l,rest:u}=Zt(c);return new Er(l,u)}var xr=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var 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 _r(){const e=process.env.SHELL;return e?.includes("zsh")?e:g("zsh",[]).cmd}class Pr{cwd;state;commandPipeUnreadable;constructor(e,t,r=!1){this.cwd=e,this.state=t,this.commandPipeUnreadable=r}async getCwd(){return this.cwd}clone(e){return new Pr(e??this.cwd,this.state,this.commandPipeUnreadable)}async*execute(e,t,r){const o={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}(o,(0,Rt.VI)(e.withName("ZshState.execute")),!1),s=r?.pipeStdin??!1,i=r?.keepBackgroundJobs??!1,a=(0,Tt.Jt)(),c=r?.workingDirectory??this.cwd,l={...process.env,...Ut,...r?.env};let u='builtin eval "$1"';i&&(u+=" 3<&- 4>&-"),s||(u+=" < /dev/null");const d=P(l),h=Gt()&&!this.commandPipeUnreadable,p=["-c",(h?qt:"")+"builtin export PATH=\"/usr/bin:/bin:/usr/sbin:/sbin${PATH:+:$PATH}\"; snap=$(command cat <&3); builtin unsetopt aliases 2>/dev/null; builtin unalias -m '*' 2>/dev/null || true; "+`${yr} builtin eval "$snap"; { builtin unsetopt nounset 2>/dev/null || true; builtin eval "\${__CURSOR_SANDBOX_ENV_RESTORE:-}" 2>/dev/null; `+j+`builtin export PWD="$(builtin pwd)"; builtin setopt aliases 2>/dev/null; ${d}${u}; }; COMMAND_EXIT_CODE=$?; dump_zsh_state >&4; builtin exit $COMMAND_EXIT_CODE`,At,...h?[]:[t]],f=r?.sandboxWorkspaceRoot??c,m=(await Fe(f,r?.sandboxPolicy)).policy,g="insecure_none"!==m.type?{...m,sandboxWorkspaceRoot:f}:m,w=Wt(_r(),p,{env:l,stdio:[s?"pipe":"ignore","pipe","pipe","pipe","pipe",h?"pipe":"ignore"],cwd:c,detached:!0},g,r?.signal);let y="";w.on("spawn",(async()=>{try{await a.write({type:"stdin_ready",stdin:w.stdin??void 0,pid:w.pid})}catch(e){}}));const v=$t({stdout:w.stdout,stderr:w.stderr,writable:a,bufferOutputEvents:r?.bufferOutputEvents,outputLimiterOptions:r?.outputLimiterOptions});w.on("error",(e=>{a.throw(e)}));let b=null,S=null,k=null,E=!1;const C=async e=>{if(!E){if(E=!0,k&&(clearTimeout(k),k=null),(0,Rt.HF)(n.ctx,"exit"),e)try{await v.waitForOutput()}catch(e){return void a.throw(e instanceof Error?e:new Error(String(e)))}if(await v.flush(),h&&zt(b,y)&&(this.commandPipeUnreadable=!0),!r?.signal?.aborted){const e=`${mr}\n`,t=`${gr}\n`;if(y.startsWith(e)&&y.endsWith(t)){let t=y.slice(e.length);t=t.slice(0,-25);const{cwd:r,rest:o}=Zt(t);r?.startsWith("/")&&(this.state=o,this.cwd=r)}}if(g.captureDenies)try{const e=await _t(w);e&&e.length>0&&await a.write({type:"sandbox_denies",events:e})}catch{}try{await a.write({type:"exit",code:b,signal:S??void 0,data:"",aborted:r?.signal?.aborted??!1}),a.close()}catch(e){a.close()}}};w.on("exit",((e,t)=>{b=e,S=t;const o=r?.closeTimeout??5e3;o>0&&(k=setTimeout((()=>{if(E)return;const e=`[shell-exec] Close event did not fire within ${o}ms after exit. This may indicate a background process is holding file descriptors open. `;i?console.warn(`${e}Leaving it running because keepBackgroundJobs is set.`):(console.warn(`${e}Killing detached process group.`),function(e,t){if(e)try{process.kill(-e,t)}catch{return}}(w.pid,"SIGKILL")),C(!1)}),o))})),w.on("close",(async()=>{await C(!0)}));const x=w.stdio[3],_=w.stdio[4],I=x instanceof It.default.Writable?x:null,R=_ instanceof It.default.Readable?_:null;h&&Vt(w,t),Jt(I,this.state),Kt(R,(e=>{y+=e})),yield*a}catch(e){o.error=e,o.hasError=!0}finally{xr(o)}}}async function Ir(e){const t={...process.env,...Ut,...e?.env},r="__CURSOR_STATE_MARKER__",o=["-o","extendedglob","-ilc",`${yr} builtin printf '${r}\\n'; dump_zsh_state`],n=Wt(_r(),o,{env:t,stdio:["ignore","pipe","pipe"],detached:!0},{type:"insecure_none"},e?.signal);let s="";n.stdout?.on("data",(e=>{s+=e.toString()})),n.on("error",(e=>{console.warn(`[shell-exec] zsh state init spawn failed; falling back to empty state: ${e instanceof Error?e.message:String(e)}`)})),await new Promise((e=>{n.on("close",(()=>{e(void 0)}))}));const i=Qt(Xt(s,r),mr,gr)??`${process.cwd()}\n`,{cwd:a,rest:c}=Zt(i);return new Pr(a,c)}function Rr(e){try{return g(e,[]).cmd!==e}catch(e){return!1}}function Tr(){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=l.default.win32.basename(t).toLowerCase();return"bash.exe"===r?t:"bin"===r?l.default.win32.join(t,"bash.exe"):l.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(g(e,[]).cmd===e)return e}catch{}return"C:\\Program Files\\Git\\bin\\bash.exe"}function Ar(e){if(e===Lt.ZshLight)return Lt.ZshLight;const t=e||process.env.SHELL||"",r="win32"===process.platform,o=r&&!e?Tr():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")?Lt.Zsh:t.includes("bash")&&s?Lt.Bash:t.includes("pwsh")||t.includes("powershell")?Lt.PowerShell:o?Lt.Bash:r&&(Rr("pwsh")||Rr("powershell"))?Lt.PowerShell:Rr("zsh")?Lt.Zsh:Rr("bash")&&s?Lt.Bash:Rr("pwsh")||Rr("powershell")?Lt.PowerShell:Lt.Naive}function Mr(e,t){let r=e;if(!e?.userTerminalHint){const t=Tr();t&&(r={...e,userTerminalHint:t})}const o=Ar(r?.userTerminalHint??""),n=t?.initBashState??ir,s=t?.initPowerShellState??hr,i=t?.initZshState??Ir,a=t?.initZshLightState??Cr;switch(o){case Lt.Zsh:return new cr((()=>i(r)));case Lt.Bash:return new cr((()=>n(r)));case Lt.PowerShell:return new cr((()=>s()));case Lt.ZshLight:return new cr((()=>a(r)));default:{const e=t?.getPowerShellExecutable??ur;return function(e){const t="win32"===process.platform,r=e?.shell??(t?ur():void 0),o=process.cwd();return new fr(o,{...e,shell:r})}({env:r?.env,shell:"win32"===process.platform?e():void 0})}}}const Dr={perUser:{type:"insecure_none"}}},"../utils/dist/lru-cache.js"(e,t,r){r.d(t,{q:()=>ue});var o,n,s,i,a,c,l,u,d,h,p,f,m,g,w,y,v,b,S,k,E,C,x,_,P,I,R,T,A,M,D,O,N,$,F,j,L,U,B,W,H,q,z,G,V,J,K,Z,X,Q=function(e,t,r,o,n){if("m"===o)throw new TypeError("Private method is not writable");if("a"===o&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===o?n.call(e,r):n?n.value=r:t.set(e,r),r},Y=function(e,t,r,o){if("a"===r&&!o)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!o:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?o:"a"===r?o.call(e):o?o.value:t.get(e)};const ee="object"==typeof performance&&performance&&"function"==typeof performance.now?performance:Date,te=new Set,re="object"==typeof process&&process?process:{},oe=(e,t,r,o)=>{"function"==typeof re.emitWarning?re.emitWarning(e,t,r,o):console.error(`[${r}] ${t}: ${e}`)};let ne=globalThis.AbortController,se=globalThis.AbortSignal;if(void 0===ne){se=class{constructor(){this._onabort=[],this.aborted=!1}addEventListener(e,t){this._onabort.push(t)}},ne=class{constructor(){this.signal=new se,t()}abort(e){if(!this.signal.aborted){this.signal.reason=e,this.signal.aborted=!0;for(const t of this.signal._onabort)t(e);this.signal.onabort?.(e)}}};let e="1"!==re.env?.LRU_CACHE_IGNORE_AC_WARNING;const t=()=>{e&&(e=!1,oe("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",t))}}Symbol("type");const ie=e=>e&&e===Math.floor(e)&&e>0&&Number.isFinite(e),ae=e=>ie(e)?e<=256?Uint8Array:e<=65536?Uint16Array:e<=2**32?Uint32Array:e<=Number.MAX_SAFE_INTEGER?ce:null:null;class ce extends Array{constructor(e){super(e),this.fill(0)}}class le{static create(e){const t=ae(e);if(!t)return[];Q(o,o,!0,"f",n);const r=new o(e,t);return Q(o,o,!1,"f",n),r}constructor(e,t){if(!Y(o,o,"f",n))throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new t(e),this.length=0}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}}o=le,n={value:!1};class ue{get perf(){return Y(this,p,"f")}static unsafeExposeInternals(e){return{starts:Y(e,_,"f"),ttls:Y(e,P,"f"),sizes:Y(e,x,"f"),keyMap:Y(e,g,"f"),keyList:Y(e,w,"f"),valList:Y(e,y,"f"),next:Y(e,v,"f"),prev:Y(e,b,"f"),get head(){return Y(e,S,"f")},get tail(){return Y(e,k,"f")},free:Y(e,E,"f"),isBackgroundFetch:t=>Y(e,s,"m",G).call(e,t),backgroundFetch:(t,r,o,n)=>Y(e,s,"m",z).call(e,t,r,o,n),moveToTail:t=>Y(e,s,"m",J).call(e,t),indexes:t=>Y(e,s,"m",B).call(e,t),rindexes:t=>Y(e,s,"m",W).call(e,t),isStale:t=>Y(e,$,"f").call(e,t)}}get max(){return Y(this,i,"f")}get maxSize(){return Y(this,a,"f")}get calculatedSize(){return Y(this,m,"f")}get size(){return Y(this,f,"f")}get fetchMethod(){return Y(this,d,"f")}get memoMethod(){return Y(this,h,"f")}get dispose(){return Y(this,c,"f")}get onInsert(){return Y(this,l,"f")}get disposeAfter(){return Y(this,u,"f")}constructor(e){s.add(this),i.set(this,void 0),a.set(this,void 0),c.set(this,void 0),l.set(this,void 0),u.set(this,void 0),d.set(this,void 0),h.set(this,void 0),p.set(this,void 0),f.set(this,void 0),m.set(this,void 0),g.set(this,void 0),w.set(this,void 0),y.set(this,void 0),v.set(this,void 0),b.set(this,void 0),S.set(this,void 0),k.set(this,void 0),E.set(this,void 0),C.set(this,void 0),x.set(this,void 0),_.set(this,void 0),P.set(this,void 0),I.set(this,void 0),R.set(this,void 0),T.set(this,void 0),A.set(this,void 0),D.set(this,(()=>{})),O.set(this,(()=>{})),N.set(this,(()=>{})),$.set(this,(()=>!1)),j.set(this,(e=>{})),L.set(this,((e,t,r)=>{})),U.set(this,((e,t,r,o)=>{if(r||o)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0})),this[X]="LRUCache";const{max:t=0,ttl:r,ttlResolution:o=1,ttlAutopurge:n,updateAgeOnGet:B,updateAgeOnHas:W,allowStale:H,dispose:q,onInsert:z,disposeAfter:G,noDisposeOnSet:V,noUpdateTTL:J,maxSize:K=0,maxEntrySize:Z=0,sizeCalculation:re,fetchMethod:ne,memoMethod:se,noDeleteOnFetchRejection:ce,noDeleteOnStaleGet:de,allowStaleOnFetchRejection:he,allowStaleOnFetchAbort:pe,ignoreFetchAbort:fe,perf:me}=e;if(void 0!==me&&"function"!=typeof me?.now)throw new TypeError("perf option must have a now() method if specified");if(Q(this,p,me??ee,"f"),0!==t&&!ie(t))throw new TypeError("max option must be a nonnegative integer");const ge=t?ae(t):Array;if(!ge)throw new Error(`invalid max value: ${t}`);if(Q(this,i,t,"f"),Q(this,a,K,"f"),this.maxEntrySize=Z||Y(this,a,"f"),this.sizeCalculation=re,this.sizeCalculation){if(!Y(this,a,"f")&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if("function"!=typeof this.sizeCalculation)throw new TypeError("sizeCalculation set to non-function")}if(void 0!==se&&"function"!=typeof se)throw new TypeError("memoMethod must be a function if defined");if(Q(this,h,se,"f"),void 0!==ne&&"function"!=typeof ne)throw new TypeError("fetchMethod must be a function if specified");if(Q(this,d,ne,"f"),Q(this,R,!!ne,"f"),Q(this,g,new Map,"f"),Q(this,w,new Array(t).fill(void 0),"f"),Q(this,y,new Array(t).fill(void 0),"f"),Q(this,v,new ge(t),"f"),Q(this,b,new ge(t),"f"),Q(this,S,0,"f"),Q(this,k,0,"f"),Q(this,E,le.create(t),"f"),Q(this,f,0,"f"),Q(this,m,0,"f"),"function"==typeof q&&Q(this,c,q,"f"),"function"==typeof z&&Q(this,l,z,"f"),"function"==typeof G?(Q(this,u,G,"f"),Q(this,C,[],"f")):(Q(this,u,void 0,"f"),Q(this,C,void 0,"f")),Q(this,I,!!Y(this,c,"f"),"f"),Q(this,A,!!Y(this,l,"f"),"f"),Q(this,T,!!Y(this,u,"f"),"f"),this.noDisposeOnSet=!!V,this.noUpdateTTL=!!J,this.noDeleteOnFetchRejection=!!ce,this.allowStaleOnFetchRejection=!!he,this.allowStaleOnFetchAbort=!!pe,this.ignoreFetchAbort=!!fe,0!==this.maxEntrySize){if(0!==Y(this,a,"f")&&!ie(Y(this,a,"f")))throw new TypeError("maxSize must be a positive integer if specified");if(!ie(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");Y(this,s,"m",F).call(this)}if(this.allowStale=!!H,this.noDeleteOnStaleGet=!!de,this.updateAgeOnGet=!!B,this.updateAgeOnHas=!!W,this.ttlResolution=ie(o)||0===o?o:1,this.ttlAutopurge=!!n,this.ttl=r||0,this.ttl){if(!ie(this.ttl))throw new TypeError("ttl must be a positive integer if specified");Y(this,s,"m",M).call(this)}if(0===Y(this,i,"f")&&0===this.ttl&&0===Y(this,a,"f"))throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!Y(this,i,"f")&&!Y(this,a,"f")){const e="LRU_CACHE_UNBOUNDED";(e=>!te.has(e))(e)&&(te.add(e),oe("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",e,ue))}}getRemainingTTL(e){return Y(this,g,"f").has(e)?1/0:0}*entries(){for(const e of Y(this,s,"m",B).call(this))void 0===Y(this,y,"f")[e]||void 0===Y(this,w,"f")[e]||Y(this,s,"m",G).call(this,Y(this,y,"f")[e])||(yield[Y(this,w,"f")[e],Y(this,y,"f")[e]])}*rentries(){for(const e of Y(this,s,"m",W).call(this))void 0===Y(this,y,"f")[e]||void 0===Y(this,w,"f")[e]||Y(this,s,"m",G).call(this,Y(this,y,"f")[e])||(yield[Y(this,w,"f")[e],Y(this,y,"f")[e]])}*keys(){for(const e of Y(this,s,"m",B).call(this)){const t=Y(this,w,"f")[e];void 0===t||Y(this,s,"m",G).call(this,Y(this,y,"f")[e])||(yield t)}}*rkeys(){for(const e of Y(this,s,"m",W).call(this)){const t=Y(this,w,"f")[e];void 0===t||Y(this,s,"m",G).call(this,Y(this,y,"f")[e])||(yield t)}}*values(){for(const e of Y(this,s,"m",B).call(this))void 0===Y(this,y,"f")[e]||Y(this,s,"m",G).call(this,Y(this,y,"f")[e])||(yield Y(this,y,"f")[e])}*rvalues(){for(const e of Y(this,s,"m",W).call(this))void 0===Y(this,y,"f")[e]||Y(this,s,"m",G).call(this,Y(this,y,"f")[e])||(yield Y(this,y,"f")[e])}[(i=new WeakMap,a=new WeakMap,c=new WeakMap,l=new WeakMap,u=new WeakMap,d=new WeakMap,h=new WeakMap,p=new WeakMap,f=new WeakMap,m=new WeakMap,g=new WeakMap,w=new WeakMap,y=new WeakMap,v=new WeakMap,b=new WeakMap,S=new WeakMap,k=new WeakMap,E=new WeakMap,C=new WeakMap,x=new WeakMap,_=new WeakMap,P=new WeakMap,I=new WeakMap,R=new WeakMap,T=new WeakMap,A=new WeakMap,D=new WeakMap,O=new WeakMap,N=new WeakMap,$=new WeakMap,j=new WeakMap,L=new WeakMap,U=new WeakMap,s=new WeakSet,M=function(){const e=new ce(Y(this,i,"f")),t=new ce(Y(this,i,"f"));Q(this,P,e,"f"),Q(this,_,t,"f"),Q(this,N,((r,o,n=Y(this,p,"f").now())=>{if(t[r]=0!==o?n:0,e[r]=o,0!==o&&this.ttlAutopurge){const e=setTimeout((()=>{Y(this,$,"f").call(this,r)&&Y(this,s,"m",K).call(this,Y(this,w,"f")[r],"expire")}),o+1);e.unref&&e.unref()}}),"f"),Q(this,D,(r=>{t[r]=0!==e[r]?Y(this,p,"f").now():0}),"f"),Q(this,O,((n,s)=>{if(e[s]){const i=e[s],a=t[s];if(!i||!a)return;n.ttl=i,n.start=a,n.now=r||o();const c=n.now-a;n.remainingTTL=i-c}}),"f");let r=0;const o=()=>{const e=Y(this,p,"f").now();if(this.ttlResolution>0){r=e;const t=setTimeout((()=>{r=0}),this.ttlResolution);t.unref&&t.unref()}return e};this.getRemainingTTL=n=>{const s=Y(this,g,"f").get(n);if(void 0===s)return 0;const i=e[s],a=t[s];return i&&a?i-((r||o())-a):1/0},Q(this,$,(n=>{const s=t[n],i=e[n];return!!i&&!!s&&(r||o())-s>i}),"f")},F=function(){const e=new ce(Y(this,i,"f"));Q(this,m,0,"f"),Q(this,x,e,"f"),Q(this,j,(t=>{Q(this,m,Y(this,m,"f")-e[t],"f"),e[t]=0}),"f"),Q(this,U,((e,t,r,o)=>{if(Y(this,s,"m",G).call(this,t))return 0;if(!ie(r)){if(!o)throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");if("function"!=typeof o)throw new TypeError("sizeCalculation must be a function");if(r=o(t,e),!ie(r))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}return r}),"f"),Q(this,L,((t,r,o)=>{if(e[t]=r,Y(this,a,"f")){const r=Y(this,a,"f")-e[t];for(;Y(this,m,"f")>r;)Y(this,s,"m",q).call(this,!0)}Q(this,m,Y(this,m,"f")+e[t],"f"),o&&(o.entrySize=r,o.totalCalculatedSize=Y(this,m,"f"))}),"f")},B=function*({allowStale:e=this.allowStale}={}){if(Y(this,f,"f"))for(let t=Y(this,k,"f");Y(this,s,"m",H).call(this,t)&&(!e&&Y(this,$,"f").call(this,t)||(yield t),t!==Y(this,S,"f"));)t=Y(this,b,"f")[t]},W=function*({allowStale:e=this.allowStale}={}){if(Y(this,f,"f"))for(let t=Y(this,S,"f");Y(this,s,"m",H).call(this,t)&&(!e&&Y(this,$,"f").call(this,t)||(yield t),t!==Y(this,k,"f"));)t=Y(this,v,"f")[t]},H=function(e){return void 0!==e&&Y(this,g,"f").get(Y(this,w,"f")[e])===e},Symbol.iterator)](){return this.entries()}find(e,t={}){for(const r of Y(this,s,"m",B).call(this)){const o=Y(this,y,"f")[r],n=Y(this,s,"m",G).call(this,o)?o.__staleWhileFetching:o;if(void 0!==n&&e(n,Y(this,w,"f")[r],this))return this.get(Y(this,w,"f")[r],t)}}forEach(e,t=this){for(const r of Y(this,s,"m",B).call(this)){const o=Y(this,y,"f")[r],n=Y(this,s,"m",G).call(this,o)?o.__staleWhileFetching:o;void 0!==n&&e.call(t,n,Y(this,w,"f")[r],this)}}rforEach(e,t=this){for(const r of Y(this,s,"m",W).call(this)){const o=Y(this,y,"f")[r],n=Y(this,s,"m",G).call(this,o)?o.__staleWhileFetching:o;void 0!==n&&e.call(t,n,Y(this,w,"f")[r],this)}}purgeStale(){let e=!1;for(const t of Y(this,s,"m",W).call(this,{allowStale:!0}))Y(this,$,"f").call(this,t)&&(Y(this,s,"m",K).call(this,Y(this,w,"f")[t],"expire"),e=!0);return e}info(e){const t=Y(this,g,"f").get(e);if(void 0===t)return;const r=Y(this,y,"f")[t],o=Y(this,s,"m",G).call(this,r)?r.__staleWhileFetching:r;if(void 0===o)return;const n={value:o};if(Y(this,P,"f")&&Y(this,_,"f")){const e=Y(this,P,"f")[t],r=Y(this,_,"f")[t];if(e&&r){const t=e-(Y(this,p,"f").now()-r);n.ttl=t,n.start=Date.now()}}return Y(this,x,"f")&&(n.size=Y(this,x,"f")[t]),n}dump(){const e=[];for(const t of Y(this,s,"m",B).call(this,{allowStale:!0})){const r=Y(this,w,"f")[t],o=Y(this,y,"f")[t],n=Y(this,s,"m",G).call(this,o)?o.__staleWhileFetching:o;if(void 0===n||void 0===r)continue;const i={value:n};if(Y(this,P,"f")&&Y(this,_,"f")){i.ttl=Y(this,P,"f")[t];const e=Y(this,p,"f").now()-Y(this,_,"f")[t];i.start=Math.floor(Date.now()-e)}Y(this,x,"f")&&(i.size=Y(this,x,"f")[t]),e.unshift([r,i])}return e}load(e){this.clear();for(const[t,r]of e){if(r.start){const e=Date.now()-r.start;r.start=Y(this,p,"f").now()-e}this.set(t,r.value,r)}}set(e,t,r={}){var o;if(void 0===t)return this.delete(e),this;const{ttl:n=this.ttl,start:a,noDisposeOnSet:d=this.noDisposeOnSet,sizeCalculation:h=this.sizeCalculation,status:p}=r;let{noUpdateTTL:m=this.noUpdateTTL}=r;const S=Y(this,U,"f").call(this,e,t,r.size||0,h);if(this.maxEntrySize&&S>this.maxEntrySize)return p&&(p.set="miss",p.maxEntrySizeExceeded=!0),Y(this,s,"m",K).call(this,e,"set"),this;let x=0===Y(this,f,"f")?void 0:Y(this,g,"f").get(e);if(void 0===x)x=0===Y(this,f,"f")?Y(this,k,"f"):0!==Y(this,E,"f").length?Y(this,E,"f").pop():Y(this,f,"f")===Y(this,i,"f")?Y(this,s,"m",q).call(this,!1):Y(this,f,"f"),Y(this,w,"f")[x]=e,Y(this,y,"f")[x]=t,Y(this,g,"f").set(e,x),Y(this,v,"f")[Y(this,k,"f")]=x,Y(this,b,"f")[x]=Y(this,k,"f"),Q(this,k,x,"f"),Q(this,f,(o=Y(this,f,"f"),++o),"f"),Y(this,L,"f").call(this,x,S,p),p&&(p.set="add"),m=!1,Y(this,A,"f")&&Y(this,l,"f")?.call(this,t,e,"add");else{Y(this,s,"m",J).call(this,x);const r=Y(this,y,"f")[x];if(t!==r){if(Y(this,R,"f")&&Y(this,s,"m",G).call(this,r)){r.__abortController.abort(new Error("replaced"));const{__staleWhileFetching:t}=r;void 0===t||d||(Y(this,I,"f")&&Y(this,c,"f")?.call(this,t,e,"set"),Y(this,T,"f")&&Y(this,C,"f")?.push([t,e,"set"]))}else d||(Y(this,I,"f")&&Y(this,c,"f")?.call(this,r,e,"set"),Y(this,T,"f")&&Y(this,C,"f")?.push([r,e,"set"]));if(Y(this,j,"f").call(this,x),Y(this,L,"f").call(this,x,S,p),Y(this,y,"f")[x]=t,p){p.set="replace";const e=r&&Y(this,s,"m",G).call(this,r)?r.__staleWhileFetching:r;void 0!==e&&(p.oldValue=e)}}else p&&(p.set="update");Y(this,A,"f")&&this.onInsert?.(t,e,t===r?"update":"replace")}if(0===n||Y(this,P,"f")||Y(this,s,"m",M).call(this),Y(this,P,"f")&&(m||Y(this,N,"f").call(this,x,n,a),p&&Y(this,O,"f").call(this,p,x)),!d&&Y(this,T,"f")&&Y(this,C,"f")){const e=Y(this,C,"f");let t;for(;t=e?.shift();)Y(this,u,"f")?.call(this,...t)}return this}pop(){try{for(;Y(this,f,"f");){const e=Y(this,y,"f")[Y(this,S,"f")];if(Y(this,s,"m",q).call(this,!0),Y(this,s,"m",G).call(this,e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(void 0!==e)return e}return}finally{if(Y(this,T,"f")&&Y(this,C,"f")){const e=Y(this,C,"f");let t;for(;t=e?.shift();)Y(this,u,"f")?.call(this,...t)}}}has(e,t={}){const{updateAgeOnHas:r=this.updateAgeOnHas,status:o}=t,n=Y(this,g,"f").get(e);if(void 0!==n){const e=Y(this,y,"f")[n];if(Y(this,s,"m",G).call(this,e)&&void 0===e.__staleWhileFetching)return!1;if(!Y(this,$,"f").call(this,n))return r&&Y(this,D,"f").call(this,n),o&&(o.has="hit",Y(this,O,"f").call(this,o,n)),!0;o&&(o.has="stale",Y(this,O,"f").call(this,o,n))}else o&&(o.has="miss");return!1}peek(e,t={}){const{allowStale:r=this.allowStale}=t,o=Y(this,g,"f").get(e);if(void 0===o||!r&&Y(this,$,"f").call(this,o))return;const n=Y(this,y,"f")[o];return Y(this,s,"m",G).call(this,n)?n.__staleWhileFetching:n}async fetch(e,t={}){const{allowStale:r=this.allowStale,updateAgeOnGet:o=this.updateAgeOnGet,noDeleteOnStaleGet:n=this.noDeleteOnStaleGet,ttl:i=this.ttl,noDisposeOnSet:a=this.noDisposeOnSet,size:c=0,sizeCalculation:l=this.sizeCalculation,noUpdateTTL:u=this.noUpdateTTL,noDeleteOnFetchRejection:d=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:h=this.allowStaleOnFetchRejection,ignoreFetchAbort:p=this.ignoreFetchAbort,allowStaleOnFetchAbort:f=this.allowStaleOnFetchAbort,context:m,forceRefresh:w=!1,status:v,signal:b}=t;if(!Y(this,R,"f"))return v&&(v.fetch="get"),this.get(e,{allowStale:r,updateAgeOnGet:o,noDeleteOnStaleGet:n,status:v});const S={allowStale:r,updateAgeOnGet:o,noDeleteOnStaleGet:n,ttl:i,noDisposeOnSet:a,size:c,sizeCalculation:l,noUpdateTTL:u,noDeleteOnFetchRejection:d,allowStaleOnFetchRejection:h,allowStaleOnFetchAbort:f,ignoreFetchAbort:p,status:v,signal:b},k=Y(this,g,"f").get(e);if(void 0===k){v&&(v.fetch="miss");const t=Y(this,s,"m",z).call(this,e,k,S,m);return t.__returned=t}{const t=Y(this,y,"f")[k];if(Y(this,s,"m",G).call(this,t)){const e=r&&void 0!==t.__staleWhileFetching;return v&&(v.fetch="inflight",e&&(v.returnedStale=!0)),e?t.__staleWhileFetching:t.__returned=t}const n=Y(this,$,"f").call(this,k);if(!w&&!n)return v&&(v.fetch="hit"),Y(this,s,"m",J).call(this,k),o&&Y(this,D,"f").call(this,k),v&&Y(this,O,"f").call(this,v,k),t;const i=Y(this,s,"m",z).call(this,e,k,S,m),a=void 0!==i.__staleWhileFetching&&r;return v&&(v.fetch=n?"stale":"refresh",a&&n&&(v.returnedStale=!0)),a?i.__staleWhileFetching:i.__returned=i}}async forceFetch(e,t={}){const r=await this.fetch(e,t);if(void 0===r)throw new Error("fetch() returned undefined");return r}memo(e,t={}){const r=Y(this,h,"f");if(!r)throw new Error("no memoMethod provided to constructor");const{context:o,forceRefresh:n,...s}=t,i=this.get(e,s);if(!n&&void 0!==i)return i;const a=r(e,i,{options:s,context:o});return this.set(e,a,s),a}get(e,t={}){const{allowStale:r=this.allowStale,updateAgeOnGet:o=this.updateAgeOnGet,noDeleteOnStaleGet:n=this.noDeleteOnStaleGet,status:i}=t,a=Y(this,g,"f").get(e);if(void 0!==a){const t=Y(this,y,"f")[a],c=Y(this,s,"m",G).call(this,t);return i&&Y(this,O,"f").call(this,i,a),Y(this,$,"f").call(this,a)?(i&&(i.get="stale"),c?(i&&r&&void 0!==t.__staleWhileFetching&&(i.returnedStale=!0),r?t.__staleWhileFetching:void 0):(n||Y(this,s,"m",K).call(this,e,"expire"),i&&r&&(i.returnedStale=!0),r?t:void 0)):(i&&(i.get="hit"),c?t.__staleWhileFetching:(Y(this,s,"m",J).call(this,a),o&&Y(this,D,"f").call(this,a),t))}i&&(i.get="miss")}delete(e){return Y(this,s,"m",K).call(this,e,"delete")}clear(){Y(this,s,"m",Z).call(this,"delete")}}X=Symbol.toStringTag,q=function(e){var t;const r=Y(this,S,"f"),o=Y(this,w,"f")[r],n=Y(this,y,"f")[r];return Y(this,R,"f")&&Y(this,s,"m",G).call(this,n)?n.__abortController.abort(new Error("evicted")):(Y(this,I,"f")||Y(this,T,"f"))&&(Y(this,I,"f")&&Y(this,c,"f")?.call(this,n,o,"evict"),Y(this,T,"f")&&Y(this,C,"f")?.push([n,o,"evict"])),Y(this,j,"f").call(this,r),e&&(Y(this,w,"f")[r]=void 0,Y(this,y,"f")[r]=void 0,Y(this,E,"f").push(r)),1===Y(this,f,"f")?(Q(this,S,Q(this,k,0,"f"),"f"),Y(this,E,"f").length=0):Q(this,S,Y(this,v,"f")[r],"f"),Y(this,g,"f").delete(o),Q(this,f,(t=Y(this,f,"f"),--t),"f"),r},z=function(e,t,r,o){const n=void 0===t?void 0:Y(this,y,"f")[t];if(Y(this,s,"m",G).call(this,n))return n;const i=new ne,{signal:a}=r;a?.addEventListener("abort",(()=>i.abort(a.reason)),{signal:i.signal});const c={signal:i.signal,options:r,context:o},l=(o,n=!1)=>{const{aborted:a}=i.signal,l=r.ignoreFetchAbort&&void 0!==o;if(r.status&&(a&&!n?(r.status.fetchAborted=!0,r.status.fetchError=i.signal.reason,l&&(r.status.fetchAbortIgnored=!0)):r.status.fetchResolved=!0),a&&!l&&!n)return u(i.signal.reason);const d=h,p=Y(this,y,"f")[t];return(p===h||l&&n&&void 0===p)&&(void 0===o?void 0!==d.__staleWhileFetching?Y(this,y,"f")[t]=d.__staleWhileFetching:Y(this,s,"m",K).call(this,e,"fetch"):(r.status&&(r.status.fetchUpdated=!0),this.set(e,o,c.options))),o},u=o=>{const{aborted:n}=i.signal,a=n&&r.allowStaleOnFetchAbort,c=a||r.allowStaleOnFetchRejection,l=c||r.noDeleteOnFetchRejection,u=h;if(Y(this,y,"f")[t]===h&&(l&&void 0!==u.__staleWhileFetching?a||(Y(this,y,"f")[t]=u.__staleWhileFetching):Y(this,s,"m",K).call(this,e,"fetch")),c)return r.status&&void 0!==u.__staleWhileFetching&&(r.status.returnedStale=!0),u.__staleWhileFetching;if(u.__returned===u)throw o};r.status&&(r.status.fetchDispatched=!0);const h=new Promise(((t,o)=>{const s=Y(this,d,"f")?.call(this,e,n,c);s&&s instanceof Promise&&s.then((e=>t(void 0===e?void 0:e)),o),i.signal.addEventListener("abort",(()=>{r.ignoreFetchAbort&&!r.allowStaleOnFetchAbort||(t(void 0),r.allowStaleOnFetchAbort&&(t=e=>l(e,!0)))}))})).then(l,(e=>(r.status&&(r.status.fetchRejected=!0,r.status.fetchError=e),u(e)))),p=Object.assign(h,{__abortController:i,__staleWhileFetching:n,__returned:void 0});return void 0===t?(this.set(e,p,{...c.options,status:void 0}),t=Y(this,g,"f").get(e)):Y(this,y,"f")[t]=p,p},G=function(e){if(!Y(this,R,"f"))return!1;const t=e;return!!t&&t instanceof Promise&&t.hasOwnProperty("__staleWhileFetching")&&t.__abortController instanceof ne},V=function(e,t){Y(this,b,"f")[t]=e,Y(this,v,"f")[e]=t},J=function(e){e!==Y(this,k,"f")&&(e===Y(this,S,"f")?Q(this,S,Y(this,v,"f")[e],"f"):Y(this,s,"m",V).call(this,Y(this,b,"f")[e],Y(this,v,"f")[e]),Y(this,s,"m",V).call(this,Y(this,k,"f"),e),Q(this,k,e,"f"))},K=function(e,t){var r;let o=!1;if(0!==Y(this,f,"f")){const n=Y(this,g,"f").get(e);if(void 0!==n)if(o=!0,1===Y(this,f,"f"))Y(this,s,"m",Z).call(this,t);else{Y(this,j,"f").call(this,n);const o=Y(this,y,"f")[n];if(Y(this,s,"m",G).call(this,o)?o.__abortController.abort(new Error("deleted")):(Y(this,I,"f")||Y(this,T,"f"))&&(Y(this,I,"f")&&Y(this,c,"f")?.call(this,o,e,t),Y(this,T,"f")&&Y(this,C,"f")?.push([o,e,t])),Y(this,g,"f").delete(e),Y(this,w,"f")[n]=void 0,Y(this,y,"f")[n]=void 0,n===Y(this,k,"f"))Q(this,k,Y(this,b,"f")[n],"f");else if(n===Y(this,S,"f"))Q(this,S,Y(this,v,"f")[n],"f");else{const e=Y(this,b,"f")[n];Y(this,v,"f")[e]=Y(this,v,"f")[n];const t=Y(this,v,"f")[n];Y(this,b,"f")[t]=Y(this,b,"f")[n]}Q(this,f,(r=Y(this,f,"f"),--r),"f"),Y(this,E,"f").push(n)}}if(Y(this,T,"f")&&Y(this,C,"f")?.length){const e=Y(this,C,"f");let t;for(;t=e?.shift();)Y(this,u,"f")?.call(this,...t)}return o},Z=function(e){for(const t of Y(this,s,"m",W).call(this,{allowStale:!0})){const r=Y(this,y,"f")[t];if(Y(this,s,"m",G).call(this,r))r.__abortController.abort(new Error("deleted"));else{const o=Y(this,w,"f")[t];Y(this,I,"f")&&Y(this,c,"f")?.call(this,r,o,e),Y(this,T,"f")&&Y(this,C,"f")?.push([r,o,e])}}if(Y(this,g,"f").clear(),Y(this,y,"f").fill(void 0),Y(this,w,"f").fill(void 0),Y(this,P,"f")&&Y(this,_,"f")&&(Y(this,P,"f").fill(0),Y(this,_,"f").fill(0)),Y(this,x,"f")&&Y(this,x,"f").fill(0),Q(this,S,0,"f"),Q(this,k,0,"f"),Y(this,E,"f").length=0,Q(this,m,0,"f"),Q(this,f,0,"f"),Y(this,T,"f")&&Y(this,C,"f")){const e=Y(this,C,"f");let t;for(;t=e?.shift();)Y(this,u,"f")?.call(this,...t)}}},"../utils/dist/path-utils.js"(e,t,r){r.d(t,{BJ:()=>p,DN:()=>u,PS:()=>m,ZU:()=>d,fl:()=>g,jl:()=>a,o1:()=>l,oL:()=>f,yn:()=>c});var o=r("node:fs/promises"),n=r("node:os"),s=r("node:path"),i=r("node:url");function a(e){return e.replace(/^~(?=$|\/|\\)/,(0,n.homedir)())}function c(e,t){return void 0!==e&&("win32"===process.platform?(0,s.normalize)(e).toLowerCase()===(0,s.normalize)(t).toLowerCase():e===t)}function l(e,t){const r=a(function(e){if(!e.startsWith("file://"))return e;try{return(0,i.fileURLToPath)(e)}catch{return e}}(e));return t&&!(0,s.isAbsolute)(r)?(0,s.resolve)(t,r):(0,s.resolve)(r)}async function u(e,t){const r=l(e,t);let n=r;for(;;)try{const e=await(0,o.realpath)(n);return(0,s.resolve)(e,(0,s.relative)(n,r))}catch(e){if("ENOENT"!==e.code)return null;const t=(0,s.dirname)(n);if(t===n)return r;n=t}}function d({basePath:e,targetPath:t}){const r=(0,s.resolve)(e),o=(0,s.resolve)(e,t);return r===(0,s.parse)(r).root?(0,s.parse)(o).root===r&&(o===r||o.length>r.length):o===r||o.startsWith(r+s.sep)}function h(e,t){for(const r of t)if(d({basePath:r,targetPath:e}))return!0;return!1}function p(e,t){const r="win32"===process.platform||"darwin"===process.platform,o=r?e.toLowerCase():e,n=r?t.toLowerCase():t;if(o===n)return!0;const i=n.endsWith(s.sep)?n:n+s.sep;return o.startsWith(i)}function f(e){return e.replace(/\\/g,"/")}const m="You cannot search other worktrees for this repository, stay within your workspace paths.";function g(e){const{targetPath:t,workspacePaths:r,mainWorktreePath:o}=e;if(void 0===t)return!1;if(0===r.length)return!1;if(!r.every((e=>function(e){return f(e).includes(".cursor/worktrees")}(e))))return!1;if(h(t,r))return!1;const n=(0,s.isAbsolute)(t)?[(0,s.resolve)(t)]:r.map((e=>(0,s.resolve)(e,t))),i=r.map((e=>function(e){const t=f(e),r=t.indexOf("/.cursor/worktrees/");if(-1===r)return;const o=t.slice(r+19).split("/");if(o.length<2)return;const n=o[0]??"";return 0!==n.length?t.slice(0,r+19+n.length):void 0}(e))).filter((e=>void 0!==e));return!!(i.length>0&&n.some((e=>h(e,i))))||!(void 0===o||!n.some((e=>h(e,[o]))))}},"../utils/dist/safe-spawn-cwd.js"(e,t,r){r.d(t,{$Y:()=>P,$f:()=>b,A:()=>v,D1:()=>S,Gq:()=>x,Gw:()=>l,KX:()=>D,N6:()=>f,Vn:()=>T,Zv:()=>p,fK:()=>A,iA:()=>_,mM:()=>k,qr:()=>E,wr:()=>O,wz:()=>R,yo:()=>C});var o=r("node:crypto?8af2"),n=r("node:fs"),s=r("node:os"),i=r("node:path"),a=r("node:stream");const c="/cursor/stores",l="cursor-fuse-cwd",u="cursor-fuse-cwd:cd",d=Buffer.from(u);function h(e){return Buffer.from(Buffer.concat(e))}class p{constructor(){this.held=Buffer.alloc(0),this.released=!1,this.seen=0,this.prefix=Buffer.alloc(0)}get bytes(){return this.seen}get stdoutPrefix(){return this.prefix}get diverged(){return this.released}note(e){const t=Buffer.from(e);if(this.seen+=t.length,this.prefix.length<32){const e=Math.min(t.length,32-this.prefix.length);this.prefix=h([this.prefix,t.subarray(0,e)])}if(this.released)return t;const r=h([this.held,t]);if(!(r.length<=d.length&&d.subarray(0,r.length).equals(r)))return this.released=!0,this.held=Buffer.alloc(0),r;this.held=r}takeHeld(){if(0===this.held.length)return void(this.released=!0);const e=this.held;return this.held=Buffer.alloc(0),this.released=!0,e}}const f=`cd "$1" || { printf %s '${u}'; exit 79; }; shift; exec "$@"`;let m,g,w=function(){try{return(0,n.readFileSync)("/proc/self/mountinfo","utf8")}catch{return}};function y(e,t){return"/"===t||e===t||e.startsWith(`${t}/`)}function v(e,t){const r=function(e){return e?.readMountinfo??w}(t)();if(void 0===r)return!1;const o=function(e,t){let r;for(const o of t)y(e,o.mountPoint)&&(void 0===r||o.mountPoint.length>=r.mountPoint.length)&&(r=o);return r}(i.default.resolve(e),function(e){return m===e&&void 0!==g||(m=e,g=function(e){const t=[];for(const n of e.split("\n")){if(0===n.length)continue;const e=n.split(" ");if(e.length<10)continue;let s=-1;for(let t=6;t<e.length;t++)if("-"===e[t]){s=t;break}const i=e[4],a=-1===s?void 0:e[s+1];void 0!==i&&void 0!==a&&0!==a.length&&t.push({mountPoint:(o=i,r=o.replace(/\\([0-7]{3})/g,((e,t)=>String.fromCharCode(Number.parseInt(t,8)))),"/"===r?"/":r.replace(/\/+$/,"")),fstype:a})}var r,o;return t}(e)),g}(r));return void 0!==o&&("fuse"===(n=o.fstype)||"fuseblk"===n||n.startsWith("fuse."));var n}function b(e){const t=i.default.resolve(e);return t===c||t.startsWith(`${c}/`)}function S(e){const t=e?.processCwd??process.cwd();return"linux"===(e?.platform??process.platform)&&v(t,e)?e?.tmpdir??(0,s.tmpdir)():t}function k(e,t,r,o){const n=o?.platform??process.platform,s=r?.cwd;if("linux"!==n||void 0===s||r?.shell||!v(s,o))return{command:e,args:[...t],options:r,hopped:!1};const a=i.default.resolve(s),c=S({processCwd:o?.processCwd,tmpdir:o?.tmpdir,platform:n,readMountinfo:o?.readMountinfo});return{command:"/bin/sh",args:["-c",f,l,a,e,...t],options:{...r,cwd:c},hopped:!0,hopCwd:a}}function E(e=process.env){return"1"===e.CURSOR_SPAWN_CWD_HOP}const C="exec_daemon.spawn.cwd_hop",x="exec_daemon.spawn.cwd_hop_cd_failed";function _(e){return{cwdKind:b(e)?"agent_store_fuse":"fuse",cwdHash:(0,o.createHash)("sha256").update(e,"utf8").digest("hex").slice(0,12)}}function P(e,t=process.env){return E(t)&&void 0!==e&&v(e)}function I(e){return`working directory is not accessible: ${i.default.resolve(e)}`}function R(e){return P(e.cwd,e.env)&&79===e.exitCode&&18===e.stdoutBytes&&("string"==typeof(t=e.stdoutPrefix)?t===u:Buffer.from(t).equals(Buffer.from(u)));var t}function T(e){const t=new Error(I(e));return t.code="ENOENT",t}function A(e,t){return e instanceof Error&&"ENOENT"===e.code&&e.message===I(t)}function M(e){return"object"==typeof e&&null!==e&&"emit"in e&&"function"==typeof e.emit&&"on"in e&&"function"==typeof e.on&&"stdout"in e&&"stdin"in e}function D(e,t){if(function(e,t){if("object"!=typeof e||null===e||!("status"in e))return!1;const r=e,o=function(e){if(null==e.stdout)return{bytes:0,prefix:Buffer.alloc(0)};const t="string"==typeof e.stdout?Buffer.from(e.stdout):h([e.stdout]);return{bytes:t.length,prefix:t.subarray(0,32)}}(r);return R({exitCode:"number"==typeof r.status?r.status:null,stdoutBytes:o.bytes,stdoutPrefix:o.prefix,cwd:t})}(e,t))throw T(t);throw e}function O(e,t){return M(e)?(function(e,t){const r=new p,o=new a.PassThrough;let n,s=!1;const i=e.stdout,c=e.emit.bind(e),l=e=>{if(e)r.takeHeld();else{const e=r.takeHeld();void 0===e||o.writableEnded||o.write(e)}o.writableEnded||o.end()},u=e=>{const t=e?.[0];return null===t||"number"==typeof t?t:null},d=e=>R({exitCode:u(e),stdoutBytes:r.bytes,stdoutPrefix:r.stdoutPrefix,cwd:t}),h=()=>(s=!0,l(!0),c("error",T(t))),f=()=>{void 0!==n&&79===u(n)&&(c("exit",...n),n=void 0)};i&&(i.on("data",(e=>{if(s)return;const t=r.note(e);if(void 0!==t)return o.write(t),void f();d(n)&&h()})),i.on("error",(e=>{o.destroy(e)})),Object.defineProperty(e,"stdout",{configurable:!0,enumerable:!0,get:()=>o})),e.emit=(e,...t)=>s?"exit"!==e&&"close"!==e&&c(e,...t):"exit"===e?(n=t,79!==u(t)?c(e,...t):d(t)?h():!(!r.diverged&&null!=i)&&(n=void 0,c(e,...t))):"close"===e?d(t)||d(n)?h():(l(!1),f(),c(e,...t)):c(e,...t)}(e,t),e):"object"==typeof(r=e)&&null!==r&&!M(r)&&"onData"in r&&"function"==typeof r.onData&&"onExit"in r&&"function"==typeof r.onExit?(function(e,t){const r=new p,o=[],n=e.onData.bind(e),s=e.onExit.bind(e);e.onData=e=>(o.push(e),n((t=>{const o="string"==typeof t?Buffer.from(t):t,n=r.note(o);void 0!==n&&e("string"==typeof t?n.toString("utf8"):n)}))),e.onExit=e=>s((n=>{const s=r.takeHeld();if(R({exitCode:n.exitCode,stdoutBytes:r.bytes,stdoutPrefix:r.stdoutPrefix,cwd:t}))e(n);else{if(void 0!==s)for(const e of o)e(s);e(n)}}))}(e,t),e):function(e){return"object"==typeof e&&null!==e&&"then"in e&&"function"==typeof e.then}(e)?e.then((e=>e),(e=>D(e,t))):e;var r}},"../utils/dist/test-resets.js"(e,t,r){r.d(t,{J:()=>n});const o="undefined"==typeof process||void 0===process.env.VITEST?void 0:globalThis.__cursorTestResets??=new Set;function n(e){o?.add(e)}},"../utils/dist/workload-spawn.js"(e,t,r){r.d(t,{D9:()=>u});var o=r("node:fs");function n(e){if(!("linux"!==process.platform||void 0===e||e<=0))try{(0,o.writeFileSync)(`/proc/${e}/oom_score_adj`,"0")}catch{}}var s=r("../utils/dist/safe-spawn-cwd.js");const i=/^\/sys\/fs\/cgroup\/[A-Za-z0-9_/.-]+$/,a=Object.freeze({kind:"direct"});function c({workloadCgroupDir:e,hopCwd:t}){const r=`echo $$ 2>/dev/null > '${e}/cgroup.procs'; echo 0 2>/dev/null > /proc/$$/oom_score_adj; `;return void 0!==t?r+s.N6:`${r}exec "$0" "$@"`}function l(e){try{return!!(0,o.statSync)(e).isDirectory()&&((0,o.accessSync)(`${e}/cgroup.procs`,o.constants.W_OK),!0)}catch{return!1}}const u=function(e,t=n){return function(r,o,n,...i){const a=i[0],l=(0,s.qr)()&&null!==(u=a)&&"object"==typeof u&&!Array.isArray(u)?(0,s.mM)(o,n,a):void 0;var u;let d,h=o,p=[...n],f=i;!0===l?.hopped&&void 0!==l.hopCwd?(f=function(e,t){return[t,...e.slice(1)]}(i,l.options),"armed"===e.kind?(h="/bin/sh",p=["-c",c({workloadCgroupDir:e.workloadCgroupDir,hopCwd:l.hopCwd}),s.Gw,l.hopCwd,o,...n]):(h=l.command,p=l.args)):"armed"===e.kind&&(h=e.executable,p=[...e.argumentPrefix,o,...n]);try{d=r(h,p,...f)}catch(e){throw!0===l?.hopped&&void 0!==l.hopCwd&&(0,s.KX)(e,l.hopCwd),e}return function(e,t){"object"==typeof e&&null!==e&&"pid"in e&&"number"==typeof e.pid?t(e.pid):"object"==typeof e&&null!==e&&"child"in e&&"object"==typeof e.child&&null!==e.child&&"pid"in e.child&&"number"==typeof e.child.pid&&t(e.child.pid)}(d,t),!0===l?.hopped&&void 0!==l.hopCwd?(0,s.wr)(d,l.hopCwd):d}}(function(e,t,r=l){return"linux"===e&&void 0!==t&&i.test(t)&&!t.includes("..")&&r(t)?Object.freeze({kind:"armed",workloadCgroupDir:t,executable:"/bin/sh",argumentPrefix:Object.freeze(["-c",c({workloadCgroupDir:t})])}):a}(process.platform,process.env.CURSOR_WORKLOAD_CGROUP))},"../utils/dist/writable-iterable.js"(e,t,r){r.d(t,{F8:()=>n,Jt:()=>s,W2:()=>o});class o extends Error{constructor(e){super(e),this.name="WriteIterableClosedError"}}class n{constructor(e,t){this.writable=e,this.map=t,this.closed=!1}async write(e){if(this.closed)throw new o("WritableIterable is closed");const t=this.map(e);await this.writable.write(t)}close(){this.closed||(this.closed=!0)}}function s(){const e=[],t=[];let r,n=!1,s=()=>{},i=()=>{};const a=()=>{const e=new Promise(((e,t)=>{s=e,i=t}));return e.catch((()=>{})),e};let c=a();function l(t,r){for(;e.length>0;){const o=e.shift();r?o.reject(r):o.resolve(t)}}function u(e){t.length=0,i(e),c=Promise.reject(e),c.catch((()=>{}))}return{async write(s){if(n)throw r??new o("WritableIterable is closed");const i=e.shift();if(i){if(i.resolve({done:!1,value:s}),e.length>0)return}else t.push(s);const a=t.length+1;for(let e=0;e<a;e++)await c},throw(e){n||(n=!0,r=e,u(e),l({done:!0,value:void 0},e))},close(){n||(n=!0,t.length=0,s(),c=Promise.reject(new o("WritableIterable is closed")),c.catch((()=>{})),l({done:!0,value:void 0}))},[Symbol.asyncIterator]:()=>({next(){s(),c=a();const o=t.shift();return void 0!==o?Promise.resolve({done:!1,value:o}):n?r?Promise.reject(r):Promise.resolve({done:!0,value:void 0}):new Promise(((t,r)=>{e.push({resolve:t,reject:r})}))},throw:e=>(n=!0,r=e,t.length=0,u(e),l({done:!0,value:void 0},e),Promise.resolve({done:!0,value:void 0})),return:()=>(n=!0,t.length=0,s(),c=Promise.reject(new Error("Iterator was closed")),c.catch((()=>{})),l({done:!0,value:void 0}),Promise.resolve({done:!0,value:void 0}))})}}}};
|